content
stringlengths
5
1.05M
hook.Add("CanTool", "ToolAbuseRestrict", function(ply, _, tool) if tool == "duplicator" and not ply:IsAdmin() then ply:ChatPrint("We don't allow the duplicator to be used here at this point in time, sorry!") return false end if tool == "fading_door" and not table.HasValue(list.Get("FDoorMaterials"), ply:GetInfo("fading_door_mat")) then ply:ChatPrint("Restricted to allowed materials only!") return false end end)
local rigel = require "rigel" rigel.MONITOR_FIFOS = false local R = require "rigelSimple" local types = require "types" local J = require "common" dofile("moduleparams_core.lua") local configs = {} local meta = {} configs.downsampleXSeq = J.cartesian{type=Type, size={IS}, V=NumP, scale={2,4,8} } meta.downsampleXSeq = {} for k,v in ipairs(configs.downsampleXSeq) do meta.downsampleXSeq[k] = {inputP=v.V, outputP=v.V, inputImageSize=v.size} meta.downsampleXSeq[k].outputImageSize={v.size[1]/v.scale, v.size[2]} end runTests( configs, meta ) file = io.open("out/moduleparams_downsamplex.compiles.txt", "w") file:write("Hello World") file:close()
package.cpath = "../?.dll;"..package.cpath local loop = require "znet".new() print("znet engine: "..loop.engine) local recv_count, recv_bytes = 0, 0 local send_count, send_bytes = 0, 0 local data = ("."):rep(1024) local count = arg[1] and arg[1]:match "client(%d*)" if count then count = count == "" and 1 or tonumber(count) for i = 1, count do loop:tcp("127.0.0.1", 8081, function(self, err) if err then print(err) return end self:send(data) :receive(function(self, s) send_count = send_count + 1 send_bytes = send_bytes + #s self:send(s) end) end) end else loop:accept(function(self, tcp) tcp:receive(function(self, s) recv_count = recv_count + 1 recv_bytes = recv_bytes + #s self:send(s) end) return true end):listen(nil, 8081) end loop:timer(function(self) print(("send: %d/%d recv: %d/%d"):format( send_count, send_bytes, recv_count, recv_bytes)) send_count, send_bytes = 0, 0 recv_count, recv_bytes = 0, 0 return true end):start(1000) loop:run()
bit = {} function bit.b(p) return 2 ^ (p - 1) -- 1-based indexing end -- Typical call: if bit.and(x, bit.b(3)) then ... function bit.band(x, p) return x % (p + p) >= p end function bit.setbit(x, p) return bit.band(x, p) and x or x + p end --[==[ BIT_FRAME_TITLE = 1 BIT_FRAME_CLOSE = 2 print(bit.setbit(BIT_FRAME_TITLE, BIT_FRAME_CLOSE)) print(bit.band(3, BIT_FRAME_TITLE)) print(bit.band(7, 1)) print(bit.band(7, 2)) print(bit.band(7, 3)) print(bit.band(8, 4)) --]==]
local fn = require('distant.fn') local Driver = require('spec.e2e.driver') describe('fn', function() local driver before_each(function() driver = Driver:setup() end) after_each(function() driver:teardown() end) describe('spawn_wait', function() local function to_tbl(res) return { success = res.success, exit_code = res.exit_code, stdout = res.stdout, stderr = res.stderr, } end it('should execute remote program and return results', function() local err, res = fn.spawn_wait({cmd = 'echo', args = {'some output'}}) assert(not err, err) assert.are.same(to_tbl(res), { success = true, exit_code = 0, stdout = 'some output\n', stderr = '', }) end) -- distant and ssh modes behave differently here as ssh treats as a success and -- echoes out that the process does not exist whereas distant clearly marks -- as an error -- -- TODO: For some reason, stderr is also not captured in the test below. distant-ssh2 -- is able to correctly capture stderr, so this will need to be investigated if driver:mode() == 'distant' then it('should support capturing stderr', function() local err, res = fn.spawn_wait({cmd = 'sh', args = {'-c', '1>&2 echo some output'}}) assert(not err, err) assert.are.same(to_tbl(res), { success = true, exit_code = 0, stdout = '', stderr = 'some output\n', }) end) it('should support capturing exit code', function() local err, res = fn.spawn_wait({cmd = 'sh', args = {'-c', 'exit 99'}}) assert(not err, err) assert.are.same(to_tbl(res), { success = false, exit_code = 99, stdout = '', stderr = '', }) end) it('should fail if the remote program is not found', function() local err, res = fn.spawn_wait({cmd = 'idonotexist'}) assert.is.truthy(err) assert.is.falsy(res) end) end end) end)
-- IupList Example in IupLua -- Creates a dialog with three frames, each one containing a list. The first is a simple list, the second one is a multiple list and the last one is a drop-down list. The second list has a callback associated. require( "iuplua" ) -- Creates a list and sets items, initial item and size list = iup.list {"Gold", "Silver", "Bronze", "None" ; value = 4, size = "EIGHTHxEIGHTH"} list[5] = "test" -- Creates frame with simple list and sets its title frm_medal = iup.frame {list ; title = "Best medal"} -- Creates a list and sets its items, multiple selection, initial items and size list_multiple = iup.list {"100m dash", "Long jump", "Javelin throw", "110m hurdlers", "Hammer throw", "High jump" ; multiple="YES", value="+--+--", size="EIGHTHxEIGHTH"} -- Creates frame with multiple list and sets its title frm_sport = iup.frame {list_multiple ; title = "Competed in"} -- Creates a list and sets its items, dropdown and amount of visible items list_dropdown = iup.list {"Less than US$ 1000", "US$ 2000", "US$ 5000", "US$ 10000", "US$ 20000", "US$ 50000", "More than US$ 100000" ; dropdown="YES", visible_items=5} -- Creates frame with dropdown list and sets its title frm_prize = iup.frame {list_dropdown ; title = "Prizes won"} -- Creates a dialog with the the frames with three lists and sets its title dlg = iup.dialog {iup.hbox {frm_medal, frm_sport, frm_prize} ; title = "IupList Example"} -- Shows dialog in the center of the screen dlg:showxy(iup.CENTER, iup.CENTER) function list_multiple:action(t, i, v) if v == 0 then state = "deselected" else state = "selected" end iup.Message("Competed in", "Item "..i.." - "..t.." - "..state) return iup.DEFAULT end if (iup.MainLoopLevel()==0) then iup.MainLoop() end
-- << utils local ipairs = ipairs local next = next local print = print local string = string local table = table local tostring = tostring local type = type local function split_comma(str) local result = {} local n = 1 for s in string.gmatch(str or "", "%s*[^,]+%s*") do if s ~= "" and s ~= "null" then result[n] = s n = n + 1 end end return result end local function _format_any_value(obj, buffer) if type(obj) == "table" then buffer[#buffer + 1] = '{' buffer[#buffer + 1] = '"' -- needs to be separate for empty tables {} for key, value in next, obj, nil do buffer[#buffer + 1] = tostring(key) .. '":' _format_any_value(value, buffer) buffer[#buffer + 1] = ',"' end buffer[#buffer] = "}" -- note the overwrite elseif type(obj) == "string" then buffer[#buffer + 1] = '"' .. tostring(obj) .. '"' elseif type(obj) == "number" or type(obj) == "boolean" then buffer[#buffer + 1] = tostring(obj) elseif type(obj) == "function" then buffer[#buffer + 1] = '"???function???"' else buffer[#buffer + 1] = '"' .. tostring(obj) .. '"' end end local function format(obj) if obj == nil then return "null" else local buffer = {} _format_any_value(obj, buffer) return table.concat(buffer) end end local function _print(obj) print(format(obj)) end local function array_filter(arr, func) local result = {} for _, elem in ipairs(arr) do if func(elem) then result[#result + 1] = elem end end return result end local function array_map(arr, func) local result = {} for index, elem in ipairs(arr) do result[#result + 1] = func(elem, index) end return result end local function array_copy(arr) return array_map(arr, function(e) return e end) end local function array_to_set(arr) local result = {} for _, v in ipairs(arr) do result[v] = true end return result end local function array_forall(arr, func) for _, v in ipairs(arr) do if not func(v) then return false end end return true end local function generate_until_ok(gen_func, ok_func) repeat local result = gen_func() if ok_func(result) then return result end until false end local function wesnoth_message(msg) local wesnoth = wesnoth wesnoth.synchronize_choice(function() local T = wesnoth.require("lua/helper.lua").set_wml_tag_metatable {} local ugly_index = msg.image and 2 or 1 wesnoth.show_dialog { T.tooltip { id = "tooltip_large" }, T.helptip { id = "tooltip_large" }, T.grid { [1] = T.row { T.column { T.image { label = msg.image } } }, [ugly_index] = T.row { T.column { T.label { label = msg.message .. "\n", use_markup = true } } }, [ugly_index + 1] = T.row { T.column { T.button { label = "\nOK\n", return_value = -1 } } }, } } return {} -- strange obligatory "table" result end) end local creepwars = creepwars creepwars.array_copy = array_copy creepwars.array_filter = array_filter creepwars.array_forall = array_forall creepwars.array_map = array_map creepwars.array_to_set = array_to_set creepwars.format = format creepwars.generate_until_ok = generate_until_ok creepwars.print = _print creepwars.split_comma = split_comma creepwars.wesnoth_message = wesnoth_message -- >>
data:extend({ --- Bio Damage for new Ammo { type = "damage-type", name = "Biological" }, })
#!/usr/bin/env lua local sys = require"sys" local thread = sys.thread thread.init() -- Usage notes print[[ Press <Enter> to quit or any chars for feedback... ]] local stdin = sys.stdin -- Event Queue local evq = assert(sys.event_queue()) local worker -- Controller local controller do local function on_event(evq, evid) print("Controller:", "Close stdin") worker:interrupt() stdin:close(true) -- Win32 workaround assert(worker:wait() == -1) evq:del(evid) end controller = assert(evq:add_timer(on_event, 30000)) end -- Worker Thread do local function read_stdin() while true do local line = stdin:read() if #line <= 2 then print("Worker:", "Notify controller") evq:sync(evq.notify, evq, controller) else sys.stdout:write("Worker:\tInput: ", line) end end end local function start() local _, err = pcall(read_stdin) if err and not (thread.self():interrupted() and err == thread.interrupt_error()) then print("Error:", err) err = nil end if not err then error("Thread Interrupt Error expected") end print("Worker:", "Terminated") return -1 end worker = assert(thread.run(start)) end assert(evq:loop())
--[[ -- added by wsh @ 2017-12-11 -- Lua侧带有可复用功能的UI组件,UIWrapGroup需要使用到 -- 注意: -- 1、这里只是作为一个接口文件来使用,具体功能需要自行继承并实现 --]] ---@class UIWrapComponent :UIBaseContainer local UIWrapComponent = BaseClass("UIWrapComponent", UIBaseContainer) ---@return UIBaseContainer local base = UIBaseContainer -- 组件被复用时回调该函数,执行组件的刷新 function UIWrapComponent:OnRefresh(real_index, check) end -- 组件添加了按钮组,则按钮被点击时回调该函数 function UIWrapComponent:OnClick(toggle_btn, real_index, check) end return UIWrapComponent
--Ai-Q function c101012073.initial_effect(c) --activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER) e1:SetCondition(c101012073.condition) c:RegisterEffect(e1) --maintain local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetProperty(EFFECT_FLAG_UNCOPYABLE+EFFECT_FLAG_CANNOT_DISABLE) e2:SetRange(LOCATION_SZONE) e2:SetCode(EVENT_PHASE+PHASE_STANDBY) e2:SetCountLimit(1) e2:SetCondition(c101012073.descon) e2:SetOperation(c101012073.desop) c:RegisterEffect(e2) --link summon count limit local e3=Effect.CreateEffect(c) e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e3:SetCode(EVENT_SPSUMMON_SUCCESS) e3:SetRange(LOCATION_SZONE) e3:SetCondition(c101012073.regcon1) e3:SetOperation(c101012073.regop1) c:RegisterEffect(e3) local e4=e3:Clone() e4:SetCondition(c101012073.regcon2) e4:SetOperation(c101012073.regop2) c:RegisterEffect(e4) local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_FIELD) e5:SetCode(101012073) e5:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e5:SetRange(LOCATION_SZONE) e5:SetTargetRange(1,1) c:RegisterEffect(e5) end function c101012073.regfilter(c,tp) return c:IsSummonType(SUMMON_TYPE_LINK) and c:GetSummonPlayer()==tp end function c101012073.regcon1(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c101012073.regfilter,1,nil,tp) end function c101012073.regop1(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetRange(LOCATION_SZONE) e1:SetTargetRange(1,0) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END) e1:SetTarget(c101012073.splimit) c:RegisterEffect(e1) end function c101012073.regcon2(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c101012073.regfilter,1,nil,1-tp) end function c101012073.regop2(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetRange(LOCATION_SZONE) e1:SetTargetRange(0,1) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END) e1:SetTarget(c101012073.splimit) c:RegisterEffect(e1) end function c101012073.splimit(e,c,tp,sumtp,sumpos) return bit.band(sumtp,SUMMON_TYPE_LINK)==SUMMON_TYPE_LINK end function c101012073.filter(c) return c:IsFaceup() and c:IsSetCard(0x135) end function c101012073.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.IsExistingMatchingCard(c101012073.filter,tp,LOCATION_MZONE,0,1,nil) end function c101012073.descon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c101012073.desop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() Duel.HintSelection(Group.FromCards(c)) if Duel.CheckReleaseGroup(tp,Card.IsType,1,nil,TYPE_LINK) and Duel.SelectYesNo(tp,aux.Stringid(101012073,0)) then local g=Duel.SelectReleaseGroup(tp,Card.IsType,1,1,nil,TYPE_LINK) Duel.Release(g,REASON_COST) else Duel.Destroy(c,REASON_COST) end end
function jtorch._saveCAddTableNode(node, ofile) -- Nothing to do for a CAddTable node end
return { include = function() includedirs { "../vendor/libuv/include/" } end, run = function() language "C" kind "SharedLib" includedirs { "../vendor/libuv/src/" } files_project '../vendor/libuv/' { 'include/uv.h', 'include/uv/tree.h', 'include/uv/errno.h', 'include/uv/threadpool.h', 'include/uv/version.h', 'src/fs-poll.c', 'src/heap-inl.h', 'src/idna.c', 'src/idna.h', 'src/inet.c', 'src/queue.h', 'src/random.c', 'src/strscpy.c', 'src/strscpy.h', 'src/threadpool.c', 'src/timer.c', 'src/uv-data-getter-setters.c', 'src/uv-common.c', 'src/uv-common.h', 'src/version.c' } defines { 'BUILDING_UV_SHARED=1' } filter "system:not windows" defines { "_LARGEFILE_SOURCE", "_FILEOFFSET_BITS=64" } links { 'm' } linkoptions { '-pthread' } files_project '../vendor/libuv/' { 'include/uv/unix.h', 'include/uv/linux.h', 'include/uv/sunos.h', 'include/uv/darwin.h', 'include/uv/bsd.h', 'include/uv/aix.h', 'src/unix/async.c', 'src/unix/atomic-ops.h', 'src/unix/core.c', 'src/unix/dl.c', 'src/unix/fs.c', 'src/unix/getaddrinfo.c', 'src/unix/getnameinfo.c', 'src/unix/internal.h', 'src/unix/loop.c', 'src/unix/loop-watcher.c', 'src/unix/pipe.c', 'src/unix/poll.c', 'src/unix/process.c', 'src/unix/random-devurandom.c', 'src/unix/signal.c', 'src/unix/spinlock.h', 'src/unix/stream.c', 'src/unix/tcp.c', 'src/unix/thread.c', 'src/unix/tty.c', 'src/unix/udp.c', -- linux 'src/unix/epoll.c', 'src/unix/linux-core.c', 'src/unix/linux-inotify.c', 'src/unix/linux-syscalls.c', 'src/unix/linux-syscalls.h', 'src/unix/procfs-exepath.c', 'src/unix/random-getrandom.c', 'src/unix/random-sysctl-linux.c', 'src/unix/no-proctitle.c', 'src/unix/procfs-exepath.c', } filter "system:windows" defines { "_GNU_SOURCE", "_WIN32_WINNT=0x0600" } links { 'advapi32', 'iphlpapi', 'psapi', 'shell32', 'ws2_32', 'userenv' } files_project '../vendor/libuv/' { 'include/uv/win.h', 'src/win/async.c', 'src/win/atomicops-inl.h', 'src/win/core.c', 'src/win/detect-wakeup.c', 'src/win/dl.c', 'src/win/error.c', 'src/win/fs.c', 'src/win/fs-event.c', 'src/win/getaddrinfo.c', 'src/win/getnameinfo.c', 'src/win/handle.c', 'src/win/handle-inl.h', 'src/win/internal.h', 'src/win/loop-watcher.c', 'src/win/pipe.c', 'src/win/thread.c', 'src/win/poll.c', 'src/win/process.c', 'src/win/process-stdio.c', 'src/win/req-inl.h', 'src/win/signal.c', 'src/win/snprintf.c', 'src/win/stream.c', 'src/win/stream-inl.h', 'src/win/tcp.c', 'src/win/tty.c', 'src/win/udp.c', 'src/win/util.c', 'src/win/winapi.c', 'src/win/winapi.h', 'src/win/winsock.c', 'src/win/winsock.h', } end }
AddCSLuaFile("shared.lua") local matWireFrame = Material( "models/wireframe" ) EFFECT.Time = 1 EFFECT.LifeTime = CurTime() EFFECT.percent = 0 EFFECT.invPer = 0 EFFECT.highPer = 0 EFFECT.height = 0 EFFECT.mins = 0 EFFECT.maxs = 0 EFFECT.AddDist = 0.2 EFFECT.ParticleDiff = Vector(0,0,0) EFFECT.Emitter = nil EFFECT.Size = 0 EFFECT.CurParticleEmit = 0 function EFFECT:Init( data ) if render.GetDXLevel() <= 90 then return false end self.LifeTime = CurTime() + self.Time self.ParentEntity = data:GetEntity() if !IsValid(self.ParentEntity) then return end self.Emitter = ParticleEmitter( self.ParentEntity:GetPos() ) self.mins = self.ParentEntity:OBBMins() self.maxs = self.ParentEntity:OBBMaxs() self.height = self.maxs.z - self.mins.z self.ParticleDiff = self.maxs - self.mins / 2 self.ParticleDiff.x = self.ParticleDiff.x * 0.8 self.ParticleDiff.y = self.ParticleDiff.y * 0.8 self.Size = self.ParticleDiff.x + self.ParticleDiff.y self.Size = self.Size / 100 if !self.ParentEntity:GetModel() then return end --//Some people manage to get models with no models self:SetModel( self.ParentEntity:GetModel() ) self:SetPos( self.ParentEntity:GetPos() ) self:SetAngles( self.ParentEntity:GetAngles() ) self:SetParent( self.ParentEntity ) local skin = self.ParentEntity:GetSkin() if !skin then skin = 0 end self:SetSkin(self.ParentEntity:GetSkin()) self.ParentEntity:SetColor(Color(0,0,0,0)) self.ParentEntity:SetNoDraw( true ) self.Emitter=ParticleEmitter(self:GetPos()) end function EFFECT:Think( ) if render.GetDXLevel() <= 90 then return false end if !IsValid(self.ParentEntity) then return false end if self.highPer <= 0 then self.ParentEntity:SetColor(Color(255,255,255,255)) self.ParentEntity:SetNoDraw( false ) self.Emitter:Finish() return false else return true end end function EFFECT:SCarSetMaterial( mat ) render.MaterialOverride( mat ) end function EFFECT:Render() if render.GetDXLevel() <= 90 then return false end if self.ParentEntity == NULL then return false end self.percent = (self.LifeTime - CurTime()) / self.Time self.highPer = self.percent + self.AddDist self.percent = math.Clamp( self.percent, 0, 1 ) self.highPer = math.Clamp( self.highPer, 0, 1 ) --Drawing original model local normal = self.ParentEntity:GetUp() * -1 local origin = self.ParentEntity:GetPos() + self.ParentEntity:GetUp() * (self.maxs.z - ( self.height * self.highPer )) local distance = normal:Dot( origin ) local oldEnableClipping = render.EnableClipping( true ) render.PushCustomClipPlane( normal, distance ) self:DrawModel() render.PopCustomClipPlane() --Drawing wire frame self:SCarSetMaterial( matWireFrame ) normal = self.ParentEntity:GetUp() distance = normal:Dot( origin ) render.PushCustomClipPlane( normal, distance ) local normal2 = self.ParentEntity:GetUp() * -1 local origin2 = self.ParentEntity:GetPos() + self.ParentEntity:GetUp() * (self.maxs.z - ( self.height * self.percent )) local distance2 = normal2:Dot( origin2 ) render.PushCustomClipPlane( normal2, distance2 ) self:DrawModel() render.PopCustomClipPlane() render.PopCustomClipPlane() self:SCarSetMaterial( 0 ) render.EnableClipping( oldEnableClipping ) self.CurParticleEmit = self.CurParticleEmit + self.Size while self.CurParticleEmit > 1 do self.CurParticleEmit = self.CurParticleEmit - 1 local height = math.Rand(0, 300) local randPos = self.ParentEntity:GetForward() * math.Rand( -self.ParticleDiff.x, self.ParticleDiff.x ) + self.ParentEntity:GetRight() * math.Rand( -self.ParticleDiff.y, self.ParticleDiff.y ) local particle = self.Emitter:Add( "sprites/gmdm_pickups/light", self.ParentEntity:GetPos() + randPos + self.ParentEntity:GetUp() * (self.maxs.z - ( self.height * self.highPer ))) particle:SetVelocity( Vector(0,0, 0.2 * (self.maxs.z - ( self.height * self.highPer )))) particle:SetDieTime(0.5) particle:SetStartAlpha( 255 ) particle:SetStartSize( math.Rand( 1, 5 ) ) particle:SetEndSize( math.Rand( 5, 10 ) ) particle:SetEndAlpha( 0 ) particle:SetRoll( math.Rand( -0.2, 0.2 ) ) particle:SetAirResistance( 10 ) end end
----------------------------------- -- Area: Mhaura -- NPC: Celestina -- Finish Quest: The Sand Charm -- Involved in Quest: Riding on the Clouds -- Guild Merchant NPC: Goldsmithing Guild -- !pos -37.624 -16.050 75.681 249 ----------------------------------- local ID = require("scripts/zones/Mhaura/IDs"); require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(OTHER_AREAS_LOG,tpz.quest.id.otherAreas.THE_SAND_CHARM) == QUEST_ACCEPTED) then if (trade:hasItemQty(13095,1) and trade:getItemCount() == 1) then player:startEvent(127); -- Finish quest "The Sand Charm" end end if (player:getQuestStatus(JEUNO,tpz.quest.id.jeuno.RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getCharVar("ridingOnTheClouds_3") == 5) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setCharVar("ridingOnTheClouds_3",0); player:tradeComplete(); player:addKeyItem(tpz.ki.SOMBER_STONE); player:messageSpecial(ID.text.KEYITEM_OBTAINED,tpz.ki.SOMBER_STONE); end end end; function onTrigger(player,npc) if (player:getCharVar("theSandCharmVar") == 3) then player:startEvent(126,13095); -- During quest "The Sand Charm" - 3rd dialog elseif (player:sendGuild(528,8,23,4)) then player:showText(npc,ID.text.GOLDSMITHING_GUILD); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 126 and option == 70) then player:setCharVar("theSandCharmVar",4); elseif (csid == 127) then player:tradeComplete(); player:setCharVar("theSandCharmVar",0); player:setCharVar("SmallDialogByBlandine",1); player:addKeyItem(tpz.ki.MAP_OF_BOSTAUNIEUX_OUBLIETTE); player:messageSpecial(ID.text.KEYITEM_OBTAINED,tpz.ki.MAP_OF_BOSTAUNIEUX_OUBLIETTE); player:addFame(MHAURA,30); player:completeQuest(OTHER_AREAS_LOG,tpz.quest.id.otherAreas.THE_SAND_CHARM); end end;
--- -- Radar rendering -- @class RADAR local surface = surface local math = math local GetTranslation local GetPTranslation local table = table local net = net local pairs = pairs local IsValid = IsValid local indicator = surface.GetTextureID("effects/select_ring") local c4warn = surface.GetTextureID("vgui/ttt/icon_c4warn") local sample_scan = surface.GetTextureID("vgui/ttt/sample_scan") local det_beacon = surface.GetTextureID("vgui/ttt/det_beacon") local near_cursor_dist = 180 local colorFallback = Color(150, 150, 150) RADAR = RADAR or {} RADAR.targets = {} RADAR.enable = false RADAR.startTime = 0 RADAR.bombs = {} RADAR.bombs_count = 0 RADAR.repeating = true RADAR.samples = {} RADAR.samples_count = 0 RADAR.called_corpses = {} --- -- Disables the scan -- @internal -- @realm client function RADAR:EndScan() self.enable = false self.startTime = 0 end --- -- Clears the radar -- @internal -- @realm client function RADAR:Clear() self:EndScan() self.bombs = {} self.samples = {} self.bombs_count = 0 self.samples_count = 0 end --- -- Cache stuff we'll be drawing -- @internal -- @realm client function RADAR.CacheEnts() -- also do some corpse cleanup here for k, corpse in pairs(RADAR.called_corpses) do if corpse.called + 45 < CurTime() then RADAR.called_corpses[k] = nil -- will make # inaccurate, no big deal end end if RADAR.bombs_count == 0 then return end -- Update bomb positions for those we know about for idx, b in pairs(RADAR.bombs) do local ent = Entity(idx) if IsValid(ent) then b.pos = ent:GetPos() end end end --- -- @ignore function ITEM:Equip(ply) RunConsoleCommand("ttt_radar_scan") end --- -- @ignore function ITEM:DrawInfo() return math.ceil(math.max(0, (LocalPlayer().radarTime or 30) - (CurTime() - RADAR.startTime))) end local function DrawTarget(tgt, size, offset, no_shrink) local scrpos = tgt.pos:ToScreen() -- sweet local sz = (util.IsOffScreen(scrpos) and not no_shrink) and (size * 0.5) or size scrpos.x = math.Clamp(scrpos.x, sz, ScrW() - sz) scrpos.y = math.Clamp(scrpos.y, sz, ScrH() - sz) if util.IsOffScreen(scrpos) then return end surface.DrawTexturedRect(scrpos.x - sz, scrpos.y - sz, sz * 2, sz * 2) -- Drawing full size? if sz == size then local text = math.ceil(LocalPlayer():GetPos():Distance(tgt.pos)) local w, h = surface.GetTextSize(text) -- Show range to target surface.SetTextPos(scrpos.x - w * 0.5, scrpos.y + offset * sz - h * 0.5) surface.DrawText(text) if tgt.t then -- Show time text = util.SimpleTime(tgt.t - CurTime(), "%02i:%02i") w, h = surface.GetTextSize(text) surface.SetTextPos(scrpos.x - w * 0.5, scrpos.y + sz * 0.5) surface.DrawText(text) elseif tgt.nick then -- Show nickname text = tgt.nick w, h = surface.GetTextSize(text) surface.SetTextPos(scrpos.x - w * 0.5, scrpos.y + sz * 0.5) surface.DrawText(text) end end end --- -- Draws the indicator on the screen -- @param Player client -- @hook -- @internal -- @realm client function RADAR:Draw(client) if not IsValid(client) then return end GetPTranslation = GetPTranslation or LANG.GetParamTranslation surface.SetFont("HudSelectionText") -- C4 warnings if self.bombs_count ~= 0 and client:IsActive() and not client:GetSubRoleData().unknownTeam then surface.SetTexture(c4warn) surface.SetTextColor(client:GetRoleColor()) surface.SetDrawColor(255, 255, 255, 200) for _, bomb in pairs(self.bombs) do if bomb.team ~= nil and bomb.team == client:GetTeam() then DrawTarget(bomb, 24, 0, true) end end end -- Corpse calls if not table.IsEmpty(self.called_corpses) then surface.SetTexture(det_beacon) surface.SetTextColor(255, 255, 255, 240) surface.SetDrawColor(255, 255, 255, 230) for _, corpse in pairs(self.called_corpses) do DrawTarget(corpse, 16, 0.5) end end -- Samples if self.samples_count ~= 0 then surface.SetTexture(sample_scan) surface.SetTextColor(200, 50, 50, 255) surface.SetDrawColor(255, 255, 255, 240) for _, sample in pairs(self.samples) do DrawTarget(sample, 16, 0.5, true) end end -- Player radar if not self.enable then return end surface.SetTexture(indicator) local radarTime = client.radarTime or 30 local remaining = math.max(0, radarTime - (CurTime() - RADAR.startTime)) local alpha_base = 50 + 180 * (remaining / radarTime) local mpos = Vector(ScrW() * 0.5, ScrH() * 0.5, 0) local subrole, alpha, scrpos, md for i = 1, #RADAR.targets do local tgt = RADAR.targets[i] alpha = alpha_base scrpos = tgt.pos:ToScreen() if scrpos.visible then md = mpos:Distance(Vector(scrpos.x, scrpos.y, 0)) if md < near_cursor_dist then alpha = math.Clamp(alpha * (md / near_cursor_dist), 40, 230) end subrole = tgt.subrole or ROLE_INNOCENT local roleData = roles.GetByIndex(subrole) local c = roleData.radarColor or (TEAMS[tgt.team] and TEAMS[tgt.team].color or colorFallback) if tgt.color then surface.SetDrawColor(tgt.color.r, tgt.color.g, tgt.color.b, alpha) surface.SetTextColor(tgt.color.r, tgt.color.g, tgt.color.b, alpha) else surface.SetDrawColor(c.r, c.g, c.b, alpha) surface.SetTextColor(c.r, c.g, c.b, alpha) end DrawTarget(tgt, 24, 0) end end end local function ReceiveC4Warn() local idx = net.ReadUInt(16) local armed = net.ReadBit() == 1 if armed then local pos = net.ReadVector() local etime = net.ReadFloat() local team = net.ReadString() RADAR.bombs[idx] = {pos = pos, t = etime, team = team} else RADAR.bombs[idx] = nil end RADAR.bombs_count = table.Count(RADAR.bombs) end net.Receive("TTT_C4Warn", ReceiveC4Warn) local function TTT_CorpseCall() local pos = net.ReadVector() local _tmp = {pos = pos, called = CurTime()} table.insert(RADAR.called_corpses, _tmp) end net.Receive("TTT_CorpseCall", TTT_CorpseCall) local function ReceiveRadarScan() local num_targets = net.ReadUInt(16) RADAR.targets = {} for i = 1, num_targets do local pos = Vector( net.ReadInt(32), net.ReadInt(32), net.ReadInt(32) ) local hasSubrole = net.ReadBool() local subrole if hasSubrole then subrole = net.ReadUInt(ROLE_BITS) end local team = net.ReadString() local color if net.ReadBool() then color = net.ReadColor() end RADAR.targets[#RADAR.targets + 1] = {pos = pos, subrole = subrole, team = team, hasSubrole = hasSubrole, color = color} end RADAR.enable = true RADAR.startTime = CurTime() end net.Receive("TTT_Radar", ReceiveRadarScan) local function ReceiveRadarTime() LocalPlayer().radarTime = net.ReadUInt(8) end net.Receive("TTT2RadarUpdateTime", ReceiveRadarTime) --- -- Creates the settings menu -- @param Panel parent -- @param Panel frame -- @return Panel the dform -- @internal -- @realm client function RADAR.CreateMenu(parent, frame) GetTranslation = GetTranslation or LANG.GetTranslation GetPTranslation = GetPTranslation or LANG.GetParamTranslation --local w, h = parent:GetSize() local dform = vgui.Create("DForm", parent) dform:SetName(GetTranslation("radar_menutitle")) dform:StretchToParent(0, 0, 0, 0) dform:SetAutoSize(false) local owned = LocalPlayer():HasEquipmentItem("item_ttt_radar") if not owned then dform:Help(GetTranslation("radar_not_owned")) return dform end local bw, bh = 100, 25 local dscan = vgui.Create("DButton", dform) dscan:SetSize(bw, bh) dscan:SetText(GetTranslation("radar_scan")) dscan.DoClick = function(s) RunConsoleCommand("ttt_radar_scan") frame:Close() end dform:AddItem(dscan) local dlabel = vgui.Create("DLabel", dform) dlabel:SetText(GetPTranslation("radar_help", {num = LocalPlayer().radarTime or 30})) dlabel:SetWrap(true) dlabel:SetTall(50) dform:AddItem(dlabel) local dcheck = vgui.Create("DCheckBoxLabel", dform) dcheck:SetText(GetTranslation("radar_auto")) dcheck:SetIndent(5) dcheck:SetValue(RADAR.repeating) dcheck.OnChange = function(s, val) net.Start("TTT2RadarUpdateAutoScan") net.WriteBool(val) net.SendToServer() RADAR.repeating = val end dform:AddItem(dcheck) dform.Think = function(s) if RADAR.repeating or not owned then dscan:SetDisabled(true) else dscan:SetDisabled(false) end end dform:SetVisible(true) return dform end
--[[ require'nvim-treesitter.configs'.setup { ensure_installed = "maintained", -- ignore_install = { "javascript" }, highlight = { enable = true, -- disable = { "c", "rust" }, }, incremental_selection = { enable = true, keymaps = { init_selection = "gnn", node_incremental = "grn", scope_incremental = "grc", node_decremental = "grm", }, }, indent = { enable = true }, rainbow = { enable = true, extended_mode = true, max_file_lines = 1000, }, autopairs = {enable = true} } local nvim_lsp = require('lspconfig') -- Use an on_attach function to only map the following keys -- after the language server attaches to the current buffer local on_attach = function(client, bufnr) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end --Enable completion triggered by <c-x><c-o> buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') -- Mappings. local opts = { noremap=true, silent=true } -- See `:help vim.lsp.*` for documentation on any of the below functions buf_set_keymap('n', 'gD', '<Cmd>lua vim.lsp.buf.declaration()<CR>', opts) buf_set_keymap('n', 'gd', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts) buf_set_keymap('n', 'K', '<Cmd>lua vim.lsp.buf.hover()<CR>', opts) buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts) buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts) buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts) buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts) buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts) buf_set_keymap('n', '<space>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts) buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts) buf_set_keymap('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts) buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts) buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts) buf_set_keymap('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts) buf_set_keymap("n", "<space>f", "<cmd>lua vim.lsp.buf.formatting()<CR>", opts) end local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true capabilities.textDocument.completion.completionItem.resolveSupport = { properties = { 'documentation', 'detail', 'additionalTextEdits', } } -- Use a loop to conveniently call 'setup' on multiple servers and -- map buffer local keybindings when the language server attaches local servers = { "pylsp", "rust_analyzer", "tsserver", "gopls", "svelte", "yamlls", "jdtls", "vuels", "html", "cssls", "ccls", "clangd" } -- local servers = { "pyright", "rust_analyzer", "tsserver" } for _, lsp in ipairs(servers) do nvim_lsp[lsp].setup { on_attach = on_attach, capabilities = capabilities, flags = { debounce_text_changes = 150, } } end function goimports(timeout_ms) local context = { source = { organizeImports = true } } vim.validate { context = { context, "t", true } } local params = vim.lsp.util.make_range_params() params.context = context -- See the implementation of the textDocument/codeAction callback -- (lua/vim/lsp/handler.lua) for how to do this properly. local result = vim.lsp.buf_request_sync(0, "textDocument/codeAction", params, timeout_ms) if not result or next(result) == nil then return end local actions = result[1].result if not actions then return end local action = actions[1] -- textDocument/codeAction can return either Command[] or CodeAction[]. If it -- is a CodeAction, it can have either an edit, a command or both. Edits -- should be executed first. if action.edit or type(action.command) == "table" then if action.edit then vim.lsp.util.apply_workspace_edit(action.edit) end if type(action.command) == "table" then vim.lsp.buf.execute_command(action.command) end else vim.lsp.buf.execute_command(action) end end vim.cmd('autocmd BufWritePre *.go lua goimports(1000)') require'compe'.setup { enabled = true; autocomplete = true; debug = false; min_length = 1; preselect = 'enable'; throttle_time = 80; source_timeout = 200; resolve_timeout = 800; incomplete_delay = 400; max_abbr_width = 100; max_kind_width = 100; max_menu_width = 100; documentation = { border = { '', '' ,'', ' ', '', '', '', ' ' }, -- the border option is the same as `|help nvim_open_win|` winhighlight = "NormalFloat:CompeDocumentation,FloatBorder:CompeDocumentationBorder", max_width = 120, min_width = 60, max_height = math.floor(vim.o.lines * 0.3), min_height = 1, }; source = { path = true; buffer = true; calc = true; nvim_lsp = true; nvim_lua = true; vsnip = true; ultisnips = true; luasnip = true; }; } ]] require("nvim-autopairs.completion.compe").setup({ map_cr = true, -- map <CR> on insert mode map_complete = true -- it will auto insert `(` after select function or method item }) local npairs = require("nvim-autopairs") npairs.setup({ check_ts = true, ts_config = { lua = {'string'},-- it will not add pair on that treesitter node javascript = {'template_string'}, java = false,-- don't check treesitter on java } }) local ts_conds = require('nvim-autopairs.ts-conds') local Rule = require('nvim-autopairs.rule') -- press % => %% is only inside comment or string npairs.add_rules({ Rule("%", "%", "lua") :with_pair(ts_conds.is_ts_node({'string','comment'})), Rule("$", "$", "lua") :with_pair(ts_conds.is_not_ts_node({'function'})) }) require'lualine'.setup { options = { theme = 'onedark', section_separators = '', component_separators = '' } }
-- Author: nakinor -- Created: 2011-12-14 -- Revised: 2016-03-19 -- 月齢を計算して求めるプログラム -- 数字をキーに出来ない? a_table = {Jan = 0, Feb = 2, Mar = 0, Apr = 2, May = 2, Jun = 4, Jul = 5, Aug = 6, Sep = 7, Oct = 8, Nov = 9, Dec = 10} a = ((os.date("%Y") - 11) % 19) * 11 b = a_table[os.date("%b")] c = os.date("%d") getsurei = math.floor((a + b + c) % 30) -- Vim script に似てる? print ("今日は" .. os.date("%Y") .. "年" .. assert(tonumber(os.date("%m"))) .. "月" .. assert(tonumber(os.date("%d"))) .. "日です。" .. "月齢は約" .. getsurei .. "日です。")
function __shared__parse_data_action(data_action, damage) if type(data_action) == "table" then if type(data_action.action_delivery) == "table" and data_action.action_delivery.target_effects then __shared__parse_data_action_target_effects(data_action.action_delivery.target_effects, damage) else for k1, v1 in pairs(data_action) do if type(v1) == "table" and v1.action_delivery then if type(v1.action_delivery) == "table" and v1.action_delivery.target_effects then __shared__parse_data_action_target_effects(v1.action_delivery.target_effects, damage) else for k2, v2 in pairs(v1.action_delivery) do if type(v2) == "table" and v2.target_effects then __shared__parse_data_action_target_effects(v2.target_effects, damage) end -- if type(v2) == "table" and v2.target_effects end -- for k2, v2 in pairs(v1.action_delivery) end -- if type(v1.action_delivery) == "table" and v1.action_delivery.target_effects end -- if type(v1) == "table" and v1.action_delivery end -- for k1, v1 in pairs(data_action) end -- if type(data_action.action_delivery) == "table" and data_action.action_delivery.target_effects end -- type(data_action) == "table" end function __shared__parse_data_action_target_effects(target_effects, damage) if type(target_effects) == "table" then for k, v in pairs(target_effects) do -- if type(v) == "table" and v.damage then v.damage.amount = (v.damage.amount or 1) / 100 * damage elseif type(v) == "table" and v.action and v.action.action_delivery and v.action.action_delivery.target_effects then __shared__parse_data_action_target_effects(v.action.action_delivery.target_effects, damage) end -- end -- for k, v in pairs(target_effects) end -- type(target_effects) == "table" end
local rndselect = require "lib.randomselect" local dijkstramap = require "lib.dijkstramap" return function(entity) entity.turn = function(self) if math.random() < 0.1 then self:move(rndselect{{-1,0}, {0, 1}, {0, -1}} ) return self end local guys = {} for guy in all(self.game.entities) do if guy ~= self.game.hero and guy ~= self and guy.z == self.z then guys[guy.x..","..guy.y] = guy end end local tx, ty = 0, 0 local num = dijkstramap.get(self.x, self.y) or 100000 local lower = function(x,y) if guys[x..","..y] then return end local t = dijkstramap.get((self.x+x), (self.y+y)) local found = t and t < num if found then num = t end return found end if num then local dir = { x = 0, y = 0 } if lower(-1, 0) then dir.x = -1 dir.y = 0 end if lower(1, 0) then dir.x = 1 dir.y = 0 end if lower(0, -1) then dir.x = 0 dir.y = -1 end if lower(0, 1) then dir.x = 0 dir.y = 1 end tx = dir.x ty = dir.y end self:move(tx, ty) end end
dofile("table_show.lua") dofile("urlcode.lua") local urlparse = require("socket.url") local luasocket = require("socket") -- Used to get sub-second time local http = require("socket.http") JSON = assert(loadfile "JSON.lua")() local item_name_newline = os.getenv("item_name_newline") local item_dir = os.getenv('item_dir') local warc_file_base = os.getenv('warc_file_base') local item_value = nil local item_type = nil local item_name = nil local url_count = 0 local tries = 0 local downloaded = {} local addedtolist = {} local abortgrab = false local ids = {} local discovered_items = {} local last_main_site_time = 0 if not urlparse or not http or not luasocket then io.stdout:write("socket not correctly installed.\n") io.stdout:flush() abortgrab = true end for ignore in io.open("ignore-list", "r"):lines() do downloaded[ignore] = true if string.match(ignore, '^https:') then downloaded[string.gsub(ignore, '^https', 'http', 1)] = true elseif string.match(ignore, '^http:') then downloaded[string.gsub(ignore, '^http:', 'https:', 1)] = true end end read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end -- So prints are not buffered - http://lua.2524044.n2.nabble.com/print-stdout-and-flush-td6406981.html io.stdout:setvbuf("no") p_assert = function(v) if not v then print("Assertion failed - aborting item") print(debug.traceback()) abortgrab = true end end local do_debug = false print_debug = function(a) if do_debug then print(a) end end print_debug("The grab script is running in debug mode. You should not see this in production.") allowed = function(url, parenturl) -- Do not recurse to other item base URLs -- page-less e.g. "type=first_holder" have "force" set on check, so this will not block them local username = string.match(url, "https?://supermariomakerbookmark%.nintendo%.net/profile/([^%?&]+)") if username and not string.match(url, "page=") then p_assert(string.match(username, "^[^/ ]+$")) if not ids[username] then discovered_items["user:" .. username] = true end return false end local course_name = string.match(url, "https?://supermariomakerbookmark%.nintendo%.net/courses/([A-F0-9][A-F0-9][A-F0-9][A-F0-9]%-[A-F0-9][A-F0-9][A-F0-9][A-F0-9]%-[A-F0-9][A-F0-9][A-F0-9][A-F0-9]%-[A-F0-9][A-F0-9][A-F0-9][A-F0-9])") if course_name then if not ids[course_name] then discovered_items["course:" .. course_name] = true end return false end -- Only get course images on course pages, and profile images on profile pages if string.match(url, "^https?://dypqnhofrd2x2%.cloudfront%.net/.*jpg$") then -- Course images p_assert(parenturl) if string.match(parenturl, "^https?://supermariomakerbookmark%.nintendo%.net/profile/") then print_debug("Rejecting " .. url .. " because it came from a profile page") return false end elseif string.match(url, "^https?://mii%-secure%.cdn%.nintendo%.net/.*png$") then -- Profile images p_assert(parenturl) if not string.match(parenturl, "^https?://mii%-secure%.cdn%.nintendo%.net/.*png$") then print_debug("Rejecting " .. url .. " because it did not come from another image.") return false end end -- General restrictions if string.match(url, "^https?://supermariomakerbookmark%.nintendo%.net/[^/]*$") or string.match(url, "^https?://www%.googletagmanager%.com") or string.match(url, "^https?://supermariomakerbookmark%.nintendo%.net/users/") -- Auth or string.match(url, "^https?://supermariomakerbookmark%.nintendo%.net/assets/") -- Static or string.match(url, "^https?://www%.esrb%.org/") or string.match(url, "^https?://www.w3.org") or string.match(url, "^https?://w3.org") then return false end -- b64 that gets picked up somewhere if string.match(url, "==$") then return false end local tested = {} for s in string.gmatch(url, "([^/]+)") do if tested[s] == nil then tested[s] = 0 end if tested[s] == 6 then return false end tested[s] = tested[s] + 1 end return true end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] if downloaded[url] == true or addedtolist[url] == true then return false end if allowed(url, parent["url"]) then addedtolist[url] = true print_debug("Derived " .. url .. " from " .. parent["url"] .. " in dcp") return true end return false end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil downloaded[url] = true local function check(urla, force) p_assert((not force) or (force == true)) -- Don't accidentally put something else for force local origurl = url local url = string.match(urla, "^([^#]+)") local url_ = string.match(url, "^(.-)%.?$") url_ = string.gsub(url_, "&amp;", "&") url_ = string.match(url_, "^(.-)%s*$") url_ = string.match(url_, "^(.-)%??$") url_ = string.match(url_, "^(.-)&?$") url_ = string.match(url_, "^(.-)/?$") if (downloaded[url_] ~= true and addedtolist[url_] ~= true) and (allowed(url_, origurl) or force) then table.insert(urls, { url=url_ }) addedtolist[url_] = true addedtolist[url] = true end end local function checknewurl(newurl) if string.match(newurl, "\\[uU]002[fF]") then return checknewurl(string.gsub(newurl, "\\[uU]002[fF]", "/")) end if string.match(newurl, "^https?:////") then check(string.gsub(newurl, ":////", "://")) elseif string.match(newurl, "^https?://") then check(newurl) elseif string.match(newurl, "^https?:\\/\\?/") then check(string.gsub(newurl, "\\", "")) elseif string.match(newurl, "^\\/") then checknewurl(string.gsub(newurl, "\\", "")) elseif string.match(newurl, "^//") then check(urlparse.absolute(url, newurl)) elseif string.match(newurl, "^/") then check(urlparse.absolute(url, newurl)) elseif string.match(newurl, "^%.%./") then if string.match(url, "^https?://[^/]+/[^/]+/") then check(urlparse.absolute(url, newurl)) else checknewurl(string.match(newurl, "^%.%.(/.+)$")) end elseif string.match(newurl, "^%./") then check(urlparse.absolute(url, newurl)) end end local function checknewshorturl(newurl) if string.match(newurl, "^%?") then check(urlparse.absolute(url, newurl)) elseif not (string.match(newurl, "^https?:\\?/\\?//?/?") or string.match(newurl, "^[/\\]") or string.match(newurl, "^%./") or string.match(newurl, "^[jJ]ava[sS]cript:") or string.match(newurl, "^[mM]ail[tT]o:") or string.match(newurl, "^vine:") or string.match(newurl, "^android%-app:") or string.match(newurl, "^ios%-app:") or string.match(newurl, "^%${")) then check(urlparse.absolute(url, newurl)) end end local function load_html() if html == nil then html = read_file(file) end end if string.match(url, "https?://supermariomakerbookmark%.nintendo%.net/profile/[^/%?]+$") and status_code == 200 then check(url .. "?type=posted", true) check(url .. "?type=liked", true) check(url .. "?type=fastest_holder", true) check(url .. "?type=first_holder", true) load_html() p_assert(string.match(html, "Play History")) profile_image = string.match(html, '<img class="mii" src="(https?://mii%-secure%.cdn%.nintendo%.net/[^"]*png)" alt="[^>]+" />') p_assert(profile_image) check(profile_image, true) end if string.match(url, "https?://supermariomakerbookmark%.nintendo%.net/course/") and status_code == 200 then load_html() p_assert(string.match(html, "Course Tag")) end -- Queue alternate profile picture types if string.match(url, "https?://mii%-secure%.cdn%.nintendo%.net/.*png$") then p_assert(string.match(url, "normal_face%.png$") or string.match(url, "like_face%.png$")) check((string.gsub(url, "normal_face%.png$", "like_face%.png"))) check((string.gsub(url, "like_face%.png$", "normal_face%.png"))) print_debug("Queuing alternate face from " .. url) end if status_code == 200 and not (string.match(url, "jpe?g$") or string.match(url, "png$")) then load_html() html = string.gsub(html, '<div class="course%-title">.-</div>', '') -- Strip out these, no real URLS and have punctuation for newurl in string.gmatch(string.gsub(html, "&quot;", '"'), '([^"]+)') do checknewurl(newurl) end for newurl in string.gmatch(string.gsub(html, "&#039;", "'"), "([^']+)") do checknewurl(newurl) end for newurl in string.gmatch(html, ">%s*([^<%s]+)") do checknewurl(newurl) end for newurl in string.gmatch(html, "[^%-]href='([^']+)'") do checknewshorturl(newurl) end for newurl in string.gmatch(html, '[^%-]href="([^"]+)"') do checknewshorturl(newurl) end for newurl in string.gmatch(html, ":%s*url%(([^%)]+)%)") do checknewurl(newurl) end end for _, urll in pairs(urls) do print_debug("Derived " .. urll.url .. " from " .. url .. " in gu") end return urls end set_new_item = function(url) local match = string.match(url, "^https?://supermariomakerbookmark%.nintendo%.net/profile/([^%?&]+)") local type_ = "user" if not match then match = string.match(url, "^https?://supermariomakerbookmark%.nintendo%.net/courses/([a-fA-F0-9%-]+)") type_ = "course" end if match and not ids[match] then --abortgrab = false ids[match] = true item_value = match item_type = type_ item_name = type_ .. ":" .. match io.stdout:write("Archiving item " .. item_name .. ".\n") io.stdout:flush() end end wget.callbacks.httploop_result = function(url, err, http_stat) status_code = http_stat["statcode"] set_new_item(url["url"]) url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. " \n") io.stdout:flush() if status_code >= 300 and status_code <= 399 then local newloc = urlparse.absolute(url["url"], http_stat["newloc"]) if downloaded[newloc] == true or addedtolist[newloc] == true or not allowed(newloc, url["url"]) then tries = 0 return wget.actions.EXIT end end if status_code >= 200 and status_code <= 399 then downloaded[url["url"]] = true end if abortgrab == true then io.stdout:write("ABORTING...\n") io.stdout:flush() return wget.actions.ABORT end if status_code == 403 and (string.match(url["url"], "^https?://supermariomakerbookmark%.nintendo%.net/")) then print("You have been banned from the Super Mario Maker website. Switch your worker to another project, and wait a few hours to be unbanned.") print("This should not happen if you are running one concurrency per IP address. If it does, tell OrIdow6 in the project channel.") os.execute("sleep " .. 60) -- Do not spam the tracker (or the site) return wget.actions.ABORT end -- if string.match(url["url"], "^https?://supermariomakerbookmark%.nintendo%.net") then -- Sleep for up to 2s average local now_t = luasocket.gettime() local makeup_time = 4 - (now_t - last_main_site_time) if makeup_time > 0 then print_debug("Sleeping for main site " .. makeup_time) os.execute("sleep " .. makeup_time) end last_main_site_time = now_t end -- local do_retry = false local maxtries = 12 local url_is_essential = false if status_code == 0 or (status_code >= 400 and status_code ~= 404) then io.stdout:write("Server returned " .. http_stat.statcode .. " (" .. err .. "). Sleeping.\n") io.stdout:flush() do_retry = true end --url_is_essential = string.match(url, "https?://supermariomakerbookmark%.nintendo%.net/profile/[^\?]+$") -- or string.match(url, "https?://supermariomakerbookmark%.nintendo%.net/courses/") url_is_essential = true -- For now, all URLS, including CDN urls, are considered such if do_retry then if tries >= maxtries then io.stdout:write("I give up...\n") io.stdout:flush() tries = 0 if not url_is_essential then return wget.actions.EXIT else print("Failed on an essential URL, aborting...") return wget.actions.ABORT end else sleep_time = math.floor(math.pow(2, tries)) tries = tries + 1 end end if do_retry and sleep_time > 0.001 then print("Sleeping " .. sleep_time .. "s") os.execute("sleep " .. sleep_time) return wget.actions.CONTINUE end tries = 0 return wget.actions.NOTHING end wget.callbacks.finish = function(start_time, end_time, wall_time, numurls, total_downloaded_bytes, total_download_time) if do_debug then for item, _ in pairs(discovered_items) do print("Would have sent discovered item " .. item) end else to_send = nil for item, _ in pairs(discovered_items) do print("Queueing item " .. item) if to_send == nil then to_send = item else to_send = to_send .. "\0" .. item end end if to_send then local tries = 0 while tries < 10 do local body, code, headers, status = http.request( "http://blackbird-amqp.meo.ws:23038/super-mario-maker-bookmarks-7woqbx2mlw8e69v/", to_send ) if code == 200 or code == 409 then break end os.execute("sleep " .. math.floor(math.pow(2, tries))) tries = tries + 1 end if tries == 10 then abortgrab = true end end end end wget.callbacks.before_exit = function(exit_status, exit_status_string) if abortgrab == true then return wget.exits.IO_FAIL end return exit_status end
local Map = class() local instance local config_map = config('map') function Map:constructor() self.tiles = config('core.tiles') -- self.items = config('core.items') -- self.buildings = config('core.buildings') self:init() end ------------------------- -- STATIC METHODS -- ------------------------- function Map.getInstance() if not instance then instance = Game.new() end return instance end ------------------------- -- METHODS -- ------------------------- function Map:init() self:initTiles() end function Map:initTiles() local tiles = self.tiles for y = 0, self.ysize - 1 do for x = 0, self.xsize - 1 do local tile = app('map.tile').new(x, y) table.insert2D(tiles, x, y, tile) end end end function Map:getTile(x, y) return self.tiles[x][y] end function Map:getTileAt(x, y) return self:getTile(x, y) end function Map:addItem(...) return app('item.item').new(...) end function Map:getBuildings() return self.buildings end function Map:getBuilding(a, b) local building_id, x, y if not b then building_id = a else x, y = a, b end if building_id then for _, building in pairs(self.buildings) do if building.id == building_id then return building end end elseif x and y then for _, building in pairs(self.buildings) do if building.tilex == x and building.tiley == y then return building end end end end function Map:addBuilding(...) local args = {...} local x, y = args[2], args[3] if self:getBuilding(x, y) then return false end local building = app('object.building').new(...) table.insert(self.buildings, building) return building end function Map:removeBuilding(a, b) local building_id, x, y if not b then building_id = a else x, y = a, b end local building if building_id then building = self:getBuilding(building_id) elseif x and y then building = self:getBuilding(x, y) end if not building then return false end building:remove() table.removeValue(self.buildings, building) return true end ------------------------- -- GETTERS -- ------------------------- function Map:getNameAttribute() return map('name') end function Map:getXsizeAttribute() return map('xsize') end function Map:getYsizeAttribute() return map('ysize') end function Map:getTilesetAttribute() return map('tileset') end function Map:getTilecountAttribute() return map('tilecount') end function Map:getBackImgAttribute() return map('back_img') end function Map:getBackScrollxAttribute() return map('back_scrollx') end function Map:getBackScrollyAttribute() return map('back_scrolly') end function Map:getBackScrolltileAttribute() return map('back_scrolltile') end function Map:getBackRAttribute() return map('back_r') end function Map:getBackGAttribute() return map('back_g') end function Map:getBackBAttribute() return map('back_b') end function Map:getStormXAttribute() return map('storm_x') end function Map:getStormYAttribute() return map('storm_y') end function Map:getMissionVipsAttribute() return map('mission_vips') end function Map:getMissionHostagesAttribute() return map('mission_hostages') end function Map:getMissionBombspotsAttribute() return map('mission_bombspots') end function Map:getMissionCtfflagsAttribute() return map('mission_ctfflags') end function Map:getMissionDompointsAttribute() return map('mission_dompoints') end function Map:getNobuyingAttribute() return map('nobuying') end function Map:getNoweaponsAttribute() return map('noweapons') end function Map:getTeleportersAttribute() return map('teleporters') end function Map:getBotnodesAttribute() return map('botnodes') end ------------------------- -- INIT -- ------------------------- return Map
local OVALE, Ovale = ... local OvaleScripts = Ovale.OvaleScripts do local name = "icyveins_priest_discipline" local desc = "[7.1.5] Icy-Veins: Priest Discipline" local code = [[ Include(ovale_common) Include(ovale_trinkets_mop) Include(ovale_trinkets_wod) Include(ovale_priest_spells) AddFunction DisciplineDefaultHealActions { Spell(power_word_shield) if SpellCount(plea) < 6 Spell(plea) Spell(shadow_mend) } AddFunction DisciplineDefaultMainActions { if (target.DebuffExpires(schism_debuff)) { if not Talent(purge_the_wicked_talent) and target.DebuffRefreshable(shadow_word_pain_debuff) and target.TimeToDie() > target.DebuffRemaining(shadow_word_pain_debuff) Spell(shadow_word_pain) if Talent(purge_the_wicked_talent) and target.DebuffRefreshable(purge_the_wicked_debuff) and target.TimeToDie() > target.DebuffRemaining(purge_the_wicked_debuff) Spell(purge_the_wicked) } if target.TimeToDie() >= 6 Spell(schism) if (not Talent(schism_talent) or not target.DebuffExpires(schism_debuff)) Spell(penance) if (not Talent(schism_talent) or not target.DebuffExpires(schism_debuff)) Spell(power_word_solace) if target.Distance() <= 30 Spell(divine_star) Spell(smite) } AddFunction DisciplineDefaultCdActions { if (not Talent(schism_talent) or not target.DebuffExpires(schism_debuff)) Spell(lights_wrath) if Talent(mindbender_talent) Spell(mindbender) Spell(power_infusion) Item(Trinket0Slot usable=1 text=13) Item(Trinket1Slot usable=1 text=14) Spell(shadowfiend) Spell(rapture) } AddIcon help=mainheal specialization=discipline { DisciplineDefaultHealActions() } AddIcon enemies=1 help=main specialization=discipline { DisciplineDefaultMainActions() } AddIcon help=cd specialization=discipline { DisciplineDefaultCdActions() } ]] OvaleScripts:RegisterScript("PRIEST", "discipline", name, desc, code, "script") end -- THE REST OF THIS FILE IS AUTOMATICALLY GENERATED. -- ANY CHANGES MADE BELOW THIS POINT WILL BE LOST. do local name = "simulationcraft_priest_shadow_t19p" local desc = "[7.0] SimulationCraft: Priest_Shadow_T19P" local code = [[ # Based on SimulationCraft profile "Priest_Shadow_T19P". # class=priest # spec=shadow # talents=1211231 Include(ovale_common) Include(ovale_trinkets_mop) Include(ovale_trinkets_wod) Include(ovale_priest_spells) AddFunction s2mcheck_value { 0.8 * { 83 + { 20 + 20 * TalentPoints(fortress_of_the_mind_talent) } * ArmorSetBonus(T20 4) - 5 * TalentPoints(sanlayn_talent) + { 33 - 13 * ArmorSetBonus(T20 4) } * TalentPoints(reaper_of_souls_talent) + ArmorSetBonus(T19 2) * 4 + 8 * HasEquippedItem(mangazas_madness) + SpellHaste() * 10 * { 1 + 0.7 * ArmorSetBonus(T20 4) } * { 2 + 0.8 * ArmorSetBonus(T19 2) + 1 * TalentPoints(reaper_of_souls_talent) + 2 * ArtifactTraitRank(mass_hysteria) - 1 * TalentPoints(sanlayn_talent) } } - actors_fight_time_mod() * 0 } AddFunction s2mcheck { if s2mcheck_value() > s2mcheck_min() s2mcheck_value() s2mcheck_min() } AddFunction actors_fight_time_mod { if TimeInCombat() + target.TimeToDie() <= 450 { 450 - { TimeInCombat() + target.TimeToDie() } } / 5 if TimeInCombat() + target.TimeToDie() > 450 and TimeInCombat() + target.TimeToDie() < 600 -{ { -450 + TimeInCombat() + target.TimeToDie() } / 10 } 0 } AddFunction s2mcheck_min { 180 } AddCheckBox(opt_interrupt L(interrupt) default specialization=shadow) AddCheckBox(opt_use_consumables L(opt_use_consumables) default specialization=shadow) AddFunction ShadowInterruptActions { if CheckBoxOn(opt_interrupt) and not target.IsFriend() and target.Casting() { if target.InRange(silence) and target.IsInterruptible() Spell(silence) if target.InRange(mind_bomb) and not target.Classification(worldboss) and target.RemainingCastTime() > 2 Spell(mind_bomb) if target.Distance(less 8) and target.IsInterruptible() Spell(arcane_torrent_mana) if target.InRange(quaking_palm) and not target.Classification(worldboss) Spell(quaking_palm) if target.Distance(less 5) and not target.Classification(worldboss) Spell(war_stomp) } } AddFunction ShadowUseItemActions { Item(Trinket0Slot text=13 usable=1) Item(Trinket1Slot text=14 usable=1) } ### actions.default AddFunction ShadowDefaultMainActions { #call_action_list,name=check,if=talent.surrender_to_madness.enabled&!buff.surrender_to_madness.up if Talent(surrender_to_madness_talent) and not BuffPresent(surrender_to_madness_buff) ShadowCheckMainActions() unless Talent(surrender_to_madness_talent) and not BuffPresent(surrender_to_madness_buff) and ShadowCheckMainPostConditions() { #run_action_list,name=s2m,if=buff.voidform.up&buff.surrender_to_madness.up if BuffPresent(voidform_buff) and BuffPresent(surrender_to_madness_buff) ShadowS2mMainActions() unless BuffPresent(voidform_buff) and BuffPresent(surrender_to_madness_buff) and ShadowS2mMainPostConditions() { #run_action_list,name=vf,if=buff.voidform.up if BuffPresent(voidform_buff) ShadowVfMainActions() unless BuffPresent(voidform_buff) and ShadowVfMainPostConditions() { #run_action_list,name=main ShadowMainMainActions() } } } } AddFunction ShadowDefaultMainPostConditions { Talent(surrender_to_madness_talent) and not BuffPresent(surrender_to_madness_buff) and ShadowCheckMainPostConditions() or BuffPresent(voidform_buff) and BuffPresent(surrender_to_madness_buff) and ShadowS2mMainPostConditions() or BuffPresent(voidform_buff) and ShadowVfMainPostConditions() or ShadowMainMainPostConditions() } AddFunction ShadowDefaultShortCdActions { #call_action_list,name=check,if=talent.surrender_to_madness.enabled&!buff.surrender_to_madness.up if Talent(surrender_to_madness_talent) and not BuffPresent(surrender_to_madness_buff) ShadowCheckShortCdActions() unless Talent(surrender_to_madness_talent) and not BuffPresent(surrender_to_madness_buff) and ShadowCheckShortCdPostConditions() { #run_action_list,name=s2m,if=buff.voidform.up&buff.surrender_to_madness.up if BuffPresent(voidform_buff) and BuffPresent(surrender_to_madness_buff) ShadowS2mShortCdActions() unless BuffPresent(voidform_buff) and BuffPresent(surrender_to_madness_buff) and ShadowS2mShortCdPostConditions() { #run_action_list,name=vf,if=buff.voidform.up if BuffPresent(voidform_buff) ShadowVfShortCdActions() unless BuffPresent(voidform_buff) and ShadowVfShortCdPostConditions() { #run_action_list,name=main ShadowMainShortCdActions() } } } } AddFunction ShadowDefaultShortCdPostConditions { Talent(surrender_to_madness_talent) and not BuffPresent(surrender_to_madness_buff) and ShadowCheckShortCdPostConditions() or BuffPresent(voidform_buff) and BuffPresent(surrender_to_madness_buff) and ShadowS2mShortCdPostConditions() or BuffPresent(voidform_buff) and ShadowVfShortCdPostConditions() or ShadowMainShortCdPostConditions() } AddFunction ShadowDefaultCdActions { #silence ShadowInterruptActions() #use_items,if=buff.voidform.up if BuffPresent(voidform_buff) ShadowUseItemActions() #potion,name=prolonged_power,if=buff.bloodlust.react|target.time_to_die<=80|(target.health.pct<35&cooldown.power_infusion.remains<30) if { BuffPresent(burst_haste_buff any=1) or target.TimeToDie() <= 80 or target.HealthPercent() < 35 and SpellCooldown(power_infusion) < 30 } and CheckBoxOn(opt_use_consumables) and target.Classification(worldboss) Item(prolonged_power_potion usable=1) #call_action_list,name=check,if=talent.surrender_to_madness.enabled&!buff.surrender_to_madness.up if Talent(surrender_to_madness_talent) and not BuffPresent(surrender_to_madness_buff) ShadowCheckCdActions() unless Talent(surrender_to_madness_talent) and not BuffPresent(surrender_to_madness_buff) and ShadowCheckCdPostConditions() { #run_action_list,name=s2m,if=buff.voidform.up&buff.surrender_to_madness.up if BuffPresent(voidform_buff) and BuffPresent(surrender_to_madness_buff) ShadowS2mCdActions() unless BuffPresent(voidform_buff) and BuffPresent(surrender_to_madness_buff) and ShadowS2mCdPostConditions() { #run_action_list,name=vf,if=buff.voidform.up if BuffPresent(voidform_buff) ShadowVfCdActions() unless BuffPresent(voidform_buff) and ShadowVfCdPostConditions() { #run_action_list,name=main ShadowMainCdActions() } } } } AddFunction ShadowDefaultCdPostConditions { Talent(surrender_to_madness_talent) and not BuffPresent(surrender_to_madness_buff) and ShadowCheckCdPostConditions() or BuffPresent(voidform_buff) and BuffPresent(surrender_to_madness_buff) and ShadowS2mCdPostConditions() or BuffPresent(voidform_buff) and ShadowVfCdPostConditions() or ShadowMainCdPostConditions() } ### actions.check AddFunction ShadowCheckMainActions { } AddFunction ShadowCheckMainPostConditions { } AddFunction ShadowCheckShortCdActions { } AddFunction ShadowCheckShortCdPostConditions { } AddFunction ShadowCheckCdActions { } AddFunction ShadowCheckCdPostConditions { } ### actions.main AddFunction ShadowMainMainActions { #shadow_word_pain,if=talent.misery.enabled&dot.shadow_word_pain.remains<gcd.max,moving=1,cycle_targets=1 if Speed() > 0 and Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < GCD() Spell(shadow_word_pain) #vampiric_touch,if=talent.misery.enabled&(dot.vampiric_touch.remains<3*gcd.max|dot.shadow_word_pain.remains<3*gcd.max),cycle_targets=1 if Talent(misery_talent) and { target.DebuffRemaining(vampiric_touch_debuff) < 3 * GCD() or target.DebuffRemaining(shadow_word_pain_debuff) < 3 * GCD() } Spell(vampiric_touch) #shadow_word_pain,if=!talent.misery.enabled&dot.shadow_word_pain.remains<(3+(4%3))*gcd if not Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < { 3 + 4 / 3 } * GCD() Spell(shadow_word_pain) #vampiric_touch,if=!talent.misery.enabled&dot.vampiric_touch.remains<(4+(4%3))*gcd if not Talent(misery_talent) and target.DebuffRemaining(vampiric_touch_debuff) < { 4 + 4 / 3 } * GCD() Spell(vampiric_touch) #void_eruption Spell(void_eruption) #shadow_word_death,if=(active_enemies<=4|(talent.reaper_of_souls.enabled&active_enemies<=2))&cooldown.shadow_word_death.charges=2&insanity<=(85-15*talent.reaper_of_souls.enabled) if { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and SpellCharges(shadow_word_death) == 2 and Insanity() <= 85 - 15 * TalentPoints(reaper_of_souls_talent) Spell(shadow_word_death) #mind_blast,if=active_enemies<=4&talent.legacy_of_the_void.enabled&(insanity<=81|(insanity<=75.2&talent.fortress_of_the_mind.enabled)) if Enemies() <= 4 and Talent(legacy_of_the_void_talent) and { Insanity() <= 81 or Insanity() <= 75.2 and Talent(fortress_of_the_mind_talent) } Spell(mind_blast) #mind_blast,if=active_enemies<=4&!talent.legacy_of_the_void.enabled|(insanity<=96|(insanity<=95.2&talent.fortress_of_the_mind.enabled)) if Enemies() <= 4 and not Talent(legacy_of_the_void_talent) or Insanity() <= 96 or Insanity() <= 95.2 and Talent(fortress_of_the_mind_talent) Spell(mind_blast) #shadow_word_pain,if=!talent.misery.enabled&!ticking&target.time_to_die>10&(active_enemies<5&(talent.auspicious_spirits.enabled|talent.shadowy_insight.enabled)),cycle_targets=1 if not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and target.TimeToDie() > 10 and Enemies() < 5 and { Talent(auspicious_spirits_talent) or Talent(shadowy_insight_talent) } Spell(shadow_word_pain) #vampiric_touch,if=active_enemies>1&!talent.misery.enabled&!ticking&(85.2*(1+0.2+stat.mastery_rating%16000)*(1+0.2*talent.sanlayn.enabled)*0.5*target.time_to_die%(gcd.max*(138+80*(active_enemies-1))))>1,cycle_targets=1 if Enemies() > 1 and not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and 85.2 * { 1 + 0.2 + MasteryRating() / 16000 } * { 1 + 0.2 * TalentPoints(sanlayn_talent) } * 0.5 * target.TimeToDie() / { GCD() * { 138 + 80 * { Enemies() - 1 } } } > 1 Spell(vampiric_touch) #shadow_word_pain,if=active_enemies>1&!talent.misery.enabled&!ticking&(47.12*(1+0.2+stat.mastery_rating%16000)*0.75*target.time_to_die%(gcd.max*(138+80*(active_enemies-1))))>1,cycle_targets=1 if Enemies() > 1 and not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and 47.12 * { 1 + 0.2 + MasteryRating() / 16000 } * 0.75 * target.TimeToDie() / { GCD() * { 138 + 80 * { Enemies() - 1 } } } > 1 Spell(shadow_word_pain) #shadow_word_void,if=talent.shadow_word_void.enabled&(insanity<=75-10*talent.legacy_of_the_void.enabled) if Talent(shadow_word_void_talent) and Insanity() <= 75 - 10 * TalentPoints(legacy_of_the_void_talent) Spell(shadow_word_void) #mind_flay,interrupt=1,chain=1 Spell(mind_flay) #shadow_word_pain Spell(shadow_word_pain) } AddFunction ShadowMainMainPostConditions { } AddFunction ShadowMainShortCdActions { unless Speed() > 0 and Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < GCD() and Spell(shadow_word_pain) or Talent(misery_talent) and { target.DebuffRemaining(vampiric_touch_debuff) < 3 * GCD() or target.DebuffRemaining(shadow_word_pain_debuff) < 3 * GCD() } and Spell(vampiric_touch) or not Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < { 3 + 4 / 3 } * GCD() and Spell(shadow_word_pain) or not Talent(misery_talent) and target.DebuffRemaining(vampiric_touch_debuff) < { 4 + 4 / 3 } * GCD() and Spell(vampiric_touch) or Spell(void_eruption) { #shadow_crash,if=talent.shadow_crash.enabled if Talent(shadow_crash_talent) Spell(shadow_crash) } } AddFunction ShadowMainShortCdPostConditions { Speed() > 0 and Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < GCD() and Spell(shadow_word_pain) or Talent(misery_talent) and { target.DebuffRemaining(vampiric_touch_debuff) < 3 * GCD() or target.DebuffRemaining(shadow_word_pain_debuff) < 3 * GCD() } and Spell(vampiric_touch) or not Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < { 3 + 4 / 3 } * GCD() and Spell(shadow_word_pain) or not Talent(misery_talent) and target.DebuffRemaining(vampiric_touch_debuff) < { 4 + 4 / 3 } * GCD() and Spell(vampiric_touch) or Spell(void_eruption) or { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and SpellCharges(shadow_word_death) == 2 and Insanity() <= 85 - 15 * TalentPoints(reaper_of_souls_talent) and Spell(shadow_word_death) or Enemies() <= 4 and Talent(legacy_of_the_void_talent) and { Insanity() <= 81 or Insanity() <= 75.2 and Talent(fortress_of_the_mind_talent) } and Spell(mind_blast) or { Enemies() <= 4 and not Talent(legacy_of_the_void_talent) or Insanity() <= 96 or Insanity() <= 95.2 and Talent(fortress_of_the_mind_talent) } and Spell(mind_blast) or not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and target.TimeToDie() > 10 and Enemies() < 5 and { Talent(auspicious_spirits_talent) or Talent(shadowy_insight_talent) } and Spell(shadow_word_pain) or Enemies() > 1 and not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and 85.2 * { 1 + 0.2 + MasteryRating() / 16000 } * { 1 + 0.2 * TalentPoints(sanlayn_talent) } * 0.5 * target.TimeToDie() / { GCD() * { 138 + 80 * { Enemies() - 1 } } } > 1 and Spell(vampiric_touch) or Enemies() > 1 and not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and 47.12 * { 1 + 0.2 + MasteryRating() / 16000 } * 0.75 * target.TimeToDie() / { GCD() * { 138 + 80 * { Enemies() - 1 } } } > 1 and Spell(shadow_word_pain) or Talent(shadow_word_void_talent) and Insanity() <= 75 - 10 * TalentPoints(legacy_of_the_void_talent) and Spell(shadow_word_void) or Spell(mind_flay) or Spell(shadow_word_pain) } AddFunction ShadowMainCdActions { #surrender_to_madness,if=talent.surrender_to_madness.enabled&target.time_to_die<=variable.s2mcheck if Talent(surrender_to_madness_talent) and target.TimeToDie() <= s2mcheck() Spell(surrender_to_madness) } AddFunction ShadowMainCdPostConditions { Speed() > 0 and Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < GCD() and Spell(shadow_word_pain) or Talent(misery_talent) and { target.DebuffRemaining(vampiric_touch_debuff) < 3 * GCD() or target.DebuffRemaining(shadow_word_pain_debuff) < 3 * GCD() } and Spell(vampiric_touch) or not Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < { 3 + 4 / 3 } * GCD() and Spell(shadow_word_pain) or not Talent(misery_talent) and target.DebuffRemaining(vampiric_touch_debuff) < { 4 + 4 / 3 } * GCD() and Spell(vampiric_touch) or Spell(void_eruption) or Talent(shadow_crash_talent) and Spell(shadow_crash) or { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and SpellCharges(shadow_word_death) == 2 and Insanity() <= 85 - 15 * TalentPoints(reaper_of_souls_talent) and Spell(shadow_word_death) or Enemies() <= 4 and Talent(legacy_of_the_void_talent) and { Insanity() <= 81 or Insanity() <= 75.2 and Talent(fortress_of_the_mind_talent) } and Spell(mind_blast) or { Enemies() <= 4 and not Talent(legacy_of_the_void_talent) or Insanity() <= 96 or Insanity() <= 95.2 and Talent(fortress_of_the_mind_talent) } and Spell(mind_blast) or not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and target.TimeToDie() > 10 and Enemies() < 5 and { Talent(auspicious_spirits_talent) or Talent(shadowy_insight_talent) } and Spell(shadow_word_pain) or Enemies() > 1 and not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and 85.2 * { 1 + 0.2 + MasteryRating() / 16000 } * { 1 + 0.2 * TalentPoints(sanlayn_talent) } * 0.5 * target.TimeToDie() / { GCD() * { 138 + 80 * { Enemies() - 1 } } } > 1 and Spell(vampiric_touch) or Enemies() > 1 and not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and 47.12 * { 1 + 0.2 + MasteryRating() / 16000 } * 0.75 * target.TimeToDie() / { GCD() * { 138 + 80 * { Enemies() - 1 } } } > 1 and Spell(shadow_word_pain) or Talent(shadow_word_void_talent) and Insanity() <= 75 - 10 * TalentPoints(legacy_of_the_void_talent) and Spell(shadow_word_void) or Spell(mind_flay) or Spell(shadow_word_pain) } ### actions.precombat AddFunction ShadowPrecombatMainActions { #shadowform,if=!buff.shadowform.up if not BuffPresent(shadowform_buff) Spell(shadowform) #mind_blast Spell(mind_blast) } AddFunction ShadowPrecombatMainPostConditions { } AddFunction ShadowPrecombatShortCdActions { } AddFunction ShadowPrecombatShortCdPostConditions { not BuffPresent(shadowform_buff) and Spell(shadowform) or Spell(mind_blast) } AddFunction ShadowPrecombatCdActions { #flask,type=flask_of_the_whispered_pact #food,type=azshari_salad #augmentation,type=defiled #snapshot_stats #potion,name=prolonged_power if CheckBoxOn(opt_use_consumables) and target.Classification(worldboss) Item(prolonged_power_potion usable=1) } AddFunction ShadowPrecombatCdPostConditions { not BuffPresent(shadowform_buff) and Spell(shadowform) or Spell(mind_blast) } ### actions.s2m AddFunction ShadowS2mMainActions { #void_bolt,if=buff.insanity_drain_stacks.value<6&set_bonus.tier19_4pc if BuffAmount(insanity_drain_stacks_buff) < 6 and ArmorSetBonus(T19 4) Spell(void_bolt) #mindbender,if=cooldown.shadow_word_death.charges=0&buff.voidform.stack>(45+25*set_bonus.tier20_4pc) if SpellCharges(shadow_word_death) == 0 and BuffStacks(voidform_buff) > 45 + 25 * ArmorSetBonus(T20 4) Spell(mindbender) #void_torrent,if=dot.shadow_word_pain.remains>5.5&dot.vampiric_touch.remains>5.5&!buff.power_infusion.up|buff.voidform.stack<5 if target.DebuffRemaining(shadow_word_pain_debuff) > 5.5 and target.DebuffRemaining(vampiric_touch_debuff) > 5.5 and not BuffPresent(power_infusion_buff) or BuffStacks(voidform_buff) < 5 Spell(void_torrent) #shadow_word_death,if=current_insanity_drain*gcd.max>insanity&(insanity-(current_insanity_drain*gcd.max)+(30+30*talent.reaper_of_souls.enabled)<100) if CurrentInsanityDrain() * GCD() > Insanity() and Insanity() - CurrentInsanityDrain() * GCD() + 30 + 30 * TalentPoints(reaper_of_souls_talent) < 100 Spell(shadow_word_death) #void_bolt Spell(void_bolt) #shadow_word_death,if=(active_enemies<=4|(talent.reaper_of_souls.enabled&active_enemies<=2))&current_insanity_drain*gcd.max>insanity&(insanity-(current_insanity_drain*gcd.max)+(30+30*talent.reaper_of_souls.enabled))<100 if { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and CurrentInsanityDrain() * GCD() > Insanity() and Insanity() - CurrentInsanityDrain() * GCD() + 30 + 30 * TalentPoints(reaper_of_souls_talent) < 100 Spell(shadow_word_death) #wait,sec=action.void_bolt.usable_in,if=action.void_bolt.usable_in<gcd.max*0.28 unless SpellCooldown(void_bolt) < GCD() * 0.28 and SpellCooldown(void_bolt) > 0 { #mind_blast,if=active_enemies<=5 if Enemies() <= 5 Spell(mind_blast) #wait,sec=action.mind_blast.usable_in,if=action.mind_blast.usable_in<gcd.max*0.28&active_enemies<=5 unless SpellCooldown(mind_blast) < GCD() * 0.28 and Enemies() <= 5 and SpellCooldown(mind_blast) > 0 { #shadow_word_death,if=(active_enemies<=4|(talent.reaper_of_souls.enabled&active_enemies<=2))&cooldown.shadow_word_death.charges=2 if { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and SpellCharges(shadow_word_death) == 2 Spell(shadow_word_death) #shadowfiend,if=!talent.mindbender.enabled&buff.voidform.stack>15 if not Talent(mindbender_talent) and BuffStacks(voidform_buff) > 15 Spell(shadowfiend) #shadow_word_void,if=talent.shadow_word_void.enabled&(insanity-(current_insanity_drain*gcd.max)+50)<100 if Talent(shadow_word_void_talent) and Insanity() - CurrentInsanityDrain() * GCD() + 50 < 100 Spell(shadow_word_void) #shadow_word_pain,if=talent.misery.enabled&dot.shadow_word_pain.remains<gcd,moving=1,cycle_targets=1 if Speed() > 0 and Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < GCD() Spell(shadow_word_pain) #vampiric_touch,if=talent.misery.enabled&(dot.vampiric_touch.remains<3*gcd.max|dot.shadow_word_pain.remains<3*gcd.max),cycle_targets=1 if Talent(misery_talent) and { target.DebuffRemaining(vampiric_touch_debuff) < 3 * GCD() or target.DebuffRemaining(shadow_word_pain_debuff) < 3 * GCD() } Spell(vampiric_touch) #shadow_word_pain,if=!talent.misery.enabled&!ticking&(active_enemies<5|talent.auspicious_spirits.enabled|talent.shadowy_insight.enabled|artifact.sphere_of_insanity.rank) if not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and { Enemies() < 5 or Talent(auspicious_spirits_talent) or Talent(shadowy_insight_talent) or ArtifactTraitRank(sphere_of_insanity) } Spell(shadow_word_pain) #vampiric_touch,if=!talent.misery.enabled&!ticking&(active_enemies<4|talent.sanlayn.enabled|(talent.auspicious_spirits.enabled&artifact.unleash_the_shadows.rank)) if not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and { Enemies() < 4 or Talent(sanlayn_talent) or Talent(auspicious_spirits_talent) and ArtifactTraitRank(unleash_the_shadows) } Spell(vampiric_touch) #shadow_word_pain,if=!talent.misery.enabled&!ticking&target.time_to_die>10&(active_enemies<5&(talent.auspicious_spirits.enabled|talent.shadowy_insight.enabled)),cycle_targets=1 if not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and target.TimeToDie() > 10 and Enemies() < 5 and { Talent(auspicious_spirits_talent) or Talent(shadowy_insight_talent) } Spell(shadow_word_pain) #vampiric_touch,if=!talent.misery.enabled&!ticking&target.time_to_die>10&(active_enemies<4|talent.sanlayn.enabled|(talent.auspicious_spirits.enabled&artifact.unleash_the_shadows.rank)),cycle_targets=1 if not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and target.TimeToDie() > 10 and { Enemies() < 4 or Talent(sanlayn_talent) or Talent(auspicious_spirits_talent) and ArtifactTraitRank(unleash_the_shadows) } Spell(vampiric_touch) #shadow_word_pain,if=!talent.misery.enabled&!ticking&target.time_to_die>10&(active_enemies<5&artifact.sphere_of_insanity.rank),cycle_targets=1 if not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and target.TimeToDie() > 10 and Enemies() < 5 and ArtifactTraitRank(sphere_of_insanity) Spell(shadow_word_pain) #mind_flay,chain=1,interrupt_immediate=1,interrupt_if=ticks>=2&(action.void_bolt.usable|(current_insanity_drain*gcd.max>insanity&(insanity-(current_insanity_drain*gcd.max)+60)<100&cooldown.shadow_word_death.charges>=1)) Spell(mind_flay) } } } AddFunction ShadowS2mMainPostConditions { } AddFunction ShadowS2mShortCdActions { unless BuffAmount(insanity_drain_stacks_buff) < 6 and ArmorSetBonus(T19 4) and Spell(void_bolt) { #shadow_crash,if=talent.shadow_crash.enabled if Talent(shadow_crash_talent) Spell(shadow_crash) } } AddFunction ShadowS2mShortCdPostConditions { BuffAmount(insanity_drain_stacks_buff) < 6 and ArmorSetBonus(T19 4) and Spell(void_bolt) or SpellCharges(shadow_word_death) == 0 and BuffStacks(voidform_buff) > 45 + 25 * ArmorSetBonus(T20 4) and Spell(mindbender) or { target.DebuffRemaining(shadow_word_pain_debuff) > 5.5 and target.DebuffRemaining(vampiric_touch_debuff) > 5.5 and not BuffPresent(power_infusion_buff) or BuffStacks(voidform_buff) < 5 } and Spell(void_torrent) or CurrentInsanityDrain() * GCD() > Insanity() and Insanity() - CurrentInsanityDrain() * GCD() + 30 + 30 * TalentPoints(reaper_of_souls_talent) < 100 and Spell(shadow_word_death) or Spell(void_bolt) or { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and CurrentInsanityDrain() * GCD() > Insanity() and Insanity() - CurrentInsanityDrain() * GCD() + 30 + 30 * TalentPoints(reaper_of_souls_talent) < 100 and Spell(shadow_word_death) or not { SpellCooldown(void_bolt) < GCD() * 0.28 and SpellCooldown(void_bolt) > 0 } and { Enemies() <= 5 and Spell(mind_blast) or not { SpellCooldown(mind_blast) < GCD() * 0.28 and Enemies() <= 5 and SpellCooldown(mind_blast) > 0 } and { { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and SpellCharges(shadow_word_death) == 2 and Spell(shadow_word_death) or not Talent(mindbender_talent) and BuffStacks(voidform_buff) > 15 and Spell(shadowfiend) or Talent(shadow_word_void_talent) and Insanity() - CurrentInsanityDrain() * GCD() + 50 < 100 and Spell(shadow_word_void) or Speed() > 0 and Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < GCD() and Spell(shadow_word_pain) or Talent(misery_talent) and { target.DebuffRemaining(vampiric_touch_debuff) < 3 * GCD() or target.DebuffRemaining(shadow_word_pain_debuff) < 3 * GCD() } and Spell(vampiric_touch) or not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and { Enemies() < 5 or Talent(auspicious_spirits_talent) or Talent(shadowy_insight_talent) or ArtifactTraitRank(sphere_of_insanity) } and Spell(shadow_word_pain) or not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and { Enemies() < 4 or Talent(sanlayn_talent) or Talent(auspicious_spirits_talent) and ArtifactTraitRank(unleash_the_shadows) } and Spell(vampiric_touch) or not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and target.TimeToDie() > 10 and Enemies() < 5 and { Talent(auspicious_spirits_talent) or Talent(shadowy_insight_talent) } and Spell(shadow_word_pain) or not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and target.TimeToDie() > 10 and { Enemies() < 4 or Talent(sanlayn_talent) or Talent(auspicious_spirits_talent) and ArtifactTraitRank(unleash_the_shadows) } and Spell(vampiric_touch) or not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and target.TimeToDie() > 10 and Enemies() < 5 and ArtifactTraitRank(sphere_of_insanity) and Spell(shadow_word_pain) or Spell(mind_flay) } } } AddFunction ShadowS2mCdActions { unless BuffAmount(insanity_drain_stacks_buff) < 6 and ArmorSetBonus(T19 4) and Spell(void_bolt) or Talent(shadow_crash_talent) and Spell(shadow_crash) or SpellCharges(shadow_word_death) == 0 and BuffStacks(voidform_buff) > 45 + 25 * ArmorSetBonus(T20 4) and Spell(mindbender) or { target.DebuffRemaining(shadow_word_pain_debuff) > 5.5 and target.DebuffRemaining(vampiric_touch_debuff) > 5.5 and not BuffPresent(power_infusion_buff) or BuffStacks(voidform_buff) < 5 } and Spell(void_torrent) { #berserking,if=buff.voidform.stack>=65 if BuffStacks(voidform_buff) >= 65 Spell(berserking) unless CurrentInsanityDrain() * GCD() > Insanity() and Insanity() - CurrentInsanityDrain() * GCD() + 30 + 30 * TalentPoints(reaper_of_souls_talent) < 100 and Spell(shadow_word_death) { #power_infusion,if=cooldown.shadow_word_death.charges=0&buff.voidform.stack>(45+25*set_bonus.tier20_4pc)|target.time_to_die<=30 if SpellCharges(shadow_word_death) == 0 and BuffStacks(voidform_buff) > 45 + 25 * ArmorSetBonus(T20 4) or target.TimeToDie() <= 30 Spell(power_infusion) unless Spell(void_bolt) or { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and CurrentInsanityDrain() * GCD() > Insanity() and Insanity() - CurrentInsanityDrain() * GCD() + 30 + 30 * TalentPoints(reaper_of_souls_talent) < 100 and Spell(shadow_word_death) { #wait,sec=action.void_bolt.usable_in,if=action.void_bolt.usable_in<gcd.max*0.28 unless SpellCooldown(void_bolt) < GCD() * 0.28 and SpellCooldown(void_bolt) > 0 { #dispersion,if=current_insanity_drain*gcd.max>insanity&!buff.power_infusion.up|(buff.voidform.stack>76&cooldown.shadow_word_death.charges=0&current_insanity_drain*gcd.max>insanity) if CurrentInsanityDrain() * GCD() > Insanity() and not BuffPresent(power_infusion_buff) or BuffStacks(voidform_buff) > 76 and SpellCharges(shadow_word_death) == 0 and CurrentInsanityDrain() * GCD() > Insanity() Spell(dispersion) } } } } } AddFunction ShadowS2mCdPostConditions { BuffAmount(insanity_drain_stacks_buff) < 6 and ArmorSetBonus(T19 4) and Spell(void_bolt) or Talent(shadow_crash_talent) and Spell(shadow_crash) or SpellCharges(shadow_word_death) == 0 and BuffStacks(voidform_buff) > 45 + 25 * ArmorSetBonus(T20 4) and Spell(mindbender) or { target.DebuffRemaining(shadow_word_pain_debuff) > 5.5 and target.DebuffRemaining(vampiric_touch_debuff) > 5.5 and not BuffPresent(power_infusion_buff) or BuffStacks(voidform_buff) < 5 } and Spell(void_torrent) or CurrentInsanityDrain() * GCD() > Insanity() and Insanity() - CurrentInsanityDrain() * GCD() + 30 + 30 * TalentPoints(reaper_of_souls_talent) < 100 and Spell(shadow_word_death) or Spell(void_bolt) or { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and CurrentInsanityDrain() * GCD() > Insanity() and Insanity() - CurrentInsanityDrain() * GCD() + 30 + 30 * TalentPoints(reaper_of_souls_talent) < 100 and Spell(shadow_word_death) or not { SpellCooldown(void_bolt) < GCD() * 0.28 and SpellCooldown(void_bolt) > 0 } and { Enemies() <= 5 and Spell(mind_blast) or not { SpellCooldown(mind_blast) < GCD() * 0.28 and Enemies() <= 5 and SpellCooldown(mind_blast) > 0 } and { { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and SpellCharges(shadow_word_death) == 2 and Spell(shadow_word_death) or not Talent(mindbender_talent) and BuffStacks(voidform_buff) > 15 and Spell(shadowfiend) or Talent(shadow_word_void_talent) and Insanity() - CurrentInsanityDrain() * GCD() + 50 < 100 and Spell(shadow_word_void) or Speed() > 0 and Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < GCD() and Spell(shadow_word_pain) or Talent(misery_talent) and { target.DebuffRemaining(vampiric_touch_debuff) < 3 * GCD() or target.DebuffRemaining(shadow_word_pain_debuff) < 3 * GCD() } and Spell(vampiric_touch) or not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and { Enemies() < 5 or Talent(auspicious_spirits_talent) or Talent(shadowy_insight_talent) or ArtifactTraitRank(sphere_of_insanity) } and Spell(shadow_word_pain) or not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and { Enemies() < 4 or Talent(sanlayn_talent) or Talent(auspicious_spirits_talent) and ArtifactTraitRank(unleash_the_shadows) } and Spell(vampiric_touch) or not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and target.TimeToDie() > 10 and Enemies() < 5 and { Talent(auspicious_spirits_talent) or Talent(shadowy_insight_talent) } and Spell(shadow_word_pain) or not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and target.TimeToDie() > 10 and { Enemies() < 4 or Talent(sanlayn_talent) or Talent(auspicious_spirits_talent) and ArtifactTraitRank(unleash_the_shadows) } and Spell(vampiric_touch) or not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and target.TimeToDie() > 10 and Enemies() < 5 and ArtifactTraitRank(sphere_of_insanity) and Spell(shadow_word_pain) or Spell(mind_flay) } } } ### actions.vf AddFunction ShadowVfMainActions { #void_bolt Spell(void_bolt) #void_torrent,if=dot.shadow_word_pain.remains>5.5&dot.vampiric_touch.remains>5.5&(!talent.surrender_to_madness.enabled|(talent.surrender_to_madness.enabled&target.time_to_die>variable.s2mcheck-(buff.insanity_drain_stacks.value)+60)) if target.DebuffRemaining(shadow_word_pain_debuff) > 5.5 and target.DebuffRemaining(vampiric_touch_debuff) > 5.5 and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) + 60 } Spell(void_torrent) #mindbender,if=set_bonus.tier20_4pc&buff.insanity_drain_stacks.value>=(21-(3*(raid_event.movement.in<15)*((active_enemies-target.adds)=1))+2*buff.bloodlust.up+2*talent.fortress_of_the_mind.enabled+2*artifact.lash_of_insanity.rank)&(!talent.surrender_to_madness.enabled|(talent.surrender_to_madness.enabled&target.time_to_die>variable.s2mcheck-buff.insanity_drain_stacks.value)) if ArmorSetBonus(T20 4) and BuffAmount(insanity_drain_stacks_buff) >= 21 - 3 * { 600 < 15 } * { Enemies() - { Enemies() - 1 } == 1 } + 2 * BuffPresent(burst_haste_buff any=1) + 2 * TalentPoints(fortress_of_the_mind_talent) + 2 * ArtifactTraitRank(lash_of_insanity) and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) } Spell(mindbender) #mindbender,if=!set_bonus.tier20_4pc&buff.insanity_drain_stacks.value>=(10+2*set_bonus.tier19_2pc+5*buff.bloodlust.up+3*equipped.mangazas_madness+2*artifact.lash_of_insanity.rank)&(!talent.surrender_to_madness.enabled|(talent.surrender_to_madness.enabled&target.time_to_die>variable.s2mcheck-(buff.insanity_drain_stacks.value)+30)) if not ArmorSetBonus(T20 4) and BuffAmount(insanity_drain_stacks_buff) >= 10 + 2 * ArmorSetBonus(T19 2) + 5 * BuffPresent(burst_haste_buff any=1) + 3 * HasEquippedItem(mangazas_madness) + 2 * ArtifactTraitRank(lash_of_insanity) and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) + 30 } Spell(mindbender) #void_bolt Spell(void_bolt) #shadow_word_death,if=(active_enemies<=4|(talent.reaper_of_souls.enabled&active_enemies<=2))&current_insanity_drain*gcd.max>insanity&(insanity-(current_insanity_drain*gcd.max)+(15+15*talent.reaper_of_souls.enabled))<100 if { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and CurrentInsanityDrain() * GCD() > Insanity() and Insanity() - CurrentInsanityDrain() * GCD() + 15 + 15 * TalentPoints(reaper_of_souls_talent) < 100 Spell(shadow_word_death) #wait,sec=action.void_bolt.usable_in,if=action.void_bolt.usable_in<gcd.max*0.28 unless SpellCooldown(void_bolt) < GCD() * 0.28 and SpellCooldown(void_bolt) > 0 { #mind_blast,if=active_enemies<=4 if Enemies() <= 4 Spell(mind_blast) #wait,sec=action.mind_blast.usable_in,if=action.mind_blast.usable_in<gcd.max*0.28&active_enemies<=4 unless SpellCooldown(mind_blast) < GCD() * 0.28 and Enemies() <= 4 and SpellCooldown(mind_blast) > 0 { #shadow_word_death,if=(active_enemies<=4|(talent.reaper_of_souls.enabled&active_enemies<=2))&cooldown.shadow_word_death.charges=2 if { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and SpellCharges(shadow_word_death) == 2 Spell(shadow_word_death) #shadowfiend,if=!talent.mindbender.enabled&buff.voidform.stack>15 if not Talent(mindbender_talent) and BuffStacks(voidform_buff) > 15 Spell(shadowfiend) #shadow_word_void,if=talent.shadow_word_void.enabled&(insanity-(current_insanity_drain*gcd.max)+25)<100 if Talent(shadow_word_void_talent) and Insanity() - CurrentInsanityDrain() * GCD() + 25 < 100 Spell(shadow_word_void) #shadow_word_pain,if=talent.misery.enabled&dot.shadow_word_pain.remains<gcd,moving=1,cycle_targets=1 if Speed() > 0 and Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < GCD() Spell(shadow_word_pain) #vampiric_touch,if=talent.misery.enabled&(dot.vampiric_touch.remains<3*gcd.max|dot.shadow_word_pain.remains<3*gcd.max)&target.time_to_die>5*gcd.max,cycle_targets=1 if Talent(misery_talent) and { target.DebuffRemaining(vampiric_touch_debuff) < 3 * GCD() or target.DebuffRemaining(shadow_word_pain_debuff) < 3 * GCD() } and target.TimeToDie() > 5 * GCD() Spell(vampiric_touch) #shadow_word_pain,if=!talent.misery.enabled&!ticking&(active_enemies<5|talent.auspicious_spirits.enabled|talent.shadowy_insight.enabled|artifact.sphere_of_insanity.rank) if not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and { Enemies() < 5 or Talent(auspicious_spirits_talent) or Talent(shadowy_insight_talent) or ArtifactTraitRank(sphere_of_insanity) } Spell(shadow_word_pain) #vampiric_touch,if=!talent.misery.enabled&!ticking&(active_enemies<4|talent.sanlayn.enabled|(talent.auspicious_spirits.enabled&artifact.unleash_the_shadows.rank)) if not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and { Enemies() < 4 or Talent(sanlayn_talent) or Talent(auspicious_spirits_talent) and ArtifactTraitRank(unleash_the_shadows) } Spell(vampiric_touch) #vampiric_touch,if=active_enemies>1&!talent.misery.enabled&!ticking&(85.2*(1+0.02*buff.voidform.stack)*(1+0.2+stat.mastery_rating%16000)*(1+0.2*talent.sanlayn.enabled)*0.5*target.time_to_die%(gcd.max*(138+80*(active_enemies-1))))>1,cycle_targets=1 if Enemies() > 1 and not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and 85.2 * { 1 + 0.02 * BuffStacks(voidform_buff) } * { 1 + 0.2 + MasteryRating() / 16000 } * { 1 + 0.2 * TalentPoints(sanlayn_talent) } * 0.5 * target.TimeToDie() / { GCD() * { 138 + 80 * { Enemies() - 1 } } } > 1 Spell(vampiric_touch) #shadow_word_pain,if=active_enemies>1&!talent.misery.enabled&!ticking&(47.12*(1+0.02*buff.voidform.stack)*(1+0.2+stat.mastery_rating%16000)*0.75*target.time_to_die%(gcd.max*(138+80*(active_enemies-1))))>1,cycle_targets=1 if Enemies() > 1 and not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and 47.12 * { 1 + 0.02 * BuffStacks(voidform_buff) } * { 1 + 0.2 + MasteryRating() / 16000 } * 0.75 * target.TimeToDie() / { GCD() * { 138 + 80 * { Enemies() - 1 } } } > 1 Spell(shadow_word_pain) #mind_flay,chain=1,interrupt_immediate=1,interrupt_if=ticks>=2&(action.void_bolt.usable|(current_insanity_drain*gcd.max>insanity&(insanity-(current_insanity_drain*gcd.max)+30)<100&cooldown.shadow_word_death.charges>=1)) Spell(mind_flay) #shadow_word_pain Spell(shadow_word_pain) } } } AddFunction ShadowVfMainPostConditions { } AddFunction ShadowVfShortCdActions { unless Spell(void_bolt) { #shadow_crash,if=talent.shadow_crash.enabled if Talent(shadow_crash_talent) Spell(shadow_crash) } } AddFunction ShadowVfShortCdPostConditions { Spell(void_bolt) or target.DebuffRemaining(shadow_word_pain_debuff) > 5.5 and target.DebuffRemaining(vampiric_touch_debuff) > 5.5 and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) + 60 } and Spell(void_torrent) or ArmorSetBonus(T20 4) and BuffAmount(insanity_drain_stacks_buff) >= 21 - 3 * { 600 < 15 } * { Enemies() - { Enemies() - 1 } == 1 } + 2 * BuffPresent(burst_haste_buff any=1) + 2 * TalentPoints(fortress_of_the_mind_talent) + 2 * ArtifactTraitRank(lash_of_insanity) and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) } and Spell(mindbender) or not ArmorSetBonus(T20 4) and BuffAmount(insanity_drain_stacks_buff) >= 10 + 2 * ArmorSetBonus(T19 2) + 5 * BuffPresent(burst_haste_buff any=1) + 3 * HasEquippedItem(mangazas_madness) + 2 * ArtifactTraitRank(lash_of_insanity) and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) + 30 } and Spell(mindbender) or Spell(void_bolt) or { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and CurrentInsanityDrain() * GCD() > Insanity() and Insanity() - CurrentInsanityDrain() * GCD() + 15 + 15 * TalentPoints(reaper_of_souls_talent) < 100 and Spell(shadow_word_death) or not { SpellCooldown(void_bolt) < GCD() * 0.28 and SpellCooldown(void_bolt) > 0 } and { Enemies() <= 4 and Spell(mind_blast) or not { SpellCooldown(mind_blast) < GCD() * 0.28 and Enemies() <= 4 and SpellCooldown(mind_blast) > 0 } and { { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and SpellCharges(shadow_word_death) == 2 and Spell(shadow_word_death) or not Talent(mindbender_talent) and BuffStacks(voidform_buff) > 15 and Spell(shadowfiend) or Talent(shadow_word_void_talent) and Insanity() - CurrentInsanityDrain() * GCD() + 25 < 100 and Spell(shadow_word_void) or Speed() > 0 and Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < GCD() and Spell(shadow_word_pain) or Talent(misery_talent) and { target.DebuffRemaining(vampiric_touch_debuff) < 3 * GCD() or target.DebuffRemaining(shadow_word_pain_debuff) < 3 * GCD() } and target.TimeToDie() > 5 * GCD() and Spell(vampiric_touch) or not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and { Enemies() < 5 or Talent(auspicious_spirits_talent) or Talent(shadowy_insight_talent) or ArtifactTraitRank(sphere_of_insanity) } and Spell(shadow_word_pain) or not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and { Enemies() < 4 or Talent(sanlayn_talent) or Talent(auspicious_spirits_talent) and ArtifactTraitRank(unleash_the_shadows) } and Spell(vampiric_touch) or Enemies() > 1 and not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and 85.2 * { 1 + 0.02 * BuffStacks(voidform_buff) } * { 1 + 0.2 + MasteryRating() / 16000 } * { 1 + 0.2 * TalentPoints(sanlayn_talent) } * 0.5 * target.TimeToDie() / { GCD() * { 138 + 80 * { Enemies() - 1 } } } > 1 and Spell(vampiric_touch) or Enemies() > 1 and not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and 47.12 * { 1 + 0.02 * BuffStacks(voidform_buff) } * { 1 + 0.2 + MasteryRating() / 16000 } * 0.75 * target.TimeToDie() / { GCD() * { 138 + 80 * { Enemies() - 1 } } } > 1 and Spell(shadow_word_pain) or Spell(mind_flay) or Spell(shadow_word_pain) } } } AddFunction ShadowVfCdActions { #surrender_to_madness,if=talent.surrender_to_madness.enabled&insanity>=25&(cooldown.void_bolt.up|cooldown.void_torrent.up|cooldown.shadow_word_death.up|buff.shadowy_insight.up)&target.time_to_die<=variable.s2mcheck-(buff.insanity_drain_stacks.value) if Talent(surrender_to_madness_talent) and Insanity() >= 25 and { not SpellCooldown(void_bolt) > 0 or not SpellCooldown(void_torrent) > 0 or not SpellCooldown(shadow_word_death) > 0 or BuffPresent(shadowy_insight_buff) } and target.TimeToDie() <= s2mcheck() - BuffAmount(insanity_drain_stacks_buff) Spell(surrender_to_madness) #silence,if=equipped.sephuzs_secret&(target.is_add|target.debuff.casting.react)&cooldown.buff_sephuzs_secret.remains<1&!buff.sephuzs_secret.up&buff.insanity_drain_stacks.value>10,cycle_targets=1 if HasEquippedItem(sephuzs_secret) and { not target.Classification(worldboss) or target.IsInterruptible() } and BuffCooldown(sephuzs_secret_buff) < 1 and not BuffPresent(sephuzs_secret_buff) and BuffAmount(insanity_drain_stacks_buff) > 10 ShadowInterruptActions() unless Spell(void_bolt) { #mind_bomb,if=equipped.sephuzs_secret&target.is_add&cooldown.buff_sephuzs_secret.remains<1&!buff.sephuzs_secret.up&buff.insanity_drain_stacks.value>10,cycle_targets=1 if HasEquippedItem(sephuzs_secret) and not target.Classification(worldboss) and BuffCooldown(sephuzs_secret_buff) < 1 and not BuffPresent(sephuzs_secret_buff) and BuffAmount(insanity_drain_stacks_buff) > 10 ShadowInterruptActions() unless Talent(shadow_crash_talent) and Spell(shadow_crash) or target.DebuffRemaining(shadow_word_pain_debuff) > 5.5 and target.DebuffRemaining(vampiric_touch_debuff) > 5.5 and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) + 60 } and Spell(void_torrent) or ArmorSetBonus(T20 4) and BuffAmount(insanity_drain_stacks_buff) >= 21 - 3 * { 600 < 15 } * { Enemies() - { Enemies() - 1 } == 1 } + 2 * BuffPresent(burst_haste_buff any=1) + 2 * TalentPoints(fortress_of_the_mind_talent) + 2 * ArtifactTraitRank(lash_of_insanity) and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) } and Spell(mindbender) or not ArmorSetBonus(T20 4) and BuffAmount(insanity_drain_stacks_buff) >= 10 + 2 * ArmorSetBonus(T19 2) + 5 * BuffPresent(burst_haste_buff any=1) + 3 * HasEquippedItem(mangazas_madness) + 2 * ArtifactTraitRank(lash_of_insanity) and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) + 30 } and Spell(mindbender) { #power_infusion,if=buff.insanity_drain_stacks.value>=(10+2*set_bonus.tier19_2pc+5*buff.bloodlust.up*(1+1*set_bonus.tier20_4pc)+3*equipped.mangazas_madness+6*set_bonus.tier20_4pc+2*artifact.lash_of_insanity.rank)&(!talent.surrender_to_madness.enabled|(talent.surrender_to_madness.enabled&target.time_to_die>variable.s2mcheck-(buff.insanity_drain_stacks.value)+61)) if BuffAmount(insanity_drain_stacks_buff) >= 10 + 2 * ArmorSetBonus(T19 2) + 5 * BuffPresent(burst_haste_buff any=1) * { 1 + 1 * ArmorSetBonus(T20 4) } + 3 * HasEquippedItem(mangazas_madness) + 6 * ArmorSetBonus(T20 4) + 2 * ArtifactTraitRank(lash_of_insanity) and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) + 61 } Spell(power_infusion) #berserking,if=buff.voidform.stack>=10&buff.insanity_drain_stacks.value<=20&(!talent.surrender_to_madness.enabled|(talent.surrender_to_madness.enabled&target.time_to_die>variable.s2mcheck-(buff.insanity_drain_stacks.value)+60)) if BuffStacks(voidform_buff) >= 10 and BuffAmount(insanity_drain_stacks_buff) <= 20 and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) + 60 } Spell(berserking) } } } AddFunction ShadowVfCdPostConditions { Spell(void_bolt) or Talent(shadow_crash_talent) and Spell(shadow_crash) or target.DebuffRemaining(shadow_word_pain_debuff) > 5.5 and target.DebuffRemaining(vampiric_touch_debuff) > 5.5 and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) + 60 } and Spell(void_torrent) or ArmorSetBonus(T20 4) and BuffAmount(insanity_drain_stacks_buff) >= 21 - 3 * { 600 < 15 } * { Enemies() - { Enemies() - 1 } == 1 } + 2 * BuffPresent(burst_haste_buff any=1) + 2 * TalentPoints(fortress_of_the_mind_talent) + 2 * ArtifactTraitRank(lash_of_insanity) and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) } and Spell(mindbender) or not ArmorSetBonus(T20 4) and BuffAmount(insanity_drain_stacks_buff) >= 10 + 2 * ArmorSetBonus(T19 2) + 5 * BuffPresent(burst_haste_buff any=1) + 3 * HasEquippedItem(mangazas_madness) + 2 * ArtifactTraitRank(lash_of_insanity) and { not Talent(surrender_to_madness_talent) or Talent(surrender_to_madness_talent) and target.TimeToDie() > s2mcheck() - BuffAmount(insanity_drain_stacks_buff) + 30 } and Spell(mindbender) or Spell(void_bolt) or { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and CurrentInsanityDrain() * GCD() > Insanity() and Insanity() - CurrentInsanityDrain() * GCD() + 15 + 15 * TalentPoints(reaper_of_souls_talent) < 100 and Spell(shadow_word_death) or not { SpellCooldown(void_bolt) < GCD() * 0.28 and SpellCooldown(void_bolt) > 0 } and { Enemies() <= 4 and Spell(mind_blast) or not { SpellCooldown(mind_blast) < GCD() * 0.28 and Enemies() <= 4 and SpellCooldown(mind_blast) > 0 } and { { Enemies() <= 4 or Talent(reaper_of_souls_talent) and Enemies() <= 2 } and SpellCharges(shadow_word_death) == 2 and Spell(shadow_word_death) or not Talent(mindbender_talent) and BuffStacks(voidform_buff) > 15 and Spell(shadowfiend) or Talent(shadow_word_void_talent) and Insanity() - CurrentInsanityDrain() * GCD() + 25 < 100 and Spell(shadow_word_void) or Speed() > 0 and Talent(misery_talent) and target.DebuffRemaining(shadow_word_pain_debuff) < GCD() and Spell(shadow_word_pain) or Talent(misery_talent) and { target.DebuffRemaining(vampiric_touch_debuff) < 3 * GCD() or target.DebuffRemaining(shadow_word_pain_debuff) < 3 * GCD() } and target.TimeToDie() > 5 * GCD() and Spell(vampiric_touch) or not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and { Enemies() < 5 or Talent(auspicious_spirits_talent) or Talent(shadowy_insight_talent) or ArtifactTraitRank(sphere_of_insanity) } and Spell(shadow_word_pain) or not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and { Enemies() < 4 or Talent(sanlayn_talent) or Talent(auspicious_spirits_talent) and ArtifactTraitRank(unleash_the_shadows) } and Spell(vampiric_touch) or Enemies() > 1 and not Talent(misery_talent) and not target.DebuffPresent(vampiric_touch_debuff) and 85.2 * { 1 + 0.02 * BuffStacks(voidform_buff) } * { 1 + 0.2 + MasteryRating() / 16000 } * { 1 + 0.2 * TalentPoints(sanlayn_talent) } * 0.5 * target.TimeToDie() / { GCD() * { 138 + 80 * { Enemies() - 1 } } } > 1 and Spell(vampiric_touch) or Enemies() > 1 and not Talent(misery_talent) and not target.DebuffPresent(shadow_word_pain_debuff) and 47.12 * { 1 + 0.02 * BuffStacks(voidform_buff) } * { 1 + 0.2 + MasteryRating() / 16000 } * 0.75 * target.TimeToDie() / { GCD() * { 138 + 80 * { Enemies() - 1 } } } > 1 and Spell(shadow_word_pain) or Spell(mind_flay) or Spell(shadow_word_pain) } } } ### Shadow icons. AddCheckBox(opt_priest_shadow_aoe L(AOE) default specialization=shadow) AddIcon checkbox=!opt_priest_shadow_aoe enemies=1 help=shortcd specialization=shadow { if not InCombat() ShadowPrecombatShortCdActions() unless not InCombat() and ShadowPrecombatShortCdPostConditions() { ShadowDefaultShortCdActions() } } AddIcon checkbox=opt_priest_shadow_aoe help=shortcd specialization=shadow { if not InCombat() ShadowPrecombatShortCdActions() unless not InCombat() and ShadowPrecombatShortCdPostConditions() { ShadowDefaultShortCdActions() } } AddIcon enemies=1 help=main specialization=shadow { if not InCombat() ShadowPrecombatMainActions() unless not InCombat() and ShadowPrecombatMainPostConditions() { ShadowDefaultMainActions() } } AddIcon checkbox=opt_priest_shadow_aoe help=aoe specialization=shadow { if not InCombat() ShadowPrecombatMainActions() unless not InCombat() and ShadowPrecombatMainPostConditions() { ShadowDefaultMainActions() } } AddIcon checkbox=!opt_priest_shadow_aoe enemies=1 help=cd specialization=shadow { if not InCombat() ShadowPrecombatCdActions() unless not InCombat() and ShadowPrecombatCdPostConditions() { ShadowDefaultCdActions() } } AddIcon checkbox=opt_priest_shadow_aoe help=cd specialization=shadow { if not InCombat() ShadowPrecombatCdActions() unless not InCombat() and ShadowPrecombatCdPostConditions() { ShadowDefaultCdActions() } } ### Required symbols # arcane_torrent_mana # auspicious_spirits_talent # berserking # dispersion # fortress_of_the_mind_talent # insanity_drain_stacks_buff # lash_of_insanity # legacy_of_the_void_talent # mangazas_madness # mass_hysteria # mind_blast # mind_bomb # mind_flay # mindbender # mindbender_talent # misery_talent # power_infusion # power_infusion_buff # prolonged_power_potion # quaking_palm # reaper_of_souls_talent # sanlayn_talent # sephuzs_secret # sephuzs_secret_buff # shadow_crash # shadow_crash_talent # shadow_word_death # shadow_word_pain # shadow_word_pain_debuff # shadow_word_void # shadow_word_void_talent # shadowfiend # shadowform # shadowform_buff # shadowy_insight_buff # shadowy_insight_talent # silence # sphere_of_insanity # surrender_to_madness # surrender_to_madness_buff # surrender_to_madness_talent # unleash_the_shadows # vampiric_touch # vampiric_touch_debuff # void_bolt # void_eruption # void_torrent # voidform_buff # war_stomp ]] OvaleScripts:RegisterScript("PRIEST", "shadow", name, desc, code, "script") end
local closeServer = TalkAction("/closeserver") function closeServer.onSay(player, words, param) if not player:getGroup():getAccess() or player:getAccountType() < ACCOUNT_TYPE_GOD then return true end if param == "shutdown" then Game.setGameState(GAME_STATE_SHUTDOWN) else Game.setGameState(GAME_STATE_CLOSED) player:sendTextMessage(MESSAGE_LOOK, "Server is now closed.") end return false end closeServer:separator(" ") closeServer:register()
-- Path of Building -- -- Module: Tree Tab -- Passive skill tree tab for the current build. -- local ipairs = ipairs local t_insert = table.insert local t_sort = table.sort local m_max = math.max local m_min = math.min local m_floor = math.floor local s_format = string.format local TreeTabClass = newClass("TreeTab", "ControlHost", function(self, build) self.ControlHost() self.build = build self.isComparing = false; self.viewer = new("PassiveTreeView") self.specList = { } self.specList[1] = new("PassiveSpec", build, latestTreeVersion) self:SetActiveSpec(1) self:SetCompareSpec(1) self.anchorControls = new("Control", nil, 0, -200, 0, 20) self.controls.specSelect = new("DropDownControl", {"LEFT",self.anchorControls,"RIGHT"}, 0, 0, 190, 20, nil, function(index, value) if self.specList[index] then self.build.modFlag = true self:SetActiveSpec(index) else self:OpenSpecManagePopup() end end) self.controls.specSelect.tooltipFunc = function(tooltip, mode, selIndex, selVal) tooltip:Clear() if mode ~= "OUT" then local spec = self.specList[selIndex] if spec then local used, ascUsed, sockets = spec:CountAllocNodes() tooltip:AddLine(16, "Class: "..spec.curClassName) tooltip:AddLine(16, "Ascendancy: "..spec.curAscendClassName) tooltip:AddLine(16, "Points used: "..used) if sockets > 0 then tooltip:AddLine(16, "Jewel sockets: "..sockets) end if selIndex ~= self.activeSpec then local calcFunc, calcBase = self.build.calcsTab:GetMiscCalculator() if calcFunc then local output = calcFunc({ spec = spec }, {}) self.build:AddStatComparesToTooltip(tooltip, calcBase, output, "^7Switching to this tree will give you:") end if spec.curClassId == self.build.spec.curClassId then local respec = 0 for nodeId, node in pairs(self.build.spec.allocNodes) do if node.type ~= "ClassStart" and node.type ~= "AscendClassStart" and not spec.allocNodes[nodeId] then if node.ascendancyName then respec = respec + 5 else respec = respec + 1 end end end if respec > 0 then tooltip:AddLine(16, "^7Switching to this tree requires "..respec.." refund points.") end end end tooltip:AddLine(16, "Game Version: "..treeVersions[spec.treeVersion].display) end end end self.controls.compareCheck = new("CheckBoxControl", {"LEFT",self.controls.specSelect,"RIGHT"}, 74, 0, 20, "Compare:", function(state) self.isComparing = state self:SetCompareSpec(self.activeCompareSpec) self.controls.compareSelect.shown = state if state then self.controls.reset:SetAnchor("LEFT",self.controls.compareSelect,"RIGHT",nil,nil,nil) else self.controls.reset:SetAnchor("LEFT",self.controls.compareCheck,"RIGHT",nil,nil,nil) end end) self.controls.compareSelect = new("DropDownControl", {"LEFT",self.controls.compareCheck,"RIGHT"}, 8, 0, 190, 20, nil, function(index, value) if self.specList[index] then self:SetCompareSpec(index) end end) self.controls.compareSelect.shown = false self.controls.reset = new("ButtonControl", {"LEFT",self.controls.compareCheck,"RIGHT"}, 8, 0, 60, 20, "Reset", function() main:OpenConfirmPopup("Reset Tree", "Are you sure you want to reset your passive tree?", "Reset", function() self.build.spec:ResetNodes() self.build.spec:AddUndoState() self.build.buildFlag = true end) end) self.controls.import = new("ButtonControl", {"LEFT",self.controls.reset,"RIGHT"}, 8, 0, 90, 20, "Import Tree", function() self:OpenImportPopup() end) self.controls.export = new("ButtonControl", {"LEFT",self.controls.import,"RIGHT"}, 8, 0, 90, 20, "Export Tree", function() self:OpenExportPopup() end) self.controls.treeSearch = new("EditControl", {"LEFT",self.controls.export,"RIGHT"}, 8, 0, 300, 20, "", "Search", "%c%(%)", 100, function(buf) self.viewer.searchStr = buf end) self.controls.powerReport = new("ButtonControl", {"LEFT", self.controls.treeSearch, "RIGHT"}, 8, 0, 140, 20, self.viewer.showHeatMap and "Hide Power Report" or "Show Power Report", function() self.viewer.showHeatMap = not self.viewer.showHeatMap self:TogglePowerReport() end) -- Sets up UI elements and power report calculations if the heatmap is already shown self:TogglePowerReport() self.controls.specConvertText = new("LabelControl", {"BOTTOMLEFT",self.controls.specSelect,"TOPLEFT"}, 0, -14, 0, 16, "^7This is an older tree version, which may not be fully compatible with the current game version.") self.controls.specConvertText.shown = function() return self.showConvert end self.controls.specConvert = new("ButtonControl", {"LEFT",self.controls.specConvertText,"RIGHT"}, 8, 0, 120, 20, "^2Convert to "..treeVersions[latestTreeVersion].display, function() local newSpec = new("PassiveSpec", self.build, latestTreeVersion) newSpec.title = self.build.spec.title newSpec.jewels = copyTable(self.build.spec.jewels) newSpec:RestoreUndoState(self.build.spec:CreateUndoState()) newSpec:BuildClusterJewelGraphs() t_insert(self.specList, self.activeSpec + 1, newSpec) self:SetActiveSpec(self.activeSpec + 1) self.modFlag = true main:OpenMessagePopup("Tree Converted", "The tree has been converted to "..treeVersions[latestTreeVersion].display..".\nNote that some or all of the passives may have been de-allocated due to changes in the tree.\n\nYou can switch back to the old tree using the tree selector at the bottom left.") end) self.jumpToNode = false self.jumpToX = 0 self.jumpToY = 0 end) function TreeTabClass:Draw(viewPort, inputEvents) self.anchorControls.x = viewPort.x + 4 self.anchorControls.y = viewPort.y + viewPort.height - 24 for id, event in ipairs(inputEvents) do if event.type == "KeyDown" then if event.key == "z" and IsKeyDown("CTRL") then self.build.spec:Undo() self.build.buildFlag = true inputEvents[id] = nil elseif event.key == "y" and IsKeyDown("CTRL") then self.build.spec:Redo() self.build.buildFlag = true inputEvents[id] = nil elseif event.key == "f" and IsKeyDown("CTRL") then self:SelectControl(self.controls.treeSearch) end end end self:ProcessControlsInput(inputEvents, viewPort) -- Determine positions if one line of controls doesn't fit in the screen width local bottomDrawerHeight = 200 self.controls.specSelect.y = -198 if not self.viewer.showHeatMap then bottomDrawerHeight = 0 self.controls.specSelect.y = 0 end local treeViewPort = { x = viewPort.x, y = viewPort.y, width = viewPort.width, height = viewPort.height - (self.showConvert and 64 + bottomDrawerHeight or 32 + bottomDrawerHeight)} if self.jumpToNode then self.viewer:Focus(self.jumpToX, self.jumpToY, treeViewPort, self.build) self.jumpToNode = false end self.viewer.compareSpec = self.isComparing and self.specList[self.activeCompareSpec] or nil self.viewer:Draw(self.build, treeViewPort, inputEvents) self.controls.compareSelect.selIndex = self.activeCompareSpec wipeTable(self.controls.compareSelect.list) for id, spec in ipairs(self.specList) do t_insert(self.controls.compareSelect.list, (spec.treeVersion ~= latestTreeVersion and ("["..treeVersions[spec.treeVersion].display.."] ") or "")..(spec.title or "Default")) end self.controls.specSelect.selIndex = self.activeSpec wipeTable(self.controls.specSelect.list) for id, spec in ipairs(self.specList) do t_insert(self.controls.specSelect.list, (spec.treeVersion ~= latestTreeVersion and ("["..treeVersions[spec.treeVersion].display.."] ") or "")..(spec.title or "Default")) end t_insert(self.controls.specSelect.list, "Manage trees...") if not self.controls.treeSearch.hasFocus then self.controls.treeSearch:SetText(self.viewer.searchStr) end if self.viewer.showHeatMap then self.controls.treeHeatMapStatSelect.list = self.powerStatList self.controls.treeHeatMapStatSelect.selIndex = 1 if self.build.calcsTab.powerStat then self.controls.treeHeatMapStatSelect:SelByValue(self.build.calcsTab.powerStat.stat, "stat") end end SetDrawLayer(1) SetDrawColor(0.05, 0.05, 0.05) DrawImage(nil, viewPort.x, viewPort.y + viewPort.height - (28 + bottomDrawerHeight), viewPort.width, 28 + bottomDrawerHeight) SetDrawColor(0.85, 0.85, 0.85) DrawImage(nil, viewPort.x, viewPort.y + viewPort.height - (32 + bottomDrawerHeight), viewPort.width, 4) if self.showConvert then SetDrawColor(0.05, 0.05, 0.05) DrawImage(nil, viewPort.x, viewPort.y + viewPort.height - (60 + bottomDrawerHeight), viewPort.width, 28) SetDrawColor(0.85, 0.85, 0.85) DrawImage(nil, viewPort.x, viewPort.y + viewPort.height - (64 + bottomDrawerHeight), viewPort.width, 4) end self:DrawControls(viewPort) end function TreeTabClass:Load(xml, dbFileName) self.specList = { } if xml.elem == "Spec" then -- Import single spec from old build self.specList[1] = new("PassiveSpec", self.build, defaultTreeVersion) self.specList[1]:Load(xml, dbFileName) self.activeSpec = 1 self.build.spec = self.specList[1] return end for _, node in pairs(xml) do if type(node) == "table" then if node.elem == "Spec" then if node.attrib.treeVersion and not treeVersions[node.attrib.treeVersion] then main:OpenMessagePopup("Unknown Passive Tree Version", "The build you are trying to load uses an unrecognised version of the passive skill tree.\nYou may need to update the program before loading this build.") return true end local newSpec = new("PassiveSpec", self.build, node.attrib.treeVersion or defaultTreeVersion) newSpec:Load(node, dbFileName) t_insert(self.specList, newSpec) end end end if not self.specList[1] then self.specList[1] = new("PassiveSpec", self.build, latestTreeVersion) end self:SetActiveSpec(tonumber(xml.attrib.activeSpec) or 1) end function TreeTabClass:PostLoad() for _, spec in ipairs(self.specList) do spec:PostLoad() end end function TreeTabClass:Save(xml) xml.attrib = { activeSpec = tostring(self.activeSpec) } for specId, spec in ipairs(self.specList) do if specId == self.activeSpec then -- Update this spec's jewels from the socket slots for _, slot in pairs(self.build.itemsTab.slots) do if slot.nodeId then spec.jewels[slot.nodeId] = slot.selItemId end end end local child = { elem = "Spec" } spec:Save(child) t_insert(xml, child) end self.modFlag = false end function TreeTabClass:SetActiveSpec(specId) local prevSpec = self.build.spec self.activeSpec = m_min(specId, #self.specList) local curSpec = self.specList[self.activeSpec] self.build.spec = curSpec self.build.buildFlag = true self.build.spec:SetWindowTitleWithBuildClass() for _, slot in pairs(self.build.itemsTab.slots) do if slot.nodeId then if prevSpec then -- Update the previous spec's jewel for this slot prevSpec.jewels[slot.nodeId] = slot.selItemId end if curSpec.jewels[slot.nodeId] then -- Socket the jewel for the new spec slot.selItemId = curSpec.jewels[slot.nodeId] end end end self.showConvert = curSpec.treeVersion ~= latestTreeVersion if self.build.itemsTab.itemOrderList[1] then -- Update item slots if items have been loaded already self.build.itemsTab:PopulateSlots() end end function TreeTabClass:SetCompareSpec(specId) self.activeCompareSpec = m_min(specId, #self.specList) local curSpec = self.specList[self.activeCompareSpec] self.compareSpec = curSpec end function TreeTabClass:OpenSpecManagePopup() main:OpenPopup(370, 290, "Manage Passive Trees", { new("PassiveSpecListControl", nil, 0, 50, 350, 200, self), new("ButtonControl", nil, 0, 260, 90, 20, "Done", function() main:ClosePopup() end), }) end function TreeTabClass:OpenImportPopup() local controls = { } local function decodeTreeLink(treeLink) local errMsg = self.build.spec:DecodeURL(treeLink) if errMsg then controls.msg.label = "^1"..errMsg else self.build.spec:AddUndoState() self.build.buildFlag = true main:ClosePopup() end end controls.editLabel = new("LabelControl", nil, 0, 20, 0, 16, "Enter passive tree link:") controls.edit = new("EditControl", nil, 0, 40, 350, 18, "", nil, nil, nil, function(buf) controls.msg.label = "" end) controls.msg = new("LabelControl", nil, 0, 58, 0, 16, "") controls.import = new("ButtonControl", nil, -45, 80, 80, 20, "Import", function() local treeLink = controls.edit.buf if #treeLink == 0 then return end if treeLink:match("poeurl%.com/") then controls.import.enabled = false controls.msg.label = "Resolving PoEURL link..." local id = LaunchSubScript([[ local treeLink = ... local curl = require("lcurl.safe") local easy = curl.easy() easy:setopt_url(treeLink) easy:setopt_writefunction(function(data) return true end) easy:perform() local redirect = easy:getinfo(curl.INFO_REDIRECT_URL) easy:close() if not redirect or redirect:match("poeurl%.com/") then return nil, "Failed to resolve PoEURL link" end return redirect ]], "", "", treeLink) if id then launch:RegisterSubScript(id, function(treeLink, errMsg) if errMsg then controls.msg.label = "^1"..errMsg controls.import.enabled = true else decodeTreeLink(treeLink) end end) end else decodeTreeLink(treeLink) end end) controls.cancel = new("ButtonControl", nil, 45, 80, 80, 20, "Cancel", function() main:ClosePopup() end) main:OpenPopup(380, 110, "Import Tree", controls, "import", "edit") end function TreeTabClass:OpenExportPopup() local treeLink = self.build.spec:EncodeURL(treeVersions[self.build.spec.treeVersion].url) local popup local controls = { } controls.label = new("LabelControl", nil, 0, 20, 0, 16, "Passive tree link:") controls.edit = new("EditControl", nil, 0, 40, 350, 18, treeLink, nil, "%Z") controls.shrink = new("ButtonControl", nil, -90, 70, 140, 20, "Shrink with PoEURL", function() controls.shrink.enabled = false controls.shrink.label = "Shrinking..." launch:DownloadPage("http://poeurl.com/shrink.php?url="..treeLink, function(page, errMsg) controls.shrink.label = "Done" if errMsg or not page:match("%S") then main:OpenMessagePopup("PoEURL Shortener", "Failed to get PoEURL link. Try again later.") else treeLink = "http://poeurl.com/"..page controls.edit:SetText(treeLink) popup:SelectControl(controls.edit) end end) end) controls.copy = new("ButtonControl", nil, 30, 70, 80, 20, "Copy", function() Copy(treeLink) end) controls.done = new("ButtonControl", nil, 120, 70, 80, 20, "Done", function() main:ClosePopup() end) popup = main:OpenPopup(380, 100, "Export Tree", controls, "done", "edit") end function TreeTabClass:ModifyNodePopup(selectedNode) local controls = { } local modGroups = { } local smallAdditions = {"Strength", "Dex", "Devotion"} if not self.build.spec.tree.legion.editedNodes then self.build.spec.tree.legion.editedNodes = { } end local function buildMods(selectedNode) wipeTable(modGroups) for _, node in pairs(self.build.spec.tree.legion.nodes) do if node.id:match("^"..selectedNode.conqueredBy.conqueror.type.."_.+") and node["not"] == (selectedNode.isNotable or false) and not node.ks then t_insert(modGroups, { label = node.dn, descriptions = copyTable(node.sd), type = selectedNode.conqueredBy.conqueror.type, id = node.id, }) end end for _, addition in pairs(self.build.spec.tree.legion.additions) do -- exclude passives that are already added (vaal, attributes, devotion) if addition.id:match("^"..selectedNode.conqueredBy.conqueror.type.."_.+") and not isValueInArray(smallAdditions, addition.dn) and selectedNode.conqueredBy.conqueror.type ~= "vaal" then t_insert(modGroups, { label = addition.dn, descriptions = copyTable(addition.sd), type = selectedNode.conqueredBy.conqueror.type, id = addition.id, }) end end end local function addModifier(selectedNode) local newLegionNode = self.build.spec.tree.legion.nodes[modGroups[controls.modSelect.selIndex].id] -- most nodes only replace or add 1 mod, so we need to just get the first control local modDesc = string.gsub(controls[1].label, "%^7", "") if selectedNode.conqueredBy.conqueror.type == "eternal" or selectedNode.conqueredBy.conqueror.type == "templar" then self.build.spec:NodeAdditionOrReplacementFromString(selectedNode, modDesc, true) selectedNode.dn = newLegionNode.dn selectedNode.sprites = newLegionNode.sprites selectedNode.icon = newLegionNode.icon selectedNode.spriteId = newLegionNode.id elseif selectedNode.conqueredBy.conqueror.type == "vaal" then selectedNode.dn = newLegionNode.dn selectedNode.sprites = newLegionNode.sprites selectedNode.icon = newLegionNode.icon selectedNode.spriteId = newLegionNode.id if modDesc ~= "" then self.specList[1]:NodeAdditionOrReplacementFromString(selectedNode, modDesc, true) end -- Vaal is the exception local i = 2 while controls[i] do modDesc = string.gsub(controls[i].label, "%^7", "") if modDesc ~= "" then self.specList[1]:NodeAdditionOrReplacementFromString(selectedNode, modDesc, false) end i = i + 1 end else -- Replace the node first before adding the new line so we don't get multiple lines if self.build.spec.tree.legion.editedNodes[selectedNode.conqueredBy.id] and self.build.spec.tree.legion.editedNodes[selectedNode.conqueredBy.id][selectedNode.id] then self.build.spec:ReplaceNode(selectedNode, self.build.spec.tree.nodes[selectedNode.id]) end self.build.spec:NodeAdditionOrReplacementFromString(selectedNode, modDesc, false) end self.build.spec:ReconnectNodeToClassStart(selectedNode) if not self.build.spec.tree.legion.editedNodes[selectedNode.conqueredBy.id] then t_insert(self.build.spec.tree.legion.editedNodes, selectedNode.conqueredBy.id, {}) end t_insert(self.build.spec.tree.legion.editedNodes[selectedNode.conqueredBy.id], selectedNode.id, copyTable(selectedNode, true)) end local function constructUI(modGroup) local totalHeight = 43 local i = 1 while controls[i] or controls["slider"..i] do controls[i] = nil controls["slider"..i] = nil i = i + 1 end -- special handling for custom vaal notables (Might of the Vaal and Legacy of the Vaal) if next(modGroup.descriptions) == nil then for idx=1,4 do controls[idx] = new("EditControl", {"TOPLEFT", controls["slider"..idx-1] or controls[idx-1] or controls.modSelect,"TOPLEFT"}, 0, 20, 600, 16, "", "Modifier "..idx, "%c%(%)", 100, function(buf) controls[idx].label = buf end) controls[idx].label = "" totalHeight = totalHeight + 20 end else for idx, desc in ipairs(modGroup.descriptions) do controls[idx] = new("LabelControl", {"TOPLEFT", controls["slider"..idx-1] or controls[idx-1] or controls.modSelect,"TOPLEFT"}, 0, 20, 600, 16, "^7"..desc) totalHeight = totalHeight + 20 if desc:match("%(%-?[%d%.]+%-[%d%.]+%)") then controls["slider"..idx] = new("SliderControl", {"TOPLEFT",controls[idx],"BOTTOMLEFT"}, 0, 2, 300, 16, function(val) controls[idx].label = itemLib.applyRange(modGroup.descriptions[idx], val) end) controls["slider"..idx]:SetVal(.5) controls["slider"..idx].width = function() return controls["slider"..idx].divCount and 300 or 100 end totalHeight = totalHeight + 20 end end end main.popups[1].height = totalHeight + 30 controls.save.y = totalHeight controls.reset.y = totalHeight controls.close.y = totalHeight end buildMods(selectedNode) controls.modSelectLabel = new("LabelControl", {"TOPRIGHT",nil,"TOPLEFT"}, 150, 25, 0, 16, "^7Modifier:") controls.modSelect = new("DropDownControl", {"TOPLEFT",nil,"TOPLEFT"}, 155, 25, 579, 18, modGroups, function(idx) constructUI(modGroups[idx]) end) controls.modSelect.tooltipFunc = function(tooltip, mode, index, value) tooltip:Clear() if mode ~= "OUT" and value then for _, line in ipairs(value.descriptions) do tooltip:AddLine(16, "^7"..line) end end end controls.save = new("ButtonControl", nil, -90, 75, 80, 20, "Add", function() addModifier(selectedNode) self.modFlag = true self.build.buildFlag = true main:ClosePopup() end) controls.reset = new("ButtonControl", nil, 0, 75, 80, 20, "Reset Node", function() if self.build.spec.tree.legion.editedNodes[selectedNode.conqueredBy.id] then self.build.spec.tree.legion.editedNodes[selectedNode.conqueredBy.id][selectedNode.id] = nil end if selectedNode.conqueredBy.conqueror.type == "vaal" and selectedNode.type == "Normal" then local legionNode = self.build.spec.tree.legion.nodes["vaal_small_fire_resistance"] selectedNode.dn = "Vaal small node" selectedNode.sd = {"Right click to set mod"} selectedNode.sprites = legionNode.sprites selectedNode.mods = {""} selectedNode.modList = new("ModList") selectedNode.modKey = "" elseif selectedNode.conqueredBy.conqueror.type == "vaal" and selectedNode.type == "Notable" then local legionNode = self.build.spec.tree.legion.nodes["vaal_notable_curse_1"] selectedNode.dn = "Vaal notable node" selectedNode.sd = {"Right click to set mod"} selectedNode.sprites = legionNode.sprites selectedNode.mods = {""} selectedNode.modList = new("ModList") selectedNode.modKey = "" else self.build.spec:ReplaceNode(selectedNode, self.build.spec.tree.nodes[selectedNode.id]) if selectedNode.conqueredBy.conqueror.type == "templar" then self.build.spec:NodeAdditionOrReplacementFromString(selectedNode,"+5 to Devotion") end end self.modFlag = true self.build.buildFlag = true main:ClosePopup() end) controls.close = new("ButtonControl", nil, 90, 75, 80, 20, "Cancel", function() main:ClosePopup() end) main:OpenPopup(800, 105, "Replace Modifier of Node", controls, "save") constructUI(modGroups[1]) end function TreeTabClass:BuildPowerReportUI() self.controls.treeHeatMapStatSelect = new("DropDownControl", {"TOPLEFT",self.controls.powerReportList,"TOPRIGHT"}, 8, 0, 150, 20, nil, function(index, value) self.build.buildFlag = true self.build.calcsTab.powerBuildFlag = true self.build.calcsTab.powerStat = value self.controls.allocatedNodeToggle.enabled = false self.controls.allocatedNodeDistance.enabled = false self.controls.powerReportList.label = "Building table..." self.build.calcsTab:BuildPower({ func = self.TogglePowerReport, caller = self }) end) self.powerStatList = { } for _, stat in ipairs(data.powerStatList) do if not stat.ignoreForNodes then t_insert(self.powerStatList, stat) end end self.controls.powerReport.tooltipText = "A report of node efficacy based on current heat map selection" self.controls.allocatedNodeToggle = new("ButtonControl", {"TOPLEFT",self.controls.treeHeatMapStatSelect,"BOTTOMLEFT"}, 0, 4, 175, 20, "Show allocated nodes", function() self.controls.powerReportList.allocated = not self.controls.powerReportList.allocated self.controls.allocatedNodeDistance.shown = self.controls.powerReportList.allocated self.controls.allocatedNodeDistance.enabled = self.controls.powerReportList.allocated self.controls.allocatedNodeToggle.label = self.controls.powerReportList.allocated and "Show Unallocated Nodes" or "Show allocated nodes" self.controls.powerReportList.pathLength = tonumber(self.controls.allocatedNodeDistance.buf or 1) self.controls.powerReportList:ReList() end) self.controls.allocatedNodeDistance = new("EditControl", {"TOPLEFT",self.controls.allocatedNodeToggle,"BOTTOMLEFT"}, 0, 4, 125, 20, 1, "Max path", "%D", 100, function(buf) self.controls.powerReportList.pathLength = tonumber(buf) self.controls.powerReportList:ReList() end) end function TreeTabClass:TogglePowerReport(caller) self = self or caller self.controls.powerReport.label = self.viewer.showHeatMap and "Hide Power Report" or "Show Power Report" local currentStat = self.build.calcsTab and self.build.calcsTab.powerStat or nil local report = {} report = self:BuildPowerReportList(currentStat) self.controls.powerReportList = new("PowerReportListControl", {"TOPLEFT",self.controls.specSelect,"TOPLEFT"}, -2, 24, 700, 220, report, currentStat and currentStat.label or "", function(selectedNode) -- this code is called by the list control when the user "selects" one of the passives in the list. -- we use this to set a flag which causes the next Draw() to recenter the passive tree on the desired node. if selectedNode.x then self.jumpToNode = true self.jumpToX = selectedNode.x self.jumpToY = selectedNode.y end end) if not self.controls.treeHeatMapStatSelect then self:BuildPowerReportUI() end -- the report doesn't support listing the "offense/defense" hybrid heatmap, as it is not a single scalar and im unsure how to quantify numerically -- especially given the heatmap's current approach of using the sqrt() of both components. that number is cryptic to users, i suspect. if currentStat and currentStat.stat then self.controls.powerReportList.label = "Click to focus node on tree" self.controls.powerReportList.enabled = true else self.controls.powerReportList.label = "^7\"Offense/Defense\" not supported. Select a specific stat from the dropdown." self.controls.powerReportList.enabled = false end self.controls.allocatedNodeToggle.enabled = self.controls.powerReportList.enabled self.controls.allocatedNodeDistance.shown = self.controls.powerReportList.allocated self.controls.allocatedNodeToggle.label = self.controls.powerReportList.allocated and "Show Unallocated Nodes" or "Show allocated nodes" end function TreeTabClass:BuildPowerReportList(currentStat) local report = {} if not (currentStat and currentStat.stat) then return report end -- locate formatting information for the type of heat map being used. -- maybe a better place to find this? At the moment, it is the only place -- in the code that has this information in a tidy place. local displayStat = nil for index, ds in ipairs(self.build.displayStats) do if ds.stat == currentStat.stat then displayStat = ds break end end -- not every heat map has an associated "stat" in the displayStats table -- this is due to not every stat being displayed in the sidebar, I believe. -- But, we do want to use the formatting knowledge stored in that table rather than duplicating it here. -- If no corresponding stat is found, just default to a generic stat display (>0=good, one digit of precision). if not displayStat then displayStat = { fmt = ".1f" } end -- search all nodes, ignoring ascendcies, sockets, etc. for nodeId, node in pairs(self.build.spec.nodes) do local isAlloc = node.alloc or self.build.calcsTab.mainEnv.grantedPassives[nodeId] if (node.type == "Normal" or node.type == "Keystone" or node.type == "Notable") and not node.ascendancyName then local pathDist if isAlloc then pathDist = #(node.depends or { }) == 0 and 1 or #node.depends else pathDist = #(node.path or { }) == 0 and 1 or #node.path end local nodePower = (node.power.singleStat or 0) * ((displayStat.pc or displayStat.mod) and 100 or 1) local pathPower = (node.power.pathPower or 0) / pathDist * ((displayStat.pc or displayStat.mod) and 100 or 1) local nodePowerStr = s_format("%"..displayStat.fmt, nodePower) local pathPowerStr = s_format("%"..displayStat.fmt, pathPower) nodePowerStr = formatNumSep(nodePowerStr) pathPowerStr = formatNumSep(pathPowerStr) if (nodePower > 0 and not displayStat.lowerIsBetter) or (nodePower < 0 and displayStat.lowerIsBetter) then nodePowerStr = colorCodes.POSITIVE .. nodePowerStr elseif (nodePower < 0 and not displayStat.lowerIsBetter) or (nodePower > 0 and displayStat.lowerIsBetter) then nodePowerStr = colorCodes.NEGATIVE .. nodePowerStr end if (pathPower > 0 and not displayStat.lowerIsBetter) or (pathPower < 0 and displayStat.lowerIsBetter) then pathPowerStr = colorCodes.POSITIVE .. pathPowerStr elseif (pathPower < 0 and not displayStat.lowerIsBetter) or (pathPower > 0 and displayStat.lowerIsBetter) then pathPowerStr = colorCodes.NEGATIVE .. pathPowerStr end t_insert(report, { name = node.dn, power = nodePower, powerStr = nodePowerStr, pathPower = pathPower, pathPowerStr = pathPowerStr, allocated = isAlloc, id = node.id, x = node.x, y = node.y, type = node.type, pathDist = pathDist }) end end -- search all cluster notables and add to the list for nodeName, node in pairs(self.build.spec.tree.clusterNodeMap) do local isAlloc = node.alloc if not isAlloc then local nodePower = (node.power.singleStat or 0) * ((displayStat.pc or displayStat.mod) and 100 or 1) local nodePowerStr = s_format("%"..displayStat.fmt, nodePower) nodePowerStr = formatNumSep(nodePowerStr) if (nodePower > 0 and not displayStat.lowerIsBetter) or (nodePower < 0 and displayStat.lowerIsBetter) then nodePowerStr = colorCodes.POSITIVE .. nodePowerStr elseif (nodePower < 0 and not displayStat.lowerIsBetter) or (nodePower > 0 and displayStat.lowerIsBetter) then nodePowerStr = colorCodes.NEGATIVE .. nodePowerStr end t_insert(report, { name = node.dn, power = nodePower, powerStr = nodePowerStr, pathPower = 0, pathPowerStr = "--", id = node.id, type = node.type, pathDist = "Cluster" }) end end -- sort it if displayStat.lowerIsBetter then t_sort(report, function (a,b) return a.power < b.power end) else t_sort(report, function (a,b) return a.power > b.power end) end return report end
local Task = require 'CompileMe.task' local Command = require 'CompileMe.command' local Project = require 'CompileMe.project' local upfind = require 'CompileMe.upfind' local class = require 'CompileMe.class' local function dirname(x) return vim.fn.fnamemodify(x, ':h') end -- This is a wrapper class so we can use getters and setters local CMakeCompiler = class(function () end) -- Getters function CMakeCompiler:__index(index) if index == "build_dir" then if not Project.get_current().build_dir then Project.get_current().build_dir = 'build' end return Project.get_current().build_dir end if index == "lists_path" then local lists = upfind('CMakeLists.txt') return lists[#lists] end if index == "api_dir" then return dirname(self.lists_path) .. '/' .. self.build_dir .. '/.cmake/api/v1' end return rawget(self, index) end -- Setters function CMakeCompiler:__newindex(index, value) return rawset(self, index, value) end -- Project variables: -- build_dir: Name of the CMake build directory. Default: 'build' local cmake = CMakeCompiler() cmake.wait_for_api_reply = function () local timeout = 2 -- Wait this many seconds before timing out local start = os.time() while vim.fn.isdirectory(cmake.api_dir .. '/reply') ~= 1 do vim.cmd('sleep 100m') if os.time() >= start + timeout then error('Timeout waiting for cmake api reply') break end end end local write_query = function(query) vim.fn.mkdir(cmake.api_dir .. '/query/client-nvim', 'p') local file = io.open(cmake.api_dir .. '/query/client-nvim/query.json', 'w') file:write(vim.fn.json_encode(query)) file:close() end local get_executables = function() write_query{ requests = {{ kind = 'codemodel', version = 2 }} } if vim.fn.isdirectory(cmake.api_dir .. '/reply') ~= 1 then -- Touch cmakelists vim.fn.writefile(vim.fn.readfile(cmake.lists_path), cmake.lists_path) end local exe_list = {} local files_to_parse = vim.fn.glob(cmake.api_dir .. '/reply/target-*', 0, 1) local has_executables = false for _, file in pairs(files_to_parse) do local fp = io.open(file, 'r') local jsonData = {} for line in fp:lines() do table.insert(jsonData, line) end local reply = vim.fn.json_decode(table.concat(jsonData, "")) for _, v in pairs(reply.backtraceGraph.commands) do if v == 'add_executable' then has_executables = true break end end if has_executables then for _, artifact in pairs(reply.artifacts or {}) do if vim.fn.has('win32') > 0 then if artifact.path:find('.exe$') then table.insert(exe_list, artifact.path) end else table.insert(exe_list, artifact.path) end end end fp:close() end if not has_executables then return nil end exe_list = vim.fn.map(exe_list, function(_, v) return cmake.build_dir .. '/' .. v end) exe_list = vim.fn.filter(exe_list, function(_, v) return vim.fn.filereadable(v) end) local dir_sep = vim.fn.has('win32') ~= 1 and '/' or '\\' return vim.fn.map(exe_list, function(_, v) return v:gsub('/', dir_sep) end) end cmake.compile = function () local build = Command { args = {'cmake', '--build', cmake.build_dir}, working_directory = dirname(cmake.lists_path) } local configure = Command { args = {'cmake', '-B', cmake.build_dir}, working_directory = dirname(cmake.lists_path) } if vim.fn.isdirectory(dirname(cmake.lists_path) .. '/' .. cmake.build_dir) ~= 1 then return Task{configure, build} else return Task{build} end end cmake.run = function () local working_directory = dirname(cmake.lists_path) local executables = get_executables() local task = Task() if executables and #executables > 0 then for _, exe in pairs(executables) do local cmd = Command() cmd.args = {exe} cmd.working_directory = working_directory table.insert(task.commands, cmd) end else task.commands = { Command{ is_vim_command = true, args = {'lua', 'require(\'CompileMe.project\').get_current().compiler.wait_for_api_reply()'} }, Command{ is_vim_command = true, args = {'CompileMe', 'run'} } } end return task end cmake.compile_and_run = function () return cmake.compile() + cmake.run() end cmake.test = function () return Task { Command { args = {'cmake', '--build', cmake.build_dir, '--target', 'test'}, working_directory = dirname(cmake.lists_path) } } end local set_build_type = function(build_type) return Task{ Command { args = {'cmake', '-B', cmake.build_dir, '-DCMAKE_BUILD_TYPE=' .. build_type}, working_directory = dirname(cmake.lists_path) } } end cmake.release = function () return set_build_type('Release') end cmake.debug = function () return set_build_type('Debug') end cmake.rel_with_deb_info = function () return set_build_type('RelWithDebInfo') end cmake.min_size_rel = function () return set_build_type('MinSizeRel') end return cmake
local cursor = {} function cursor.set_stack(player, cursor_stack, player_table, item_name) local is_cheating = player.cheat_mode or (player.controller_type == defines.controllers.editor) local spawn_item = player_table.settings.spawn_items_when_cheating -- space exploration - don't spawn items when in the satellite view if script.active_mods["space-exploration"] and player.controller_type == defines.controllers.god then spawn_item = false end -- don't bother if they don't have an inventory local main_inventory = player.get_main_inventory() if main_inventory then -- set cursor stack local item_stack, item_stack_index, inventory_index for _, inventory in pairs{ main_inventory, player.get_inventory(defines.inventory.character_ammo), player.get_inventory(defines.inventory.character_guns) } do item_stack, item_stack_index = inventory.find_item_stack(item_name) if item_stack and item_stack.valid then inventory_index = inventory.index break end end if item_stack and item_stack.valid then if player.clear_cursor() then -- actually transfer from the source inventory, then set the hand location cursor_stack.transfer_stack(item_stack) player.hand_location = {inventory = inventory_index, slot = item_stack_index} end return true elseif spawn_item and is_cheating then local stack_spec = {name = item_name, count = game.item_prototypes[item_name].stack_size} -- insert into main inventory first, then transfer and set the hand location if main_inventory.can_insert(stack_spec) and player.clear_cursor() then main_inventory.insert(stack_spec) local new_stack, new_stack_index = main_inventory.find_item_stack(item_name) cursor_stack.transfer_stack(new_stack) player.hand_location = {inventory = main_inventory.index, slot = new_stack_index} else player.create_local_flying_text{ text = {"message.qis-main-inventory-full"}, create_at_cursor = true } player.play_sound{ path = "utility/cannot_build" } end return true elseif player.clear_cursor() then player_table.last_item = item_name player.cursor_ghost = item_name return true end end end return cursor
function love.conf(t) t.modules.audio = true t.modules.sound = true t.modules.keyboard = true t.modules.event = true t.modules.image = true t.modules.graphics = true t.modules.timer = true t.modules.thread = true t.modules.physics = true t.title = "Platformer training" t.window.fullscreen = false t.window.vsync = false t.window.fsaa = false t.window.width = 600 t.window.height = 512 end
--[[ module: DataAccessObjectTest author: DylanYang time: 2021-02-24 13:04:38 idea: For the current example, it is only running in simulation. advance: ]] local StudentDaoImpl = require("patterns.j2ee.dataAccessObject.StudentDaoImpl") local super = require("patterns.BaseTest") local _M = Class("DataAccessObjectTest", super) local public = _M.public function _M.protected:DoExecTest() local studentDao = StudentDaoImpl.new() --print all students for i, student in pairs(studentDao:GetAllStudents()) do print(string.format("Student: [RollNo : %s, Name : %s ]", student.rollNo, student.name)) end --update student local student =studentDao:GetAllStudents()[1] student.name = "Michael" --Emulation: From memory, update to database studentDao:UpdateStudent(student) --get student local student = studentDao:GetStudent(1) print(string.format("Student: [RollNo : %s, Name : %s ]", student.rollNo, student.name)) end return _M
local libos = require "libos" local utils = require "utils" -- file templates local TEMPLATE_BODY = [[ return { %s } ]] local TEMPLATE_LABEL = [[ { type = "label", id = %d, export = "default_label", width = 200, height = 100, font = "", align = 0, size = 16, color = 0xffffffff, noedge = true, }, ]] local TEMPLATE_PICTURE = [[ { type = "picture", id = %d, export = "%s", { tex = %d, src = { %d, %d, %d, %d, %d, %d, %d, %d }, screen = { %d, %d, %d, %d, %d, %d, %d, %d }, }, }, ]] local TEMPLATE_ANIMATION = [[ { type = "animation", id = %d, export = "%s", component = { %s }, %s }, ]] -- ejoy2d package local pkg_mt = {} pkg_mt.__index = pkg_mt function pkg_mt:add_img(img) table.insert(self.sheets, img) -- treat image as sheet with a single rect local item = {} item.type = "picture" item.id = self:_next_id() item.data = {#self.sheets, {0,0}, {img.w,img.h}, {img.ox,img.oy}} self.items[img.name] = item end function pkg_mt:add_sheet(sheet) table.insert(self.sheets, sheet) for _,v in ipairs(sheet.imgs) do local item = {} item.type = "picture" item.id = self:_next_id() item.data = {#self.sheets, v.pos, v.size, v.offset} -- texid, pos, size, offset self.items[v.name] = item end end function pkg_mt:add_anim(anim) -- image name sequence local item = {} item.type = "animation" item.id = self:_next_id() item.data = anim.actions -- frames self.items[anim.name] = item end function pkg_mt:save(path) -- save image sheet for i,v in ipairs(self.sheets) do local picture_path = string.format("%s/%s.%d", path, self.name, i) v:save(picture_path, false, self.fmt) end -- save description file local body = string.format(TEMPLATE_LABEL, self:_next_id()) for k,v in pairs(self.items) do if v.type == "picture" then body = body..self:_serialize_picture(v.id, k, v.data) end end for k,v in pairs(self.items) do if v.type == "animation" then body = body..self:_serialize_animation(v.id, k, v.data) end end local all = string.format(TEMPLATE_BODY, body) local lua_path = string.format("%s/%s.lua", path, self.name) libos:writefile(lua_path, all) utils:logf("ejoy2d package <%s> saved", self.name) end function pkg_mt:_serialize_picture(id, name, data) local pos = data[2] local size = data[3] local offset = data[4] local tex = data[1] local sl = pos[1] local sr = pos[1] + size[1] local st = pos[2] local sb = pos[2] + size[2] local dl = (-size[1]/2 + offset[1]) * 16 -- left = (-w/2 + ox) * 16 local dr = (size[1]/2 + offset[1]) * 16 local dt = (-size[2]/2 + offset[2]) * 16 local db = (size[2]/2 + offset[2]) * 16 return string.format(TEMPLATE_PICTURE, id, name, tex, sl, st, sl, sb, sr, sb, sr, st, dl, dt, dl, db, dr, db, dr, dt) end function pkg_mt:_serialize_animation(id, name, data) local com2idx = {} local idx2com = {} local str_a = "" -- action section for _,act in ipairs(data) do local frame_list = {} for _,frm in ipairs(act) do -- multiple frames in one action local com_list = {} for _,com in ipairs(frm) do -- multiple components in one frame if not com2idx[com.name] then table.insert(idx2com, com.name) com2idx[com.name] = #idx2com - 1 -- idx base 0 end local idx_only = true local str_com = string.format("{ index = %d, ", com2idx[com.name]) if com.scale or com.rot or com.trans then idx_only = false local mat = utils:create_matrix(com.scale, com.rot, com.trans) str_com = str_com..string.format("mat = { %d, %d, %d, %d, %d, %d }, ", mat[1], mat[2], mat[3], mat[4], mat[5], mat[6]) end if com.color then idx_only = false str_com = str_com..string.format("color = 0x%08x", com.color) end if com.additive then idx_only = false str_com = str_com..string.format("additive = 0x%08x", com.additive) end str_com = str_com.."}" if idx_only then table.insert(com_list, tostring(com2idx[com.name])) -- simple component without attributes else table.insert(com_list, str_com) end end local str_f = string.format("\t\t{ %s },", table.concat(com_list, ", ")) table.insert(frame_list, str_f) end str_a = string.format("\t{\n%s\n\t},", table.concat(frame_list, "\n")) end local str_c = "" -- component section for _,com in ipairs(idx2com) do local item = self.items[com] if item then str_c = string.format("%s\t\t{ id = %d, name = \"%s\" },\n", str_c, item.id, com) -- one component one line else str_c = string.format("%s\t\t{ name = \"%s\" },\n", str_c, com) -- anchor end end return string.format(TEMPLATE_ANIMATION, id, name, str_c, str_a) end function pkg_mt:_next_id() local ret = self._id self._id = self._id + 1 return ret end -- ejoy2d package module local M = {} function M:new_pkg(name, fmt) local pkg = {} pkg._id = 0 pkg.name = name pkg.fmt = fmt pkg.sheets = {} pkg.items = {} -- name:item return setmetatable(pkg, pkg_mt) end return M
------------------------------------------------------------------------------- -- Ɀeus' Enhanced Vita Snooper by ZeusOfTheCrows, based on work by Keinta15 -- -- Original work by Smoke5 -- ------------------------------------------------------------------------------- -- Initiating Sound Device Sound.init() -- init colors white = Color.new(235, 219, 178, 255) orange = Color.new(254, 128, 025, 255) red = Color.new(204, 036, 029, 255) green = Color.new(152, 151, 026, 255) grey = Color.new(189, 174, 147, 255) black = Color.new(040, 040, 040, 255) -- init images bgimg = Graphics.loadImage("app0:/resources/img/bgd.png") crossimg = Graphics.loadImage("app0:/resources/img/crs.png") squareimg = Graphics.loadImage("app0:/resources/img/sqr.png") circleimg = Graphics.loadImage("app0:/resources/img/ccl.png") triangleimg = Graphics.loadImage("app0:/resources/img/tri.png") sttselctimg = Graphics.loadImage("app0:/resources/img/ssl.png") homeimg = Graphics.loadImage("app0:/resources/img/hom.png") rtriggerimg = Graphics.loadImage("app0:/resources/img/rtr.png") ltriggerimg = Graphics.loadImage("app0:/resources/img/ltr.png") upimg = Graphics.loadImage("app0:/resources/img/dup.png") downimg = Graphics.loadImage("app0:/resources/img/ddn.png") leftimg = Graphics.loadImage("app0:/resources/img/dlf.png") rightimg = Graphics.loadImage("app0:/resources/img/drt.png") analogueimg = Graphics.loadImage("app0:/resources/img/anl.png") frontTouch = Graphics.loadImage("app0:/resources/img/gry.png") backTouch = Graphics.loadImage("app0:/resources/img/blu.png") -- offsets touch image to account for image size. should be half of resolution -- ztodo? could be automatic, see Graphics.getImageWidth/Height(img) -- x, y (arrays index from 1...) touchoffset = {30, 32} -- init font varwFont = Font.load("app0:/resources/fnt/fir-san-reg.ttf") monoFont = Font.load("app0:/resources/fnt/fir-cod-reg.ttf") Font.setPixelSizes(varwFont, 25) Font.setPixelSizes(monoFont, 25) -- loading sounds snd1 = Sound.openOgg("app0:/resources/snd/audio-test.ogg") hsnd1={hsnd1,hsnd1} -- init short button names cross = SCE_CTRL_CROSS square = SCE_CTRL_SQUARE circle = SCE_CTRL_CIRCLE triangle = SCE_CTRL_TRIANGLE start = SCE_CTRL_START select = SCE_CTRL_SELECT home = SCE_CTRL_PSBUTTON -- not used: can't get it to register if disabled rtrigger = SCE_CTRL_RTRIGGER ltrigger = SCE_CTRL_LTRIGGER up = SCE_CTRL_UP down = SCE_CTRL_DOWN left = SCE_CTRL_LEFT right = SCE_CTRL_RIGHT -- init vars to avoid nil lx, ly, rx, ry = 0.0, 0.0, 0.0, 0.0 lxmax, lymax, rxmax, rymax = 0.0, 0.0, 0.0, 0.0 -- homeButtonLocked = false ------------------------------ mini functions --------------------------------- -- func for padding numbers - to avoid jumping text function lPad(str, len, char) -- default arguments len = len or 5 -- 5 because of decimal point char = char or "0" str = tostring(str) if char == nil then char = '' end return string.rep(char, len - #str) .. str end -- func for calculating "max" of stick range from 0 function calcMax(currNum, currMax) num = math.abs(currNum - 127) max = math.abs(currMax) if num > max then return num else return max end end -- plays sound (i think) function soundTest() for s=1,2 do if hsnd1[s]==nil then hsnd1[s] = Sound.openOgg("app0:/resources/snd/audio-test.ogg") Sound.play(hsnd1[s],NOLOOP) break end end end ------------------------ monolithic functions --------------------------------- function drawInfo(pad) -- ui -- Starting drawing phase Graphics.initBlend() Screen.clear() -- programmatically colour background Graphics.fillRect(0, 960, 0, 544, black) Graphics.drawImage(0, 40, bgimg) -- Display info Font.print(varwFont, 008, 008, "Enhanced VPad Snooper v1.2.0 by ZeusOfTheCrows", orange) Font.print(varwFont, 205, 078, "Press Start + Select to exit", grey) Font.print(varwFont, 205, 103, "Press L + R to reset max stick range", grey) Font.print(varwFont, 205, 128, "Press X + O for Sound Test", grey) Font.print(varwFont, 205, 153, "Press Δ + Π for Gyro/Accelerometer [NYI]", grey) Font.print(monoFont, 720, 078, battpercent .. "%", battcolr) Font.print(monoFont, 010, 480, "Left: " .. lPad(lx) .. ", " .. lPad(ly) .. "\nMax: " .. lPad(lxmax) .. ", " .. lPad(lymax), white) Font.print(monoFont, 670, 482, "Right: " .. lPad(rx) .. ", " .. lPad(ry) .. "\nMax: " .. lPad(rxmax) .. ", " .. lPad(rymax), white) -- Screen.flip() --[[ bitmask 1 select 2 ? 4 ? 8 start 16 dpad up 32 dpad right 64 dpad down 128 dpad left 256 l trigger 512 r trigger 1024 2048 4096 triangle 8193 circle 16384 cross 32768 square ]] --- checks for input -- Draw and move left analog stick on screen Graphics.drawImage((74 + lx / 8), (254 + ly / 8), analogueimg) -- Graphics.drawImage((90), (270), analogueimg) -- Draw and move right analog on screen Graphics.drawImage((794 + rx / 8), (254 + ry / 8), analogueimg) -- Graphics.drawImage((810), (270), analogueimg) -- Draw face buttons if pressed if Controls.check(pad, circle) then Graphics.drawImage(888, 169, circleimg) end if Controls.check(pad, cross) then Graphics.drawImage(849, 207, crossimg) end if Controls.check(pad, triangle) then Graphics.drawImage(849, 130, triangleimg) end if Controls.check(pad, square) then Graphics.drawImage(812, 169, squareimg) end if Controls.check(pad, select) then Graphics.drawImage(807, 378, sttselctimg) end if Controls.check(pad, start) then Graphics.drawImage(858, 378, sttselctimg) end if Controls.check(pad, home) then Graphics.fillRect(0, 960, 0, 544, Color.new(0, 0, 0)) Graphics.drawImage(087, 376, homeimg) end if Controls.check(pad, ltrigger) then Graphics.drawImage(68, 43, ltriggerimg) end if Controls.check(pad, rtrigger) then Graphics.drawImage(775, 43, rtriggerimg) end -- Draw up directional button if pressed x113, y91 if Controls.check(pad, up) then Graphics.drawImage(77, 134, upimg) end -- Draw down directional button if pressed if Controls.check(pad, down) then --Graphics.drawRotateImage(94, 231, dpad, 3.14) -- couldn't make the intergers to work? I may be dumb Graphics.drawImage(77, 193, downimg) end -- Draw left directional button if pressed if Controls.check(pad, left) then --Graphics.drawRotateImage(65, 203, dpad, -1.57) -- couldn't make the intergers to work Graphics.drawImage(44, 167, leftimg) end -- Draw right directional button if pressed if Controls.check(pad, right) then --Graphics.drawRotateImage(123, 203, dpad, 1.57) -- couldn't make the intergers to work Graphics.drawImage(103, 167, rightimg) end -- Draw front touch on screen if tx1 ~= nil then Graphics.drawImage(tx1 - touchoffset[1], ty1 - touchoffset[2], frontTouch) end if tx2 ~= nil then Graphics.drawImage(tx2 - touchoffset[1], ty2 - touchoffset[2], frontTouch) end if tx3 ~= nil then Graphics.drawImage(tx3 - touchoffset[1], ty3 - touchoffset[2], frontTouch) end if tx4 ~= nil then Graphics.drawImage(tx4 - touchoffset[1], ty4 - touchoffset[2], frontTouch) end if tx5 ~= nil then Graphics.drawImage(tx5 - touchoffset[1], ty5 - touchoffset[2], frontTouch) end if tx6 ~= nil then Graphics.drawImage(tx6 - touchoffset[1], ty6 - touchoffset[2], frontTouch) end -- Draw rear touch on screen -- -50 and -56.5 added because image wasn't placed under finger if rtx1 ~= nil then Graphics.drawImage(rtx1 - touchoffset[1], rty1 - touchoffset[2], backTouch) end if rtx2 ~= nil then Graphics.drawImage(rtx2 - touchoffset[1], rty2 - touchoffset[2], backTouch) end if rtx3 ~= nil then Graphics.drawImage(rtx3 - touchoffset[1], rty3 - touchoffset[2], backTouch) end if rtx4 ~= nil then Graphics.drawImage(rtx4 - touchoffset[1], rty4 - touchoffset[2], backTouch) end -- Terminating drawing phase Screen.flip() Graphics.termBlend() end function handleControls(pad) -- reset stick max if Controls.check(pad, ltrigger) and Controls.check(pad, rtrigger) then lxmax, lymax, rxmax, rymax = 0.0, 0.0, 0.0, 0.0 end -- Sound Testing if Controls.check(pad, cross) and Controls.check(pad, circle) then soundTest() end if Controls.check(pad, start) and Controls.check(pad, select) then System.exit() end -- toggle homebutton lock (can't make it work) -- if Controls.check(pad, start) and Controls.check(pad, select) then -- if homeButtonLocked == false then -- -- lock home button and declare so -- homeButtonLocked = true -- Controls.lockHomeButton() -- else -- homeButtonLocked = false -- Controls.unlockHomeButton() -- end -- end end -- main loop while true do pad = Controls.read() -- init battery stats battpercent = System.getBatteryPercentage() if System.isBatteryCharging() then battcolr = green elseif battpercent < 15 then battcolr = red else battcolr = grey end -- update sticks lx,ly = Controls.readLeftAnalog() rx,ry = Controls.readRightAnalog() -- calculate max stick values lxmax = calcMax(lx, lxmax) lymax = calcMax(ly, lymax) rxmax = calcMax(rx, rxmax) rymax = calcMax(ry, rymax) -- init/update touch registration tx1, ty1, tx2, ty2, tx3, ty3, tx4, ty4, tx5, ty5, tx6, ty6 = Controls.readTouch() rtx1, rty1, rtx2, rty2, rtx4, rty4 = Controls.readRetroTouch() for i=1,2 do if hsnd1[i] and not Sound.isPlaying(hsnd1[i]) then Sound.close(hsnd1[i]) hsnd1[i]=nil end end handleControls(pad) drawInfo(pad) end
--- -- Timer utils module -- Added in API_VER:6 -- local skynet = require 'skynet' local class = require 'middleclass' local timer = class('FreeIOE_Lib_Utils_Timer') --- -- span --- Time span in seconds -- function timer:initialize(cb, span, integral_time) self._cb = cb self._span = span self._integral_time = integral_time end function timer:start() skynet.fork(function() --- Set the last time local span = self._span local now = skynet.time() local last_cb_time = now if self._integral_time then last_cb_time = (now // span) * span end --- Next time local next_cb_time = last_cb_time + self._span while not self._stop do skynet.sleep(math.floor((next_cb_time - skynet.time()) * 100), self) last_cb_time = next_cb_time next_cb_time = next_cb_time + self._span if self._cb then pcall(self._cb, last_cb_time) end end end) end function timer:stop() if not self._stop then self._stop = true skynet.wakeup(self) end end return timer
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local voices = { { text = 'Hmm, we should do something about your outfit.' }, { text = 'Ah, another adventurer. Let\'s talk a little.' }, { text = 'Psst! Come over here for a little trade.' }, { text = 'Hello, hello! Don\'t be shy, I don\'t bite.' }, { text = 'By the way, if you want to look at old hints again, find the \'Help\' button near your inventory and select \'Tutorial Hints\'.' } } npcHandler:addModule(VoiceModule:new(voices)) local function setNewTradeTable(table) local items, item = {} for i = 1, #table do item = table[i] items[item.id] = {itemId = item.id, buyPrice = item.buy, sellPrice = item.sell, subType = 0, realName = item.name} end return items end local function getTable() local itemsList = { {name="meat", id=2666, sell=2}, {name="ham", id=2671, sell=2}, } return itemsList end local storeTalkCid = {} local function greetCallback(cid) local player = Player(cid) if player:getStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage) < 1 then npcHandler:setMessage(MESSAGE_GREET, "Be greeted, |PLAYERNAME|! As a tailor and merchant I have to say - we need to do something about your {outfit}, shall we?") player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage, 1) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosQuestLog, 1) storeTalkCid[cid] = 1 elseif player:getStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage) == 1 then npcHandler:setMessage(MESSAGE_GREET, "Hey, I thought you were going to run away, but luckily you came back. I'll show you how to change your {outfit}, okay?") storeTalkCid[cid] = 1 elseif player:getStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage) == 2 then npcHandler:setMessage(MESSAGE_GREET, "Welcome back! You know, after providing my little outfit service, I like to ask a little favour of you. Can you {help} me?") storeTalkCid[cid] = 2 elseif player:getStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage) == 3 then npcHandler:setMessage(MESSAGE_GREET, "Oh hey |PLAYERNAME|, you didn't answer my question yet - could you help me get some {food}? I'll even give you some gold for it.") storeTalkCid[cid] = 3 elseif player:getStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage) == 4 then npcHandler:setMessage(MESSAGE_GREET, "Welcome back |PLAYERNAME|, I hope you changed your mind and will bring me some {meat}? I'll even give you some gold for it.") storeTalkCid[cid] = 4 elseif player:getStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage) == 5 then npcHandler:setMessage(MESSAGE_GREET, "Welcome back, |PLAYERNAME|! Did you have a successful hunt and carry a piece of {meat} or ham with you?") storeTalkCid[cid] = 5 elseif player:getStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage) == 6 then if player:getItemCount(2666) > 0 or player:getItemCount(2671) > 0 then npcHandler:setMessage(MESSAGE_GREET, "Welcome back, Isleth Eagonst! Do you still have that piece of meat or ham? If so, please ask me for a {trade} and I'll give you some gold for it.") storeTalkCid[cid] = 6 else npcHandler:setMessage(MESSAGE_GREET, "Welcome back, |PLAYERNAME|! Where did you put that delicious piece of food? Did you eat it yourself? Well, if you find another one, please come back.") npcHandler:releaseFocus(cid) npcHandler:resetNpc(cid) end elseif player:getStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage) == 7 then npcHandler:setMessage(MESSAGE_GREET, "Hey there, |PLAYERNAME|! Well, that's how trading with NPCs like me works. I think you are ready now to cross the bridge to Rookgaard! Take care!") player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosQuestLog, 7) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage, 8) npcHandler:releaseFocus(cid) npcHandler:resetNpc(cid) elseif player:getStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage) == 8 then npcHandler:setMessage(MESSAGE_GREET, "Hello again, |PLAYERNAME|! What are you still doing here? You should head over the bridge to Rookgaard village now!") npcHandler:releaseFocus(cid) npcHandler:resetNpc(cid) end return true end local function releasePlayer(cid) if not Player(cid) then return end npcHandler:releaseFocus(cid) npcHandler:resetNpc(cid) end local function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false end local player = Player(cid) if isInArray({"yes", "help", "ok"}, msg) then if storeTalkCid[cid] == 1 then npcHandler:say("Very well. Just choose an outfit and a colour combination that suits you. You can open this dialogue anytime by right-clicking on yourself and selecting 'Set Outfit'. Just try it and then talk to me again!", cid) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage, 2) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosQuestLog, 2) player:sendTutorial(12) npcHandler:releaseFocus(cid) npcHandler:resetNpc(cid) elseif storeTalkCid[cid] == 2 then npcHandler:say("You see, I'm quite hungry from standing here all day. Could you get me some {food}?", cid) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage, 3) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosQuestLog, 3) storeTalkCid[cid] = 3 elseif storeTalkCid[cid] == 3 then npcHandler:say("Thank you! I would do it myself, but I don't have a weapon. Just kill a few rabbits or deer, loot food from them and bring me one piece of {meat} or ham, will you?", cid) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage, 4) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosQuestLog, 4) storeTalkCid[cid] = 4 elseif storeTalkCid[cid] == 4 then npcHandler:say("Splendid. I'll be awaiting your return eagerly. Don't forget that you can click on the 'Chase Opponent' button to run after those fast creatures. Good {bye} for now!", cid) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage, 5) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosQuestLog, 5) npcHandler:releaseFocus(cid) npcHandler:resetNpc(cid) elseif storeTalkCid[cid] == 5 then if player:getItemCount(2666) > 0 or player:getItemCount(2671) > 0 then npcHandler:say("What's that delicious smell? That must be a piece of meat! Please hurry, simply ask me for a {trade} and I'll give you two gold pieces for it!", cid) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosQuestLog, 6) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage, 6) storeTalkCid[cid] = 6 else npcHandler:say("Hmm. No, I don't think you have something with you that I'd like to eat. Please come back once you looted a piece of meat or a piece of ham from a rabbit or deer.", cid) npcHandler:releaseFocus(cid) npcHandler:resetNpc(cid) end elseif storeTalkCid[cid] == 7 then npcHandler:say({ "Well, that's how trading with NPCs like me works. I think you are ready now to cross the bridge to Rookgaard, just follow the path to the northwest. Good luck, |PLAYERNAME|! ...", "And by the way: if you thought all of this was boring and you'd rather skip the tutorial with your next character, just say 'skip tutorial' to Santiago. ...", "Then you'll miss out on those nice items and experience though. Hehehe! It's your choice. Well, take care for now!" }, cid) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosQuestLog, 7) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage, 8) npcHandler:releaseFocus(cid) npcHandler:resetNpc(cid) end elseif msgcontains(msg, "outfit") then if storeTalkCid[cid] == 1 then npcHandler:say({ "Well, that's how trading with NPCs like me works. I think you are ready now to cross the bridge to Rookgaard, just follow the path to the northwest. Good luck, |PLAYERNAME|! ...", "And by the way: if you thought all of this was boring and you'd rather skip the tutorial with your next character, just say 'skip tutorial' to Santiago. ...", "Then you'll miss out on those nice items and experience though. Hehehe! It's your choice. Well, take care for now!" }, cid) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosQuestLog, 7) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage, 8) addEvent(releasePlayer, 1000, cid) end elseif msgcontains(msg, "trade") then if storeTalkCid[cid] == 6 then npcHandler:say("Very nice! Food for me! Sell it to me, fast! Once you sold your food to me, just say {ready} to let me know you are done.", cid) player:sendTutorial(13) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage, 7) storeTalkCid[cid] = 7 local items = setNewTradeTable(getTable()) local function onSell(cid, item, subType, amount, ignoreEquipped) if items[item].sellPrice then return player:removeItem(items[item].itemId, amount, -1, ignoreEquipped) and player:addMoney(items[item].sellPrice * amount) and player:sendTextMessage(MESSAGE_INFO_DESCR, 'You sold '..amount..'x '..items[item].realName..' for '..items[item].sellPrice * amount..' gold coins.') end return true end openShopWindow(cid, getTable(), onBuy, onSell) end elseif msgcontains(msg, "ready") then if storeTalkCid[cid] == 7 then npcHandler:say({ "Well, that's how trading with NPCs like me works. I think you are ready now to cross the bridge to Rookgaard, just follow the path to the northwest. Good luck, |PLAYERNAME|! ...", "And by the way: if you thought all of this was boring and you'd rather skip the tutorial with your next character, just say 'skip tutorial' to Santiago. ...", "Then you'll miss out on those nice items and experience though. Hehehe! It's your choice. Well, take care for now!" }, cid) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosQuestLog, 7) player:setStorageValue(Storage.RookgaardTutorialIsland.CarlosNpcGreetStorage, 8) addEvent(releasePlayer, 5000, cid) end end return true end local function onReleaseFocus(cid) storeTalkCid[cid] = nil end npcHandler:setCallback(CALLBACK_ONRELEASEFOCUS, onReleaseFocus) npcHandler:setCallback(CALLBACK_GREET, greetCallback) npcHandler:setMessage(MESSAGE_FAREWELL, "Good bye |PLAYERNAME|!.") npcHandler:setMessage(MESSAGE_WALKAWAY, "Good bye traveller and enjoy your stay on Rookgaard.") npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
require "control/window_manager.lua" require "control/movie_player_manager.lua" require "control/button_manager.lua" require "control/menu_manager.lua" require "control/toolbar_manager.lua" require "control/image_manager.lua" require "control/layout_manager.lua" require "control/listview_manager.lua" require "control/static_manager.lua" require "control/groupbox_manager.lua" require "control/checkbox_manager.lua" require "control/radiobutton_manager.lua" require "control/combobox_manager.lua" require "control/audio_player_manager.lua" require "control/graphic_text_manager.lua" -- 게임이 종료되고 있는 중인지 체크 local isClosing = false -- 시작 방식 설정 - true 면 오리지날 조조전 버전 local dialog = false DEBUG(true) function Start() local title = "三國志曺操傳" local mainSize = { Width = 640, Height = 400 } mainMenu = MenuManager:CreateMenu({MenuManager:CreateMenuItem({ Text = "파일", ChildItems = {MenuManager:CreateMenuItem({ Text = "불러오기", Enabled = false }), MenuManager:CreateMenuItem({ Text = "저장" }), MenuManager:CreateMenuItem({ Seperator = true }), MenuManager:CreateMenuItem({ Text = "종료", Event = { Click = function() main:Close() end } })} })}) -- 배경 이미지 생성 backgroundImage = ImageManager:CreateImage({ FilePath = "logo.me5", Image = { Group = "Logo", Item = 0 } }) -- 메인 Window 생성 main = WindowManager:Create({ Width = mainSize.Width, Height = mainSize.Height, Center = true, TitleName = title, BackgroundColor = { R = 0, G = 0, B = 0 }, Event = { MouseLButtonUp = function() -- 오프닝 동영상이 재생 중이면 멈춤 if openningMovie:IsPlaying() then openningMovie:Destroy() end -- 종료 중이면 Delay 없애기 if isClosing then gameManager:StopDelay() end end, Close = function() isClosing = true -- 종료 배경 이미지 생성 exitBackgroundImage = ImageManager:CreateImage({ FilePath = "logo.me5", Image = { Group = "Logo", Item = 1 } }) -- 레이아웃 생성 exitBackgroundLayout = LayoutManager:CreateLayout({}) exitBackgroundLayout:AddImage(exitBackgroundImage, 0, 0) -- 버튼 삭제 for i = 1, #mainDialogButtons do mainDialogButtons[i]:Destroy() end main:SetSize(exitBackgroundImage:Width(), exitBackgroundImage:Height()) main:Center() -- 배경 이미지 레이아웃 삭제, 종료 배경 이미지 레이아웃 추가 main:Clear() main:AddLayout(exitBackgroundLayout) -- 3초 딜레이 gameManager:Delay(3000) end, Destroy = function() -- 게임 종료 gameManager:Quit() end, Size = function(self, w, h) if backgroundLayout ~= nil and toolbar ~= nil then -- 크기 조절시 툴바 크기와 레이아웃 비율 변경 toolbar:AutoSize() ratioX = w / mainSize.Width ratioY = h / mainSize.Height backgroundLayout:SetRatioX(ratioX) backgroundLayout:SetRatioY(ratioY) if mainDialogButtons ~= nil then for i = 1, #mainDialogButtons do local changedWidth = mainDialogButtons.OriginalWidth * ratioX local changedHeight = mainDialogButtons.OriginalHeight * ratioY local changedX = mainDialogButtons.OriginalX * ratioX local index = tonumber(mainDialogButtons[i]:UserData()) local changedY = (mainDialogButtons.OriginalY + (index - 1) * mainDialogButtons.OriginalYGap) * ratioY mainDialogButtons[i]:Move(changedX, changedY) mainDialogButtons[i]:SetSize(changedWidth, changedHeight) end end end end }, Menu = mainMenu }) -- 종료 툴바 버튼 생성 exitToolbarButton = ToolbarManager:CreateToolbarButton({ Tooltip = "종료", Event = { Click = function() main:Close() end }, Image = ImageManager:CreateImage({ FilePath = "logo.me5", Image = { Group = 1, Item = 0 }, MaskColor = 0xC0C0C0 }), Enabled = false }) -- 툴바 생성 toolbar = ToolbarManager:CreateToolbar({ Parent = main, ImageSize = { Width = 24, Height = 28 }, Buttons = {exitToolbarButton, ToolbarManager:CreateToolbarButton({ Tooltip = "저장", Image = ImageManager:CreateImage({ FilePath = "logo.me5", Image = { Group = 1, Item = 1 }, MaskColor = 0xC0C0C0 }), Enabled = false }), ToolbarManager:CreateToolbarButton({ Tooltip = "불러오기", Image = ImageManager:CreateImage({ FilePath = "logo.me5", Image = { Group = 1, Item = 2 }, MaskColor = 0xC0C0C0 }), Enabled = false })}, Show = true }) -- 배경 이미지 레이아웃 생성 backgroundLayout = LayoutManager:CreateLayout({}) -- 메인 창 띄우기 main:Show() main:Center() -- 오프닝 동영상 생성 openningMovie = MoviePlayerManager:Create({ FileName = "LOGO.avi", Parent = main, Event = { End = function() end }, Center = true }) -- 재생 openningMovie:Play() -- 재생되는 동안 이 아래는 실행되지 않음 -- -- 동영상 종료된 후 종료 툴바 버튼 활성화 exitToolbarButton:Enable() -- 레이아웃에 이미지 추가 backgroundLayout:AddImage(backgroundImage, 0, 0) -- 레이아웃 추가 main:AddLayout(backgroundLayout) -- 오리지날 조조전 버전 if dialog then -- dialog 창 생성 mainDialog = WindowManager:Create({ Parent = main, Width = 202, Height = 142, TitleName = title, ControlBox = false, MinButton = false, MaxButton = false, BackgroundColor = { R = 0xF0, G = 0xF0, B = 0xF0 }, Center = true, Modal = true }) -- 버튼 생성 mainDialogButtons = { Text = {"새로운 게임을 시작한다", "저장 데이터를 불러온다", "환경 설정", "게임 종료"}, MouseLButtonUp = {nil, function() require "dialog/load_dialog.lua" end, function() require "dialog/config_dialog.lua" end, function() mainDialog:Close() main:Close() end} } for i = 1, 4 do mainDialogButtons[i] = ButtonManager:Create({ Parent = mainDialog, Text = mainDialogButtons.Text[i], TextColor = { Pushed = { R = 0xFF, G = 0x00, B = 0x00 } }, Width = 176, Height = 30, X = 12, Y = 11 + (i - 1) * 30, BorderWidth = 1, Transparent = false, Show = true, Event = { MouseLButtonUp = mainDialogButtons.MouseLButtonUp[i] } }) end -- Modal 창으로 띄움 mainDialog:ShowModalWindow() else -- 버튼 이미지 불러오기 mainDialogButtonImages = {} for i = 1, 8 do mainDialogButtonImages[i] = ImageManager:CreateImage({ FilePath = "logo.me5", Image = { Group = "TitleButton", Item = i - 1 } }) end buttonImageIndex = {-1, -1, -1, -1} buttonImageIndex[1] = backgroundLayout:AddImage(mainDialogButtonImages[1], 640, 28) buttonImageIndex[2] = backgroundLayout:AddImage(mainDialogButtonImages[3], 640, 98) buttonImageIndex[3] = backgroundLayout:AddImage(mainDialogButtonImages[5], 640, 168) buttonImageIndex[4] = backgroundLayout:AddImage(mainDialogButtonImages[7], 640, 238) -- 버튼 이미지 애니메이션 for i = 0, 550, 10 do if i <= 220 then backgroundLayout:MoveImage(buttonImageIndex[1], 640 - i, 28) end if i > 110 and i <= 330 then backgroundLayout:MoveImage(buttonImageIndex[2], 640 - (i - 110), 98) end if i > 220 and i <= 440 then backgroundLayout:MoveImage(buttonImageIndex[3], 640 - (i - 220), 168) end if i > 330 then backgroundLayout:MoveImage(buttonImageIndex[4], 640 - (i - 330), 238) end end -- 버튼 이벤트 설정 mainDialogButtons = { MouseLButtonUp = {function() -- 버튼 삭제 for i = 1, #mainDialogButtons do mainDialogButtons[i]:Destroy() end require "scenario/r00.lua" end, function() require "dialog/load_dialog.lua" end, function() require "dialog/config_dialog.lua" end, function() main:Close() end}, MouseEnter = function(self) local button = ButtonManager:CreateInstance(self) local index = tonumber(button:UserData()) backgroundLayout:DeleteImage(buttonImageIndex[index], false) buttonImageIndex[index] = backgroundLayout:AddImage(mainDialogButtonImages[index * 2], 420, 28 + (index - 1) * 70) end, MouseLeave = function(self) local button = ButtonManager:CreateInstance(self) local index = tonumber(button:UserData()) backgroundLayout:DeleteImage(buttonImageIndex[index], false) buttonImageIndex[index] = backgroundLayout:AddImage(mainDialogButtonImages[index * 2 - 1], 420, 28 + (index - 1) * 70) end, OriginalHeight = 44, OriginalWidth = 176, OriginalX = 420, OriginalY = 28, OriginalYGap = 70 } -- 버튼 생성 for i = 1, 4 do mainDialogButtons[i] = ButtonManager:Create({ Parent = main, Width = 176, Height = 44, X = 420, Y = 28 + (i - 1) * 70, BorderWidth = 0, Transparent = true, Show = true, Event = { MouseLButtonUp = mainDialogButtons.MouseLButtonUp[i], MouseEnter = mainDialogButtons.MouseEnter, MouseLeave = mainDialogButtons.MouseLeave }, UserData = tostring(i) }) end backgroupSound = AudioPlayerManager:LoadFromMe5File("sound.me5", { Group = "SoundTrack", Item = 0 }) backgroupSound:Play() end end Start()
function mixDrugs(drug1, drug2, drug1name, drug2name) -- 30 = Cannabis Sativa -- 31 = Cocaine Alkaloid -- 32 = Lysergic Acid -- 33 = Unprocessed PCP -- 34 = Cocaine -- 35 = Drug 2 -- 36 = Drug 3 -- 37 = Drug 4 -- 38 = Marijuana -- 39 = Drug 6 -- 40 = Drug 7 -- 41 = LSD -- 42 = Drug 9 -- 43 = Angel Dust local drugName local drugID if (drug1 == 31 and drug2 == 31) then -- Cocaine drugName = "Cocaine" drugID = 34 elseif (drug1==30 and drug2==31) or (drug1==31 and drug2==30) then -- Drug 2 drugName = "Drug 2" drugID = 35 elseif (drug1==32 and drug2==31) or (drug1==31 and drug2==32) then -- Drug 3 drugName = "Drug 3" drugID = 36 elseif (drug1==33 and drug2==31) or (drug1==31 and drug2==33) then -- Drug 4 drugName = "Drug 4" drugID = 37 elseif (drug1==30 and drug2==30) then -- Marijuana drugName = "Marijuana" drugID = 38 elseif (drug1==30 and drug2==32) or (drug1==32 and drug2==30) then -- Drug 6 drugName = "Drug 6" drugID = 39 elseif (drug1==30 and drug2==33) or (drug1==33 and drug2==30) then -- Drug 7 drugName = "Drug 7" drugID = 40 elseif (drug1==32 and drug2==32) then -- LSD drugName = "LSD" drugID = 41 elseif (drug1==32 and drug2==33) or (drug1==33 and drug2==32) then -- Drug 9 drugName = "Drug 9" drugID = 42 elseif (drug1==33 and drug2==33) then -- Angel Dust drugName = "Angel Dust" drugID = 43 end if (drugName == nil or drugID == nil) then outputChatBox("Error #1000 - Report on http://bugs.valhallagaming.net", source, 255, 0, 0) return end exports.global:takeItem(source, drug1) exports.global:takeItem(source, drug2) local given = exports.global:giveItem(source, drugID, 1) if (given) then outputChatBox("You mixed '" .. drug1name .. "' and '" .. drug2name .. "' to form '" .. drugName .. "'", source) exports.global:sendLocalMeAction(source, "mixes some chemicals together.") else outputChatBox("You do not have enough space to mix these chemicals.", source, 255, 0, 0) exports.global:giveItem(source, drug1, 1) exports.global:giveItem(source, drug2, 1) end end addEvent("mixDrugs", true) addEventHandler("mixDrugs", getRootElement(), mixDrugs) function raidForChemicals(thePlayer) local logged = getElementData(thePlayer, "loggedin") if (logged==1) then local raided = getElementData(thePlayer, "raided") if not (raided) or (raided==0) then local x, y, z = getElementPosition(thePlayer) local colShape = createColSphere(x, y, z, 5) local vehicles = getElementsWithinColShape(colShape, "vehicle") local found = false for key, value in ipairs(vehicles) do if (getElementModel(value)==416) then local locked = isVehicleLocked(value) found = true if (locked) then outputChatBox("You try to enter the ambulance, but find it is locked.", thePlayer, 255, 0, 0) exports.global:sendLocalMeAction(thePlayer, "attempts to enter the back of the ambulance.") else setElementData(thePlayer, "raided", 1) setTimer(setElementData, 300000, 1, thePlayer, "raided", 0) local rand1 = math.random(30, 33) local rand2 = math.random(30, 33) local given1 = exports.global:giveItem(thePlayer, rand1, 1) local given2 = exports.global:giveItem(thePlayer, rand2, 1) if (given1) or (given2) then outputChatBox("You broke into the back of the ambulance and stole some chemicals.", thePlayer, 0, 255, 0) exports.global:sendLocalMeAction(thePlayer, "enters the back of the ambulance and steals some chemicals.") elseif not (given1) and not (given2) then outputChatBox("You do not have enough space to take those items.", thePlayer, 255, 0, 0) exports.global:sendLocalMeAction(thePlayer, "enters the back of the ambulance and attempts to steal some chemicals but drops them.") end end break end end if not (found) then outputChatBox("You are too far away.", thePlayer, 255, 0, 0) end else outputChatBox("Please wait before raiding again.", thePlayer, 255, 0, 0) end end end --addCommandHandler("raid", raidForChemicals, false, false)
#!@path_to_lua@/lua -- -*- lua -*- ----------------------------------------------------------------- -- addto: Add to a path like environment variable. -- -- Standard usage is Bash: -- -- $ unset FOO -- $ export FOO=$(addto --append FOO a b c) -- $ echo " FOO: %$FOO%" -- FOO: %a:b:c% -- $ export FOO=$(addto --append FOO d e f); echo " FOO: %$FOO%" -- FOO: %a:b:c:d:e:f% -- @script addto -------------------------------------------------------------------------- -- Lmod License -------------------------------------------------------------------------- -- -- Lmod is licensed under the terms of the MIT license reproduced below. -- This means that Lmod is free software and can be used for both academic -- and commercial purposes at absolutely no cost. -- -- ---------------------------------------------------------------------- -- -- Copyright (C) 2008-2018 Robert McLay -- -- 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 sys_lua_path = "@sys_lua_path@" if (sys_lua_path:sub(1,1) == "@") then sys_lua_path = package.path end local sys_lua_cpath = "@sys_lua_cpath@" if (sys_lua_cpath:sub(1,1) == "@") then sys_lua_cpath = package.cpath end package.path = sys_lua_path package.cpath = sys_lua_cpath local arg_0 = arg[0] _G._DEBUG = false local posix = require("posix") local readlink = posix.readlink local stat = posix.stat local st = stat(arg_0) while (st.type == "link") do local lnk = readlink(arg_0) if (arg_0:find("/") and (lnk:find("^/") == nil)) then local dir = arg_0:gsub("/[^/]*$","") lnk = dir .. "/" .. lnk end arg_0 = lnk st = stat(arg_0) end local ia,ja = arg_0:find(".*/") local cmd_dir = "./" if (ia) then cmd_dir = arg_0:sub(1,ja) end package.path = cmd_dir .. "../tools/?.lua;" .. cmd_dir .. "../tools/?/init.lua;" .. cmd_dir .. "?.lua;" .. sys_lua_path package.cpath = cmd_dir .. "../lib/?.so;".. sys_lua_cpath require("strict") require("string_utils") require("pairsByKeys") local lfs = require("lfs") local Optiks = require("Optiks") local s_masterTbl = {} function cmdDir() return cmd_dir end function masterTbl() return s_masterTbl end function isDir(d) if (d == nil) then return false end local attr = lfs.attributes(d) return (attr and attr.mode == "directory") end function myInsert(appendFlg, existFlg) local insert = table.insert if (appendFlg) then if (existFlg) then return function (arr, v) if (isDir(v)) then insert(arr, v) end end else return function (arr, v) insert(arr, v) end end else if (existFlg) then return function (arr, v) if (isDir(v)) then insert(arr, 1, v) end end else return function (arr, v) insert(arr, 1, v) end end end end function myClean(cleanFlg) if (cleanFlg) then return function (path) path = path:gsub('//','/') if (path:sub(-1,-1) == '/') then path = path:sub(1,-2) end if (path == "") then path = false end return path end else return function (path) if (path == "") then path = false end return path end end end function myChkDir(existFlg) if (existFlg) then return function(path) return isDir(path) end else return function(path) return true end end end function main() local remove = table.remove local concat = table.concat local envVarA = {} ------------------------------------------------------------------------ -- evaluate command line arguments options() local masterTbl = masterTbl() local pargs = masterTbl.pargs local cleanFlg = masterTbl.cleanFlg local sep = masterTbl.sep local envVar = os.getenv(pargs[1]) local insert = myInsert(masterTbl.appendFlg, masterTbl.existFlg) local cleanPath = myClean(cleanFlg) local chkDir = myChkDir(masterTbl.existFlg) remove(pargs,1) local function build_array(s,A) if (s == ":") then A[#A + 1] = false else for path in s:split(':') do A[#A+1] = cleanPath(path) end end end ------------------------------------------------------------------------ -- Convert empty string input values into false and clean path if requested -- Also separate colons into separate arguments local valueA = {} for j = 1,#pargs do build_array(pargs[j], valueA) end ------------------------------------------------------------------------ -- Convert empty string envVar values into false and clean path if requested if (envVar) then build_array(envVar, envVarA) end ------------------------------------------------------------------------ -- Make a hash table of input values local valueT = {} for j = 1, #valueA do valueT[valueA[j]] = true end ------------------------------------------------------------------------ -- Remove any entries in input from envVarA local newA = {} for j = 1, #envVarA do local v = envVarA[j] if (not valueT[v]) then if (v == false) then v = "" end newA[#newA+1] = v end end ------------------------------------------------------------------------ -- Insert/append new entries with magic insert function. for j = 1, #valueA do local v = valueA[j] if (v == false) then v = "" end insert(newA, v) end io.stdout:write(concat(newA,sep),"\n") end function options() local masterTbl = masterTbl() local usage = "Usage: addto [options] envVar path1 path2 ..." local cmdlineParser = Optiks:new{usage=usage, version="1.0"} cmdlineParser:add_option{ name = {'-v','--verbose'}, dest = 'verbosityLevel', action = 'count', } cmdlineParser:add_option{ name = {'--append'}, dest = 'appendFlg', action = 'store_true', default = false, } cmdlineParser:add_option{ name = {'-e', '--exist', '--exists'}, dest = 'existFlg', action = 'store_true', default = false, } cmdlineParser:add_option{ name = {'-d', '--delete'}, dest = 'delete', action = 'store', default = nil, } cmdlineParser:add_option{ name = {'--clean'}, dest = 'cleanFlg', action = 'store_true', default = false, help = "Remove extra '/'s" } cmdlineParser:add_option{ name = {'--sep'}, dest = 'sep', action = 'store', default = ":", help = "separator (default is ':')" } local optionTbl, pargs = cmdlineParser:parse(arg) for v in pairs(optionTbl) do masterTbl[v] = optionTbl[v] end masterTbl.pargs = pargs end main()
#!/bin/sh _=[[ . "${0%%/*}/regress.sh" exec runlua "$0" "$@" ]] require"regress".export".*" local co = coroutine.create(function() coroutine.yield() end) coroutine.resume(co) -- kick off coroutine coroutine.resume(co) -- resume a yield with no arguments local status = coroutine.status(co) check(status == "dead", "expected dead coroutine (got %q)", status) local cq = require"cqueues".new() cq:attach(co) cq:step() -- previously would trigger C assert and abort process say"OK"
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB local S = E:GetModule('Skins') --Lua functions local _G = _G --WoW API / Variables local function MirrorTimer_OnUpdate(frame, elapsed) if frame.paused then return end if frame.timeSinceUpdate >= 0.3 then local minutes = frame.value/60 local seconds = frame.value%60 local text = frame.label:GetText() if frame.value > 0 then frame.TimerText:SetFormattedText("%s (%d:%02d)", text, minutes, seconds) else frame.TimerText:SetFormattedText("%s (0:00)", text) end frame.timeSinceUpdate = 0 else frame.timeSinceUpdate = frame.timeSinceUpdate + elapsed end end local function LoadSkin() if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.mirrorTimers ~= true then return end --Mirror Timers (Underwater Breath etc.), credit to Azilroka for i = 1, _G.MIRRORTIMER_NUMTIMERS do local mirrorTimer = _G['MirrorTimer'..i] local statusBar = _G['MirrorTimer'..i..'StatusBar'] local text = _G['MirrorTimer'..i.."Text"] mirrorTimer:StripTextures() mirrorTimer:Size(222, 18) mirrorTimer.label = text statusBar:SetStatusBarTexture(E.media.normTex) E:RegisterStatusBar(statusBar) statusBar:CreateBackdrop() statusBar:Size(222, 18) text:Hide() local TimerText = mirrorTimer:CreateFontString(nil, 'OVERLAY') TimerText:FontTemplate() TimerText:Point("CENTER", statusBar, "CENTER", 0, 0) mirrorTimer.TimerText = TimerText mirrorTimer.timeSinceUpdate = 0.3 --Make sure timer value updates right away on first show mirrorTimer:HookScript("OnUpdate", MirrorTimer_OnUpdate) E:CreateMover(mirrorTimer, "MirrorTimer"..i.."Mover", L["MirrorTimer"]..i, nil, nil, nil, "ALL,SOLO") end end S:AddCallback("MirrorTimers", LoadSkin)
weapon[1]={} weapon[1].impulse=200 weapon[1].recul=weapon[1].impulse weapon[1].bulletnumber=0 weapon[1].bulletnumbermax=10 weapon[1].reloadingmagazinetime=70 weapon[1].reloadingbullettime=10 weapon[1].density=0.7 weapon[1].width=0.5*meter weapon[1].height=0.3*meter weapon[1].magazine=5 weapon[1].bullet={} weapon[1].shoot = function ( x,y,orientation) local i=weapon[1].bulletnumber weapon[1].bullet[i]={} weapon[1].bullet[i].body=love.physics.newBody( world, x, y, "dynamic") weapon[1].bullet[i].shape=love.physics.newRectangleShape(weapon[1].width,weapon[1].height) weapon[1].bullet[i].fixture=love.physics.newFixture(weapon[1].bullet[i].body,weapon[1].bullet[i].shape,weapon[1].density) weapon[1].bullet[i].fixture:setUserData("bullet") weapon[1].bullet[i].fixture:setCategory(3) weapon[1].bullet[i].body:setBullet(true) weapon[1].bullet[i].draw=function() if weapon[1].bullet[i].body:isActive() then love.graphics.setColor(10,10,10) love.graphics.polygon("fill",weapon[1].bullet[i].body:getWorldPoints(weapon[1].bullet[i].shape:getPoints())) end end weapon[1].bullet[i].body:applyLinearImpulse(orientation*weapon[1].impulse,0) weapon[1].bulletnumber=weapon[1].bulletnumber+1%32 end weapon[1].trigger = nil weapon[1].trigger = function(character) local o = character.orientation local angle = character.body:getAngle() local x=character.body:getX() local y=character.body:getY() if character.charge then character.body:applyLinearImpulse(-weapon[1].recul*o,0,x+math.sin(angle),y-math.cos(angle)) -- à changer avec la position de l'arme ou pas weapon[1].shoot(x+o*character.height*1.5,y,o) character.magazine=character.magazine-1 character.charge=false character.reloading=0 end end weapon[1].update=nil weapon[1].update=function(character) if not character.charge then character.reloading=character.reloading+1 if character.magazine==0 then if character.reloading>weapon[1].reloadingmagazinetime then character.charge=true character.magazine=weapon[1].magazine end else if character.reloading>weapon[1].reloadingbullettime then character.charge=true end end end end
--[[ @file Main.lua @brief lullbc testsuite entry file. if you want to run the testsuite, please lua executable/library files and lullbc library files to this file directory. --]] -- Import lullbc library(set to _G), default test use release version -- library, if you want to use debug version library to run testsuite, -- !!!!!!!!please changed to `llbc = require 'llbc_debug'`!!!!!!!! llbc = require 'llbc' -- Import all common module testcases. local TestCase_Com_VerInfo = require 'common.testcase_com_verInfo' local TestCase_Com_MonkeyPatch = require 'common.testcase_com_monkey_patch' local TestCase_Com_ObjectOriented = require 'common.testcase_com_object_oriented' -- Import all core module testcases. local TestCase_Core_Log = require 'core.log.testcase_core_log' local TestCase_Core_Timer = require 'core.timer.testcase_core_timer' local TestCase_Core_Thread = require 'core.thread.testcase_core_thread' local TestCase_Core_Helper_GUID= require 'core.helper.testcase_core_helper_guid' local TestCase_Core_Utils_Util_Func = require 'core.utils.testcase_core_utils_util_func' local TestCase_Core_Utils_Util_Table = require 'core.utils.testcase_core_utils_util_table' local TestCase_Core_Utils_Util_String = require 'core.utils.testcase_core_utils_util_string' -- Import all communication module testcases. -- ... ... local function Main(...) -- Startup llbc. llbc.startup() -- All common module testcases. TestCase_Com_VerInfo.run(...) -- TestCase_Com_MonkeyPatch.run(...) -- TestCase_Com_ObjectOriented.run(...) -- All core module testcases... -- TestCase_Core_Log.run(...) -- TestCase_Core_Timer.run(...) -- TestCase_Core_Thread.run() -- TestCase_Core_Helper_GUID.run(...) -- TestCase_Core_Utils_Util_Func.run(...) -- TestCase_Core_Utils_Util_Table.run(...) -- TestCase_Core_Utils_Util_String.run(...) -- All communication module testcases... -- ... ... -- Cleanup llbc. llbc.cleanup() end Main(...)
local lu = require 'luaunit' local openssl = require 'openssl' local crl, csr = openssl.x509.crl, openssl.x509.req TestCRL = {} function TestCRL:setUp() self.alg = 'sha1' self.cadn = openssl.x509.name.new({{commonName = 'CA'}, {C = 'CN'}}) self.dn = openssl.x509.name.new({{commonName = 'DEMO'}, {C = 'CN'}}) self.digest = 'sha1WithRSAEncryption' end function TestCRL:testNew() local pkey = assert(openssl.pkey.new()) local req = assert(csr.new(self.cadn, pkey)) local t = req:parse() lu.assertEquals(type(t), 'table') local cacert = openssl.x509.new(1, -- serialNumber req -- copy name and extensions ) cacert:validat(os.time(), os.time() + 3600 * 24 * 365) assert(cacert:sign(pkey, cacert)) -- self sign lu.assertEquals(cacert:subject(), cacert:issuer()) local list = assert(crl.new({ {sn = 1, time = os.time()}, {sn = 2, time = os.time()}, {sn = 3, time = os.time()}, {sn = 4, time = os.time()} }, cacert, pkey)) assert(#list == 4) -- print_r(list:parse()) local other = crl.new() assert(other:issuer(cacert:issuer())) assert(other:version(0)) assert(other:updateTime(50000000)) assert(other:lastUpdate(os.time())) assert(other:nextUpdate(os.time() + 50000000)) assert(other:add('21234', os.time())) assert(other:add('31234', os.time())) assert(other:add('41234', os.time())) assert(other:add('11234', os.time())) assert(other:sign(pkey, cacert)) assert(other:verify(cacert)) assert(other:export()) t = other:get(0) lu.assertIsTable(t) end function TestCRL:testRead() local dat = [[ -----BEGIN X509 CRL----- MIIBNDCBnjANBgkqhkiG9w0BAQIFADBFMSEwHwYDVQQKExhFdXJvcGVhbiBJQ0Ut VEVMIFByb2plY3QxIDAeBgNVBAsTF0NlcnRpZmljYXRpb24gQXV0aG9yaXR5Fw05 NzA2MDkxNDQyNDNaFw05NzA3MDkxNDQyNDNaMCgwEgIBChcNOTcwMzAzMTQ0MjU0 WjASAgEJFw05NjEwMDIxMjI5MjdaMA0GCSqGSIb3DQEBAgUAA4GBAH4vgWo2Tej/ i7kbiw4Imd30If91iosjClNpBFwvwUDBclPEeMuYimHbLOk4H8Nofc0fw11+U/IO KSNouUDcqG7B64oY7c4SXKn+i1MWOb5OJiWeodX3TehHjBlyWzoNMWCnYA8XqFP1 mOKp8Jla1BibEZf14+/HqCi2hnZUiEXh -----END X509 CRL----- ]] local r = crl.read(dat) lu.assertIsTable(r:parse()) -- print_r(r:parse()) local e = r:export() lu.assertEquals(e, dat) e = r:export('der') local r1 = crl.read(e) assert(r:cmp(r1) == (r == r1)) assert(r == r1) lu.assertEquals(r:version(), 0) lu.assertEquals(r:issuer():tostring(), '/O=European ICE-TEL Project/OU=Certification Authority') lu.assertEquals(r:lastUpdate():toprint(), 'Jun 9 14:42:43 1997 GMT') lu.assertEquals(r:nextUpdate():toprint(), 'Jul 9 14:42:43 1997 GMT') lu.assertEquals(r:extensions(), nil) local l, n = r:updateTime() lu.assertEquals(r:lastUpdate(), l) lu.assertEquals(r:nextUpdate(), n) lu.assertEquals(r:count(), #r) lu.assertEquals(#r, 2) end
local U = require("lib.Utils") local Class = require("lib.Class") local Vector2 = require("lib.Vector2") local Button = Class:derive("Button") local function mouse_in_bounds(self, mx, my) return mx >= self.pos.x - self.w / 2 and mx <= self.pos.x + self.w / 2 and my >= self.pos.y - self.h / 2 and my <= self.pos.y + self.h / 2 end function Button:new(x, y, w, h, text) self.pos = Vector2(x or 0, y or 0) self.w = w self.h = h self.text = text --Button Colors self.normal = U.color(0.5, 0.125, 0.125, 0.75) self.highlight = U.color(0.75, 0.125, 0.125, 1) self.pressed = U.color(1, 0.125, 0.125, 1) self.disabled = U.gray(0.5, 0.5) --Text colors self.text_normal = U.color(1) self.text_disabled = U.gray(0.5, 1) self.text_color = self.text_normal self.color = self.normal self.prev_left_click = false self.interactible = true end function Button:text_colors(normal, disabled) assert(type(normal) == "table", "normal parameter must be a table!") assert(type(disabled) == "table", "disabled parameter must be a table!") self.text_normal = normal self.text_disabled = disabled end function Button:colors(normal, highlight, pressed, disabled) assert(type(normal) == "table", "normal parameter must be a table!") assert(type(highlight) == "table", "highlight parameter must be a table!") assert(type(pressed) == "table", "pressed parameter must be a table!") --assert(type(disabled) == "table", "disabled parameter must be a table!") self.normal = normal self.highlight = highlight self.pressed = pressed self.disabled = disabled or self.disabled end --Set the left position of the button -- function Button:left(x) self.pos.x = x + self.w / 2 end --Set the top position of the button -- function Button:top(y) self.pos.y = y + self.h / 2 end function Button:enable(enabled) self.interactible = enabled if not enabled then self.color = self.disabled self.text_color = self.text_disabled else self.text_color = self.text_normal end end function Button:update(dt) if not self.interactible then return end local mx, my = love.mouse.getPosition() local left_click = love.mouse.isDown(1) local in_bounds = mouse_in_bounds(self, mx, my) if in_bounds and not left_click then if self.prev_left_click and self.color == self.pressed then _G.events:invoke("onBtnClick", self) end self.color = self.highlight elseif in_bounds and left_click and not self.prev_left_click then self.color = self.pressed elseif not in_bounds then self.color = self.normal end self.prev_left_click = left_click end function Button:draw() -- love.graphics.line(self.pos.x, self.pos.y - self.h / 2, self.pos.x, self.pos.y + self.h / 2) -- love.graphics.line(self.pos.x - self.w / 2, self.pos.y, self.pos.x + self.w / 2, self.pos.y) local r, g, b, a = love.graphics.getColor() love.graphics.setColor(self.color) love.graphics.rectangle("fill", self.pos.x - self.w / 2, self.pos.y - self.h / 2, self.w, self.h, 4, 4) local f = love.graphics.getFont() local _, lines = f:getWrap(self.text, self.w) local fh = f:getHeight() love.graphics.setColor(self.text_color) love.graphics.printf(self.text, self.pos.x - self.w / 2, self.pos.y - (fh /2 * #lines), self.w, "center") love.graphics.setColor(r, g, b, a) end return Button
-- loads the map local composer = require( "composer" ) local scene = composer.newScene() -- ----------------------------------------------------------------------------------- -- Code outside of the scene event functions below will only be executed ONCE unless -- the scene is removed entirely (not recycled) via "composer.removeScene()" -- ----------------------------------------------------------------------------------- enemyCount = 0 enemyCountDisplay:removeSelf() enemyCountDisplay = display.newText(enemyCount, 40, 40, native.systemFont, 30) playerHP = playerHP + 3 if(playerHP > 10) then playerHP = 10 end -- ----------------------------------------------------------------------------------- -- Scene event functions -- ----------------------------------------------------------------------------------- function changeLevelToCredits ( event ) roomNumber = "Room Credits" displayRoom.alpha = 0 composer.gotoScene( "scenes.credits" ) composer.removeScene("scenes.level6") end -- create() function scene:create( event ) local sceneGroup = self.view -- Code here runs when the scene is first created but has not yet appeared on screen --position the map in the center end -- show() function scene:show( event ) local widget = require "widget" local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Code here runs when the scene is still off screen (but is about to come on screen) elseif ( phase == "did" ) then -- Code here runs when the scene is entirely on screen map = display.newImage(sceneGroup, "graphics/maps/credits.png") map.xScale = 1 map.yScale = 1 map.x = 0 map.y = 0 map:toBack() local exitButton2 = display.newImageRect("graphics/menu/ExitButton.png", 497, 200) exitButton2.x = 0 exitButton2.y = 500 exitButton2:addEventListener("tap" , closeapp) myPlayer.x = 0 myPlayer.y = 0 MouseX = 0 MouseY = 0 camera.x = ((myPlayer.x) + (MouseX / 3)) - 215 --camera x value camera.y = ((myPlayer.y) + (MouseY / 3)) - 230 --camera y value grappleCooldown = false grappleFinished = true CurrentVelocityX = 0 CurrentVelocityY = 0 myPlayer:setLinearVelocity(CurrentVelocityX, CurrentVelocityY) --variable map is stored/loaded into cameraGroup = display.currentStage myPlayer:toBack() myPlayerMovementSpeed = 0 --create enemies here --function to set alpha channels local z = 0 --Outer walls and myName is the collision identifier local wallsHitbox = display.newGroup() --insert walls here end end -- hide() function scene:hide( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Code here runs when the scene is on screen (but is about to go off screen) -- loads the map elseif ( phase == "did" ) then -- Code here runs immediately after the scene goes entirely off screen end end -- destroy() function scene:destroy( event ) local sceneGroup = self.view -- Code here runs prior to the removal of scene's view end -- ----------------------------------------------------------------------------------- -- Scene event function listeners -- ----------------------------------------------------------------------------------- scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) -- ----------------------------------------------------------------------------------- return scene
#!/usr/bin/env luajit local ffi = require 'ffi' local unistd = require 'ffi.c.unistd' require 'ffi.c.stdlib' local dirp = unistd.getcwd(nil, 0) local dir = ffi.string(dirp) ffi.C.free(dirp) -- chdir to the base -- (another alternative would be to execute this script from the base) -- I think that's what the Relativity project did unistd.chdir'../..' local table = require 'ext.table' local class = require 'ext.class' -- global cmdline = {sys='console'} local cols = table() local rows = table() for _,info in ipairs{ {'fe', 'forward Euler'}, {'rk4', 'Runge-Kutta 4'}, {'be', 'backward Euler'}, } do local suffix, integrator= table.unpack(info) local f = io.open(dir..'/var-ranges-'..suffix..'.txt', 'w') local App = class(require 'hydro.app') function App:setup() --local solver = require 'hydro.solver.z4c-fd'{ local solver = require 'hydro.solver.bssnok-fd'{ app = self, dim = 2, coord = 'cartesian', mins = {-1, -1, -1}, maxs = {1, 1, 1}, gridSize = {16, 16, 16}, initState = 'Alcubierre warp bubble', integrator = integrator, } self.solvers:insert(solver) -- start the solver off self.running = true self.exitTime = .5 -- track var system -- is currently intertwined with the display system self.trackVars = table() for _,var in ipairs(solver.displayVars) do if var.name:sub(1,2) == 'U ' -- seems to be crashing when reducing vector fields ... and not var.vectorField then self.trackVars:insert(var) end end -- initialize what variables to track f:write'#t' for _,var in ipairs(self.trackVars) do f:write('\t',var.name..'_min') f:write('\t',var.name..'_max') f:write('\t',var.name..'_avg') end f:write'\n' f:flush() end function App:update() App.super.update(self) -- also TODO - make dumpFile more modular -- with headers and getters local solver = self.solvers[1] f:write(solver.t) for _,var in ipairs(self.trackVars) do local ymin, ymax, yavg = solver:calcDisplayVarRangeAndAvg(var) f:write(('\t%.16e'):format(ymin)) f:write(('\t%.16e'):format(ymax)) f:write(('\t%.16e'):format(yavg)) end f:write'\n' f:flush() end App():run() f:close() end print'done!'
--[[ STEAL MY SHIT AND I'LL FUCK YOU UP PRETTY MUCH EVERYTHING BY MAURICE GU�GAN AND IF SOMETHING ISN'T BY ME THEN IT SHOULD BE OBVIOUS OR NOBODY CARES Please keep in mind that for obvious reasons, I do not hold the rights to artwork, audio or trademarked elements of the game. This license only applies to the code and original other assets. Obviously. Duh. Anyway, enjoy. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 Copyright (C) 2004 Sam Hocevar <[email protected]> Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO.]] --[[ ----------------------------------------------------------------------------- "AWESOME" mod by Alesan99 OTHER COOL DUDES -Maurice and Fakeuser for regular turrets -Hans1998 for the banzai bill sprite -Automatik for helping me with the poison mushroom -Superjustinbros for some sprites -Qcode for some code and advice -Trosh for raccoon sprites from SE -Galas for power up sprites -Bobthelawyer for mario's hammer physics code -KGK64 for Dry beetle sprites -Skysometric for animated quad cache code from Mari0 SE Community Edtion -Oxiriar and Toonn from the Mari0 Gang Discord for smb3 item sprites -NH1507 for toad and toadette character sprites -HansAgain for new portal sprites, new mario sprites, and pneumatic tubes -Subpixel for bowser3, rotodiscs, ninji, and splunkin sprites -Critfish for overgrown portal sprites -Aidan for general bugtesting and misc. contributions on github -MadNyle for propeller sound effect and mega mushroom -fußmatte for helping create a TON of new characters for the font and Esperanto Translation -HugoBDesigner for Portugese-Br translation -Los for Russian Translation -William and Kant for contributions on github ----------------------------------------------------------------------------- ]] local debugconsole = false --debug if debugconsole then debuginputon = true; debuginput = "print()"; print("DEBUG ON") end local debugGraph,fpsGraph,memGraph,drawGraph local debugGraphs = false VERSION = 13.0122 VERSIONSTRING = "13d (11/4/21)" android = (love.system.getOS() == "Android" or love.system.getOS() == "iOS") --[DROID] androidtest = false--testing android on pc local updatesoundlist local loadingbarv = 0 --0-1 local loadingbardraw = function(add) love.graphics.clear() love.graphics.push() if android then love.graphics.scale(winwidth/(width*16*scale), winheight/(224*scale)) end love.graphics.setColor(150, 150, 150) properprint("loading mari0..", ((width*16)*scale)/2-string.len("loading mari0..")*4*scale, 20*scale) love.graphics.setColor(50, 50, 50) local scale2 = scale if scale2 <= 1 then scale2 = 0.5 else scale2 = 1 end properprint(loadingtext, ((width*16)*scale)/2-string.len(loadingtext)*4*scale, ((height*16)*scale)/2+165*scale2) if FamilyFriendly then love.graphics.setColor(255, 255, 255) properprint("stys.eu", ((width*16)*scale)/2-string.len("stys.eu")*4*scale, 110*scale) else love.graphics.setColor(255, 255, 255) love.graphics.draw(logo, ((width*16)*scale)/2, ((height*16)*scale)/2, 0, scale2, scale2, 142, 150) end loadingbarv = loadingbarv + (add)/(8) love.graphics.setColor(255,255,255) love.graphics.rectangle("fill", 0, (height*16-3)*scale, (width*16*loadingbarv)*scale, 3*scale) love.graphics.pop() love.graphics.present() end function love.load() loadingbarv = 0 marioversion = 1006 versionstring = "version 1.6" shaderlist = love.filesystem.getDirectoryItems( "shaders/" ) dlclist = {"dlc_a_portal_tribute", "dlc_acid_trip", "dlc_escape_the_lab", "dlc_scienceandstuff", "dlc_smb2J", "dlc_the_untitled_game"} magicdns_session_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" magicdns_session = "" for i = 1, 8 do rand = math.random(string.len(magicdns_session_chars)) magicdns_session = magicdns_session .. string.sub(magicdns_session_chars, rand, rand) end --use love.filesystem.getIdentity() when it works magicdns_identity = love.filesystem.getSaveDirectory():split("/") magicdns_identity = string.upper(magicdns_identity[#magicdns_identity]) local rem for i, v in pairs(shaderlist) do if v == "init.lua" then rem = i else shaderlist[i] = string.sub(v, 1, string.len(v)-5) end end table.remove(shaderlist, rem) table.insert(shaderlist, 1, "none") currentshaderi1 = 1 currentshaderi2 = 1 if android and not androidtest then love.filesystem.setIdentity("mari0_android") --[DROID] else love.filesystem.setIdentity("mari0") end local ok, result = pcall(loadconfig) if not ok then print("Corrupt settings: " .. tostring(result)) players = 1 defaultconfig() end saveconfig() if fourbythree then width = 16 else width = 25 end height = 14 --? fsaa = 0 fullscreen = false if scale == 2 and resizable then changescale(5, fullscreen) else changescale(scale, fullscreen) end love.window.setTitle( "Mari0: AE" ) --version check by checking for a const that was added in 0.8.0 if love._version_major == nil then error("You have an outdated version of Love! Get 0.10.0 or higher and retry.") end love.window.setIcon(love.image.newImageData("graphics/icon.png")) love.graphics.setDefaultFilter("nearest") love.graphics.setBackgroundColor(0, 0, 0) logo = love.graphics.newImage("graphics/stabyourself.png") --deleted later to save memory logoblood = love.graphics.newImage("graphics/stabyourselfblood.png") --UTF8 Font fontimage = love.graphics.newImage("graphics/SMB/font.png") fontbackimage = love.graphics.newImage("graphics/SMB/fontback.png") font = love.graphics.newFont("font.fnt", "graphics/SMB/font.png") fontback = love.graphics.newFont("font.fnt", "graphics/SMB/fontback.png") fontCAP = love.graphics.newFont("fontcap.fnt", "graphics/SMB/font.png") fontbackCAP = love.graphics.newFont("fontcap.fnt", "graphics/SMB/fontback.png") --gamefont = font --gamefontback = fontback --gamefontCAP = fontCAP --gamefontbackCAp = fontbackCAP love.graphics.setFont(font) utf8 = require("utf8") local t = require("libs/utf8_simple") utf8.chars = t.chars utf8.sub = t.sub fontglyphs = [[ ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 ⇒←→↑↓ .!?,:;'"-_+=><#%&*()[]{}/\ @©~¡¿°^$£€¥ ÁÂÀÄÅÃÆÇÉÊÈËÍÎÌÏÑÓÔÒÖÕØŒÚÛ ÙÜŠÝŸẞÞÐĆŃŚŹĄĘŁĈĜĤĴŜŬŽİŞƏĞ áâàäåãæçéêèëíîìïñóôòöõøœúû ùüšýÿßþðćńśźąęłĉĝĥĵŝŭžışəğ АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШ ЩЪЫЬЭЮЯ№«»„ абвгдеёжзийклмнопрстуфхцчш щъыьэюя ]] fontglyphs = fontglyphs:gsub(" ","") fontquads = {} fontquadsback = {} fontindexCAP = {} --all uppercase fontindexOLD = {} --old font with all uppercase and U=up D=down A=, B=- --local out = string.format("chars count=%s\n", utf8.len(fontglyphs:gsub("\n",""))) --Export font.fnt (doesn't) local s = fontglyphs:split("\n") for line = 1, #s do for i, c, b in utf8.chars(s[line]) do fontquads[c] = love.graphics.newQuad((i-1)*10+1, (line-1)*10+1, 8, 8, fontimage:getWidth(),fontimage:getHeight()) fontquadsback[c] = love.graphics.newQuad((i-1)*10, (line-1)*10, 10, 10, fontimage:getWidth(),fontimage:getHeight()) --UPPER CASE local ci = c if line == 2 then ci = utf8.sub(s[1],i,i) elseif line == 8 or line == 9 then ci = utf8.sub(s[line-2],i,i) elseif line == 12 or line == 13 then ci = utf8.sub(s[line-2],i,i) end fontindexCAP[c] = ci --export font.fnt layout --out = out .. string.format("char id=%d x=%d y=%d width=10 height=10 xoffset=-1 yoffset=0 xadvance=8 page=0 chnl=15\n", utf8.codepoint(c), (i-1)*10, (line-1)*10) --Capitals --local qx,qy = fontquads[ci]:getViewport() --out = out .. string.format("char id=%d x=%d y=%d width=10 height=10 xoffset=-1 yoffset=0 xadvance=8 page=0 chnl=15\n", utf8.codepoint(c), qx-1,qy-1) end end --love.system.setClipboardText(out) fontindexCAP["{"] = "←" fontindexCAP["}"] = "→" for j, w in pairs(fontindexCAP) do fontindexOLD[j] = w end fontindexOLD["A"] = "," fontindexOLD["B"] = "-" fontindexOLD["D"] = "↓" fontindexOLD["U"] = "↑" if love.filesystem.exists("alesans_entities/familyfriendly.txt") then FamilyFriendly = true end math.randomseed(os.time());math.random();math.random() --intro loadingtexts = {"reticulating splines", "rendering important stuff", "01110000011011110110111001111001", "sometimes, i dream about cheese", "baking cake", "happy explosion day", "raising coolness by a fifth", "yay facepunch", "stabbing myself", "sharpening knives", "tanaka, thai kick", "loading game genie..", "slime will find you", "becoming self-aware", "it's a secret to everybody", "there is no minus world", "oh my god, jc, a bomb", "silly loading message here", "motivational art by jorichi", "you're my favorite deputy", "licensed under wtfpl", "banned in australia", "loading anti-piracy module", "watch out there's a sni", "attack while its tail's up!", "what a horrible night to have a curse", "han shot first", "establishing connection to nsa servers..","how do i programm", "making palette inaccurate..", "y cant mario crawl?", "please hold..", "avoiding lawsuits", "loading bugs", "traduciendo a ingles", "fixign typo..", "swing your arms", "this message will self destruct in 3 2 1", "preparing deadly neurotoxin", "loading asleons entetis..", "now with online multiplayer", "any second now..", "all according to keikaku", "we need pow blocks!", "cross your fingers", "not accurate to the nes!", "improved stability to enhance user experience.", "0118 999 881 999 119 7253", "hoo-ray", "removing herobrine", "how do i play multiplayer????", "not mario maker", "hello there", "this statement is false", "zap to the extreme", "it just works", "eat your arms", "travelling qpus...", "im a tire", "in real life!", "bold and brash", "giant enemy crabs", "but im super duper, with a big tuper", "see that mountain? you can climb it", "loading alesan99's stuff"} loadingtext = loadingtexts[math.random(#loadingtexts)] loadingbardraw(1) --require ALL the files! require "shaders" require "spriteloader" require "variables" require "class" require "sha1" require "netplay" JSON = require "JSON" require "notice" require "languages" local luas = {"intro", "menu", "levelscreen", "game", "editor", "physics", "online", "quad", "animatedquad", "entity", "dailychallenge", "portalwall", "tile", "mario", "mushroom", "hatconfigs", "flower", "star", "coinblockanimation", "scrollingscore", "platform", "platformspawner", "portalparticle", "portalprojectile", "box", "emancipationgrill", "door", "button", "groundlight", "wallindicator", "walltimer", "lightbridge", "faithplate", "laser", "laserdetector", "gel", "geldispenser", "cubedispenser", "pushbutton", "screenboundary", "fireball", "gui", "blockdebris", "firework", "vine", "spring", "seesaw", "seesawplatform", "bubble", "rainboom", "miniblock", "notgate", "musicloader", "smbsitem", "donut", "levelball", "leaf", "mariotail", "windleaf", "energylauncher", "energycatcher", "blocktogglebutton", "squarewave", "delayer", "coin", "funnel", "longfire", "pedestal", "portalent", "text", "regiontrigger", "tiletool", "enemytool", "randomizer", "yoshi", "musicchanger", "mariohammer", "regiondrag", "flipblock", "characters", "checkpoint", "onlinemenu", "lobby", "magic", "doorsprite", "enemies", "enemy", "itemanimation", "cappy", "emancipationfizzle", "emancipateanimation", "ceilblocker", "belt", "hatloader", "poof", "animationguiline", "animation", "animationsystem", "animationtrigger", "dialogbox", "portal", "orgate", "andgate", "animatedtiletrigger", "rsflipflop", "animatedtimer", "collectable", "powblock", "smallspring", "risingwater", "redseesaw", "snakeblock", "frozencoin", "entitytooltip", "spawnanimation", "camerastop", "clearpipe", "track", "tilemoving", "laserfield", "checkpointflag", "ice", "pipe", "errorwindow"} for i = 1, #luas do require(luas[i]) end print("done loading .luas!") loadingbardraw(1) local enemyluas = love.filesystem.getDirectoryItems("enemies") for i = 1, #enemyluas do require("enemies/" .. enemyluas[i]:sub(1, enemyluas[i]:len()-4)) end print("done loading enemies!") loadingbardraw(1) --json error window JSONcrashgame = true jsonerrorwindow = errorwindow:new("","") --internet connection http = require("socket.http") http.TIMEOUT = 1 credited = true http.TIMEOUT = 7 graphicspack = "SMB" --SMB, ALLSTARS playertypei = 1 playertype = playertypelist[playertypei] --portal, minecraft if volume == 0 then soundenabled = false else soundenabled = true end love.filesystem.createDirectory("mappacks") love.filesystem.createDirectory("alesans_entities") love.filesystem.createDirectory("alesans_entities/mappacks") love.filesystem.createDirectory("alesans_entities/onlinemappacks") love.filesystem.createDirectory("alesans_entities/characters") love.filesystem.createDirectory("alesans_entities/hats") --[[copy included zip dlcs to save folder (because of course you can't mount from source directory :/) local zips = love.filesystem.getDirectoryItems("alesans_entities/dlc_mappacks") if #zips > 0 then for j, w in pairs(zips) do if not love.filesystem.exists("alesans_entities/onlinemappacks/" .. w) then local filedata = love.filesystem.newFileData("alesans_entities/dlc_mappacks/" .. w) love.filesystem.write("alesans_entities/onlinemappacks/" .. w, filedata) if j == 1 and not love.filesystem.exists("alesans_entities/onlinemappacks/" .. w) then break end end end end]] --mount dlc zip files if onlinedlc then local zips = love.filesystem.getDirectoryItems("alesans_entities/onlinemappacks") if #zips > 0 then for j, w in pairs(zips) do mountmappack(w) end end end if checkmappack and love.filesystem.exists(mappackfolder .. "/" .. checkmappack .. "/") then mappack = checkmappack checkmappack = nil saveconfig() end loadingbardraw(1) --check date for daily challenges datet = {os.date("%m"),os.date("%d"),os.date("%Y")} DChigh = {"-", "-", "-"} DChightemp = false if love.filesystem.exists("alesans_entities/dc.txt") then local s = love.filesystem.read("alesans_entities/dc.txt") local s2 = s:split("~") DCcompleted = tonumber(s2[1]) if s2[2] == datet[1] .. "/" .. datet[2] .. "/" .. datet[3] then DChigh[1] = "finished" DChightemp = true end else DCcompleted = 0 end DCchalobjective = select(2, getdailychallenge()) DCchalobjectivet = {""} --wrap the text so it won't look ugly in the menu local splt = DCchalobjective:split(" ") local i = 1 while splt[i] do if (DCchalobjectivet[#DCchalobjectivet] .. splt[i] .. " "):len() <= 15 then DCchalobjectivet[#DCchalobjectivet] = DCchalobjectivet[#DCchalobjectivet] .. splt[i] .. " " i = i + 1 else table.insert(DCchalobjectivet, "") end end --nitpicks loadnitpicks() loadcustomplayers() editormode = false yoffset = 0 love.graphics.setPointSize(3*scale) love.graphics.setLineWidth(3*scale) uispace = math.floor(width*16*scale/4) guielements = {} --limit hats for playerno = 1, players do for i = 1, #mariohats[playerno] do if mariohats[playerno][i] > hatcount then mariohats[playerno][i] = hatcount end end end defaultcustomtext("initial") loadcustomtext() loadingbardraw(1) --custom players --loadplayer() --Backgroundcolors backgroundcolor = {} backgroundcolor[1] = {92, 148, 252} backgroundcolor[2] = {0, 0, 0} backgroundcolor[3] = {32, 56, 236} backgroundcolor[4] = {0, 0, 0} --custom --[[backgroundcolor[5] = {60, 188, 252} backgroundcolor[6] = {168, 228, 252} backgroundcolor[7] = {252, 216, 168} backgroundcolor[8] = {252, 188, 176} backgroundcolor[9] = {24, 60, 92}]] --IMAGES-- menuselectimg = love.graphics.newImage("graphics/" .. graphicspack .. "/menuselect.png") mappackback = love.graphics.newImage("graphics/GUI/mappackback.png") mappacknoicon = love.graphics.newImage("graphics/GUI/mappacknoicon.png") mappackonlineicon = love.graphics.newImage("graphics/GUI/mappackonlineicon.png") mappackloadingicon = love.graphics.newImage("graphics/GUI/mappackloading.png") mappackoverlay = love.graphics.newImage("graphics/GUI/mappackoverlay.png") mappackhighlight = love.graphics.newImage("graphics/GUI/mappackhighlight.png") mappackscrollbar = love.graphics.newImage("graphics/GUI/mappackscrollbar.png") uparrowimg = love.graphics.newImage("graphics/GUI/uparrow.png") downarrowimg = love.graphics.newImage("graphics/GUI/downarrow.png") customenemyiconimg = love.graphics.newImage("graphics/GUI/customenemy.png") pathmarkerimg = love.graphics.newImage("graphics/GUI/pathmarker.png") trackmarkerimg = love.graphics.newImage("graphics/GUI/trackmarker.png") antsimg = love.graphics.newImage("graphics/GUI/ants.png") markbaseimg = love.graphics.newImage("graphics/markbase.png") markoverlayimg = love.graphics.newImage("graphics/markoverlay.png") --tiles smbtilesimg = love.graphics.newImage("graphics/" .. graphicspack .. "/smbtiles.png") portaltilesimg = love.graphics.newImage("graphics/" .. graphicspack .. "/portaltiles.png") entitiesimg = love.graphics.newImage("graphics/" .. graphicspack .. "/entities.png") tilequads = {} rgblist = {} --add smb tiles loadtiles("smb", "initial") --add portal tiles loadtiles("portal", "initial") --add entities entityquads = {} loadtiles("entity", "initial") --formated entities list entitiesform = { {name = "level markers", 1,8,100,312,11, --erase and start 21,--[[161,]]31,--[[233,256,]]81, --pipes (possibly combine them later?) 257, --celing block (possibly camera block too?) 23,24,25, 89, 33,34, 95,96, 131,132, 159,160, --zones 35, --drag in 304,--camera stop }, {name = "platforming elements", 309,--[[18,19,]]32,41,--[[42,]]92,80,289, --platforms 258,137, --donut 148,278, --block like entities 266,287, --conveyors 290, --snake block 93,122,281,282, --springs 14,219,--vines 163,248,249,250, --doors 79,--[[82,]]265,191, 228, --fire 315, --grinder 285,164, --water 211,292,293, 178,208,279,179,180,--buttons 300,301, --helmet boxes 302,--clear pipe 306,--tracks! }, {name = "items", --[[297,]]2,3,101,4,187,296,5, --regulars 121,269,217,218,113, --smbs items 299,202,155,141,151,252,253,254,255,239,311,193,286,307,308, --new powerups 207, --yoshi 154, --? Ball }, {name = "enemies", 6,--[[9,]]103,114,237,118,--[[119,]] --goomba 7,--[[10,]]117,78,158,116, 12,--[[13,]]77, 156,--[[157,]] --koopa, red, blue 98,--[[99,]]263,261,115, --spiny 75,--[[76,]]209,262,130, --beetle 212,--[[213,]] --spiketop 70,102,123,124,147,149,129,305, --plants 15,120,241,138,221, --hammer bros 16,17,298,184, 94,162,242, --fishies (and bloopers) 22,83,264, 109,110, --lakitu and sun 188, --fuzzy 60,246,104,105,150,--[[192,]]303,145,--[[146,]] --bullets and military stuff 142,260,247, 111,--[[112,]]--boos and splunkins --[[125,]]224,283,284,234,259, 127,--[[128,]]288,126,133,--[[134,]]235,--[[236,]]135,136, 97, --castle stuffs 90,91,153,238,316,240, --bowser bosses 106,216,107,108,280, --smbs enemies 203,--[[204,]]140,214,215,--smb2 enemies 139,152,189,190, --flying beetles --[[143,]]314,144,223, --moles 220, 243, 244,251, 245, 294,295, --mario maker enemies 313, --super size }, {name = "i/o objects", 275,210,271,270,291,200,199,276,277,201,205}, {name = "gates", 30,74, --not really logic gates 84,274,273,186,272,185,206}, {name = "portal elements", 20,165,222, --cubes 40,267,268, 68,--[[69,]] --buttons 28,--[[29,]] --doors --[[26,]]27,--[[311,]] --emancipation and laserfield 36,--[[37,38,39,]] 52,--[[53,54,55,]] 56,--[[57,58,59,]] --lasers 43,44,45,46,47,48, --powerline 49,--[50,51,]] --faithplate 67, 61,--[[62,63, 64,65,66, 71,72,73, 181,182,183, 225,226,227,]] --dispensers 85,--[[86,87,88,]] --gel 166,--[[167,168,169,]] 170,--[[171,172,173,]] --energy launcher 174,--[[175, 176,177,]] 194, --turrets 195, --glados 196, 197,198, --portals 231,--[[229,230,232]] --funnels 310,--pneumatic tube (just clearpipe but shhh) }, {name = "custom enemies", }, } local namespacing = 10 local ly = 0 --listy for list = 1, #entitiesform do ly = ly + namespacing entitiesform[list].y = ly entitiesform[list].h = 17*(math.ceil(#entitiesform[list]/22)) ly = ly + entitiesform[list].h end --check if entities are missing because i'm stupid --[[local entitycheck = {} for i = 1, entitiescount do entitycheck[i] = 0 --false end for j, form in pairs(entitiesform) do for i = 1, #form do entitycheck[form[i] ] = entitycheck[form[i] ] + 1-- = true end end for j, w in pairs(entitycheck) do local s = w if s == 0 then s = "false" else s = "true " .. s end print(j .. " - " .. s) end]] --sledge bro shock shockimg = love.graphics.newImage("graphics/" .. graphicspack .. "/shock.png") shockquad = {} shockquad[1] = love.graphics.newQuad(0, 0, 4, 25, 8, 25) shockquad[2] = love.graphics.newQuad(4, 0, 4, 25, 8, 25) --if lights out mode isn't supported on device mariolightimg = love.graphics.newImage("graphics/" .. graphicspack .. "/mariolight.png") calendarimg = love.graphics.newImage("graphics/" .. graphicspack .. "/calendar.png") --menut tips menutips = {"resize the game window by changing the scale to 'resizable' in the options!", "download dlc mappacks by going to the dlc tab in the mappack menu!", "is there a problem with the mod? tell me at the stabyourself.net forums!", "there are currently about " .. math.floor(entitiescount-100) .. " new entities in this mod! try them out!", --"change your mappack folder to 'alesans_entities/mappacks' in the options to prevent crashes when you use unmodded mari0!", "lock your mouse with f12!", "display fps with f11!", "experienced an error? post your error found in 'mari0/alesans_entities/crashes' at the stabyourself.net forums!", "you can access the mari0 folder easily by pressing 'm' in the mappack selection menu!", "try out the dlc mappacks!", "try out today's daily challenge by going to the mappack selection menu and going to the 'daily challenge' tab!", "finish the super mario bros. mappack to unlock something special!", "turn on assist mode in the editor by pressing the +/equal sign key!", "play with friends online! press the left key to start!", "enter fullscreen with alt and enter.", "change your character in the settings!", "add more playable characters in the 'mari0/alesans_entities/characters' folder."} disabletips = false loadingbardraw(1) ------------------------------ ------------QUADS------------- ------------------------------ numberglyphs = "012458" font2quads = {} for i = 1, 6 do font2quads[string.sub(numberglyphs, i, i)] = love.graphics.newQuad((i-1)*4, 0, 4, 8, 32, 8) end directionsimg = love.graphics.newImage("graphics/GUI/directions.png") local directionquadnames = {"hor", "ver", "left", "up", "right", "down", "cw", "ccw", "left up", "right up", "left down", "right down"} directionsquad = {} for x = 1, #directionquadnames do directionsquad[directionquadnames[x]] = love.graphics.newQuad((x-1)*7, 0, 7, 7, #directionquadnames*7, 7) end pathmarkerquad = { love.graphics.newQuad(0, 0, 16, 16, 64, 48), love.graphics.newQuad(16, 0, 16, 16, 64, 48), love.graphics.newQuad(0, 16, 32, 16, 64, 48), love.graphics.newQuad(0, 32, 32, 16, 64, 48), love.graphics.newQuad(32, 16, 32, 32, 64, 48), } trackmarkerquad = { love.graphics.newQuad(0, 0, 16, 16, 64, 16), love.graphics.newQuad(16, 0, 16, 16, 64, 16), love.graphics.newQuad(32, 0, 16, 16, 64, 16), love.graphics.newQuad(48, 0, 16, 16, 64, 16), } linktoolpointerimg = love.graphics.newImage("graphics/GUI/linktoolpointer.png") local pipedirs = {"up", "left", "down", "right", "default", ""} pipesimg = love.graphics.newImage("graphics/GUI/pipes.png") pipesquad = {} for y = 1, 4 do pipesquad[y] = {} for x = 1, 6 do pipesquad[y][pipedirs[x]] = love.graphics.newQuad((x-1)*16, (y-1)*16, 16, 16, 96, 64) end end loadquads(true) --portals portalquad = {} for i = 0, 7 do portalquad[i] = love.graphics.newQuad(0, i*4, 32, 4, 32, 28) end --portals portal1quad = {} for i = 0, 7 do portal1quad[i] = love.graphics.newQuad(0, i*4, 32, 4, 64, 32) end portal2quad = {} for i = 0, 7 do portal2quad[i] = love.graphics.newQuad(32, i*4, 32, 4, 64, 32) end --Portal props pushbuttonquad = {} for y = 1, 4 do pushbuttonquad[y] = {} for x = 1, 2 do pushbuttonquad[y][x] = love.graphics.newQuad(16*(x-1), 16*(y-1), 16, 16, 32, 64) end end buttonquad = {} for y = 1, 4 do buttonquad[y] = {} for i = 1, 3 do buttonquad[y][i] = {} for x = 1, 2 do buttonquad[y][i][x] = love.graphics.newQuad(64*(i-1)+32*(x-1), 5*(y-1), 32, 5, 192, 20) end end end wallindicatorquad = {} for y = 1, 4 do wallindicatorquad[y] = {love.graphics.newQuad(0, 16*(y-1), 16, 16, 32, 64), love.graphics.newQuad(16, 16*(y-1), 16, 16, 32, 64)} end walltimerquad = {} for y = 1, 4 do walltimerquad[y] = {} for i = 1, 10 do walltimerquad[y][i] = love.graphics.newQuad((i-1)*16, (y-1)*16, 16, 16, 160, 64) end end excursionquad = {} for x = 1, 8 do excursionquad[x] = love.graphics.newQuad((x-1)*8, 0, 8, 32, 64, 32) end gelquad = {love.graphics.newQuad(0, 0, 12, 12, 36, 12), love.graphics.newQuad(12, 0, 12, 12, 36, 12), love.graphics.newQuad(24, 0, 12, 12, 36, 12)} --ground lights groundlightquad = {} for s = 1, 4 do groundlightquad[s] = {} for x = 1, 6 do groundlightquad[s][x] = {} for y = 1, 2 do groundlightquad[s][x][y] = love.graphics.newQuad((x-1)*16, (s-1)*32+(y-1)*16, 16, 16, 96, 128) end end end --turrets turretquad = {} for x = 1, 2 do turretquad[x] = love.graphics.newQuad((x-1)*12, 0, 12, 14, 24, 14) end --cube dispenser cubedispenserquad = {} for y = 1, 4 do cubedispenserquad[y] = love.graphics.newQuad(0, (y-1)*32, 32, 32, 32, 128) end --gel dispensers geldispenserquad = {} for y = 1, 4 do geldispenserquad[y] = {} for x = 1, 5 do geldispenserquad[y][x] = love.graphics.newQuad((x-1)*32, (y-1)*32, 32, 32, 160, 128) end end --faithplate faithplatequad = {} for y = 1, 4 do faithplatequad[y] = love.graphics.newQuad(0, (y-1)*16, 32, 16, 32, 32) end --laserdetector laserdetectorquad = {} for x = 1, 2 do laserdetectorquad[x] = love.graphics.newQuad((x-1)*16, 0, 16, 16, 32, 16) end --emanceside emancesidequad = {} for y = 1, 4 do emancesidequad[y] = {} for x = 1, 2 do emancesidequad[y][x] = love.graphics.newQuad((x-1)*5, (y-1)*8, 5, 8, 10, 32) end end --ice icequad = {} for i = 1, 9 do icequad[i] = love.graphics.newQuad((((i-1)%3))*8, math.floor(i/3-.1)*8, 8, 8, 24, 24) end bunnyearsimg = love.graphics.newImage("graphics/" .. graphicspack .. "/bunnyears.png") bunnyearsquad = {} for x = 1, 3 do bunnyearsquad[x] = love.graphics.newQuad((x-1)*15, 0, 15, 7, 30, 7) end capeimg = love.graphics.newImage("graphics/" .. graphicspack .. "/cape.png") capequad = {} for x = 1, 19 do capequad[x] = love.graphics.newQuad((x-1)*16, 0, 16, 34, 304, 34) end --eh rainboomquad = {} for x = 1, 7 do for y = 1, 7 do rainboomquad[x+(y-1)*7] = love.graphics.newQuad((x-1)*204, (y-1)*182, 204, 182, 1428, 1274) end end --magic! magicimg = love.graphics.newImage("graphics/magic.png") magicquad = {} for x = 1, 6 do magicquad[x] = love.graphics.newQuad((x-1)*9, 0, 9, 9, 54, 9) end --GUI checkboximg = love.graphics.newImage("graphics/GUI/checkbox.png") checkboxquad = {{love.graphics.newQuad(0, 0, 9, 9, 18, 18), love.graphics.newQuad(9, 0, 9, 9, 18, 18)}, {love.graphics.newQuad(0, 9, 9, 9, 18, 18), love.graphics.newQuad(9, 9, 9, 9, 18, 18)}} dropdownarrowimg = love.graphics.newImage("graphics/GUI/dropdownarrow.png") quickmenuarrowimg = love.graphics.newImage("graphics/GUI/quickmenuarrow.png") customimagebackimg = love.graphics.newImage("graphics/GUI/customimageback.png") tilepropertiesimg = love.graphics.newImage("graphics/tileproperties.png") mappackonlineiconquad = {} mappackonlineiconquad[1] = love.graphics.newQuad(0, 0, 50, 50, 64, 64) mappackonlineiconquad[2] = love.graphics.newQuad(50, 0, 14, 14, 64, 64) mappackonlineiconquad[3] = love.graphics.newQuad(50, 14*1, 14, 14, 64, 64) mappackonlineiconquad[4] = love.graphics.newQuad(50, 14*2, 14, 14, 64, 64) mappackonlineiconquad[5] = love.graphics.newQuad(50, 14*3, 14, 14, 64, 64) mappackonlineiconquad[6] = love.graphics.newQuad(0, 50, 14, 14, 64, 64) mappackonlineiconquad[7] = love.graphics.newQuad(14, 50, 14, 14, 64, 64) hudclockquad = {} hudclockquad[false] = love.graphics.newQuad(0, 0, 10, 9, 10, 18) hudclockquad[true] = love.graphics.newQuad(0, 9, 10, 9, 10, 18) --outline --Portal FX portalgunimg = love.graphics.newImage("graphics/" .. graphicspack .. "/portalgun.png") portalparticleimg = love.graphics.newImage("graphics/" .. graphicspack .. "/portalparticle.png") portalcrosshairimg = love.graphics.newImage("graphics/" .. graphicspack .. "/portalcrosshair.png") portaldotimg = love.graphics.newImage("graphics/" .. graphicspack .. "/portaldot.png") portalprojectileimg = love.graphics.newImage("graphics/" .. graphicspack .. "/portalprojectile.png") portalprojectileparticleimg = love.graphics.newImage("graphics/" .. graphicspack .. "/portalprojectileparticle.png") --Menu shit huebarimg = love.graphics.newImage("graphics/GUI/huebar.png") huebarmarkerimg = love.graphics.newImage("graphics/GUI/huebarmarker.png") volumesliderimg = love.graphics.newImage("graphics/GUI/volumeslider.png") laserfieldimg = love.graphics.newImage("graphics/" .. graphicspack .. "/laserfield.png") gradientimg = love.graphics.newImage("graphics/gradient.png");gradientimg:setFilter("linear", "linear") rainboomimg = love.graphics.newImage("graphics/rainboom.png") --sprites customsprites = false loadcustomsprites(true) --Ripping off minecraftbreakimg = love.graphics.newImage("graphics/Minecraft/blockbreak.png") minecraftbreakquad = {} for i = 1, 10 do minecraftbreakquad[i] = love.graphics.newQuad((i-1)*16, 0, 16, 16, 160, 16) end minecraftgui = love.graphics.newImage("graphics/Minecraft/gui.png") minecraftselected = love.graphics.newImage("graphics/Minecraft/selected.png") minecraftpickaxeimg = love.graphics.newImage("graphics/Minecraft/pickaxe.png") minecraftpickaxequad = {} for y = 1, 5 do minecraftpickaxequad[y] = love.graphics.newQuad(0, (y-1)*20, 20, 20, 20, 100) end print("done loading all quads!") loadingbardraw(1) --AUDIO-- --sounds jumpsound = love.audio.newSource("sounds/jump.ogg", "static") jumpbigsound = love.audio.newSource("sounds/jumpbig.ogg", "static") jumptinysound = love.audio.newSource("sounds/jumptiny.ogg", "static") stompsound = love.audio.newSource("sounds/stomp.ogg", "static") shotsound = love.audio.newSource("sounds/shot.ogg", "static") blockhitsound = love.audio.newSource("sounds/blockhit.ogg", "static") blockbreaksound = love.audio.newSource("sounds/blockbreak.ogg", "static") coinsound = love.audio.newSource("sounds/coin.ogg", "static") pipesound = love.audio.newSource("sounds/pipe.ogg", "static") boomsound = love.audio.newSource("sounds/boom.ogg", "static") mushroomappearsound = love.audio.newSource("sounds/mushroomappear.ogg", "static") mushroomeatsound = love.audio.newSource("sounds/mushroomeat.ogg", "static") shrinksound = love.audio.newSource("sounds/shrink.ogg", "static") deathsound = love.audio.newSource("sounds/death.ogg", "static") gameoversound = love.audio.newSource("sounds/gameover.ogg", "static") fireballsound = love.audio.newSource("sounds/fireball.ogg", "static") oneupsound = love.audio.newSource("sounds/oneup.ogg", "static") levelendsound = love.audio.newSource("sounds/levelend.ogg", "static") castleendsound = love.audio.newSource("sounds/castleend.ogg", "static") scoreringsound = love.audio.newSource("sounds/scorering.ogg", "static");scoreringsound:setLooping(true) intermissionsound = love.audio.newSource("sounds/intermission.ogg", "stream") firesound = love.audio.newSource("sounds/fire.ogg", "static") bridgebreaksound = love.audio.newSource("sounds/bridgebreak.ogg", "static") bowserfallsound = love.audio.newSource("sounds/bowserfall.ogg", "static") vinesound = love.audio.newSource("sounds/vine.ogg", "static") swimsound = love.audio.newSource("sounds/swim.ogg", "static") rainboomsound = love.audio.newSource("sounds/rainboom.ogg", "static") konamisound = love.audio.newSource("sounds/konami.ogg", "static") pausesound = love.audio.newSource("sounds/pause.ogg", "static") bulletbillsound = love.audio.newSource("sounds/bulletbill.ogg", "static") stabsound = love.audio.newSource("sounds/stab.ogg", "static") iciclesound = love.audio.newSource("sounds/icicle.ogg", "static") thwompsound = love.audio.newSource("sounds/thwomp.ogg", "static") boomerangsound = love.audio.newSource("sounds/boomerang.ogg", "static") raccoonswingsound = love.audio.newSource("sounds/raccoonswing.ogg", "static") raccoonplanesound = love.audio.newSource("sounds/raccoonplane.ogg", "static");raccoonplanesound:setLooping(true) skidsound = love.audio.newSource("sounds/skid.ogg", "static") turretshotsound = love.audio.newSource("sounds/turretshot.ogg", "static") pbuttonsound = love.audio.newSource("sounds/pbutton.ogg", "stream");pbuttonsound:setLooping(true) windsound = love.audio.newSource("sounds/wind.ogg", "static");windsound:setLooping(true) suitsound = love.audio.newSource("sounds/suit.ogg", "static") koopalingendsound = love.audio.newSource("sounds/koopalingend.ogg", "static") bowserendsound = love.audio.newSource("sounds/bowserend.ogg", "static") dooropensound = love.audio.newSource("sounds/dooropen.ogg", "static") doorclosesound = love.audio.newSource("sounds/doorclose.ogg", "static") keysound = love.audio.newSource("sounds/key.ogg", "static") keyopensound = love.audio.newSource("sounds/keyopen.ogg", "static") heelsound = love.audio.newSource("sounds/heel.ogg", "static") weirdmushroomsound = love.audio.newSource("sounds/weirdmushroom.ogg", "static") jumpskinnysound = love.audio.newSource("sounds/jumpskinny.ogg", "static") energybouncesound = love.audio.newSource("sounds/energybounce.ogg", "static") shufflesound = love.audio.newSource("sounds/shuffle.ogg", "static");shufflesound:setLooping(true) grabsound = love.audio.newSource("sounds/grab.ogg", "static") throwsound = love.audio.newSource("sounds/throw.ogg", "static") switchsound = love.audio.newSource("sounds/switch.ogg", "static") iciclefallsound = love.audio.newSource("sounds/iciclefall.ogg", "static") helmetsound = love.audio.newSource("sounds/helmet.ogg", "static") helmethitsound = love.audio.newSource("sounds/helmethit.ogg", "static") propellersound = love.audio.newSource("sounds/propeller.ogg", "static") clearpipesound = love.audio.newSource("sounds/clearpipe.ogg", "static") checkpointsound = love.audio.newSource("sounds/checkpoint.ogg", "static") megamushroomsound = love.audio.newSource("sounds/megamushroom.ogg", "stream");megamushroomsound:setLooping(true) powblocksound = love.audio.newSource("sounds/powblock.ogg", "static") cannonfastsound = love.audio.newSource("sounds/cannonfast.ogg", "static") bumperhitsound = love.audio.newSource("sounds/bumperhit.ogg", "static") bumperjumpsound = love.audio.newSource("sounds/bumperjump.ogg", "static") stompbigsound = love.audio.newSource("sounds/stompbig.ogg", "static") thwompbigsound = love.audio.newSource("sounds/thwompbig.ogg", "static") superballsound = love.audio.newSource("sounds/superball.ogg", "static") superballeatsound = love.audio.newSource("sounds/superballeat.ogg", "static") capeflysound = love.audio.newSource("sounds/capefly.ogg", "static") mushroombigeatsound = love.audio.newSource("sounds/mushroombigeat.ogg", "static") groundpoundsound = love.audio.newSource("sounds/groundpound.ogg", "static") sausagesound = love.audio.newSource("sounds/totaka.ogg", "static")--this is for um, the sausage entity. babysound = love.audio.newSource("sounds/baby.ogg", "static") --i don't like this but i KNOW someone is going to complain about sounds if i don't do this collectable1sound = love.audio.newSource("sounds/collectable1.ogg", "static") collectable2sound = love.audio.newSource("sounds/collectable2.ogg", "static") collectable3sound = love.audio.newSource("sounds/collectable3.ogg", "static") collectable4sound = love.audio.newSource("sounds/collectable4.ogg", "static") collectable5sound = love.audio.newSource("sounds/collectable5.ogg", "static") collectable6sound = love.audio.newSource("sounds/collectable6.ogg", "static") collectable7sound = love.audio.newSource("sounds/collectable7.ogg", "static") collectable8sound = love.audio.newSource("sounds/collectable8.ogg", "static") collectable9sound = love.audio.newSource("sounds/collectable9.ogg", "static") collectable10sound = love.audio.newSource("sounds/collectable10.ogg", "static") glados1sound = love.audio.newSource("sounds/glados/glados1.ogg", "stream") glados2sound = love.audio.newSource("sounds/glados/glados2.ogg", "static") portal1opensound = love.audio.newSource("sounds/portal1open.ogg", "static");portal1opensound:setVolume(0.3) portal2opensound = love.audio.newSource("sounds/portal2open.ogg", "static");portal2opensound:setVolume(0.3) portalentersound = love.audio.newSource("sounds/portalenter.ogg", "static");portalentersound:setVolume(0.3) portalfizzlesound = love.audio.newSource("sounds/portalfizzle.ogg", "static");portalfizzlesound:setVolume(0.3) lowtimesound = love.audio.newSource("sounds/lowtime.ogg", "static") updatesoundlist = function() soundlist = {jumpsound, jumpbigsound, stompsound, shotsound, blockhitsound, blockbreaksound, coinsound, pipesound, boomsound, mushroomappearsound, mushroomeatsound, shrinksound, deathsound, gameoversound, turretshotsound, oneupsound, levelendsound, castleendsound, scoreringsound, intermissionsound, firesound, fireballsound, bridgebreaksound, bowserfallsound, vinesound, swimsound, rainboomsound, portal1opensound, portal2opensound, portalentersound, portalfizzlesound, lowtimesound, pausesound, stabsound, bulletbillsound, iciclesound, thwompsound, boomerangsound, raccoonswingsound, raccoonplanesound, skidsound, jumptinysound, pbuttonsound, windsound, suitsound, koopalingendsound, bowserendsound, dooropensound, doorclosesound, keysound, keyopensound, weirdmushroomsound, jumpskinnysound, energybouncesound, shufflesound, grabsound, throwsound, collectable1sound, collectable2sound, collectable3sound, collectable4sound, collectable5sound, collectable6sound, collectable7sound, collectable8sound, collectable9sound, collectable10sound, switchsound, iciclefallsound, helmetsound, helmethitsound, propellersound, clearpipesound, megamushroomsound, stompbigsound, thwompbigsound, superballeatsound, superballsound, capeflysound, mushroombigeatsound, bumperhitsound, bumperjumpsound, cannonfastsound, powblocksound, checkpointsound, groundpoundsound} soundliststring = {"jump", "jumpbig", "stomp", "shot", "blockhit", "blockbreak", "coin", "pipe", "boom", "mushroomappear", "mushroomeat", "shrink", "death", "gameover", "turretshot", "oneup", "levelend", "castleend", "scorering", "intermission", "fire", "fireball", "bridgebreak", "bowserfall", "vine", "swim", "rainboom", "portal1open", "portal2open", "portalenter", "portalfizzle", "lowtime", "pause", "stab", "bulletbill", "icicle", "thwomp", "boomerang", "raccoonswing", "raccoonplane", "skid", "jumptiny", "pbutton", "wind", "suit", "koopalingend", "bowserend", "dooropen", "doorclose", "key", "keyopen", "weirdmushroom", "jumpskinny", "energybounce", "shuffle", "grab", "throw", "collectable1","collectable2","collectable3","collectable4","collectable5","collectable6","collectable7","collectable8", "collectable9", "collectable10", "switch", "iciclefall", "helmet", "helmethit", "propeller", "clearpipe", "megamushroom", "stompbig", "thwompbig", "superballeat", "superball", "capefly", "mushroombigeat", "bumperhit", "bumperjump", "cannonfast", "powblock", "checkpoint", "groundpound"} local temptable = {} --sort the sounds for i, t in pairs(soundlist) do table.insert(temptable, {t, soundliststring[i]}) end table.sort(temptable, function(a, b) return a[2] < b[2] end) for i, t in pairs(temptable) do soundlist[i] = t[1] soundliststring[i] = t[2] end end updatesoundlist() print("done loading all " .. #soundlist .. " sounds!") loadingbardraw(1) musici = 2 shaders:init() shaders:set(1, shaderlist[currentshaderi1]) shaders:set(2, shaderlist[currentshaderi2]) --[[for i, v in pairs(dlclist) do delete_mappack(v) end]] for i = 1, #mariocharacter do if mariocharacter[i] then setcustomplayer(mariocharacter[i], i, "initial") end end --mouse cursors if (not android) and (not androidsafe) then--fuck you love2d android, just fucking these instead of crashing mousecursor_hand = love.mouse.getSystemCursor("hand") mousecursor_sizewe = love.mouse.getSystemCursor("sizewe") end --android buttons if android then require "android" androidLoad() end --debug graphs if debugGraphs then debugGraph = require "libs/debugGraph" fpsGraph = debugGraph:new('fps', 0, 0) memGraph = debugGraph:new('mem', 0, 30) drawGraph = debugGraph:new('custom', 0, 60) end --Set Language if CurrentLanguage and CurrentLanguage ~= "english" then set_language(CurrentLanguage) end loadingbardraw(1) intro_load() end function love.update(dt) if music then music:update() end dt = math.min(0.01666667, dt) --speed if speed ~= speedtarget then if speed > speedtarget then speed = math.max(speedtarget, speed+(speedtarget-speed)*dt*5) elseif speed < speedtarget then speed = math.min(speedtarget, speed+(speedtarget-speed)*dt*5) end if math.abs(speed-speedtarget) < 0.02 then speed = speedtarget end if speed > 0 then for i, v in pairs(soundlist) do v:setPitch( speed ) end music.pitch = speed love.audio.setVolume(volume) else love.audio.setVolume(0) end end dt = dt * speed gdt = dt if frameadvance == 1 then return elseif frameadvance == 2 then frameadvance = 1 end if jsonerrorwindow.opened and jsonerrorwindow:update(dt) then end if skipupdate then skipupdate = false return end --netplay_update(dt) if CLIENT then client_update(dt) elseif SERVER then server_update(dt) end keyprompt_update() if gamestate == "menu" or gamestate == "mappackmenu" or gamestate == "onlinemenu" or gamestate == "lobby" or gamestate == "options" then menu_update(dt) elseif gamestate == "levelscreen" or gamestate == "gameover" or gamestate == "sublevelscreen" or gamestate == "mappackfinished" or gamestate == "dclevelscreen" then levelscreen_update(dt) elseif gamestate == "game" then game_update(dt) elseif gamestate == "intro" then intro_update(dt) end for i, v in pairs(guielements) do v:update(dt) end if debugGraphs then --Update the graphs fpsGraph:update(dt) memGraph:update(dt) drawGraph:update(dt, drawGraph.drawcalls) end if android then androidUpdate(dt) end notice.update(dt) end function love.draw() if resizable or android then if canvassupported or android then if letterboxfullscreen and (shaders.passes[1].on or shaders.passes[2].on) then love.graphics.setColor(0, 0, 0) love.graphics.rectangle("fill", 0, 0, winwidth, winheight) end love.graphics.setCanvas(canvas) love.graphics.clear() canvas:renderTo(lovedraw) love.graphics.setCanvas() if letterboxfullscreen and not (shaders.passes[1].on or shaders.passes[2].on) then love.graphics.setColor(0, 0, 0) love.graphics.rectangle("fill", 0, 0, winwidth, winheight) local cw, ch = canvas:getWidth(), canvas:getHeight()--current size local tw, th = winwidth, winheight--target size local s if cw/tw > ch/th then s = tw/cw else s = th/ch end love.graphics.setColor(255, 255, 255) love.graphics.draw(canvas, winwidth/2, winheight/2, 0, s, s, cw/2, ch/2) else love.graphics.setColor(255, 255, 255) love.graphics.draw(canvas, 0, 0, 0, winwidth/(width*16*scale), winheight/(224*scale)) end if android and not androidLowRes then androidDraw() end else love.graphics.scale(winwidth/(width*16*scale), winheight/(224*scale)) lovedraw() end else lovedraw() end if debugGraphs then --Draw graphs love.graphics.setColor(255,255,255) local stats = love.graphics.getStats() love.graphics.setLineWidth(2) drawGraph.label = "Drawcalls: " .. stats.drawcalls drawGraph.drawcalls = stats.drawcalls fpsGraph:draw() memGraph:draw() drawGraph:draw() end end function lovedraw() shaders:predraw() if resizable then if canvassupported then love.graphics.setColor(love.graphics.getBackgroundColor()) love.graphics.rectangle("fill", 0, 0, width*16*scale, height*16*scale) end end love.graphics.setColor(255, 255, 255) love.graphics.push() if gamestate == "menu" or gamestate == "mappackmenu" or gamestate == "onlinemenu" or gamestate == "lobby" or gamestate == "options" then menu_draw() elseif gamestate == "levelscreen" or gamestate == "gameover" or gamestate == "mappackfinished" or gamestate == "dclevelscreen" then levelscreen_draw() elseif gamestate == "game" then game_draw() elseif gamestate == "intro" then intro_draw() end love.graphics.pop() notice.draw() if showfps then love.graphics.setColor(255, 255, 255, 180) properprintfast(love.timer.getFPS(), 2*scale, 2*scale) end if jsonerrorwindow.opened then jsonerrorwindow:draw() end if android and androidLowRes then androidDraw() end shaders:postdraw() if debugconsole and debuginputon then love.graphics.setColor(0, 0, 0) love.graphics.print(debuginput, 1, 1) love.graphics.setColor(255, 255, 255) love.graphics.print(debuginput, 2, 2) end --testing sublevels (i KNOW you'll need this) --love.graphics.setColor(255,255,255) --properprint("mariosublevel: " .. tostring(mariosublevel) .. "\nprevsublevel: " .. tostring(prevsublevel) .. "\nactualsublevel: " .. tostring(actualsublevel), 2, 2) love.graphics.setColor(255, 255,255) end function saveconfig() local s = "" for i = 1, #controls do s = s .. "playercontrols:" .. i .. ":" local count = 0 for j, k in pairs(controls[i]) do local c = "" for l = 1, #controls[i][j] do c = c .. controls[i][j][l] if l ~= #controls[i][j] then c = c .. "-" end end s = s .. j .. "-" .. c count = count + 1 s = s .. "," end s = s:sub(1,-2) .. ";" end if mariocharacter then s = s .. "mariocharacter:" for i = 1, 4 do if mariocharacter[i] then s = s .. mariocharacter[i] .. "," else s = s .. "mario," end end s = s .. ";" end for i = 1, #mariocolors do s = s .. "playercolors:" .. i .. ":" for j = 1, #mariocolors[i] do for k = 1, 3 do s = s .. mariocolors[i][j][k] if j == #mariocolors[i] and k == 3 then s = s .. ";" else s = s .. "," end end end end for i = 1, #portalhues do s = s .. "portalhues:" .. i .. ":" s = s .. round(portalhues[i][1], 4) .. "," .. round(portalhues[i][2], 4) .. ";" end for i = 1, #mariohats do s = s .. "mariohats:" .. i if #mariohats[i] > 0 then s = s .. ":" end for j = 1, #mariohats[i] do s = s .. mariohats[i][j] if j == #mariohats[i] then s = s .. ";" else s = s .. "," end end if #mariohats[i] == 0 then s = s .. ";" end end if resizable then s = s .. "scale:2;" else s = s .. "scale:" .. scale .. ";" end if letterboxfullscreen then s = s .. "letterbox;" end s = s .. "shader1:" .. shaderlist[currentshaderi1] .. ";" s = s .. "shader2:" .. shaderlist[currentshaderi2] .. ";" s = s .. "volume:" .. volume .. ";" s = s .. "mouseowner:" .. mouseowner .. ";" if mappackfolder == "alesans_entities/mappacks" then s = s .. "modmappacks;" end s = s .. "mappack:" .. mappack .. ";" if vsync then s = s .. "vsync;" end if gamefinished then s = s .. "gamefinished;" end --reached worlds for i, v in pairs(reachedworlds) do s = s .. "reachedworlds:" .. i .. ":" local n = math.max(8, #reachedworlds[i]) for j = 1, n do if v[j] then s = s .. 1 else s = s .. 0 end if j == n then s = s .. ";" else s = s .. "," end end end s = s .. "resizable:" .. tostring(resizable) .. ";" if CurrentLanguage then s = s .. "language:" .. CurrentLanguage .. ";" end if fourbythree then s = s .. "fourbythree;" end if localnick then s = s .. "localnick:" .. localnick .. ";" end love.filesystem.write("alesans_entities/options.txt", s) end function loadconfig(nodefaultconfig) players = 1 if not nodefaultconfig then defaultconfig() end local s if love.filesystem.exists("alesans_entities/options.txt") then s = love.filesystem.read("alesans_entities/options.txt") elseif love.filesystem.exists("options.txt") then s = love.filesystem.read("options.txt") else return end s1 = s:split(";") for i = 1, #s1-1 do s2 = s1[i]:split(":") if s2[1] == "playercontrols" then if controls[tonumber(s2[2])] == nil then controls[tonumber(s2[2])] = {} end s3 = s2[3]:split(",") for j = 1, #s3 do s4 = s3[j]:split("-") controls[tonumber(s2[2])][s4[1]] = {} for k = 2, #s4 do if tonumber(s4[k]) ~= nil then controls[tonumber(s2[2])][s4[1]][k-1] = tonumber(s4[k]) else controls[tonumber(s2[2])][s4[1]][k-1] = s4[k] end end end players = math.max(players, tonumber(s2[2])) elseif s2[1] == "playercolors" then if mariocolors[tonumber(s2[2])] == nil then mariocolors[tonumber(s2[2])] = {} end s3 = s2[3]:split(",") mariocolors[tonumber(s2[2])] = {} for j = 1, math.floor(#s3/3) do table.insert(mariocolors[tonumber(s2[2])], {tonumber(s3[3*(j-1)+1]), tonumber(s3[3*(j-1)+2]), tonumber(s3[3*(j-1)+3])}) end elseif s2[1] == "portalhues" then if portalhues[tonumber(s2[2])] == nil then portalhues[tonumber(s2[2])] = {} end s3 = s2[3]:split(",") portalhues[tonumber(s2[2])] = {tonumber(s3[1]), tonumber(s3[2])} elseif s2[1] == "mariohats" then local playerno = tonumber(s2[2]) mariohats[playerno] = {} if s2[3] == "mariohats" then --SAVING WENT WRONG OMG elseif s2[3] then s3 = s2[3]:split(",") for i = 1, #s3 do local hatno = tonumber(s3[i]) --[[if hatno > hatcount then hatno = hatcount end]] --hats are limited later mariohats[playerno][i] = hatno end end elseif s2[1] == "scale" then if not nodefaultconfig then if android then scale = 1 else scale = tonumber(s2[2]) end end elseif s2[1] == "letterbox" then letterboxfullscreen = true elseif s2[1] == "shader1" then for i = 1, #shaderlist do if shaderlist[i] == s2[2] then currentshaderi1 = i end end elseif s2[1] == "shader2" then for i = 1, #shaderlist do if shaderlist[i] == s2[2] then currentshaderi2 = i end end elseif s2[1] == "volume" then volume = tonumber(s2[2]) love.audio.setVolume( volume ) elseif s2[1] == "mouseowner" then mouseowner = tonumber(s2[2]) elseif s2[1] == "mappack" then if love.filesystem.exists(mappackfolder .. "/" .. s2[2] .. "/") then mappack = s2[2] else checkmappack = s2[2] end elseif s2[1] == "gamefinished" then gamefinished = true elseif s2[1] == "vsync" then vsync = true elseif s2[1] == "reachedworlds" then reachedworlds[s2[2]] = {} local s3 = s2[3]:split(",") for i = 1, #s3 do if tonumber(s3[i]) == 1 then reachedworlds[s2[2]][i] = true elseif #s3 > 8 then reachedworlds[s2[2]][i] = false end end elseif s2[1] == "modmappacks" then mappackfolder = "alesans_entities/mappacks" elseif s2[1] == "resizable" then if s2[2] then resizable = (s2[2] == "true") else resizable = true end elseif s2[1] == "fourbythree" then fourbythree = true elseif s2[1] == "language" then CurrentLanguage = s2[2] elseif s2[1] == "localnick" then localnick = s2[2] elseif s2[1] == "mariocharacter" then local s3 = s2[2]:split(",") for i = 1, #s3 do if s3[i] == "false" then mariocharacter[i] = "mario" else mariocharacter[i] = s3[i] end end end end for i = 1, math.max(4, players) do if not portalhues[i] then break else portalcolor[i] = {getrainbowcolor(portalhues[i][1]), getrainbowcolor(portalhues[i][2])} end end players = 1 end function loadcustomtext() if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/endingmusic.ogg") then endingmusic = love.audio.newSource(mappackfolder .. "/" .. mappack .. "/endingmusic.ogg");endingmusic:play();endingmusic:stop() elseif love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/endingmusic.mp3") then endingmusic = love.audio.newSource(mappackfolder .. "/" .. mappack .. "/endingmusic.mp3");endingmusic:play();endingmusic:stop() else endingmusic = konamisound end if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/text.txt") then local s = love.filesystem.read(mappackfolder .. "/" .. mappack .. "/text.txt") defaultcustomtext() --read .txt local lines if string.find(s, "\r\n") then lines = s:split("\r\n") else lines = s:split("\n") end for i = 1, #lines do local s2 = lines[i]:split("=") local s3 if string.find(s2[1], ":") then s3 = s2[1]:split(":") else s3 = {s2[1]} end if s3[1] == "endingtextcolor" then local s4 = s2[2]:split(",") for j = 1, 3 do endingtextcolor[j] = tonumber(s4[j]) end elseif s3[1] == "endingtext" then local s4 = s2[2]:split(",") for j = 1, #s4 do endingtext[j] = s4[j] end elseif s3[1] == "endingcolorname" then endingtextcolorname = s2[2] elseif s3[1] == "playername" then if s2[2] ~= "mario" then --for custom characters playername = s2[2] end elseif s3[1] == "hudtextcolor" then local s4 = s2[2]:split(",") for j = 1, 3 do hudtextcolor[j] = tonumber(s4[j]) end elseif s3[1] == "hudcolorname" then hudtextcolorname = s2[2] elseif s3[1] == "hudvisible" then hudvisible = (s2[2] == "true") elseif s3[1] == "hudworldletter" then hudworldletter = (s2[2] == "true") elseif s3[1] == "hudoutline" then hudoutline = (s2[2] == "true") elseif s3[1] == "hudsimple" then hudsimple = (s2[2] == "true") elseif s3[1] == "toadtext" then local s4 = s2[2]:split(",") for j = 1, 3 do toadtext[j] = s4[j] end elseif s3[1] == "peachtext" then local s4 = s2[2]:split(",") for j = 1, 5 do peachtext[j] = s4[j] end elseif s3[1] == "steve" then pressbtosteve = (s2[2] == "true") elseif s3[1] == "levelscreen" then local s4 = s2[2]:split(",") if #s4 == 0 then s4 = {s2[2]} end for n = 1, #s4 do local s5 = s4[n]:split("|") levelscreentext[s5[1] .. "-" .. s5[2]] = s5[3] end elseif s3[1] == "hudhidecollectables" then local s4 = s2[2]:split(",") for j = 1, #s4 do hudhidecollectables[j] = (s4[j] == "t") end end end else defaultcustomtext() end end function defaultcustomtext(initial) endingtextcolor = {255, 255, 255} endingtextcolorname = "white" endingtext = {"congratulations!", "you have finished this mappack!"} toadtext = {"thank you mario!", "but our princess is in", "another castle!"} peachtext = {"thank you mario!", "your quest is over.", "we present you a new quest.", "push button b", "to play as steve"} levelscreentext = {} pressbtosteve = true if not initial then if mariocharacter[1] and characters.data[mariocharacter[1]] then playername = characters.data[mariocharacter[1]].name else playername = "mario" end end hudtextcolor = {255, 255, 255} hudtextcolorname = "white" hudvisible = true hudworldletter = false hudoutline = false hudsimple = false hudhidecollectables = {false, false, false, false, false, false, false, false, false, false} end function savecustomtext() local s = "" if textcolorl == "red" then s = s .. "endingtextcolor=216, 40, 0" elseif textcolorl == "blue" then s = s .. "endingtextcolor=32, 52, 236" elseif textcolorl == "yellow" then s = s .. "endingtextcolor=252, 221, 52" elseif textcolorl == "green" then s = s .. "endingtextcolor=0, 168, 0" elseif textcolorl == "orange" then s = s .. "endingtextcolor=252, 152, 56" elseif textcolorl == "pink" then s = s .. "endingtextcolor=252, 116, 180" elseif textcolorl == "purple" then s = s .. "endingtextcolor=116, 0, 116" else s = s .. "endingtextcolor=255,255,255" end s = s .. "\r\nendingcolorname=" .. textcolorl s = s .. "\r\nendingtext=" .. guielements["editendingtext1"].value .. "," .. guielements["editendingtext2"].value s = s .. "\r\nplayername=" .. guielements["editplayername"].value s = s .. "\r\n" if textcolorp == "red" then s = s .. "hudtextcolor=216, 40, 0" elseif textcolorp == "blue" then s = s .. "hudtextcolor=32, 52, 236" elseif textcolorp == "yellow" then s = s .. "hudtextcolor=252, 221, 52" elseif textcolorp == "green" then s = s .. "hudtextcolor=0, 168, 0" elseif textcolorp == "orange" then s = s .. "hudtextcolor=252, 152, 56" elseif textcolorp == "pink" then s = s .. "hudtextcolor=252, 116, 180" elseif textcolorp == "purple" then s = s .. "hudtextcolor=116, 0, 116" elseif textcolorp == "black" then s = s .. "hudtextcolor=0,0,0" else s = s .. "hudtextcolor=255,255,255" end s = s .. "\r\nhudcolorname=" .. textcolorp s = s .. "\r\nhudvisible=" .. tostring(hudvisible) s = s .. "\r\nhudworldletter=" .. tostring(hudworldletter) s = s .. "\r\nhudoutline=" .. tostring(hudoutline) s = s .. "\r\nhudsimple=" .. tostring(hudsimple) s = s .. "\r\ntoadtext=" .. guielements["edittoadtext1"].value .. "," .. guielements["edittoadtext2"].value .. "," .. guielements["edittoadtext3"].value s = s .. "\r\npeachtext=" .. guielements["editpeachtext1"].value .. "," .. guielements["editpeachtext2"].value .. "," .. guielements["editpeachtext3"].value .. "," .. guielements["editpeachtext4"].value .. "," .. guielements["editpeachtext5"].value s = s .. "\r\nsteve=" .. tostring(pressbtosteve) if guielements["editlevelscreentext"].value ~= "" then levelscreentext[marioworld .. "-" .. mariolevel] = guielements["editlevelscreentext"].value end s = s .. "\r\nlevelscreen=" local amount = false for t, text in pairs(levelscreentext) do s = s .. t:gsub("-", "|") .. "|" .. text .. "," amount = true end if not amount then s = s .. "1|1|" else s = s:sub(1, -2) end s = s .. "\r\nhudhidecollectables=" for i = 1, #hudhidecollectables do if hudhidecollectables[i] then s = s .. "t," else s = s .. "f," end end s = s:sub(1, -2) love.filesystem.write(mappackfolder .. "/" .. mappack .. "/text.txt", s) loadcustomtext() notice.new("Saved custom text!", notice.white, 2) end function defaultconfig() -------------- -- CONTORLS -- -------------- -- Joystick stuff: -- joy, #, hat, #, direction (r, u, ru, etc) -- joy, #, axe, #, pos/neg -- joy, #, but, # -- You cannot set Hats and Axes as the jump button. Bummer. mouseowner = 1 controls = {} local i = 1 controlstable = {"left", "right", "up", "down", "run", "jump", "reload", "use", "aimx", "aimy", "portal1", "portal2", "pause"} controls[i] = {} controls[i]["right"] = {"d"} controls[i]["left"] = {"a"} controls[i]["down"] = {"s"} controls[i]["up"] = {"w"} controls[i]["run"] = {"lshift"} controls[i]["jump"] = {" "} controls[i]["aimx"] = {""} --mouse aiming, so no need controls[i]["aimy"] = {""} controls[i]["portal1"] = {""} controls[i]["portal2"] = {""} controls[i]["reload"] = {"r"} controls[i]["use"] = {"e"} controls[i]["pause"] = {""} for i = 2, 4 do controls[i] = {} controls[i]["right"] = {"joy", i-1, "hat", 1, "r"} controls[i]["left"] = {"joy", i-1, "hat", 1, "l"} controls[i]["down"] = {"joy", i-1, "hat", 1, "d"} controls[i]["up"] = {"joy", i-1, "hat", 1, "u"} controls[i]["run"] = {"joy", i-1, "but", 3} controls[i]["jump"] = {"joy", i-1, "but", 1} controls[i]["aimx"] = {"joy", i-1, "axe", 5, "neg"} controls[i]["aimy"] = {"joy", i-1, "axe", 4, "neg"} controls[i]["portal1"] = {"joy", i-1, "but", 5} controls[i]["portal2"] = {"joy", i-1, "but", 6} controls[i]["reload"] = {"joy", i-1, "but", 4} controls[i]["use"] = {"joy", i-1, "but", 2} controls[i]["pause"] = {""} end ------------------- -- PORTAL COLORS -- ------------------- portalhues = {} portalcolor = {} for i = 1, 4 do local players = 4 portalhues[i] = {(i-1)*(1/players), (i-1)*(1/players)+0.5/players} portalcolor[i] = {getrainbowcolor(portalhues[i][1]), getrainbowcolor(portalhues[i][2])} end --hats. mariohats = {} for i = 1, 4 do mariohats[i] = {1} end ------------------ -- MARIO COLORS -- ------------------ --1: hat, pants (red) --2: shirt, shoes (brown-green) --3: skin (yellow-orange) mariocolors = {} mariocolors[1] = {{224, 32, 0}, {136, 112, 0}, {252, 152, 56}} mariocolors[2] = {{255, 255, 255}, { 0, 160, 0}, {252, 152, 56}} mariocolors[3] = {{ 0, 0, 0}, {200, 76, 12}, {252, 188, 176}} mariocolors[4] = {{ 32, 56, 236}, { 0, 128, 136}, {252, 152, 56}} for i = 5, players do mariocolors[i] = mariocolors[math.random(4)] end mariocharacter = {"mario", "mario", "mario", "mario"} --options scale = 2 resizable = true letterboxfullscreen = false volume = 1 mappack = "smb" vsync = false mappackfolder = "mappacks" fourbythree = false localnick = false reachedworlds = {} end function suspendgame() local st = {} if marioworld == "M" then marioworld = 8 mariolevel = 4 end st.world = marioworld st.level = mariolevel st.coincount = mariocoincount st.score = marioscore st.players = players st.lives = mariolives st.size = {} st.character = {} st.fireenemy = {} st.colors = {} st.shoe = {} for i = 1, players do if objects["player"][i] then local p = objects["player"][i] st.size[i] = p.size st.character[i] = p.character if p.fireenemy then st.fireenemy[i] = p.fireenemy st.colors[i] = p.colors end --st.shoe[i] = p.shoe --needs to be changed for yoshi else st.size[i] = 1 end end st.solidblockperma = solidblockperma --save collectables oh boy local c = false for i = 1, #collectablescount do if collectablescount[i] > 0 then c = true break end end if c then st.collectables = collectables st.collectablescount = collectablescount end st.animationnumbers = animationnumbers st.mappack = mappack st.mappackfolder = mappackfolder local s = JSON:encode_pretty(st) love.filesystem.write("suspend", s) love.audio.stop() menu_load() end function continuegame() if not love.filesystem.exists("suspend") then return end local s = love.filesystem.read("suspend") local st = JSON:decode(s) mariosizes = {} mariolives = {} marioworld = st.world mariolevel = st.level mariocoincount = st.coincount marioscore = st.score players = st.players if mariolivecount ~= false then mariolives = st.lives end mariosizes = st.size mariocharacter = st.character for i = 1, #mariocharacter do if mariocharacter[i] then setcustomplayer(mariocharacter[i], i) end end --[[for i, shoe in pairs(st.shoe) do marioproperties[i].shoe = shoe end]] for i, fireenemy in pairs(st.fireenemy) do marioproperties[i].fireenemy = fireenemy end for i, customcolors in pairs(st.colors) do marioproperties[i].customcolors = customcolors end mappack = st.mappack mappackfolder = st.mappackfolder if (not st.collectables) then --save the game if collectables are involved love.filesystem.remove("suspend") end loadbackground("1-1.txt") if solidblockperma then solidblockperma = st.solidblockperma end if st.collectables and st.collectablescount then collectables = st.collectables collectablescount = st.collectablescount end if st.animationnumbers then animationnumbers = st.animationnumbers end end function changescale(s, fullscreen) if android or (s == 5) then if android then scale = 1 elseif fullscreen then local w, h = love.window.getDesktopDimensions() scale = math.max(1, math.floor(w/(width*16))) else scale = 2 end resizable = true uispace = math.floor(width*16*scale/4) love.window.setMode(width*16*scale, 224*scale, {fullscreen=fullscreen, vsync=vsync, msaa=fsaa, resizable=true, minwidth=width*16, minheight=224}) --27x14 blocks (15 blocks actual height) gamewidth, gameheight = love.graphics.getDimensions() if android then gamewidth, gameheight = width*16, height*16 elseif fullscreen then gamewidth, gameheight = width*16*scale, height*16*scale end winwidth, winheight = love.graphics.getDimensions() if fullscreen then winwidth, winheight = love.window.getDesktopDimensions() end canvassupported = true--love.graphics.isSupported("canvas") if canvassupported then canvas = love.graphics.newCanvas(width*16*scale, height*16*scale) canvas:setFilter("nearest", "nearest") end if shaders then shaders:refresh() end else scale = s resizable = false if fullscreen then fullscreen = true scale = 2 love.window.setMode(800, 600, {fullscreen=fullscreen, vsync=vsync, msaa=fsaa}) end uispace = math.floor(width*16*scale/4) love.window.setMode(width*16*scale, height*16*scale, {fullscreen=fullscreen,vsync=vsync, msaa=fsaa}) --27x14 blocks (15 blocks actual height) gamewidth, gameheight = love.graphics.getDimensions() winwidth, winheight = love.graphics.getDimensions() if shaders then shaders:refresh() end end end --resizing stuff function love.resize(w, h) winwidth, winheight = w, h if resizable and canvassupported then if winwidth < (width*16*scale)*1.5 or winheight < (224*scale)*1.5 then canvas:setFilter("linear", "linear") else canvas:setFilter("nearest", "nearest") end --[[if winwidth/(width*16*scale) and winheight/(224*scale) == math.floor(winheight/(224*scale)) then canvas:setFilter("nearest", "nearest") else canvas:setFilter("linear", "linear") end]] end if shaders then shaders:refresh() end end lgs = love.graphics.setScissor function love.graphics.setScissor(x, y, w, h) if x and y and w and h then if resizable and not canvassupported then x, y, w, h = x*(winwidth/gamewidth), y*(winheight/gameheight), w*(winwidth/gamewidth), h*(winheight/gameheight) end lgs(x, y, w, h) else lgs() end end lmx = love.mouse.getX function love.mouse.getX() if android then local x,y = androidGetMouse() return x end local x = lmx() if resizable and letterboxfullscreen and canvassupported and canvas then local cw, ch = canvas:getWidth(), canvas:getHeight()--current size local tw, th = winwidth, winheight--target size local s if cw/tw > ch/th then s = tw/cw else s = th/ch end x = math.max(0, math.min(cw*s, x - ((tw*0.5)-(cw*s*0.5))))/s elseif resizable then x = x/(winwidth/gamewidth) end return x end lmy = love.mouse.getY function love.mouse.getY() if android then local x,y = androidGetMouse() return y end local y = lmy() if resizable and letterboxfullscreen and canvassupported and canvas then local cw, ch = canvas:getWidth(), canvas:getHeight()--current size local tw, th = winwidth, winheight--target size local s if cw/tw > ch/th then s = tw/cw else s = th/ch end y = math.max(0, math.min(ch*s, y - ((th*0.5)-(ch*s*0.5))))/s elseif resizable then y = y/(winheight/gameheight) end return y end function love.mouse.getPosition() if android then return androidGetMouse() end local x, y = love.mouse.getX(), love.mouse.getY() return x, y end ---------------- function love.keypressed(key, scancode, isrepeat, textinput) if key == "space" then key = " " end if debugconsole then if key == "backspace" and debuginputon then debuginput = debuginput:sub(1, -2) elseif key == "return" and debuginputon then func = loadstring(debuginput) ok, result = pcall(func) -- execute the chunk safely if not ok then -- will be false if there is an error print('The following error happened: ' .. tostring(result)) else print('The result of loading is: ' .. tostring(result)) end elseif key == "tab" then debuginputon = not debuginputon if debuginputon then love.keyboard.setKeyRepeat(true) else love.keyboard.setKeyRepeat(false) end end if debuginputon then return end end if jsonerrorwindow.opened then jsonerrorwindow:keypressed(key) return end if keyprompt then keypromptenter("key", key) return end for i, v in pairs(guielements) do if v:keypress(key,textinput) then return end end if key == "return" and love.keyboard.isDown("lalt") then fullscreen = not fullscreen if fullscreen then winwidth, winheight = love.window.getDesktopDimensions() changescale(5, fullscreen) else winwidth, winheight = love.graphics.getDimensions() changescale(scale, fullscreen) end if gamestate == "game" then updatespritebatch() end return end if key == "f10" then if android then --hide ui androidHIDE = not androidHIDE else HITBOXDEBUG = not HITBOXDEBUG end elseif key == "f11" then showfps = not showfps elseif key == "f12" then love.mouse.setGrabbed(not love.mouse.isGrabbed()) end if gamestate == "menu" or gamestate == "mappackmenu" or gamestate == "onlinemenu" or gamestate == "lobby" or gamestate == "options" then --konami code if key == konami[konamii] or (android and key == androidkonami[konamii]) then--[[DROID]] konamii = konamii + 1 if konamii == #konami+1 then if konamisound:isStopped() then playsound(konamisound) end gamefinished = true saveconfig() konamii = 1 notice.new("Cheats unlocked!", notice.white, 5) end else konamii = 1 end menu_keypressed(key, unicode) elseif gamestate == "game" then game_keypressed(key, textinput) elseif gamestate == "levelscreen" or gamestate == "gameover" then levelscreen_keypressed(key) elseif gamestate == "intro" then intro_keypressed() end end function love.keyreleased(key, unicode) if key == "space" then key = " " end if gamestate == "menu" or gamestate == "options" then menu_keyreleased(key, unicode) elseif gamestate == "game" then game_keyreleased(key, unicode) end end function love.textinput(c) if android --[[and not androidtest]] then --[[DROID]] love.keypressed(c,nil,nil,"textinput") else if debugconsole and debuginputon then debuginput = debuginput .. c end end end function love.mousepressed(x, y, button, istouch) button = nummousebutton(button) if android then if istouch == true then return false elseif androidtest and istouch ~= "simulated" then love.touchpressed(1,x,y) return false end elseif resizable and letterboxfullscreen and canvassupported and canvas then x, y = love.mouse.getPosition() elseif resizable then x, y = x/(winwidth/gamewidth), y/(winheight/gameheight) end if jsonerrorwindow.opened then jsonerrorwindow:mousepressed(x, y, button) return end if gamestate == "menu" or gamestate == "mappackmenu" or gamestate == "onlinemenu" or gamestate == "lobby" or gamestate == "options" then menu_mousepressed(x, y, button) elseif gamestate == "game" then game_mousepressed(x, y, button) elseif gamestate == "intro" then intro_mousepressed() end --animations priorities if animationguilines and editormode and editormenuopen and (not changemapwidthmenu) and (not guielements["animationselectdrop"].extended) and editorstate == "animations" then local b = false for i, v in pairs(animationguilines) do for k, w in pairs(v) do if w:haspriority() then w:click(x, y, button) return end end end if x >= animationguiarea[1]*scale and y >= animationguiarea[2]*scale and x < animationguiarea[3]*scale and y < animationguiarea[4]*scale then addanimationtriggerbutton:click(x, y, button) addanimationconditionbutton:click(x, y, button) addanimationactionbutton:click(x, y, button) for i, v in pairs(animationguilines) do for k, w in pairs(v) do if w:click(x, y, button) then return end end end end end if ignoregui then ignoregui = false return end for i, v in pairs(guielements) do if v.priority then if v:click(x, y, button) then return end end end for i, v in pairs(guielements) do if not v.priority then if v:click(x, y, button) then return end end end end function love.mousereleased(x, y, button, istouch) button = nummousebutton(button) if android then if istouch == true then return false elseif androidtest and istouch ~= "simulated" then love.touchreleased(1,x,y) return false end elseif resizable and letterboxfullscreen and canvassupported and canvas then x, y = love.mouse.getPosition() elseif resizable then x, y = x/(winwidth/gamewidth), y/(winheight/gameheight) end if jsonerrorwindow.opened then jsonerrorwindow:mousereleased(x, y, button) return end if gamestate == "menu" or gamestate == "options" or gamestate == "mappackmenu" then menu_mousereleased(x, y, button) elseif gamestate == "game" then game_mousereleased(x, y, button) end if ignoregui then ignoregui = false return end for i, v in pairs(guielements) do v:unclick(x, y, button) end end function love.mousemoved(x, y, dx, dy, istouch) if android then if istouch == true then return false elseif androidtest and istouch ~= "simulated" then if love.mouse.isDown("l","notAndroid") then love.touchmoved(1,x,y,dx,dy) end return false end elseif resizable and letterboxfullscreen and canvassupported and canvas then x, y = love.mouse.getPosition() local cw, ch = canvas:getWidth(), canvas:getHeight()--current size local tw, th = winwidth, winheight--target size local s if cw/tw > ch/th then s = tw/cw else s = th/ch end dx, dy = dx/(s), dy/(s) elseif android or resizable then x, y = x/(winwidth/gamewidth), y/(winheight/gameheight) dx, dy = dx/(winwidth/gamewidth), dy/(winheight/gameheight) end if gamestate == "menu" or gamestate == "options" or gamestate == "mappackmenu" then menu_mousemoved(x, y, dx, dy) elseif gamestate == "game" then if editormode then editor_mousemoved(x, y, dx, dy) end end end function love.wheelmoved(x, y) if y > 0 then love.mousepressed(love.mouse.getX(), love.mouse.getY(), "wu") elseif y < 0 then love.mousepressed(love.mouse.getX(), love.mouse.getY(), "wd") end end function love.filedropped(file) if gamestate == "menu" or gamestate == "mappackmenu" then menu_filedropped(file) elseif gamestate == "game" and editormode then editor_filedropped(file) end end --really lazy 0.10.0 conversion local oldmouse_isDown = love.mouse.isDown function love.mouse.isDown(b,notAndroid) b = mousebuttonnum(b) if android and not notAndroid then return androidMouseDown(b) end return oldmouse_isDown(b) end local nummousebuttont = {"l", "r", "m", "x1", "x2", l = 1, r = 2, m = 3, x1 = 4, x2 = 5} function nummousebutton(b) if type(b) == "number" then return nummousebuttont[b] or "l" else return b end end function mousebuttonnum(b) if type(b) == "string" then return nummousebuttont[b] or 1 else return b end end local oldkeyboard_isDown = love.keyboard.isDown function love.keyboard.isDown(k) if k == " " then k = "space" end return oldkeyboard_isDown(k) end function love.joystickpressed(joystick, button, simulated) local joystick = joystick if not simulated then joystick = joystick:getID() end if keyprompt then keypromptenter("joybutton", joystick, button) return end if gamestate == "menu" or gamestate == "mappackmenu" or gamestate == "onlinemenu" or gamestate == "lobby" or gamestate == "options" then menu_joystickpressed(joystick, button) elseif gamestate == "game" then game_joystickpressed(joystick, button) elseif gamestate == "levelscreen" or gamestate == "gameover" then levelscreen_joystickpressed(joystick, button) end end function love.joystickreleased(joystick, button, simulated) local joystick = joystick if not simulated then joystick = joystick:getID() end if gamestate == "menu" or gamestate == "options" then menu_joystickreleased(joystick, button) elseif gamestate == "game" then game_joystickreleased(joystick, button) end end local function getjoysticki(i) local joysticks = love.joystick.getJoysticks() return joysticks[i] end function love.joystick.getHatCount(i) return getjoysticki(i):getHatCount() end function love.joystick.getHat(i, h) --id, hat if getjoysticki(i) then return getjoysticki(i):getHat(h) else return "c" end end function love.joystick.getAxisCount(i) return getjoysticki(i):getAxisCount() end function love.joystick.getAxis(i, j) --id, axis if getjoysticki(i) and getjoysticki(i).getAxis then return getjoysticki(i):getAxis(j) else return 0 --workaround for annoying joystick bug end end function love.joystickadded(joystick) if android and notice then if joystick:isGamepad() then local gamepadName = joystick:getName() if gamepadName then notice.new(string.format("%s connected!", gamepadName), notice.white) else notice.new(string.format("Unknown gamepad connected!", gamepadName), notice.white) end end end end function love.joystick.isDown(i, b) if getjoysticki(i) then return getjoysticki(i):isDown(b) else return false end end function round(num, idp) --Not by me local mult = 10^(idp or 0) return math.floor(num * mult + 0.5) / mult end function getrainbowcolor(i) local whiteness = 255 local r, g, b if i < 1/6 then r = 1 g = i*6 b = 0 elseif i >= 1/6 and i < 2/6 then r = (1/6-(i-1/6))*6 g = 1 b = 0 elseif i >= 2/6 and i < 3/6 then r = 0 g = 1 b = (i-2/6)*6 elseif i >= 3/6 and i < 4/6 then r = 0 g = (1/6-(i-3/6))*6 b = 1 elseif i >= 4/6 and i < 5/6 then r = (i-4/6)*6 g = 0 b = 1 else r = 1 g = 0 b = (1/6-(i-5/6))*6 end return {round(r*whiteness), round(g*whiteness), round(b*whiteness), 255} end function newRecoloredImage(path, tablein, tableout) local imagedata = love.image.newImageData( path ) local width, height = imagedata:getWidth(), imagedata:getHeight() for y = 0, height-1 do for x = 0, width-1 do local oldr, oldg, oldb, olda = imagedata:getPixel(x, y) if olda > 128 then for i = 1, #tablein do if oldr == tablein[i][1] and oldg == tablein[i][2] and oldb == tablein[i][3] then local r, g, b = unpack(tableout[i]) imagedata:setPixel(x, y, r, g, b, olda) end end end end end return love.graphics.newImage(imagedata) end function string:split(d) local data = {} local from, to = 1, string.find(self, d) while to do table.insert(data, string.sub(self, from, to-1)) from = to+d:len() to = string.find(self, d, from) end table.insert(data, string.sub(self, from)) return data end function tablecontains(t, entry) for i, v in pairs(t) do if v == entry then return true end end return false end function tablecontainsi(t, entry) for i, v in pairs(t) do if v == entry then return i end end return false end function getaveragecolor(imgdata, cox, coy) local xstart = (cox-1)*17 local ystart = (coy-1)*17 local r, g, b = 0, 0, 0 local count = 0 for x = xstart, xstart+15 do for y = ystart, ystart+15 do local pr, pg, pb, a = imgdata:getPixel(x, y) if a > 127 then r, g, b = r+pr, g+pg, b+pb count = count + 1 end end end r, g, b = r/count, g/count, b/count return r, g, b end function getaveragecolor2(imgdata, cox, coy) local xstart = (cox-1)*16 local ystart = (coy-1)*16 if imgdata:getHeight() > 16 then xstart = (cox-1)*17 ystart = (coy-1)*17 end local r, g, b = 0, 0, 0 local count = 0 for x = xstart, xstart+15 do for y = ystart, ystart+15 do local pr, pg, pb, a = imgdata:getPixel(x, y) if a > 127 then r, g, b = r+pr, g+pg, b+pb count = count + 1 end end end r, g, b = r/count, g/count, b/count return r, g, b end function keyprompt_update() if keyprompt then for i = 1, prompt.joysticks do for j = 1, #prompt.joystick[i].validhats do local dir = love.joystick.getHat(i, prompt.joystick[i].validhats[j]) if dir ~= "c" then keypromptenter("joyhat", i, prompt.joystick[i].validhats[j], dir) return end end for j = 1, prompt.joystick[i].axes do local value = love.joystick.getAxis(i, j) if value > prompt.joystick[i].axisposition[j] + joystickdeadzone then keypromptenter("joyaxis", i, j, "pos") return elseif value < prompt.joystick[i].axisposition[j] - joystickdeadzone then keypromptenter("joyaxis", i, j, "neg") return end end end end end function print_r (t, indent) --Not by me local indent=indent or '' for key,value in pairs(t) do io.write(indent,'[',tostring(key),']') if type(value)=="table" then io.write(':\n') print_r(value,indent..'\t') else io.write(' = ',tostring(value),'\n') end end end function love.focus(f) if (not f) and gamestate == "game"and (not editormode) and (not testlevel) and (not levelfinished) and (not everyonedead) and (not CLIENT) and (not SERVER) and (not dontPauseOnUnfocus) then pausemenuopen = true love.audio.pause() end end function openSaveFolder(subfolder) --By Slime local path = love.filesystem.getSaveDirectory() path = subfolder and path.."/"..subfolder or path local cmdstr local successval = 0 if android then notice.new("On android use a file manager\nand go to:\nAndroid > data > Love.to.mario >\nfiles > save > mari0_android >\nalesans_entities > mappacks", notice.red, 15) return false elseif os.getenv("WINDIR") then -- lolwindows --cmdstr = "Explorer /root,%s" if path:match("LOVE") then --hardcoded to fix ISO characters in usernames and made sure release mode doesn't mess anything up -saso cmdstr = "Explorer %%appdata%%\\LOVE\\mari0" else cmdstr = "Explorer %%appdata%%\\mari0" end path = path:gsub("/", "\\") successval = 1 elseif os.getenv("HOME") then if path:match("/Library/Application Support") then -- OSX cmdstr = "open \"%s\"" else -- linux? cmdstr = "xdg-open \"%s\"" end end -- returns true if successfully opened folder return cmdstr and os.execute(cmdstr:format(path)) == successval end function getupdate() local onlinedata, code = http.request("http://server.stabyourself.net/mari0/?mode=mappacks") if code ~= 200 then return false elseif not onlinedata then return false end local latestversion local split1 = onlinedata:split("<") for i = 2, #split1 do local split2 = split1[i]:split(">") if split2[1] == "latestversion" then latestversion = tonumber(split2[2]) end end if latestversion and latestversion > marioversion then return true end return false end --TTF Printing function properprintfast(s, x, y, size) if s == nil then return end local size = size or 1 --use with emulogic or any 8x8 font love.graphics.setFont(font) love.graphics.print(s, x, y-scale, 0, size*scale, size*scale) end function properprintfastbackground(s, x, y, size) --outlines if s == nil then return end local size = size or 1 love.graphics.setFont(fontback) love.graphics.print(s, x, y-scale, 0, size*scale, size*scale) love.graphics.setFont(font) love.graphics.print(s, x, y-scale, 0, size*scale, size*scale) end function properprintfastf(s, x, y, w, size) --word wrap if s == nil then return end local size = size or 1 love.graphics.setFont(font) love.graphics.printf(s, x, y-scale, w, "left", 0, size*scale, size*scale) end function properprintFast(s, x, y, size) --CAPITALS if s == nil then return end local size = size or 1 love.graphics.setFont(fontCAP) love.graphics.print(s, x, y-scale, 0, size*scale, size*scale) end function properprintFastbackground(s, x, y, size) if s == nil then return end local size = size or 1 love.graphics.setFont(fontbackCAP) love.graphics.print(s, x, y-scale, 0, size*scale, size*scale) love.graphics.setFont(fontCAP) love.graphics.print(s, x, y-scale, 0, size*scale, size*scale) end --UTF-8 Printing function properprintf(s, x, y, size) --UTF-8 if s then local size = size or 1 local startx = x for i, char, b in utf8.chars(tostring(s)) do if char == " " then elseif char == "\n" then x = startx-((i)*(8*size))*scale y = y + (10*size)*scale elseif fontquads[char] then love.graphics.draw(fontimage, fontquads[char], x+((i-1)*(8*size))*scale, y, 0, size*scale, size*scale) end end end end function properprintfbackground(s, x, y, include, color, size) --UTF-8 outline if s then local size = size or 1 local startx, starty = x, y for i, char, b in utf8.chars(tostring(s)) do if char == " " then elseif char == "\n" then x = startx-((i)*(8*size))*scale y = y + (10*size)*scale elseif fontquadsback[char] then love.graphics.draw(fontbackimage, fontquadsback[char], x+((i-1)*(8*size)-1*size)*scale, y-(1*size)*scale, 0, size*scale, size*scale) end end if include ~= false then if color then love.graphics.setColor(color) end properprintf(s, startx, starty, size) end end end function properprintF(s, x, y, size) --UTF-8 CAPITALS if s then local size = size or 1 local startx = x for i, char, b in utf8.chars(tostring(s)) do if char == " " then elseif char == "\n" then x = startx-((i)*(8*size))*scale y = y + (10*size)*scale elseif fontquads[char] then love.graphics.draw(fontimage, fontquads[fontindexCAP[char]], x+((i-1)*(8*size))*scale, y, 0, size*scale, size*scale) end end end end function properprintFbackground(s, x, y, include, color, size) --UTF-8 CAPITALS OUTLINE if s then local size = size or 1 local startx, starty = x, y for i, char, b in utf8.chars(tostring(s)) do if char == " " then elseif char == "\n" then x = startx-((i)*(8*size))*scale y = y + (10*size)*scale elseif fontquadsback[char] then love.graphics.draw(fontbackimage, fontquadsback[fontindexCAP[char]], x+((i-1)*(8*size)-1*size)*scale, y-(1*size)*scale, 0, size*scale, size*scale) end end if include ~= false then if color then love.graphics.setColor(color) end properprintF(s, startx, starty, size) end end end --Normal Mari0 Printing (no utf-8, Capitals may be displayed as a special character) function properprint(s, x, y, size) if s == nil then return end local size = size or 1 s = tostring(s) local startx = x for i = 1, string.len(s) do local char = string.sub(s, i, i) if char == " " then elseif char == "\n" then x = startx-((i)*(8*size))*scale y = y + (10*size)*scale elseif fontquads[char] then love.graphics.draw(fontimage, fontquads[fontindexOLD[char]], x+((i-1)*(8*size))*scale, y, 0, size*scale, size*scale) end end end function properprintbackground(s, x, y, include, color, size) local size = size or 1 local startx, starty = x, y local skip = 0 for i = 1, string.len(tostring(s)) do if skip > 0 then skip = skip - 1 else local char = string.sub(s, i, i) if char == " " then elseif char == "\n" then x = startx-((i)*(8*size))*scale y = y + (10*size)*scale elseif fontquadsback[char] then love.graphics.draw(fontbackimage, fontquadsback[fontindexOLD[char]], x+((i-1)*(8*size)-1*size)*scale, y-(1*size)*scale, 0, size*scale, size*scale) end end end if include ~= false then if color then love.graphics.setColor(color) end properprint(s, startx, starty, size) end end local function error_printer(msg, layer) print((debug.traceback("Error: " .. tostring(msg), 1+(layer or 1)):gsub("\n[^\n]+$", ""))) end function love.errhand(msg) msg = tostring(msg) error_printer(msg, 2) if not love.window or not love.graphics or not love.event then return end if not love.graphics.isCreated() or not love.window.isOpen() then local success, status = pcall(love.window.setMode, 800, 600) if not success or not status then return end end if love.mouse then love.mouse.setVisible(true) love.mouse.setGrabbed(false) love.mouse.setRelativeMode(false) end if love.joystick then -- Stop all joystick vibrations. for i,v in ipairs(love.joystick.getJoysticks()) do v:setVibration() end end local screenshot = false if love.graphics.newScreenshot then local s, r = pcall(function() return love.graphics.newImage(love.graphics.newScreenshot()) end) if s and r then screenshot = r end end -- Load. if love.audio then love.audio.stop() end love.graphics.reset() love.graphics.setBackgroundColor(0, 0, 0) local fontscale = scale or 2 if not font then font = love.graphics.newFont(8*scale) fontscale = 1 end love.graphics.setFont(font) love.graphics.setColor(255, 255, 255, 255) local trace = debug.traceback() love.graphics.clear() local err = {} local traceback = {} table.insert(err, "Error\n") table.insert(err, msg.."\n\n") for l in string.gmatch(trace, "(.-)\n") do if not string.match(l, "boot.lua") then l = string.gsub(l, "stack traceback:", "Traceback [" .. VERSION .. "]\n") table.insert(traceback, l) end end local p = table.concat(err, "\n") local p2 = table.concat(traceback, "\n") p = string.gsub(p, "\t", "") p = string.gsub(p, "%[string \"(.-)\"%]", "%1") p2 = string.gsub(p2, "\t", "") p2 = string.gsub(p2, "%[string \"(.-)\"%]", "%1") p2 = p2 .. "\n\nCrash saved in\nalesans_entities\\crashes" if love.filesystem and love.filesystem.createDirectory and love.filesystem.write and love.filesystem.getDirectoryItems and love.filesystem.remove then love.filesystem.createDirectory("alesans_entities/crashes") local items = love.filesystem.getDirectoryItems("alesans_entities/crashes") or {} if #items >= 10 then for i = 1, #items do love.filesystem.remove("alesans_entities/crashes/" .. items[i]) end items = love.filesystem.getDirectoryItems("alesans_entities/crashes") end local s = "" for j, w in pairs(err) do s = s .. w .. "\r\n" end for j, w in pairs(traceback) do s = s .. w .. "\r\n" end if VERSION then s = s .. "version: " .. VERSION end love.filesystem.write("alesans_entities/crashes/" .. #items+1 .. ".txt", s) end local function draw() love.graphics.clear(love.graphics.getBackgroundColor()) if screenshot then love.graphics.setColor(30, 30, 30) love.graphics.draw(screenshot, 0, 0, 0, love.graphics.getWidth()/screenshot:getWidth(), love.graphics.getHeight()/screenshot:getHeight()) if gradientimg and width and height then love.graphics.setColor(0, 0, 0) love.graphics.draw(gradientimg, 0, 0, 0, love.graphics.getWidth()/(width*16), love.graphics.getHeight()/(height*16)) end end love.graphics.setColor(255, 255, 255) love.graphics.printf({{255,255,255,255},p,{255,255,255,100},p2}, 10, 10, (love.graphics.getWidth() - 10)/fontscale, nil, 0, fontscale, fontscale) love.graphics.print("Mari0 AE Version " .. VERSIONSTRING, love.graphics.getWidth() - font:getWidth("Mari0 AE Version " .. VERSIONSTRING)*fontscale - 5*scale, love.graphics.getHeight() - 15*scale, 0, fontscale, fontscale) love.graphics.present() end draw() local e, a, b, c while true do love.event.pump() for e, a, b, c in love.event.poll() do if e == "quit" then return elseif e == "keypressed" and a == "escape" then return elseif e == "touchpressed" then local name = love.window.getTitle() if #name == 0 or name == "Untitled" then name = "Game" end local buttons = {"OK", "Cancel"} local pressed = love.window.showMessageBox("Quit "..name.."?", "", buttons) if pressed == 1 then return end end end draw() if love.timer then love.timer.sleep(0.1) end end end function love.quit() if CLIENT or SERVER then net_quit() end return false end function loadcustombackground(filename) local i = 1 custombackgroundimg = {} custombackgroundwidth = {} custombackgroundheight = {} custombackgroundquad = {} custombackgroundanim = {} --try to load map specific background first local levelstring = marioworld .. "-" .. mariolevel local actualsublevel = actualsublevel or mariosublevel if actualsublevel ~= 0 then --changed mariosublevel to actualsublevel because mariosublevel isn't accurate (edit: changed back, revert if anyone complains) (edit: reverted because someone complained) levelstring = levelstring .. "_" .. actualsublevel end local name = levelstring .. "background" if filename and type(filename) == "string" then name = "backgrounds/" .. filename else filename = false--not a string end while love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/" .. name .. i .. ".png") do custombackgroundimg[i] = love.graphics.newImage(mappackfolder .. "/" .. mappack .. "/" .. name .. i .. ".png") custombackgroundwidth[i] = custombackgroundimg[i]:getWidth()/16 custombackgroundheight[i] = custombackgroundimg[i]:getHeight()/16 if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/" .. name .. i .. ".json") then --load animation local data = love.filesystem.read(mappackfolder .. "/" .. mappack .. "/" .. name .. i .. ".json") if not data then return end data = data:gsub("\r", "") loadcustombackgroundanim(custombackgroundimg, custombackgroundwidth, custombackgroundheight, custombackgroundanim, i, data) elseif not SlowBackgrounds then custombackgroundimg[i]:setWrap("repeat","repeat") custombackgroundquad[i] = love.graphics.newQuad(0,0,width*16,height*16,custombackgroundimg[i]:getWidth(),custombackgroundimg[i]:getHeight()) end i = i +1 end if #custombackgroundimg == 0 then if filename and love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/backgrounds/" .. filename .. ".png") then custombackgroundimg[i] = love.graphics.newImage(mappackfolder .. "/" .. mappack .. "/backgrounds/" .. filename .. ".png") custombackgroundwidth[i] = custombackgroundimg[i]:getWidth()/16 custombackgroundheight[i] = custombackgroundimg[i]:getHeight()/16 if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/backgrounds/" .. filename .. ".json") then --load animation local data = love.filesystem.read(mappackfolder .. "/" .. mappack .. "/backgrounds/" .. filename .. ".json") if not data then return end data = data:gsub("\r", "") loadcustombackgroundanim(custombackgroundimg, custombackgroundwidth, custombackgroundheight, custombackgroundanim, i, data) elseif not SlowBackgrounds then custombackgroundimg[i]:setWrap("repeat","repeat") custombackgroundquad[i] = love.graphics.newQuad(0,0,width*16,height*16,custombackgroundimg[i]:getWidth(),custombackgroundimg[i]:getHeight()) end return end while love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/background" .. i .. ".png") do custombackgroundimg[i] = love.graphics.newImage(mappackfolder .. "/" .. mappack .. "/background" .. i .. ".png") custombackgroundwidth[i] = custombackgroundimg[i]:getWidth()/16 custombackgroundheight[i] = custombackgroundimg[i]:getHeight()/16 i = i +1 end end if #custombackgroundimg == 0 then custombackgroundimg[i] = love.graphics.newImage("graphics/SMB/portalbackground.png") custombackgroundwidth[i] = custombackgroundimg[i]:getWidth()/16 custombackgroundheight[i] = custombackgroundimg[i]:getHeight()/16 if not SlowBackgrounds then custombackgroundimg[i]:setWrap("repeat","repeat") custombackgroundquad[i] = love.graphics.newQuad(0,0,width*16,height*16,custombackgroundimg[i]:getWidth(),custombackgroundimg[i]:getHeight()) end end end function loadcustomforeground(filename) local i = 1 customforegroundimg = {} customforegroundwidth = {} customforegroundheight = {} customforegroundanim = {} --try to load map specific foreground first local levelstring = marioworld .. "-" .. mariolevel local actualsublevel = actualsublevel or mariosublevel if actualsublevel ~= 0 then levelstring = levelstring .. "_" .. actualsublevel end local name = levelstring .. "foreground" if filename and type(filename) == "string" then name = "backgrounds/" .. filename else filename = false--not a string end while love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/" .. name .. i .. ".png") do customforegroundimg[i] = love.graphics.newImage(mappackfolder .. "/" .. mappack .. "/" .. name .. i .. ".png") customforegroundwidth[i] = customforegroundimg[i]:getWidth()/16 customforegroundheight[i] = customforegroundimg[i]:getHeight()/16 if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/" .. name .. i .. ".json") then --load animation local data = love.filesystem.read(mappackfolder .. "/" .. mappack .. "/" .. name .. i .. ".json") if not data then return end data = data:gsub("\r", "") loadcustombackgroundanim(customforegroundimg, customforegroundwidth, customforegroundheight, customforegroundanim, i, data) end i = i +1 end if #customforegroundimg == 0 then if filename and love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/backgrounds/" .. filename .. ".png") then customforegroundimg[i] = love.graphics.newImage(mappackfolder .. "/" .. mappack .. "/backgrounds/" .. filename .. ".png") customforegroundwidth[i] = customforegroundimg[i]:getWidth()/16 customforegroundheight[i] = customforegroundimg[i]:getHeight()/16 if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/backgrounds/" .. filename .. ".json") then --load animation local data = love.filesystem.read(mappackfolder .. "/" .. mappack .. "/backgrounds/" .. filename .. ".json") if not data then return end data = data:gsub("\r", "") loadcustombackgroundanim(customforegroundimg, customforegroundwidth, customforegroundheight, customforegroundanim, i, data) end return end while love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/foreground" .. i .. ".png") do customforegroundimg[i] = love.graphics.newImage(mappackfolder .. "/" .. mappack .. "/foreground" .. i .. ".png") customforegroundwidth[i] = customforegroundimg[i]:getWidth()/16 customforegroundheight[i] = customforegroundimg[i]:getHeight()/16 i = i +1 end end if #customforegroundimg == 0 then customforegroundimg[i] = love.graphics.newImage("graphics/SMB/portalforeground.png") customforegroundwidth[i] = customforegroundimg[i]:getWidth()/16 customforegroundheight[i] = customforegroundimg[i]:getHeight()/16 end end function loadcustombackgrounds() custombackgrounds = {"default"} local fl = love.filesystem.getDirectoryItems(mappackfolder .. "/" .. mappack .. "/backgrounds") for i = 1, #fl do local v = mappackfolder .. "/" .. mappack .. "/backgrounds/" .. fl[i] local extension = string.sub(v, -4, -1) local number = string.sub(v, -5, -5) if extension == ".png" and (number == "1" or (not tonumber(number))) then local name = string.sub(fl[i], 1, -6) if not tonumber(number) then name = string.sub(fl[i], 1, -5) end local bg = string.sub(v, 1, -6) local i = 1 table.insert(custombackgrounds, name) --[[else local name = string.sub(fl[i], 1, -5) local bg = string.sub(v, 1, -5) table.insert(custombackgrounds, name)]] end end end function loadcustombackgroundanim(img, width, height, anim, i, data) --timer, x, y, x speed, y speed, quad, frame, frames, quadi, quadcountx, quadcounty, delay anim[i] = JSON:decode(data) anim[i].x = 0 anim[i].y = 0 for id, v in pairs(anim[i]) do local a = id:lower() if type(v) == "string" then anim[i][a] = v:lower() else anim[i][a] = v end end --animation quads local b = anim[i] if b.quadcountx or b.quadcounty then b.quad = {} b.quadi = 1 b.frame = 1 local setframes = false if b.delay and tonumber(b.delay) then b.delay = {b.delay} end if not b.frames then b.frames = {} setframes = true end b.timer = b.delay[1] local x2 = b.quadcountx or 1 --frames hor local y2 = b.quadcounty or 1 --frames ver local w = width[i]*16 local h = height[i]*16 width[i] = width[i]/x2 height[i] = height[i]/y2 local c = 1 --count for y = 1, y2 do for x = 1, x2 do table.insert(b.quad, love.graphics.newQuad((x-1)*(w/x2), (y-1)*(h/y2), w/x2, h/y2, w, h)) if setframes then table.insert(b.frames, #b.quad) end c = c + 1 end end end end function loadanimatedtiles() --animated --Taken directly from SE if animatedtilecount then for i = 1, animatedtilecount do tilequads[i+90000] = nil end end animatedtiles = {} animatedrgblist = {} animatedtilesframe = {} local fl = love.filesystem.getDirectoryItems(mappackfolder .. "/" .. mappack .. "/animated") animatedtilecount = 0 local i = 1 while love.filesystem.isFile(mappackfolder .. "/" .. mappack .. "/animated/" .. i .. ".png") do local v = mappackfolder .. "/" .. mappack .. "/animated/" .. i .. ".png" if love.filesystem.isFile(v) and string.sub(v, -4) == ".png" then if love.filesystem.isFile(string.sub(v, 1, -5) .. ".txt") then animatedtilecount = animatedtilecount + 1 local t = animatedquad:new(v, love.filesystem.read(string.sub(v, 1, -5) .. ".txt"), animatedtilecount+90000) tilequads[animatedtilecount+90000] = t table.insert(animatedtiles, t) local image = love.image.newImageData(mappackfolder .. "/" .. mappack .. "/animated/" .. i .. ".png") animatedrgblist[animatedtilecount+90000] = {} local tilewidth = 16 if image:getHeight() > 16 then --SE Tiles tilewidth = 17 end for x = 1, math.floor(image:getWidth()/tilewidth) do local r, g, b = getaveragecolor2(image, x, 1) animatedrgblist[animatedtilecount+90000][x] = {r, g, b} end animatedtilesframe[animatedtilecount+90000] = 1 end end i = i + 1 end end function loadcustomsounds() local starmusicexists = love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/sounds/starmusic.ogg") local starmusicfastexists = love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/sounds/starmusic-fast.ogg") if starmusicexists and starmusicfastexists then music:preload(mappackfolder .. "/" .. mappack .. "/sounds/starmusic.ogg", "starmusic") music:preload(mappackfolder .. "/" .. mappack .. "/sounds/starmusic-fast.ogg", "starmusic-fast") customstarmusic = true else if starmusicexists then notice.new("can't load custom starmusic.ogg\nstarmusic-fast.ogg is missing!", notice.red, 6) elseif starmusicfastexists then notice.new("can't load custom starmusic-fast.ogg\nstarmusic.ogg is missing!", notice.red, 6) end if customstarmusic then music:preload("sounds/starmusic.ogg", "starmusic") music:preload("sounds/starmusic-fast.ogg", "starmusic-fast") end customstarmusic = false end if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/sounds/princessmusic.ogg") then music:preload(mappackfolder .. "/" .. mappack .. "/sounds/princessmusic.ogg", "princessmusic") customprincessmusic = true else if customprincessmusic then music:preload("sounds/princessmusic.ogg", "princessmusic") end customprincessmusic = false end if love.filesystem.isDirectory(mappackfolder .. "/" .. mappack .. "/sounds") or customsounds then for i, j in pairs(soundliststring) do if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/sounds/" .. j .. ".ogg") then local method = "static" if j == "pbutton" or j == "megamushroom" then method = "stream" end _G[j .. "sound"] = love.audio.newSource(mappackfolder .. "/" .. mappack .. "/sounds/" .. j .. ".ogg", method);_G[j .. "sound"]:setVolume(0);_G[j .. "sound"]:play();_G[j .. "sound"]:stop();_G[j .. "sound"]:setVolume(1) if j == "scorering" or j == "raccoonplane" or j == "wind" or j == "pbutton" or j == "megamushroom" then _G[j .. "sound"]:setLooping(true) end if not customsounds then customsounds = {} end customsounds[i] = true elseif customsounds then if customsounds[i] then local method = "static" if j == "pbutton" or j == "megamushroom" then method = "stream" end _G[j .. "sound"] = love.audio.newSource("sounds/" .. j .. ".ogg", method);_G[j .. "sound"]:setVolume(0);_G[j .. "sound"]:play();_G[j .. "sound"]:stop();_G[j .. "sound"]:setVolume(1) if j == "scorering" or j == "raccoonplane" or j == "wind" or j == "pbutton" or j == "megamushroom" then _G[j .. "sound"]:setLooping(true) end end customsounds[i] = nil end end updatesoundlist() end end function loadcustommusic() custommusiclist = {} local files = love.filesystem.getDirectoryItems(mappackfolder .. "/" .. mappack .. "/music") for i, s in pairs(files) do if s:sub(-4) == ".mp3" or s:sub(-4) == ".ogg" then if not (s:sub(-9, -5) == "-fast" or s:sub(-10, -5) == "-intro") then table.insert(custommusiclist, "music/" .. s) end end end custommusics = {} musictable = {"none", "overworld", "underground", "castle", "underwater", "star", "custom"} editormusictable = {"none", "overworld", "underground", "castle", "underwater", "star", "custom"} for i = 0, 99 do custommusics[i] = false if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/music" .. tostring(i) .. ".ogg") then custommusics[i] = mappackfolder .. "/" .. mappack .. "/music" .. tostring(i) .. ".ogg" music:load(custommusics[i]) elseif love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/music" .. tostring(i) .. ".mp3") then custommusics[i] = mappackfolder .. "/" .. mappack .. "/music" .. tostring(i) .. ".mp3" music:load(custommusics[i]) elseif i > 9 then break --stop counting music if one is missing end end for i, s in pairs(custommusiclist) do custommusics[s] = mappackfolder .. "/" .. mappack .. "/" .. s music:load(custommusics[s]) table.insert(musictable, s) table.insert(editormusictable, s:sub(7, -5):lower()) end if love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/music.ogg") then custommusics[1] = mappackfolder .. "/" .. mappack .. "/music.ogg" music:load(custommusics[1]) elseif love.filesystem.exists(mappackfolder .. "/" .. mappack .. "/music.mp3") then custommusics[1] = mappackfolder .. "/" .. mappack .. "/music.mp3" music:load(custommusics[1]) end end function getmappacklevels() local levels = {} mappacklevels = {} minusworld = false local worlds = defaultworlds local files = love.filesystem.getDirectoryItems(mappackfolder .. "/" .. mappack) for i, s in pairs(files) do local f1 = s:find("-") if s:sub(-4) == ".txt" and f1 then --check if level file (false positives can't hurt though) s = s:sub(1, -5) local w = s:sub(1, f1-1) --world local f2 = (s:find("_")) or math.huge --find underscore between level and sublevel local l = s:sub(f1+1, math.min(#s, f2-1))--level local sl if w == "M" then --check if minus world minusworld = true else --count worlds w = tonumber(w) if not w then --nothing?? elseif w > maxworlds then --might miss minus world but who cares w = maxworlds --break (unquote this to speed up (will not properly count levels though)) elseif w > worlds then worlds = w end --sub level sl = 0 if f2 ~= math.huge then sl = s:sub(f2+1, -1) sl = tonumber(sl) if not sl then sl = 0 end end --count levels l = tonumber(l) if w and l then local number_of_levels = math.max(defaultlevels, math.min(l, maxlevels)) if not levels[w] then levels[w] = {} --where levels are stored end while number_of_levels > #levels[w] do table.insert(levels[w], defaultsublevels) --where number of sublevels are stored end --get highest sublevel if levels[w][l] and sl > levels[w][l] then levels[w][l] = math.max(defaultsublevels, math.min(maxsublevels, sl)) end end end end end for i = 1, worlds do local levelcount = {defaultsublevels,defaultsublevels,defaultsublevels,defaultsublevels} if levels[i] then levelcount = levels[i] end --print("world: ", i, " levels: ", #levelcount, " sublevels: ", unpack(levelcount)) table.insert(mappacklevels, levelcount) end end function loadnitpicks() --shit i don't want to add --if people complain about stuff they can use this nitpicks = false if love.filesystem.exists("alesans_entities/nitpicks.json") then local data = love.filesystem.read("alesans_entities/nitpicks.json") t = JSON:decode(data or "") --CASE INSENSITVE THING for i, v in pairs(t) do t[i:lower()] = v end --this probably doesn't work dropshadow = t.dropshadow AutoAssistMode = t.assistmode --also available in settings.txt if t.fourbythree then fourbythree = true if fourbythree then width = 16 else width = 25 end if scale == 2 and resizable then changescale(5, fullscreen) else changescale(scale, fullscreen) end end if t.windowwidth and t.windowheight then width = t.windowwidth height = t.windowheight maxtilespritebatchsprites = math.max(maxtilespritebatchsprites,width*height+width+height+1) if scale == 2 and resizable then changescale(5, fullscreen) else changescale(scale, fullscreen) end end PlayMusicInEditor = t.playmusicineditor DisableToolTips = t.disabletooltips DisableMouseInMainMenu = t.disablemouseinmainmenu if t.noportalgun then playertypei = 5 playertype = playertypelist[playertypei] end if t.mariomakergravity then maxyspeed = smbmaxyspeed --SMB: 14 mari0maxyspeed = maxyspeed end DontPauseOnUnfocus = t.dontpauseonunfocus FireButtonCannonHelmet = t.firebuttoncannonhelmet PipesInEditor = t.pipesineditor NoOnlineMultiplayerNames = t.noonlinemultiplayernames if t.letterbox ~= nil then letterboxfullscreen = t.letterbox --mouse inputs will be in the wrong place! end CustomPortalColors = t.customportalcolors UseButtonCappy = t.usebuttoncappy local oldfamilyfriendly = FamilyFriendly FamilyFriendly = t.familyfriendly or t.ilovefamilyguy if FamilyFriendly then love.filesystem.write("alesans_entities/familyfriendly.txt","") elseif oldfamilyfriendly then love.filesystem.remove("alesans_entities/familyfriendly.txt") end if t.showfps then showfps = t.showfps end InfiniteLivesMultiplayer = t.infinitelivesmultiplayer SlowBackgrounds = t.slowbackgrounds NoCharacterZipNotices = t.nocharacterzipnotices NoMusic = t.nomusic EditorZoom = t.editorzoom DirectDLCDownloads = t.directdlcdownloads _3DMODE = t.render3d HITBOXDEBUG = t.viewhitboxes if t.pcversion then android = false androidsafe = true end if t.hideandroidbuttons then androidHIDE = true end if t.androidversion then android = t.androidversion androidtest = true changescale(scale, fullscreen) end if t.debugGraphs then debugGraphs = t.debugGraphs end if t.console then if love._openConsole then love._openConsole() end end end end function disablecheats() playertype = "portal" playertypei = 1 bullettime = false speedtarget = 1 portalknockback = false bigmario = false goombaattack = false sonicrainboom = false playercollisions = false infinitetime = false infinitelives = false darkmode = false end --sausage (don't ask) function dothesausage(i) if i then if i == 1 and sausagesound then titleimage = love.graphics.newImage("graphics/" .. graphicspack .. "/nippon/title.png") goombaimage = love.graphics.newImage("graphics/" .. graphicspack .. "/nippon/goomba.png") goombaimageframes = math.floor(goombaimage:getWidth()/16) goombaquad = {} for y = 1, 4 do goombaquad[y] = {} for x = 1, goombaimageframes do goombaquad[y][x] = love.graphics.newQuad((x-1)*16, (y-1)*16, 16, 16, goombaimage:getWidth(), 64) end end plantimg = love.graphics.newImage("graphics/" .. graphicspack .. "/nippon/plant.png") axeimg = love.graphics.newImage("graphics/" .. graphicspack .. "/nippon/axe.png") castleflagimg = love.graphics.newImage("graphics/" .. graphicspack .. "/nippon/castleflag.png") peachimg = love.graphics.newImage("graphics/" .. graphicspack .. "/nippon/peach.png") toadimg = love.graphics.newImage("graphics/" .. graphicspack .. "/nippon/toad.png") starimg = love.graphics.newImage("graphics/" .. graphicspack .. "/nippon/star.png") love.graphics.setBackgroundColor(0, 0, 0) end else if sausagesound then playsound(sausagesound) sausagesound = nil end end end function shallowcopy(orig) local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in pairs(orig) do copy[orig_key] = orig_value end else -- number, string, boolean, etc copy = orig end return copy end function deepcopy(orig) local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end setmetatable(copy, deepcopy(getmetatable(orig))) else -- number, string, boolean, etc copy = orig end return copy end
return { {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, desc_get = "", name = "能代1", init_effect = "", time = 0, color = "blue", picture = "", desc = "", stack = 1, id = 12830, icon = 12830, last_effect = "", effect_list = { { type = "BattleBuffCastSkill", trigger = { "onStartGame" }, arg_list = { skill_id = 12830, target = "TargetSelf" } }, { type = "BattleBuffField", trigger = {}, arg_list = { buff_id = 12832, target = "TargetPlayerVanguardFleet" } } } }
---@class vm local vm = require 'vm.vm' ---@param uri uri ---@param child vm.node|string ---@param parent vm.node|string ---@param mark? table ---@return boolean function vm.isSubType(uri, child, parent, mark) if type(parent) == 'string' then parent = vm.createNode(vm.getGlobal('type', parent)) end if type(child) == 'string' then child = vm.createNode(vm.getGlobal('type', child)) end if not child or not parent then return false end mark = mark or {} for obj in child:eachObject() do if obj.type ~= 'global' or obj.cate ~= 'type' then goto CONTINUE_CHILD end if mark[obj.name] then return false end mark[obj.name] = true for parentNode in parent:eachObject() do if parentNode.type ~= 'global' or parentNode.cate ~= 'type' then goto CONTINUE_PARENT end if parentNode.name == 'any' or obj.name == 'any' then return true end if parentNode.name == obj.name then return true end for _, set in ipairs(obj:getSets(uri)) do if set.type == 'doc.class' and set.extends then for _, ext in ipairs(set.extends) do if ext.type == 'doc.extends.name' and vm.isSubType(uri, ext[1], parentNode.name, mark) then return true end end end if set.type == 'doc.alias' and set.extends then for _, ext in ipairs(set.extends.types) do if ext.type == 'doc.type.name' and vm.isSubType(uri, ext[1], parentNode.name, mark) then return true end end end end ::CONTINUE_PARENT:: end ::CONTINUE_CHILD:: end return false end ---@param uri uri ---@param tnode vm.node ---@param knode vm.node ---@return vm.node? function vm.getTableValue(uri, tnode, knode) local result = vm.createNode() for tn in tnode:eachObject() do if tn.type == 'doc.type.table' then for _, field in ipairs(tn.fields) do if vm.isSubType(uri, vm.compileNode(field.name), knode) then if field.extends then result:merge(vm.compileNode(field.extends)) end end end end if tn.type == 'doc.type.array' then result:merge(vm.compileNode(tn.node)) end if tn.type == 'table' then for _, field in ipairs(tn) do if field.type == 'tableindex' then if field.value then result:merge(vm.compileNode(field.value)) end end if field.type == 'tablefield' then if vm.isSubType(uri, knode, 'string') then if field.value then result:merge(vm.compileNode(field.value)) end end end if field.type == 'tableexp' then if vm.isSubType(uri, knode, 'integer') and field.tindex == 1 then if field.value then result:merge(vm.compileNode(field.value)) end end end end end end if result:isEmpty() then return nil end return result end ---@param uri uri ---@param tnode vm.node ---@param vnode vm.node ---@return vm.node? function vm.getTableKey(uri, tnode, vnode) local result = vm.createNode() for tn in tnode:eachObject() do if tn.type == 'doc.type.table' then for _, field in ipairs(tn.fields) do if field.extends then if vm.isSubType(uri, vm.compileNode(field.extends), vnode) then result:merge(vm.compileNode(field.name)) end end end end if tn.type == 'doc.type.array' then result:merge(vm.declareGlobal('type', 'integer')) end if tn.type == 'table' then for _, field in ipairs(tn) do if field.type == 'tableindex' then if field.index then result:merge(vm.compileNode(field.index)) end end if field.type == 'tablefield' then result:merge(vm.declareGlobal('type', 'string')) end if field.type == 'tableexp' then result:merge(vm.declareGlobal('type', 'integer')) end end end end if result:isEmpty() then return nil end return result end
local I18N = require("core.I18N") I18N.add { common = { nothing_happens = "何もおきない… ", something_is_put_on_the_ground = "何かが足元に転がってきた。", you_put_in_your_backpack = "{itemname($1, 1)}をバックパックに入れた。", it_is_impossible = "それは無理だ。", }, }
local helper = require('arken.Helper') local dispatcher = require('arken.dispatcher') local test = {} test.before = function() dispatcher.prefix = "" dispatcher.controller = nil dispatcher.controller_name = nil dispatcher.action = nil end test.should_return_html = function() local result = helper:img("main.png") local html = [[<img src="/images/main.png?0" title="main" />]] assert( result == html, result ) end test.should_return_html_with_title = function() local result = helper:img("main.png", { title = 'my image' } ) local html = [[<img src="/images/main.png?0" title="my image" />]] assert( result == html, result ) end test.should_return_html_with_prefix = function() dispatcher.prefix = '/app' local result = helper:img("main.png", { title = 'my image' } ) dispatcher.prefix = '' local html = [[<img src="/app/images/main.png?0" title="my image" />]] assert( result == html, result ) end return test
function love.load() fieldWidth = 20 fieldHeight = 15 totalBombs = 10 field = {} for y = 1, fieldHeight do field[y] = {} for x = 1, fieldWidth do field[y][x] = {type = 0, subType = 0} end end cellSize = 30 cellTypes = { [-1] = {data = "B", color = {0, 0, 0}}, [0] = {data = "", color = {0, 0, 0}}, [1] = {data = "1", color = {0, 0, 0.8}}, [2] = {data = "2", color = {0, 0.8, 0}}, [3] = {data = "3", color = {0.8, 0.8, 0}}, [4] = {data = "4", color = {0.8, 0, 0}}, [5] = {data = "5", color = {0, 0, 0.6}}, [6] = {data = "6", color = {0, 0.6, 0}}, [7] = {data = "7", color = {0.6, 0.6, 0}}, [8] = {data = "8", color = {0.6, 0, 0}} } function checkPosition(x, y) return x > 0 and x <= fieldWidth and y > 0 and y <= fieldHeight end function generateField() fieldGenerated = true local positions = {} for y = 1, fieldHeight do for x = 1, fieldWidth do if x ~= currentX or y ~= currentY then table.insert(positions, {x = x, y = y}) end end end for i = 1, totalBombs do local posIdx = love.math.random(#positions) local position = table.remove(positions, posIdx) field[position.y][position.x].type = -1 for y = -1, 1 do for x = -1, 1 do local tempX = position.x + x local tempY = position.y + y if checkPosition(tempX, tempY) and field[tempY][tempX].type ~= -1 then field[tempY][tempX].type = field[tempY][tempX].type + 1 end end end end for y = 1, fieldHeight do for x = 1, fieldWidth do if field[y][x].type > 0 then totalNumbers = totalNumbers + 1 end end end startTime = love.timer.getTime() end gameOver = false gameOverTime = 0 fieldGenerated = false flagsCounter = 0 totalNumbers = 0 numbersOpened = 0 end function love.draw() local function draw_cell(x, y, cell) if cell.subType == 1 then love.graphics.setColor(0.9, 0.9, 0.9) elseif cell.subType == 4 then love.graphics.setColor(0.8, 0, 0) else if (love.mouse.isDown(1) or love.mouse.isDown(2)) and x == currentX and y == currentY then love.graphics.setColor(0.3, 0.3, 0.3) else love.graphics.setColor(0.6, 0.6, 0.6) end end love.graphics.rectangle( 'fill', (x - 1) * cellSize, (y - 1) * cellSize, cellSize - 1, cellSize - 1 ) if cell.subType == 1 then love.graphics.setColor(cellTypes[cell.type].color) love.graphics.print( cellTypes[cell.type].data, (x - 1) * cellSize + cellSize/4, (y - 1) * cellSize) elseif cell.subType == 2 then love.graphics.setColor(0.4, 0, 0) love.graphics.print( "F", (x - 1) * cellSize + cellSize/4, (y - 1) * cellSize) elseif cell.subType == 3 then love.graphics.setColor(0, 0, 0) love.graphics.print( "?", (x - 1) * cellSize + cellSize/4, (y - 1) * cellSize) elseif gameOver and cell.type == -1 then love.graphics.setColor(cellTypes[cell.type].color) love.graphics.print( cellTypes[cell.type].data, (x - 1) * cellSize + cellSize/4, (y - 1) * cellSize) end end love.graphics.setNewFont(24) for y = 1, fieldHeight do for x = 1, fieldWidth do draw_cell(x, y, field[y][x]) end end love.graphics.setColor(0.9, 0.9, 0.9) love.graphics.setNewFont(32) love.graphics.print("Bombs: "..totalBombs, 615, 100) love.graphics.print("Flags: "..flagsCounter, 615, 150) if fieldGenerated then if gameOver then diff = gameOverTime - startTime else diff = love.timer.getTime() - startTime end seconds = math.ceil(diff % 60) minutes = math.floor(diff / 60) love.graphics.print(minutes..":"..seconds, 615, 200) end end function love.update(dt) if not gameOver then currentX = math.ceil(love.mouse.getX() / 30) currentY = math.ceil(love.mouse.getY() / 30) end end function love.mousereleased(mouseX, mouseY, button) local function setGameOver() gameOver = true gameOverTime = love.timer.getTime() end local function dfs(cellX, cellY) for y = -1, 1 do for x = -1, 1 do local tempX = cellX + x local tempY = cellY + y if checkPosition(tempX, tempY) and field[tempY][tempX].subType == 0 then if field[tempY][tempX].type == -1 then setGameOver() field[tempY][tempX].subType = 4 else field[tempY][tempX].subType = 1 end if field[tempY][tempX].type == 0 then dfs(tempX, tempY) elseif field[tempY][tempX].type > 0 then numbersOpened = numbersOpened + 1 if numbersOpened == totalNumbers then setGameOver() end end end end end end local function countFlags(cellX, cellY) local ans = 0 for y = -1, 1 do for x = -1, 1 do local tempX = cellX + x local tempY = cellY + y if checkPosition(tempX, tempY) and field[tempY][tempX].subType == 2 then ans = ans + 1 end end end return ans end if not gameOver then if button == 1 then if not fieldGenerated then generateField() end if checkPosition(currentX, currentY) then local cell = field[currentY][currentX] if cell.subType == 0 then if cell.type == -1 then setGameOver() cell.subType = 4 else cell.subType = 1 if cell.type == 0 then dfs(currentX, currentY) elseif cell.type > 0 then numbersOpened = numbersOpened + 1 if numbersOpened == totalNumbers then setGameOver() end end end end end elseif button == 2 then if checkPosition(currentX, currentY) then local cell = field[currentY][currentX] if cell.subType == 0 then cell.subType = 2 flagsCounter = flagsCounter + 1 elseif cell.subType == 2 then cell.subType = 3 flagsCounter = flagsCounter - 1 elseif cell.subType == 3 then cell.subType = 0 end end elseif button == 3 then if checkPosition(currentX, currentY) then local cell = field[currentY][currentX] if cell.subType == 1 and cell.type > 0 and countFlags(currentX, currentY) == cell.type then dfs(currentX, currentY) end end end end end function love.keypressed(key) if gameOver and key == "r" then love.load() end end
-- https://www.reddit.com/r/neovim/comments/jvisg5/lets_talk_formatting_again/ -- Use an on_attach function to only map the following keys -- after the language server attaches to the current buffer local on_attach = function(client, bufnr) if client.resolved_capabilities.document_formatting then vim.cmd([[ augroup Format au! * <buffer> au BufWritePre <buffer> lua vim.lsp.buf.formatting_sync(nil, 1000) augroup END ]]) end -- So that the only client with format capabilities is efm if client.name ~= "gopls" and client.name ~= "go" and client.name ~= "efm" and client.name ~= "rnix" then client.resolved_capabilities.document_formatting = false end require("lsp_signature").on_attach() vim.api.nvim_buf_set_option(bufnr, "omnifunc", "v:lua.vim.lsp.omnifunc") local opts = { noremap = true, silent = true } vim.api.nvim_buf_set_keymap(bufnr, "n", "gD", "<cmd>lua vim.lsp.buf.declaration()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "K", "<cmd>lua vim.lsp.buf.hover()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "gi", "<cmd>lua vim.lsp.buf.implementation()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "<C-k>", "<cmd>lua vim.lsp.buf.signature_help()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>wa", "<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>wr", "<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>", opts) vim.api.nvim_buf_set_keymap( bufnr, "n", "<leader>wl", "<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>", opts ) vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>D", "<cmd>lua vim.lsp.buf.type_definition()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>rn", "<cmd>lua vim.lsp.buf.rename()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>ca", "<cmd>lua vim.lsp.buf.code_action()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>e", "<cmd>lua vim.diagnostic.open_float()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "[d", "<cmd>lua vim.diagnostic.goto_prev()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "]d", "<cmd>lua vim.diagnostic.goto_next()<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>q", "<cmd>lua vim.diagnostic.setloclist()<CR>", opts) vim.api.nvim_buf_set_keymap( bufnr, "n", "<leader>so", [[<cmd>lua require('telescope.builtin').lsp_document_symbols()<CR>]], opts ) vim.cmd([[ command! Format execute 'lua vim.lsp.buf.formatting()' ]]) end return on_attach
object_mobile_som_cww8a_battle_droid = object_mobile_som_shared_cww8a_battle_droid:new { } ObjectTemplates:addTemplate(object_mobile_som_cww8a_battle_droid, "object/mobile/som/cww8a_battle_droid.iff")
local function setup(args) local xplr = xplr args = args or {} args.mode = args.mode or "default" args.keys = args.keys or { ["ctrl-e"] = "tabedit", ["e"] = "e", } for key, command in pairs(args.keys) do xplr.config.modes.builtin[args.mode].key_bindings.on_key[key] = { help = "nvim :" .. command, messages = { "PopMode", { BashExecSilently = [=[ nvim-ctrl "]=] .. command .. [=[ ${XPLR_FOCUS_PATH:?}" ]=], }, }, } end end return { setup = setup }
return { HOOK_CHUNK_UNLOADED = { CalledWhen = "A chunk has been unloaded from the memory.", DefaultFnName = "OnChunkUnloaded", -- also used as pagename Desc = [[ This hook is called when a chunk is unloaded from the memory. Though technically still in memory, the plugin should behave as if the chunk was already not present. In particular, {{cWorld}} block API should not be used in the area of the specified chunk. ]], Params = { { Name = "World", Type = "{{cWorld}}", Notes = "The world from which the chunk is unloading" }, { Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" }, { Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" }, }, Returns = [[ If the function returns false or no value, the next plugin's callback is called. If the function returns true, no other callback is called for this event. There is no behavior that plugins could override. ]], }, -- HOOK_CHUNK_UNLOADED }
--Created by the QnEditor,do not modify.If not,you will die very nankan! local MAP = { var = { Image_line = 1, Button_info = 2, Text_nickname = 3, Image_money = 4, Text_num = 5, }, ui = { [1] = {"Image_line"}, [2] = {"Button_info"}, [3] = {"Text_nickname"}, [4] = {"Image_money"}, [5] = {"Text_num"}, }, func = { [2] = "onBindInfo", }, } return MAP;
local skynet = require "skynet" local sd = require "skynet.sharedata.corelib" local service skynet.init(function() service = skynet.uniqueservice "sharedatad" end) local sharedata = {} local cache = setmetatable({}, { __mode = "kv" }) local function monitor(name, obj, cobj) local newobj = cobj while true do newobj = skynet.call(service, "lua", "monitor", name, newobj) if newobj == nil then break end sd.update(obj, newobj) skynet.send(service, "lua", "confirm" , newobj) end if cache[name] == obj then cache[name] = nil end end function sharedata.query(name) if cache[name] then return cache[name] end local obj = skynet.call(service, "lua", "query", name) local r = sd.box(obj) skynet.send(service, "lua", "confirm" , obj) skynet.fork(monitor,name, r, obj) cache[name] = r return r end function sharedata.new(name, v, ...) skynet.call(service, "lua", "new", name, v, ...) end function sharedata.update(name, v, ...) skynet.call(service, "lua", "update", name, v, ...) end function sharedata.delete(name) skynet.call(service, "lua", "delete", name) end function sharedata.flush() for name, obj in pairs(cache) do sd.flush(obj) end collectgarbage() end function sharedata.deepcopy(name, ...) if cache[name] then local cobj = cache[name].__obj return sd.copy(cobj, ...) end local cobj = skynet.call(service, "lua", "query", name) local ret = sd.copy(cobj, ...) skynet.send(service, "lua", "confirm" , cobj) return ret end return sharedata
-- Section for example.com VirtualHost "example.com" enabled = false -- Remove this line to enable this host -- Assign this host a certificate for TLS, otherwise it would use the one -- set in the global section (if any). -- Note that old-style SSL on port 5223 only supports one certificate, and will always -- use the global one. ssl = { key = "/etc/prosody/certs/example.com.key"; certificate = "/etc/prosody/certs/example.com.crt"; } ------ Components ------ -- You can specify components to add hosts that provide special services, -- like multi-user conferences, and transports. -- For more information on components, see http://prosody.im/doc/components -- Set up a MUC (multi-user chat) room server on conference.example.com: Component "conference.example.com" "muc" -- Set up a SOCKS5 bytestream proxy for server-proxied file transfers: --Component "proxy.example.com" "proxy65" ---Set up an external component (default component port is 5347) --Component "gateway.example.com" -- component_secret = "password"
-- contrib/buildbot_all.lua -- Copyright (C) 2012 Andrzje Bieniek <[email protected]> -- Copyright (C) 2017 Jörg Thalheim <[email protected]> -- -- This file is part of Vicious. -- -- Vicious is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as -- published by the Free Software Foundation, either version 2 of the -- License, or (at your option) any later version. -- -- Vicious is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Vicious. If not, see <https://www.gnu.org/licenses/>. -- {{{ Grab environment local setmetatable = setmetatable local pcall = pcall local json_status, json = pcall(require, "json") local io = { popen = io.popen } local pairs = pairs local assert = assert -- }}} local bb = {} --list of all buildbot builders local bs = {OK=1, FAILED=2, RUNNING=3} local bc = {"green", "red", "yellow"} local buildbot_all = {} BB = {} BB.__index = BB function BB.create(url, builder) local b = {} setmetatable(b,BB) b.url = url -- buildbot url b.builder = builder -- builder name b.lastChecked = 0 -- last checked build number b.lastSuccessful = 0 -- last successful build number b.lastResult = nil -- last json parsed result b.lastError = nil -- last error string or nil if no error return b end function BB:_queryBuildbot(build_number) local f = io.popen("curl --connect-timeout 1 "..self.url.."/json/builders/"..self.builder.."/builds/"..build_number) local jsbuilder = f:read("*all") f:close() if #jsbuilder == 0 then return false, "can't read from url" end local result_status, result = pcall(json.decode, jsbuilder, false) if not result_status then return false, "can't parse json data" end return true, result end function BB:_getBuildStatus(result) if #result['text'] > 0 then local text = result['text'] if text[1] == "build" and text[2] == "successful" and #text == 2 then --successful return bs.OK else --failed return bs.FAILED end else --in progress return bs.RUNNING end end -- Function queries buildbot to refresh builds status. -- * if build is successful or failed it will not be queried again, number is stored in lasteChecked -- * up to 10 last builds will be checked to find last successful build function BB:refresh() local last_pass_fail = 0 local nr = -1 local last_result local iter_counter = 0 self.lastError = nil self.lastResult = nil --- there is a gap to fill in, iterate all not checked builds starting from latest while nr > self.lastChecked or nr == -1 do local r_status, r = self:_queryBuildbot(nr) local s if not r_status then self.lastError = r return end s = self:_getBuildStatus(r) if not last_result then last_result = r end nr = r['number'] assert(nr > 0) if last_pass_fail == 0 and (s == bs.OK or s == bs.FAILED) then last_pass_fail = nr end if s == bs.OK then --successful self.lastSuccessful = nr break; end nr = nr - 1 iter_counter = iter_counter + 1 if iter_counter > 10 then --check max last 10 builds when searching for successful build break; end end if last_pass_fail ~= 0 then self.lastChecked = last_pass_fail end if last_result then self.lastResult = last_result end end function BB:getLastSuccessful() return self.lastSuccessful end function BB:getCurrent() return self.lastResult['number'] end function BB:getCurrentStatus() return self:_getBuildStatus(self.lastResult) end function BB:getBuilder() return self.builder end function BB:getError() return self.lastError end local function getBuilderStatus(b) local s = "[" .. b:getBuilder() --check if json library was loaded correctly if not json_status then return s .. ".<span color=\"orange\">can't find libluaX.X-json</span>]" end local err = b:getError() if err then return s .. ".<span color=\"orange\">" .. err .. "</span>]" end if b:getLastSuccessful() ~= 0 then success_build_nr_str = "<span color=\"green\">".. b:getLastSuccessful() .."</span>" else success_build_nr_str = "-" end local current_build_color = bc[b:getCurrentStatus()] current_build_nr_str = "<span color=\""..current_build_color.."\">"..b:getCurrent().."</span>" if current_build_color ~= "green" then s = s .. "." .. current_build_nr_str end return s .. "." .. success_build_nr_str .. "]" end -- {{{ Buildbot widget type local function worker(format, warg) if #bb == 0 then --fill up bb with builders when worker function is run for the first time for i,v in pairs(warg) do bb[#bb+1] = BB.create(v["url"], v["builder"]) end end local str = "" for i,v in pairs(bb) do v:refresh() str = str .. " " .. getBuilderStatus(v) end return {str .. " "} end -- }}} setmetatable(buildbot_all, { __call = function(_, ...) return worker(...) end })
g_VR = g_VR or {} local convars, convarValues = vrmod.GetConvars() vrmod.AddCallbackedConvar("vrmod_net_tickrate", nil, tostring(math.ceil(1/engine.TickInterval())), FCVAR_REPLICATED, nil, nil, nil, tonumber, nil) local function netReadFrame() local frame = { ts = net.ReadFloat(), characterYaw = net.ReadUInt(7) * 2.85714, finger1 = net.ReadUInt(7) / 100, finger2 = net.ReadUInt(7) / 100, finger3 = net.ReadUInt(7) / 100, finger4 = net.ReadUInt(7) / 100, finger5 = net.ReadUInt(7) / 100, finger6 = net.ReadUInt(7) / 100, finger7 = net.ReadUInt(7) / 100, finger8 = net.ReadUInt(7) / 100, finger9 = net.ReadUInt(7) / 100, finger10 = net.ReadUInt(7) / 100, hmdPos = net.ReadVector(), hmdAng = net.ReadAngle(), lefthandPos =net.ReadVector(), lefthandAng = net.ReadAngle(), righthandPos = net.ReadVector(), righthandAng = net.ReadAngle(), } if net.ReadBool() then frame.waistPos = net.ReadVector() frame.waistAng = net.ReadAngle() frame.leftfootPos = net.ReadVector() frame.leftfootAng = net.ReadAngle() frame.rightfootPos = net.ReadVector() frame.rightfootAng = net.ReadAngle() end return frame end local function buildClientFrame(relative) local frame = { characterYaw = LocalPlayer():InVehicle() and LocalPlayer():GetAngles().yaw or g_VR.characterYaw, hmdPos = g_VR.tracking.hmd.pos, hmdAng = g_VR.tracking.hmd.ang, lefthandPos = g_VR.tracking.pose_lefthand.pos, lefthandAng = g_VR.tracking.pose_lefthand.ang, righthandPos = g_VR.tracking.pose_righthand.pos, righthandAng = g_VR.tracking.pose_righthand.ang, finger1 = g_VR.input.skeleton_lefthand.fingerCurls[1], finger2 = g_VR.input.skeleton_lefthand.fingerCurls[2], finger3 = g_VR.input.skeleton_lefthand.fingerCurls[3], finger4 = g_VR.input.skeleton_lefthand.fingerCurls[4], finger5 = g_VR.input.skeleton_lefthand.fingerCurls[5], finger6 = g_VR.input.skeleton_righthand.fingerCurls[1], finger7 = g_VR.input.skeleton_righthand.fingerCurls[2], finger8 = g_VR.input.skeleton_righthand.fingerCurls[3], finger9 = g_VR.input.skeleton_righthand.fingerCurls[4], finger10 = g_VR.input.skeleton_righthand.fingerCurls[5], } if g_VR.sixPoints then frame.waistPos = g_VR.tracking.pose_waist.pos frame.waistAng = g_VR.tracking.pose_waist.ang frame.leftfootPos = g_VR.tracking.pose_leftfoot.pos frame.leftfootAng = g_VR.tracking.pose_leftfoot.ang frame.rightfootPos = g_VR.tracking.pose_rightfoot.pos frame.rightfootAng = g_VR.tracking.pose_rightfoot.ang end if relative then local plyPos, plyAng = LocalPlayer():GetPos(), (LocalPlayer():InVehicle() and LocalPlayer():GetVehicle():GetAngles() or Angle()) frame.hmdPos, frame.hmdAng = WorldToLocal(frame.hmdPos, frame.hmdAng, plyPos, plyAng) frame.lefthandPos, frame.lefthandAng = WorldToLocal(frame.lefthandPos, frame.lefthandAng, plyPos, plyAng) frame.righthandPos, frame.righthandAng = WorldToLocal(frame.righthandPos, frame.righthandAng, plyPos, plyAng) if g_VR.sixPoints then frame.waistPos, frame.waistAng = WorldToLocal(frame.waistPos, frame.waistAng, plyPos, plyAng) frame.leftfootPos, frame.leftfootAng = WorldToLocal(frame.leftfootPos, frame.leftfootAng, plyPos, plyAng) frame.rightfootPos, frame.rightfootAng = WorldToLocal(frame.rightfootPos, frame.rightfootAng, plyPos, plyAng) end end return frame end local function netWriteFrame(frame) net.WriteFloat(SysTime()) local tmp = frame.characterYaw + math.ceil(math.abs(frame.characterYaw)/360)*360 --normalize and convert characterYaw to 0-360 tmp = tmp - math.floor(tmp/360)*360 net.WriteUInt(frame.characterYaw*0.35,7) --crush from 0-360 to 0-127 net.WriteUInt(frame.finger1*100,7) net.WriteUInt(frame.finger2*100,7) net.WriteUInt(frame.finger3*100,7) net.WriteUInt(frame.finger4*100,7) net.WriteUInt(frame.finger5*100,7) net.WriteUInt(frame.finger6*100,7) net.WriteUInt(frame.finger7*100,7) net.WriteUInt(frame.finger8*100,7) net.WriteUInt(frame.finger9*100,7) net.WriteUInt(frame.finger10*100,7) net.WriteVector(frame.hmdPos) net.WriteAngle(frame.hmdAng) net.WriteVector(frame.lefthandPos) net.WriteAngle(frame.lefthandAng) net.WriteVector(frame.righthandPos) net.WriteAngle(frame.righthandAng) net.WriteBool(frame.waistPos ~= nil) if frame.waistPos then net.WriteVector(frame.waistPos) net.WriteAngle(frame.waistAng) net.WriteVector(frame.leftfootPos) net.WriteAngle(frame.leftfootAng) net.WriteVector(frame.rightfootPos) net.WriteAngle(frame.rightfootAng) end end if CLIENT then vrmod.AddCallbackedConvar("vrmod_net_delay", nil, "0.1", nil, nil, nil, nil, tonumber, nil) vrmod.AddCallbackedConvar("vrmod_net_delaymax", nil, "0.2", nil, nil, nil, nil, tonumber, nil) vrmod.AddCallbackedConvar("vrmod_net_storedframes", nil, "15", nil, nil, nil, nil, tonumber, nil) g_VR.net = { --[[ "steamid" = { frames = { 1 = { ts = Float characterYaw = Float characterWalkX = Float characterWalkY = Float originHeight = Float hmdPos = Vector hmdAng = Angle lefthandPos = Vector lefthandAng = Angle righthandPos = Vector righthandAng = Angle finger1..10 = Float } 2 = ... 3 = ... ... }, latestFrameIndex = Int lerpedFrame = Table playbackTime = Float (playhead position in frame timestamp space) sysTime = Float (used to determine dt from previous lerp for advancing playhead position) buffering = Bool debugState = String debugNextFrame = Int debugPreviousFrame = Int debugFraction = Float characterAltHead = Bool dontHideBullets = Bool } ]] } --[[ for testing net_debug g_VR.net["STEAM_0:1:47301228"] = { frames = { {ts=1}, {ts=2}, {ts=3}, {ts=4}, {ts=5}, {ts=6}, {ts=7}, {ts=8}, {ts=9.8}, {ts=10}, }, playbackTime = 9, debugState = "buffering (reached end)", debugNextFrame = 2, debugPreviousFrame = 1, debugFraction = 0.5, } --]] local debugToggle = false concommand.Add( "vrmod_net_debug", function( ply, cmd, args ) if debugToggle then hook.Remove("PostRender","vrutil_netdebug") debugToggle = false return end debugToggle = true hook.Add("PostRender","vrutil_netdebug",function() cam.Start2D() surface.SetFont( "ChatFont" ) surface.SetTextColor( 255, 255, 255 ) surface.SetTextPos( 128, 100) surface.DrawText( "vrmod_net_debug" ) local leftSide, rightSide = 140, 628 local verticalSpacing = 100 local iply = 0 for k,v in pairs(g_VR.net) do if not v.playbackTime then continue end if SysTime()-(v.debugTpsT or 0) > 1 then v.debugTpsT = SysTime() v.debugTps = v.debugTickCount v.debugTickCount = 0 end local mints, maxts = 9999999,0 for i = 1,#v.frames do mints = v.frames[i].ts<mints and v.frames[i].ts or mints maxts = v.frames[i].ts>maxts and v.frames[i].ts or maxts end surface.SetDrawColor(0,0,0,200) surface.DrawRect(128, 128+iply*verticalSpacing, 512, 90) surface.SetFont( "ChatFont" ) surface.SetTextColor( 255, 255, 255 ) surface.SetTextPos( 140, 140 + iply*verticalSpacing ) surface.DrawText( k.. " | "..v.debugState.. " | "..(v.debugTps or 0).." | "..math.floor((maxts-v.playbackTime)*1000) ) surface.SetDrawColor(0,0,0,200) surface.DrawRect(leftSide, 160+iply*verticalSpacing, rightSide-leftSide, 20) local tileWidth = (rightSide-leftSide)/#v.frames for i = 1,#v.frames do tsfraction = (v.frames[i].ts - mints) / (maxts - mints) surface.SetDrawColor(255-tsfraction*255,0,tsfraction*255,255) surface.DrawRect(leftSide + tileWidth*(i-1), 160+iply*verticalSpacing, 2, 20) if i == v.debugPreviousFrame or i == v.debugNextFrame then surface.SetDrawColor(0,255,0) surface.DrawRect(leftSide + tileWidth*(i-1), 160+iply*verticalSpacing+(i==v.debugNextFrame and 18 or 0), 2, 2) if i == v.debugPreviousFrame then surface.DrawRect(leftSide + tileWidth*(i-1 + v.debugFraction), 159+iply*verticalSpacing, 2, 22) end end end surface.SetDrawColor(0,0,0,200) surface.DrawRect(leftSide, 185+iply*verticalSpacing, rightSide-leftSide, 20) for i = 1,#v.frames do tsfraction = (v.frames[i].ts - mints) / (maxts - mints) surface.SetDrawColor(255-tsfraction*255,0,tsfraction*255,255) surface.DrawRect(leftSide + tsfraction*(rightSide-leftSide-2), 185+iply*verticalSpacing, 2, 20) end surface.SetDrawColor(0,255,0,255) surface.DrawRect(leftSide + ((v.playbackTime - mints) / (maxts - mints))*(rightSide-leftSide-2), 185+iply*verticalSpacing, 2, 20) iply = iply + 1 end cam.End2D() end) end ) function VRUtilNetworkInit() --called by localplayer when they enter vr -- transmit loop timer.Create("vrmod_transmit", 1/convarValues.vrmod_net_tickrate, 0,function() if g_VR.threePoints then net.Start("vrutil_net_tick",true) --write viewHackPos net.WriteVector(g_VR.viewModelMuzzle and g_VR.viewModelMuzzle.Pos or Vector(0,0,0)) --write frame netWriteFrame(buildClientFrame(true)) net.SendToServer() end end) net.Start("vrutil_net_join") --send some stuff here that doesnt need to be in every frame net.WriteBool(GetConVar("vrmod_althead"):GetBool()) net.WriteBool(GetConVar("vrmod_floatinghands"):GetBool()) net.SendToServer() end -- update all lerpedFrames, except for the local player (this function will be hooked to PreRender) local function LerpOtherVRPlayers() local lerpDelay = convarValues.vrmod_net_delay local lerpDelayMax = convarValues.vrmod_net_delaymax for k,v in pairs(g_VR.net) do local ply = player.GetBySteamID(k) if #v.frames < 2 or not ply then --len check discards the localplayer, ply might be invalid for a few frames before exit msg upon disconnect continue end if v.buffering then if not (v.playbackTime > v.frames[v.latestFrameIndex].ts - lerpDelay) then v.buffering = false v.sysTime = SysTime() v.debugState = "playing" end else --advance playhead v.playbackTime = v.playbackTime + (SysTime()-v.sysTime) v.sysTime = SysTime() --check if we reached the end if v.playbackTime > v.frames[v.latestFrameIndex].ts then v.buffering = true v.debugState = "buffering (reached end)" v.playbackTime = v.frames[v.latestFrameIndex].ts end --check if we're too far behind if (v.frames[v.latestFrameIndex].ts - v.playbackTime) > lerpDelayMax then v.buffering = true v.playbackTime = v.frames[v.latestFrameIndex].ts v.debugState = "buffering (catching up)" end end --lerp according to current playhead pos for i = 1,#v.frames do local nextFrame = i local previousFrame = i-1 if previousFrame == 0 then previousFrame = #v.frames end if v.frames[nextFrame].ts >= v.playbackTime and v.frames[previousFrame].ts <= v.playbackTime then local fraction = (v.playbackTime - v.frames[previousFrame].ts) / (v.frames[nextFrame].ts - v.frames[previousFrame].ts) -- v.debugNextFrame = nextFrame v.debugPreviousFrame = previousFrame v.debugFraction = fraction -- v.lerpedFrame = {} for k2,v2 in pairs(v.frames[previousFrame]) do if k2 == "characterYaw" then v.lerpedFrame[k2] = LerpAngle(fraction, Angle(0,v2,0), Angle(0,v.frames[nextFrame][k2],0)).yaw elseif isnumber(v2) then v.lerpedFrame[k2] = Lerp(fraction, v2, v.frames[nextFrame][k2]) elseif isvector(v2) then v.lerpedFrame[k2] = LerpVector(fraction, v2, v.frames[nextFrame][k2]) elseif isangle(v2) then v.lerpedFrame[k2] = LerpAngle(fraction, v2, v.frames[nextFrame][k2]) end end -- local plyPos, plyAng = ply:GetPos(), Angle() if ply:InVehicle() then plyAng = ply:GetVehicle():GetAngles() local _, forwardAng = LocalToWorld(Vector(),Angle(0,90,0),Vector(), plyAng) v.lerpedFrame.characterYaw = forwardAng.yaw end v.lerpedFrame.hmdPos, v.lerpedFrame.hmdAng = LocalToWorld(v.lerpedFrame.hmdPos,v.lerpedFrame.hmdAng,plyPos,plyAng) v.lerpedFrame.lefthandPos, v.lerpedFrame.lefthandAng = LocalToWorld(v.lerpedFrame.lefthandPos,v.lerpedFrame.lefthandAng,plyPos,plyAng) v.lerpedFrame.righthandPos, v.lerpedFrame.righthandAng = LocalToWorld(v.lerpedFrame.righthandPos,v.lerpedFrame.righthandAng,plyPos,plyAng) if v.lerpedFrame.waistPos then v.lerpedFrame.waistPos, v.lerpedFrame.waistAng = LocalToWorld(v.lerpedFrame.waistPos,v.lerpedFrame.waistAng,plyPos,plyAng) v.lerpedFrame.leftfootPos, v.lerpedFrame.leftfootAng = LocalToWorld(v.lerpedFrame.leftfootPos,v.lerpedFrame.leftfootAng,plyPos,plyAng) v.lerpedFrame.rightfootPos, v.lerpedFrame.rightfootAng = LocalToWorld(v.lerpedFrame.rightfootPos,v.lerpedFrame.rightfootAng,plyPos,plyAng) end -- break end end end end function VRUtilNetUpdateLocalPly() local tab = g_VR.net[LocalPlayer():SteamID()] if g_VR.threePoints and tab then tab.lerpedFrame = buildClientFrame() return tab.lerpedFrame end end function VRUtilNetworkCleanup() --called by localplayer when they exit vr timer.Remove("vrmod_transmit") net.Start("vrutil_net_exit") net.SendToServer() end net.Receive("vrutil_net_tick",function(len) local ply = net.ReadEntity() if not IsValid(ply) then return end local tab = g_VR.net[ply:SteamID()] if not tab then return end tab.debugTickCount = tab.debugTickCount+1 local frame = netReadFrame() if tab.latestFrameIndex == 0 then tab.playbackTime = frame.ts elseif frame.ts <= tab.frames[tab.latestFrameIndex].ts then return end local index = tab.latestFrameIndex + 1 if index > convarValues.vrmod_net_storedframes then index = 1 end tab.frames[index] = frame tab.latestFrameIndex = index end) net.Receive("vrutil_net_join",function(len) local ply = net.ReadEntity() if not IsValid(ply) then return end --todo fix this properly lol g_VR.net[ply:SteamID()] = { characterAltHead = net.ReadBool(), dontHideBullets = net.ReadBool(), frames = {}, latestFrameIndex = 0, buffering = true, debugState = "buffering (initial)", debugTickCount = 0, } hook.Add("PreRender","vrutil_hook_netlerp",LerpOtherVRPlayers) hook.Run( "VRMod_Start", ply ) end) local swepOriginalFovs = {} net.Receive("vrutil_net_exit",function(len) local steamid = net.ReadString() if game.SinglePlayer() then steamid = LocalPlayer():SteamID() end local ply = player.GetBySteamID(steamid) g_VR.net[steamid] = nil if table.Count(g_VR.net) == 0 then hook.Remove("PreRender","vrutil_hook_netlerp") end if ply == LocalPlayer() then for k,v in pairs(swepOriginalFovs) do local wep = ply:GetWeapon(k) if IsValid(wep) then wep.ViewModelFOV = v end end swepOriginalFovs = {} end hook.Run( "VRMod_Exit", ply, steamid ) end) net.Receive("vrutil_net_switchweapon",function(len) local class = net.ReadString() local vm = net.ReadString() if class == "" or vm == "" or vm == "models/weapons/c_arms.mdl" then g_VR.viewModel = nil g_VR.openHandAngles = g_VR.defaultOpenHandAngles g_VR.closedHandAngles = g_VR.defaultClosedHandAngles g_VR.currentvmi = nil g_VR.viewModelMuzzle = nil return end ----------------------- if GetConVar("vrmod_useworldmodels"):GetBool() then vrmod.SetRightHandOpenFingerAngles( g_VR.zeroHandAngles ) vrmod.SetRightHandClosedFingerAngles( g_VR.zeroHandAngles ) timer.Create("vrutil_waitforwm",0,0,function() if IsValid(LocalPlayer():GetActiveWeapon()) and LocalPlayer():GetActiveWeapon():GetClass() == class then timer.Remove("vrutil_waitforwm") g_VR.viewModel = LocalPlayer():GetActiveWeapon() end end) return end ------------------------- local vmi = g_VR.viewModelInfo[class] or {} local model = vmi.modelOverride ~= nil and vmi.modelOverride or vm g_VR.viewModel = LocalPlayer():GetViewModel() local wep = LocalPlayer():GetActiveWeapon() if wep.ViewModelFOV then if not swepOriginalFovs[class] then swepOriginalFovs[class] = wep.ViewModelFOV end wep.ViewModelFOV = GetConVar("fov_desired"):GetFloat() end --create offsets if they don't exist if vmi.offsetPos == nil or vmi.offsetAng == nil then vmi.offsetPos, vmi.offsetAng = Vector(0,0,0), Angle(0,0,0) local cm = ClientsideModel(model) if IsValid(cm) then cm:SetupBones() local bone = cm:LookupBone("ValveBiped.Bip01_R_Hand") if bone then local boneMat = cm:GetBoneMatrix(bone) local bonePos, boneAng = boneMat:GetTranslation(), boneMat:GetAngles() boneAng:RotateAroundAxis(boneAng:Forward(),180) vmi.offsetPos, vmi.offsetAng = WorldToLocal(Vector(0,0,0),Angle(0,0,0),bonePos,boneAng) vmi.offsetPos = vmi.offsetPos + g_VR.viewModelInfo.autoOffsetAddPos end cm:Remove() end end --create finger poses vmi.closedHandAngles = vrmod.GetRightHandFingerAnglesFromModel( model ) vrmod.SetRightHandClosedFingerAngles( vmi.closedHandAngles ) vrmod.SetRightHandOpenFingerAngles( vmi.closedHandAngles ) g_VR.viewModelInfo[class] = vmi g_VR.currentvmi = vmi end) hook.Add("CreateMove","vrutil_hook_joincreatemove",function(cmd) hook.Remove("CreateMove","vrutil_hook_joincreatemove") timer.Simple(2,function() net.Start("vrutil_net_requestvrplayers") net.SendToServer() end) timer.Simple(2,function() if SysTime() < 120 then GetConVar("vrmod_autostart"):SetBool(false) end if GetConVar("vrmod_autostart"):GetBool() then timer.Create("vrutil_timer_tryautostart",1,0,function() local pm = LocalPlayer():GetModel() if pm ~= nil and pm ~= "models/player.mdl" and pm ~= "" then VRUtilClientStart() timer.Remove("vrutil_timer_tryautostart") end end) end end) end) net.Receive("vrutil_net_entervehicle",function(len) hook.Call("VRMod_EnterVehicle", nil) end) net.Receive("vrutil_net_exitvehicle",function(len) hook.Call("VRMod_ExitVehicle", nil) end) elseif SERVER then util.AddNetworkString("vrutil_net_join") util.AddNetworkString("vrutil_net_exit") util.AddNetworkString("vrutil_net_switchweapon") util.AddNetworkString("vrutil_net_tick") util.AddNetworkString("vrutil_net_requestvrplayers") util.AddNetworkString("vrutil_net_entervehicle") util.AddNetworkString("vrutil_net_exitvehicle") vrmod.NetReceiveLimited("vrutil_net_tick", convarValues.vrmod_net_tickrate + 5,1200,function(len, ply) --print("sv received net_tick, len: "..len) if g_VR[ply:SteamID()] == nil then return end local viewHackPos = net.ReadVector() local frame = netReadFrame() g_VR[ply:SteamID()].latestFrame = frame if not viewHackPos:IsZero() and util.IsInWorld(viewHackPos) then ply.viewOffset = viewHackPos-ply:EyePos()+ply.viewOffset ply:SetCurrentViewOffset(ply.viewOffset) ply:SetViewOffset(Vector(0,0,ply.viewOffset.z)) else ply:SetCurrentViewOffset(ply.originalViewOffset) ply:SetViewOffset(ply.originalViewOffset) end --relay frame to everyone except sender net.Start("vrutil_net_tick",true) net.WriteEntity(ply) netWriteFrame(frame) net.SendOmit(ply) end) vrmod.NetReceiveLimited("vrutil_net_join",5,2,function(len, ply) if g_VR[ply:SteamID()] ~= nil then return end ply:DrawShadow(false) ply.originalViewOffset = ply:GetViewOffset() ply.viewOffset = Vector(0,0,0) --add gt entry g_VR[ply:SteamID()] = { --store join values so we can re-send joins to players that connect later characterAltHead = net.ReadBool(), dontHideBullets = net.ReadBool(), } ply:Give("weapon_vrmod_empty") ply:SelectWeapon("weapon_vrmod_empty") --relay join message to everyone except players that aren't fully loaded in yet local omittedPlayers = {} for k,v in ipairs( player.GetAll() ) do if not v.hasRequestedVRPlayers then omittedPlayers[#omittedPlayers+1] = v end end net.Start("vrutil_net_join") net.WriteEntity(ply) net.WriteBool(g_VR[ply:SteamID()].characterAltHead) net.WriteBool(g_VR[ply:SteamID()].dontHideBullets) net.SendOmit( omittedPlayers ) hook.Run( "VRMod_Start", ply ) end) local function net_exit(steamid) if g_VR[steamid] ~= nil then g_VR[steamid] = nil local ply = player.GetBySteamID(steamid) ply:SetCurrentViewOffset(ply.originalViewOffset) ply:SetViewOffset(ply.originalViewOffset) ply:StripWeapon("weapon_vrmod_empty") --relay exit message to everyone net.Start("vrutil_net_exit") net.WriteString(steamid) net.Broadcast() hook.Run( "VRMod_Exit", ply ) end end vrmod.NetReceiveLimited("vrutil_net_exit",5,0,function(len, ply) net_exit(ply:SteamID()) end) hook.Add("PlayerDisconnected","vrutil_hook_playerdisconnected",function(ply) net_exit(ply:SteamID()) end) vrmod.NetReceiveLimited("vrutil_net_requestvrplayers",5,0,function(len, ply) ply.hasRequestedVRPlayers = true for k,v in pairs(g_VR) do local vrPly = player.GetBySteamID(k) if IsValid(vrPly) then net.Start("vrutil_net_join") net.WriteEntity(vrPly) net.WriteBool(g_VR[k].characterAltHead) net.WriteBool(g_VR[k].dontHideBullets) net.Send(ply) else print("VRMod: Invalid SteamID \""..k.."\" found in player table") end end end) hook.Add("PlayerDeath","vrutil_hook_playerdeath",function(ply, inflictor, attacker) if g_VR[ply:SteamID()] ~= nil then net.Start("vrutil_net_exit") net.WriteString(ply:SteamID()) net.Broadcast() end end) hook.Add("PlayerSpawn","vrutil_hook_playerspawn",function(ply) if g_VR[ply:SteamID()] ~= nil then ply:Give("weapon_vrmod_empty") net.Start("vrutil_net_join") net.WriteEntity(ply) net.WriteBool(g_VR[ply:SteamID()].characterAltHead) net.WriteBool(g_VR[ply:SteamID()].dontHideBullets) net.Broadcast() end end) hook.Add("PlayerSwitchWeapon","vrutil_hook_playerswitchweapon",function(ply, old, new) if g_VR[ply:SteamID()] ~= nil then net.Start("vrutil_net_switchweapon") if IsValid(new) then net.WriteString(new:GetClass()) net.WriteString(new:GetWeaponViewModel()) else net.WriteString("") net.WriteString("") end net.Send(ply) timer.Simple(0,function() --new:AddEffects(EF_NODRAW) end) end end) hook.Add("PlayerEnteredVehicle","vrutil_hook_playerenteredvehicle",function(ply, veh) if g_VR[ply:SteamID()] ~= nil then ply:SelectWeapon("weapon_vrmod_empty") ply:SetActiveWeapon(ply:GetWeapon("weapon_vrmod_empty")) net.Start("vrutil_net_entervehicle") net.Send(ply) end end) hook.Add("PlayerLeaveVehicle","vrutil_hook_playerleavevehicle",function(ply, veh) if g_VR[ply:SteamID()] ~= nil then net.Start("vrutil_net_exitvehicle") net.Send(ply) end end) end
-- Provides a singleton that tracks and adds output to each event handler and listener and script timer being fired. Meant for debugging purposes. -- Event handlers are the functions on each list of the events object. -- Event listeners include the functions that are added via core:add_listener. -- Script timers include the functions that are added via cm:callback. -- Internally, all event listeners for a particular event name are done in an event handler, while all script timers are done in a TimeTrigger event listener. -- Note: Only including lbm_utils for the new methods it adds to table et al, rather than functions on lbm_utils itself. cm:load_global_script "lib.lbm_utils" local events_tracker = { logging_level = 0, all_event_handler_records = nil, event_listener_records = nil, event_listener_to_record = nil, orig_core_add_listener = nil, orig_core_clean_listeners = nil, orig_core_remove_listener = nil, script_timer_records = nil, orig_cm_callback = nil, orig_cm_remove_callback = nil, } function events_tracker.enabled() return events_tracker.logging_level > 0 end local function context_string(context) if type(context.trigger) == "function" then return "trigger => " .. tostring(context:trigger()) else return "string => " .. tostring(context.string) end end -- Enables tracking (simple log output) of each event handler and listener being fired. -- Optional argument specifies the logging level to enable it. If omitted, defaults to logging level 1. -- * Log level 1: Only logs when handlers/listeners/timers fire. -- * Log level 2: Also logs when handlers/listeners/timers are added or removed. -- * Log level 3: Also logs each handler/listener/timer that exists upon enabling and disabling. -- To disable event tracking, call events_tracker.disable(). -- WARNING: This may cause an initial noticeable pause while executing, especially at higher log levels, and continues to slow the game down until disabled. function events_tracker.enable(logging_level) if logging_level == nil then logging_level = 1 elseif logging_level < 1 then error("[event] logging level must be >=1") end if events_tracker.logging_level > 1 then if events_tracker.logging_level ~= logging_level then events_tracker.logging_level = logging_level out("[event] tracking already enabled - updating logging level to " .. logging_level) else out("[event] tracking already enabled at logging level " .. logging_level) end return end local events = get_events() local all_event_handler_records = {} events_tracker.all_event_handler_records = all_event_handler_records local function track_event_handler(event_name, i) local event_handlers = events[event_name] local event_handler_records = all_event_handler_records[event_name] if not event_handler_records then event_handler_records = {} all_event_handler_records[event_name] = event_handler_records end local event_handler_record = { orig_handler = event_handlers[i], desc = event_name .. (event_handlers[i] and " handler " .. i or " temporary handler"), } event_handler_records[i] = event_handler_record event_handlers[i] = function(context, ...) out("[event] firing " .. event_handler_record.desc .. ": " .. context_string(context)) --out("[event] firing " .. event_handler_record.desc .. ": " .. context_string(context) .. " - context interface: " .. tostring(getmetatable(context))) if event_handler_record.orig_handler then return event_handler_record.orig_handler(context, ...) end end event_handler_record.new_handler = event_handlers[i] if events_tracker.logging_level >= 3 then out("[event] enabled tracking of " .. event_handler_record.desc) end return event_handler_record end for event_name, event_handlers in pairs(events) do if event_name == "_NAME" or event_name == "_M" or event_name == "_PACKAGE" then -- These are 'hidden' properties added by the module() call within events.lua, so ignore them. else local event_handler_records = all_event_handler_records[event_name] if not event_handler_records then event_handler_records = {} all_event_handler_records[event_name] = event_handler_records end local num_event_handlers = #event_handlers if num_event_handlers == 0 then track_event_handler(event_name, 1) else for i = 1, num_event_handlers do track_event_handler(event_name, i) end end end end local event_listener_records, event_listener_to_record = {}, {} events_tracker.event_listener_records, events_tracker.event_listener_to_record = event_listener_records, event_listener_to_record local function track_event_listener(event_listener, adjective, cur_logging_level, req_logging_level) local event_listener_record = { event_listener = event_listener, orig_condition = event_listener.condition, orig_callback = event_listener.callback, desc = (event_listener.persistent and "" or "non-persistent ") .. event_listener.event .. " listener " .. event_listener.name, } if type(event_listener.condition) ~= 'boolean' then event_listener.condition = function(context, ...) local ret_status, ret_val = pcall(event_listener_record.orig_condition, context, ...) if ret_status then if not ret_val then out("[event] not firing " .. event_listener_record.desc .. ": condition => " .. tostring(ret_val) .. "; " .. context_string(context)) end return ret_val else out("[event] not firing " .. event_listener_record.desc .. ": condition => ERROR: " .. tostring(ret_val) .. "; " .. context_string(context)) error(ret_val) end end end event_listener.callback = function(context, ...) out("[event] firing " .. event_listener_record.desc .. ": " .. context_string(context)) return event_listener_record.orig_callback(context, ...) end if cur_logging_level >= req_logging_level then out("[event] enabled tracking of " .. adjective .. event_listener_record.desc) end event_listener_to_record[event_listener] = event_listener_record event_listener_records[#event_listener_records + 1] = event_listener_record return event_listener_record end local event_listeners = core.event_listeners for i = 1, #event_listeners do track_event_listener(event_listeners[i], "", logging_level, 3) end local orig_core_add_listener = core.add_listener events_tracker.orig_core_add_listener = orig_core_add_listener core.add_listener = function(self, new_name, event_name, ...) -- Add new event handler if one's going to be created by add_listener. local old_num_event_handlers = #(events[event_name] or {}) core:attach_to_event(event_name) local new_num_event_handlers = #events[event_name] if old_num_event_handlers ~= new_num_event_handlers then track_event_handler(event_name, new_num_event_handlers) end local success = orig_core_add_listener(self, new_name, event_name, ...) if success == false then -- check for explicit false, don't include nil return false end track_event_listener(event_listeners[#event_listeners], "new ", events_tracker.logging_level, 2) end -- Note: core.clean_listeners and core.remove_listener are recursive functions, which are hard to hook into, so just replace them wholesale. -- They also provide convenient opportunities to track any event listeners that we somehow missed. local function remove_event_listeners(predicate, untracked_listener_callback, postfix_phrase, cur_logging_level) for i = #event_listener_records, 1, -1 do local event_listener_record = event_listener_records[i] local event_listener = event_listener_record.event_listener if predicate(event_listener) then table.remove(event_listener_records, i) local j = i if event_listeners[i] ~= event_listener then j = table.key_of(event_listeners, event_listener) end if j then table.remove(event_listeners, j) if cur_logging_level >= 2 then out("[event] removed " .. event_listener_record.desc .. postfix_phrase) end else out("[event] WARNING: could not find (to remove) tracked " .. event_listener_record.desc) end end end for i = #event_listeners, 1, -1 do local event_listener = event_listeners[i] if not event_listener_to_record[event_listener] then local will_remove = predicate(event_listener) untracked_listener_callback(event_listener, will_remove) if will_remove then table.remove(event_listeners, i) if cur_logging_level >= 2 then local event_listener_desc = (event_listener.persistent and "" or "non-persistent ") .. event_listener.event .. " listener " .. event_listener.name out("[event] removed " .. event_listener_desc .. postfix_phrase) end end end end end local orig_core_clean_listeners = core.clean_listeners events_tracker.orig_core_clean_listeners = orig_core_clean_listeners core.clean_listeners = function(self) remove_event_listeners(function(event_listener) -- predicate return event_listener.to_remove end, function(event_listener, will_remove) -- untracked_listener_callback -- Even if removing this missed event listener, we're going to track it, since it's about to fire once track_event_listener(event_listener, "previously unexpectedly non-tracked ", events_tracker.logging_level, 2) end, " (about to fire once)", events_tracker.logging_level) end local orig_core_remove_listener = core.remove_listener events_tracker.orig_core_remove_listener = orig_core_remove_listener core.remove_listener = function(self, listener_name) remove_event_listeners(function(event_listener) -- predicate return event_listener.name == listener_name end, function(event_listener, will_remove) -- untracked_listener_callback if not will_remove then -- if it's being removed, don't bother tracking it track_event_listener(event_listener, "previously unexpectedly non-tracked ", events_tracker.logging_level, 2) end end, "", events_tracker.logging_level) end local script_timer_records = {} events_tracker.script_timer_records = script_timer_records local function track_script_timer(id, script_timer, adjective, cur_logging_level, req_logging_level) local script_timer_record = { id = id, script_timer = script_timer, orig_callback = script_timer.callback, desc = "script timer " .. id .. (script_timer.name and " named " .. script_timer.name or ""), } script_timer.callback = function(...) out("[event] one-time firing " .. script_timer_record.desc) script_timer_records[id] = nil script_timer_record.orig_callback(...) end if cur_logging_level >= req_logging_level then out("[event] enabled tracking of " .. adjective .. script_timer_record.desc) end script_timer_records[id] = script_timer_record return script_timer_record end local script_timers = cm.script_timers for id, script_timer in pairs(script_timers) do track_script_timer(id, script_timer, "", logging_level, 3) end local orig_cm_callback = cm.callback events_tracker.orig_cm_callback = orig_cm_callback cm.callback = function(...) -- Get next script timer's id by copying logic in cm:callback. local new_id = 0 while script_timers[new_id] do new_id = new_id + 1 end local success = orig_cm_callback(...) if success == false then -- check for explicit false, don't include nil return false end local script_timer = script_timers[new_id] track_script_timer(new_id, script_timer, "new ", events_tracker.logging_level, 2) end local orig_cm_remove_callback = cm.remove_callback events_tracker.orig_cm_remove_callback = orig_cm_remove_callback cm.remove_callback = function(self, name) for id, script_timer_record in pairs(script_timer_records) do local script_timer = script_timer_record.script_timer if script_timer.name == name then script_timer_records[id] = nil if events_tracker.logging_level >= 2 then out("[event] removed " .. script_timer_record.desc) end end end orig_cm_remove_callback(self, name) end events_tracker.logging_level = logging_level out("[event] tracking enabled") end -- Disables tracking added via events_tracker:enable(). -- WARNING: This may cause a noticeable pause while executing. function events_tracker.disable() local logging_level = events_tracker.logging_level if logging_level == 0 then out("[event] tracking already disabled") return end local events = get_events() for event_name, event_handler_records in pairs(events_tracker.all_event_handler_records) do local event_handlers = events[event_name] if type(event_handlers) ~= "table" then out("[event] WARNING: event handlers for " .. event_name .. " are of type '" .. type(event_handlers) .. "' instead of expected type 'table'") end if event_handlers then for i = 1, #event_handler_records do local event_handler_record = event_handler_records[i] local j = i if event_handlers[i] ~= event_handler_record.new_handler then j = table.key_of(event_handlers, event_handler_record.new_handler) end if j then if event_handler_record.orig_handler == nil then table.remove(event_handlers, j) if logging_level >= 3 then out("[event] removed temporary " .. event_name .. " handler") end else event_handlers[j] = event_handler_record.orig_handler if logging_level >= 3 then out("[event] disabled tracking of " .. event_name .. " handler " .. i) end end else out("[event] WARNING: could not find (to disable) tracking of " .. event_name .. " handler " .. i) end end end end local event_listeners = core.event_listeners local event_listener_records = events_tracker.event_listener_records for i = 1, #event_listener_records do local event_listener_record = event_listener_records[i] local event_listener = event_listener_record.event_listener event_listener.condition = event_listener_record.orig_condition event_listener.callback = event_listener_record.orig_callback local j = i if event_listeners[i] ~= event_listener then j = table.key_of(event_listeners, event_listener) end if j then if logging_level >= 3 then out("[event] disabled tracking of " .. event_listener_record.desc) end else out("[event] WARNING: could not find (to disable) tracking of " .. event_listener_record.desc) end end core.add_listener = events_tracker.orig_core_add_listener core.clean_listeners = events_tracker.orig_core_clean_listeners core.remove_listener = events_tracker.orig_core_remove_listener local script_timers = cm.script_timers for id, script_timer_record in pairs(events_tracker.script_timer_records) do local script_timer = script_timer_record.script_timer script_timer.callback = script_timer_record.orig_callback if script_timers[id] == script_timer then if logging_level >= 3 then out("[event] disabled tracking of " .. script_timer_record.desc) end else out("[event] WARNING: could not find (to disable) tracking of " .. script_timer_record.desc) end end cm.callback = events_tracker.orig_cm_callback cm.remove_callback = events_tracker.orig_cm_remove_callback -- Nil out the fields with table values to help with gc events_tracker.all_event_handler_records = nil events_tracker.event_listener_records = nil events_tracker.event_listener_to_record = nil events_tracker.script_timer_records = nil events_tracker.logging_level = 0 out("[event] tracking disabled") end -- Temporarily adds output to each event handler and listener being fired during the call of given func and arguments. -- Optional first argument specifies the logging level to enable it. If omitted, defaults to logging level 1. -- Internally uses events_tracker.enable() and events_tracker.disable() - see WARNINGs in their docs. function events_tracker.enable_during_call(logging_level, func, ...) local ret_status, ret_val if type(logging_level) == "function" then -- Then logging_level was omitted, and logging_level is actually the function, and func is the first argument to the function call. events_tracker.enable() ret_status, ret_val = pcall(logging_level, func, ...) else events_tracker.enable(logging_level) ret_status, ret_val = pcall(func, ...) end events_tracker.disable() if ret_status then return ret_val else error(ret_val) end end return events_tracker
local ffi = require('ffi') local C = ffi.C local _M = {} ffi.cdef[[ void cf_nocompress_set_enabled(void*, unsigned); ]] function _M.enable(val) local r = getfenv(0).__ngx_req if not r then return error("no request found") end if val == true then C.cf_nocompress_set_enabled(r, 1); else C.cf_nocompress_set_enabled(r, 0); end end return _M
--New object_tangible_item_shared_costume_data_container = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_costume_data_container.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_costume_data_container, "object/tangible/item/shared_costume_data_container.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_crafted_armor_recolor_kit = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_crafted_armor_recolor_kit.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_crafted_armor_recolor_kit, "object/tangible/item/shared_crafted_armor_recolor_kit.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_crafted_structure_customization_kit = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_crafted_structure_customization_kit.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_crafted_structure_customization_kit, "object/tangible/item/shared_crafted_structure_customization_kit.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_crusader_armor_dye_kit = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_crusader_armor_dye_kit.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_crusader_armor_dye_kit, "object/tangible/item/shared_crusader_armor_dye_kit.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_data_cube_holobeast = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_data_cube_holobeast.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_data_cube_holobeast, "object/tangible/item/shared_data_cube_holobeast.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_efol_11_publish_gift_crate = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_efol_11_publish_gift_crate.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_efol_11_publish_gift_crate, "object/tangible/item/shared_efol_11_publish_gift_crate.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_esb_publish_gift_crate = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_esb_publish_gift_crate.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_esb_publish_gift_crate, "object/tangible/item/shared_esb_publish_gift_crate.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_generic_vehicle_customization = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_generic_vehicle_customization.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_generic_vehicle_customization, "object/tangible/item/shared_generic_vehicle_customization.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_ground_air_rocket = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_ground_air_rocket.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_ground_air_rocket, "object/tangible/item/shared_ground_air_rocket.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_hoth_turret_s1_destroyed = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_hoth_turret_s1_destroyed.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_hoth_turret_s1_destroyed, "object/tangible/item/shared_hoth_turret_s1_destroyed.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_hoth_turret_s2_destroyed = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_hoth_turret_s2_destroyed.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_hoth_turret_s2_destroyed, "object/tangible/item/shared_hoth_turret_s2_destroyed.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_item_blackwing_canister = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_item_blackwing_canister.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_item_blackwing_canister, "object/tangible/item/shared_item_blackwing_canister.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_item_blackwing_canister_with_detonator = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_item_blackwing_canister_with_detonator.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_item_blackwing_canister_with_detonator, "object/tangible/item/shared_item_blackwing_canister_with_detonator.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_item_outbreak_perfume_hidden_content = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_item_outbreak_perfume_hidden_content.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_item_outbreak_perfume_hidden_content, "object/tangible/item/shared_item_outbreak_perfume_hidden_content.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_item_outbreak_scout_camera_hidden_content = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_item_outbreak_scout_camera_hidden_content.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_item_outbreak_scout_camera_hidden_content, "object/tangible/item/shared_item_outbreak_scout_camera_hidden_content.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_item_outbreak_stun_baton_hidden_content = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_item_outbreak_stun_baton_hidden_content.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_item_outbreak_stun_baton_hidden_content, "object/tangible/item/shared_item_outbreak_stun_baton_hidden_content.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_item_outbreak_tie_helmet_hidden_content = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_item_outbreak_tie_helmet_hidden_content.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_item_outbreak_tie_helmet_hidden_content, "object/tangible/item/shared_item_outbreak_tie_helmet_hidden_content.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_nuna_egg_flower_dead = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_nuna_egg_flower_dead.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_nuna_egg_flower_dead, "object/tangible/item/shared_nuna_egg_flower_dead.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_nuna_egg_flower_stage_01 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_nuna_egg_flower_stage_01.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_nuna_egg_flower_stage_01, "object/tangible/item/shared_nuna_egg_flower_stage_01.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_nuna_egg_flower_stage_02 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_nuna_egg_flower_stage_02.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_nuna_egg_flower_stage_02, "object/tangible/item/shared_nuna_egg_flower_stage_02.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_nuna_egg_flower_stage_03 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_nuna_egg_flower_stage_03.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_nuna_egg_flower_stage_03, "object/tangible/item/shared_nuna_egg_flower_stage_03.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_bh_space = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_bh_space.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_bh_space, "object/tangible/item/shared_publish_gift_bh_space.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_chapter_11_snow_balls = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_chapter_11_snow_balls.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_chapter_11_snow_balls, "object/tangible/item/shared_publish_gift_chapter_11_snow_balls.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_chapter_11_snow_machine = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_chapter_11_snow_machine.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_chapter_11_snow_machine, "object/tangible/item/shared_publish_gift_chapter_11_snow_machine.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_chapter_7_painting_01 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_chapter_7_painting_01.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_chapter_7_painting_01, "object/tangible/item/shared_publish_gift_chapter_7_painting_01.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_chapter_7_painting_02 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_chapter_7_painting_02.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_chapter_7_painting_02, "object/tangible/item/shared_publish_gift_chapter_7_painting_02.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_magic_painting_1 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_magic_painting_1.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_magic_painting_1, "object/tangible/item/shared_publish_gift_magic_painting_1.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_magic_painting_10 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_magic_painting_10.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_magic_painting_10, "object/tangible/item/shared_publish_gift_magic_painting_10.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_magic_painting_2 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_magic_painting_2.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_magic_painting_2, "object/tangible/item/shared_publish_gift_magic_painting_2.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_magic_painting_3 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_magic_painting_3.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_magic_painting_3, "object/tangible/item/shared_publish_gift_magic_painting_3.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_magic_painting_4 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_magic_painting_4.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_magic_painting_4, "object/tangible/item/shared_publish_gift_magic_painting_4.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_magic_painting_5 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_magic_painting_5.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_magic_painting_5, "object/tangible/item/shared_publish_gift_magic_painting_5.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_magic_painting_6 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_magic_painting_6.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_magic_painting_6, "object/tangible/item/shared_publish_gift_magic_painting_6.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_magic_painting_7 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_magic_painting_7.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_magic_painting_7, "object/tangible/item/shared_publish_gift_magic_painting_7.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_magic_painting_8 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_magic_painting_8.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_magic_painting_8, "object/tangible/item/shared_publish_gift_magic_painting_8.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_magic_painting_9 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_magic_painting_9.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_magic_painting_9, "object/tangible/item/shared_publish_gift_magic_painting_9.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_magic_painting_ctrl_obj = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_magic_painting_ctrl_obj.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_magic_painting_ctrl_obj, "object/tangible/item/shared_publish_gift_magic_painting_ctrl_obj.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_update_14 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_update_14.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_update_14, "object/tangible/item/shared_publish_gift_update_14.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_update_15 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_update_15.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_update_15, "object/tangible/item/shared_publish_gift_update_15.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_publish_gift_update_16 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_publish_gift_update_16.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_publish_gift_update_16, "object/tangible/item/shared_publish_gift_update_16.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_pvp_spec_ops_imperial_dye_kit = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_pvp_spec_ops_imperial_dye_kit.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_pvp_spec_ops_imperial_dye_kit, "object/tangible/item/shared_pvp_spec_ops_imperial_dye_kit.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_rare_loot_chest_1 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_rare_loot_chest_1.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_rare_loot_chest_1, "object/tangible/item/shared_rare_loot_chest_1.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_rare_loot_chest_2 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_rare_loot_chest_2.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_rare_loot_chest_2, "object/tangible/item/shared_rare_loot_chest_2.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_rare_loot_chest_3 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_rare_loot_chest_3.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_rare_loot_chest_3, "object/tangible/item/shared_rare_loot_chest_3.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_serving_droid = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_serving_droid.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_serving_droid, "object/tangible/item/shared_serving_droid.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_target_dummy_publish_giftbox = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_target_dummy_publish_giftbox.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_target_dummy_publish_giftbox, "object/tangible/item/shared_target_dummy_publish_giftbox.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_texture_kit = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_texture_kit.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_texture_kit, "object/tangible/item/shared_texture_kit.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_vet_reward_homing_beacon = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_vet_reward_homing_beacon.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_vet_reward_homing_beacon, "object/tangible/item/shared_vet_reward_homing_beacon.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_wampa_snow_globe = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_wampa_snow_globe.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_wampa_snow_globe, "object/tangible/item/shared_wampa_snow_globe.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_item_shared_data_cube = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_data_cube.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_data_cube, "object/tangible/item/shared_data_cube.iff") --********************************************************************************************************************************** object_tangible_item_shared_ig_droid_head = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_ig_droid_head.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_ig_droid_head, "object/tangible/item/shared_ig_droid_head.iff") --********************************************************************************************************************************** object_tangible_item_shared_leather_package = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_leather_package.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_leather_package, "object/tangible/item/shared_leather_package.iff") --********************************************************************************************************************************** object_tangible_item_shared_loot_cash = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_loot_cash.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_loot_cash, "object/tangible/item/shared_loot_cash.iff") --********************************************************************************************************************************** object_tangible_item_shared_loot_cube = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_loot_cube.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_loot_cube, "object/tangible/item/shared_loot_cube.iff") --********************************************************************************************************************************** object_tangible_item_shared_puddle_water_01 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_puddle_water_01.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_puddle_water_01, "object/tangible/item/shared_puddle_water_01.iff") --********************************************************************************************************************************** object_tangible_item_shared_pvp_spec_ops_rebel_dye_kit = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/item/shared_pvp_spec_ops_rebel_dye_kit.iff" } ObjectTemplates:addClientTemplate(object_tangible_item_shared_pvp_spec_ops_rebel_dye_kit, "object/tangible/item/shared_pvp_spec_ops_rebel_dye_kit.iff") --**********************************************************************************************************************************
StopCommand = Command:extends{} StopCommand.className = "StopCommand" function StopCommand:execute() if not SB.rtModel.hasStarted then return end pcall(function() local OnStartEditingSynced = SB.model.game.OnStartEditingSynced if OnStartEditingSynced then OnStartEditingSynced() end end) Log.Notice("Stopping game...") for _, allyTeamID in ipairs(Spring.GetAllyTeamList()) do Spring.SetGlobalLos(allyTeamID, true) end Spring.StopSoundStream() Spring.SetGameRulesParam("sb_gameMode", "dev") SB.rtModel:GameStop() -- use meta data (except variables) from the new (runtime) model -- enable all triggers local meta = SB.model:GetMetaData() for _, trigger in pairs(meta.triggers) do trigger.enabled = true end meta.variables = SB.model.oldModel.meta.variables local teamData = SB.model.oldModel.meta.teams SB.model.oldModel.meta = meta SB.model.oldModel.meta.teams = nil GG.Delay.DelayCall(function() SB.model:Clear() end, {}, 1) GG.Delay.DelayCall(function() SB.model:Load(SB.model.oldModel) SB.model.oldHeightMap:Load() SB.delay(function() SB.model.teamManager:load(teamData) end) end, {}, 9) if SB_USE_PLAY_PAUSE then Spring.SendCommands("pause 1") end end
-- Namespace Variables local addon, addonTbl = ...; -- Module-Local Variables local frame; local isFrameVisible; local L = addonTbl.L; local function ShowTooltip(self, text) GameTooltip:SetOwner(self, "ANCHOR_RIGHT"); GameTooltip:SetText(text); GameTooltip:Show(); end -- Displays a custom tooltip. --[[ self: This is the instance of the GameTooltip object text: Text to display when the tooltip is shown ]] local function HideTooltip(self) if GameTooltip:GetOwner() == self then GameTooltip:Hide(); end end -- Synopsis: Hides a custom tooltip. --[[ self: This is the instance of the GameTooltip object ]] local function PlaySound(soundKit) PlaySound(soundKit); end -- Synopsis: Plays the provided soundkit. --[[ soundKit: Name of the soundkit to play (https://github.com/Gethe/wow-ui-source/blob/live/SharedXML/SoundKitConstants.lua) ]] local function Hide(frame) isFrameVisible = false; frame:Hide(); end -- Synopsis: Hides the provided frame from the screen. --[[ frame: Name of the frame to hide ]] local function Show(frame) if isFrameVisible then Hide(frame); else isFrameVisible = true; -- WIDGETS if not frame["title"] then -- If title doesn't exist, then it's likely that none of the other widgets exist. addonTbl.CreateWidget("FontString", "title", L["RELEASE"] .. L["ADDON_NAME_SETTINGS"], frame, "CENTER", frame.TitleBg, "CENTER", 5, 0); addonTbl.CreateWidget("FontString", "itemCounter", addonTbl.GetCount(LastSeenClassicItemsDB), frame, "CENTER", frame, "CENTER", 0, -10); addonTbl.CreateWidget("Button", "showSourcesCheckButton", L["SHOW_SOURCES"], frame, "CENTER", frame, "CENTER", -60, -35); addonTbl.CreateWidget("DropDownMenu", "modeDropDownMenu", "", frame, "CENTER", frame, "CENTER", 0, 15); elseif frame["itemCounter"] then -- If the widgets were already created, we don't want to recreate the itemCounter widget, but update it. addonTbl.UpdateWidget("itemCounter", frame, addonTbl.GetCount(LastSeenClassicItemsDB)); end if frame then frame:SetMovable(true); frame:EnableMouse(true); frame:RegisterForDrag("LeftButton"); frame:SetScript("OnDragStart", frame.StartMoving); frame:SetScript("OnDragStop", frame.StopMovingOrSizing); frame:ClearAllPoints(); frame:SetPoint("CENTER", WorldFrame, "CENTER"); end -- FRAME BEHAVIORS -- Settings Frame X Button frame.CloseButton:SetScript("OnClick", function(self) Hide(frame) end); -- When the player selects the X on the frame, hide it. Same behavior as typing the command consecutively. -- Mode DropDown Menu frame.modeDropDownMenu:SetScript("OnEnter", function(self) ShowTooltip(self, L["MODE_DESCRIPTIONS"]) end); -- When the player hovers over the dropdown menu, display a custom tooltip. frame.modeDropDownMenu:SetScript("OnLeave", function(self) HideTooltip(self) end); -- When the player is no longer hovering, hide the tooltip. if LastSeenClassicSettingsCacheDB["mode"] then UIDropDownMenu_SetText(modeDropDownMenu, LastSeenClassicSettingsCacheDB["mode"]); end -- Show Sources Check Button if LastSeenClassicSettingsCacheDB["showSources"] then frame.showSourcesCheckButton:SetChecked(true); addonTbl.showSources = true; else frame.showSourcesCheckButton:SetChecked(false); addonTbl.showSources = false; end frame.showSourcesCheckButton:SetScript("OnClick", function(self, event, arg1) if self:GetChecked() then addonTbl.showSources = true; LastSeenClassicSettingsCacheDB.showSources = true; else addonTbl.showSources = false; LastSeenClassicSettingsCacheDB.showSources = false; end end); frame.showSourcesCheckButton:SetScript("OnEnter", function(self) ShowTooltip(self, L["SHOW_SOURCES_DESC"]) end); -- When the player hovers over the show sources check button, display a custom tooltip. frame.showSourcesCheckButton:SetScript("OnLeave", function(self) HideTooltip(self) end); -- When the player is no longer hovering, hide the tooltip. frame:Show(); end end -- Synopsis: Displays the provided frame on screen. --[[ frame: Name of the frame to display ]] addonTbl.CreateFrame = function(name, height, width) -- If the frame is already created, then call the Show function instead. if not frame then frame = CreateFrame("Frame", name, UIParent, "BasicFrameTemplateWithInset"); frame:SetSize(height, width); Show(frame); else Show(frame); end end -- Synopsis: Responsible for building a frame. --[[ name: Name of the frame height: The height, in pixels, of the frame width: The width or length, in pixels, of the frame ]]
local null = nil if type(ngx) == "table" then null = ngx.null end -- Normalize results local _n = function(res, err) if res == null then res = nil end return res, err end local resty_call = function(self, cmd, ...) return _n(self._db[string.lower(cmd)](self._db, ...)) end local resty_queue = function(self, cmd, ...) self._queue[#self._queue + 1] = {cmd = cmd, args = {...}} end local resty_commit = function(self) self._db:init_pipeline() for _, command in ipairs(self._queue) do self._db[string.lower(command.cmd)](self._db, unpack(command.args)) end self._queue = {} return _n(self._db:commit_pipeline()) end local _wrap_in_pcall = function(...) local success, res = pcall(...) if success then return res, nil else return nil, res end end local resp_call = function(self, ...) return _wrap_in_pcall(self._db.call, self._db, ...) end local resp_queue = function(self, ...) return _wrap_in_pcall(self._db.queue, self._db, ...) end local resp_commit = function(self, ...) return _wrap_in_pcall(self._db.commit, self._db, ...) end local providers = setmetatable({}, { __index = function (t, k) error("provider '" .. k .. "' is unimplemented") end }) providers["lua-resty-redis"] = { call = resty_call, queue = resty_queue, commit = resty_commit } providers["resp"] = { call = resp_call, queue = resp_queue, commit = resp_commit } local deduct_provider = function(db, provider) if provider then return provider end if type(db.init_pipeline) == "function" then return "lua-resty-redis" elseif type(db.call) == "function" and type(db.queue) == "function" then return "resp" end end local new = function(db, provider) provider = deduct_provider(db, provider) if not provider then return "", "No provider is specified!" end local self = {} self._db = db self._queue = {} setmetatable(self, {__index = providers[provider]}) return self end return { new = new }
local CorePackages = game:GetService("CorePackages") local AppTempCommon = CorePackages.AppTempCommon local Modules = game:GetService("CoreGui").RobloxGui.Modules local ShareGame = Modules.Settings.Pages.ShareGame local Immutable = require(AppTempCommon.Common.Immutable) local ReceivedUserInviteStatus = require(ShareGame.Actions.ReceivedUserInviteStatus) local StoppedToastTimer = require(ShareGame.Actions.StoppedToastTimer) local Constants = require(ShareGame.Constants) local InviteStatus = Constants.InviteStatus return function(state, action) state = state or { failedInvites = {}, } if action.type == ReceivedUserInviteStatus.name then local inviteStatus = action.inviteStatus if inviteStatus == InviteStatus.Moderated or inviteStatus == InviteStatus.Failed then local inviteStatusModel = { timeStamp = tick(), userId = action.userId, status = inviteStatus, } state = Immutable.JoinDictionaries(state, { failedInvites = Immutable.JoinDictionaries( state.failedInvites, Immutable.Append(state.failedInvites, inviteStatusModel) ), }) end elseif action.type == StoppedToastTimer.name then state = Immutable.JoinDictionaries(state, { failedInvites = {}, }) end return state end
ESX = nil toggleState = false Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end while ESX.GetPlayerData().job == nil do Citizen.Wait(10) end end) --nui RegisterCommand("atm", function() if nearATM() then if toggleState == false then playAnim('mp_common', 'givetake1_a', Config.AnimationTime) toggle(true) getPlayerData() sendHistory() else toggle(false) end end end) RegisterNUICallback("notif", function(data, cb) sendNotif(data.text, data.type) end) function toggle(open) SetNuiFocus(open, open) SendNUIMessage({ type = "toggleMenu", toggle = open }) toggleState = open end function getPlayerData() ESX.TriggerServerCallback("kocadede-banking:GetPlayerData", function(PlayerData) SendNUIMessage({ type = "getPlayerData", data = PlayerData }) end) end RegisterNUICallback('exit', function() toggle(false) end) RegisterNUICallback('withdraw', function(data) TriggerServerEvent("vlast-banking:withdraw", data) end) RegisterNUICallback('deposit', function(data) TriggerServerEvent("vlast-banking:deposit", data) end) RegisterNUICallback('addHistory', function(data) TriggerServerEvent("vlast-banking-addBankHistory", data) end) RegisterNUICallback('transfer', function(data) TriggerServerEvent("vlast-banking-transfer", data) end) function sendHistory() ESX.TriggerServerCallback("kocadede-getPlayerAccountHistory", function(history) SendNUIMessage({ type = "sendHistory", history = history }) end) end -- lua function nearATM() local player = PlayerPedId() local playerloc = GetEntityCoords(player, 0) for _, search in pairs(Config.ATM) do local distance = GetDistanceBetweenCoords(search.x, search.y, search.z, playerloc['x'], playerloc['y'], playerloc['z'], true) if distance <= 2 then return true end end end function nearBank() local player = PlayerPedId() local playerloc = GetEntityCoords(player, 0) for _, search in pairs(Config.Bank) do local distance = GetDistanceBetweenCoords(search.x, search.y, search.z, playerloc['x'], playerloc['y'], playerloc['z'], true) if Vdist2(GetEntityCoords(PlayerPedId(), false), search.x, search.y, search.z) < 2.5 then DrawText3D(search.x, search.y, search.z, Config.Text["banktext"]) end if distance <= 3 then return true end end end function playAnim(animDict, animName, duration) RequestAnimDict(animDict) while not HasAnimDictLoaded(animDict) do Citizen.Wait(0) end TaskPlayAnim(PlayerPedId(), animDict, animName, 1.0, -1.0, duration, 49, 1, false, false, false) RemoveAnimDict(animDict) end --BANK Citizen.CreateThread(function() if Config.ShowBlips then for k,v in ipairs(Config.Bank)do local blip = AddBlipForCoord(v.x, v.y, v.z) SetBlipSprite (blip, v.id) SetBlipDisplay(blip, 4) SetBlipScale (blip, 0.1) SetBlipColour (blip, 2) SetBlipAsShortRange(blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(Config.Text["bank_blip"]) EndTextCommandSetBlipName(blip) end end end) --ATM Citizen.CreateThread(function() if Config.ShowBlips and Config.OnlyBank == false then for k,v in ipairs(Config.ATM)do local blip = AddBlipForCoord(v.x, v.y, v.z) SetBlipSprite (blip, v.id) SetBlipDisplay(blip, 4) SetBlipScale (blip, 0.9) SetBlipColour (blip, 2) SetBlipAsShortRange(blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(_U("atm_blip")) EndTextCommandSetBlipName(blip) end end end) function DrawText3D(x,y,z,text,size) local onScreen,_x,_y=World3dToScreen2d(x,y,z) local px,py,pz=table.unpack(GetGameplayCamCoords()) SetTextScale(0.35,0.35) SetTextFont(4) SetTextProportional(1) SetTextColour(255, 255, 255, 215) SetTextEntry("STRING") SetTextCentre(1) AddTextComponentString(text) DrawText(_x,_y) local factor = (string.len(text)) / 370 --DrawRect(_x,_y+0.0125, 0.015+ factor, 0.03, 41, 11, 41, 68) --DrawRect(_x,_y+0.0125, 0.015+ factor, 0.03, 41, 11, 41, 100) DrawRect(_x,_y + 0.03, 41, 11, 41, 100) end Citizen.CreateThread(function() local performans = 1000 while true do Citizen.Wait(performans) if nearBank() then performans = 1 else performans = 1000 end end end)
----------------------------------- -- Area: Stellar Fulcrum -- Door: Qe'Lov Gate -- !pos -520 -4 17 179 ------------------------------------- require("scripts/globals/bcnm"); function onTrade(player,npc,trade) TradeBCNM(player,npc,trade); end; function onTrigger(player,npc) EventTriggerBCNM(player,npc); end; function onEventUpdate(player,csid,option,extras) EventUpdateBCNM(player,csid,option,extras); end; function onEventFinish(player,csid,option) EventFinishBCNM(player,csid,option); end;
class("GetShipCommand", pm.SimpleCommand).execute = function (slot0, slot1) slot3 = slot1:getBody().type or 1 slot5 = slot2.callBack slot6 = slot2.isBatch slot7 = slot2.canSkipBatch slot8 = slot2.isSkip slot9 = slot2.anim if not getProxy(BuildShipProxy):getBuildShip(slot2.pos) then pg.TipsMgr.GetInstance():ShowTips(i18n("ship_getShip_error_noShip")) if slot5 then slot5() end return end if not slot11:isFinish() then pg.TipsMgr.GetInstance():ShowTips(i18n("ship_getShip_error_notFinish")) if slot5 then slot5() end return end slot12 = getProxy(BayProxy) if not slot6 and getProxy(PlayerProxy).getData(slot14).getMaxShipBag(slot15) <= #slot12:getShips() then NoPosMsgBox(i18n("switch_to_shop_tip_noDockyard"), openDockyardClear, gotoChargeScene, openDockyardIntensify) if slot5 then slot5() end return end pg.ConnectionMgr.GetInstance():Send(12025, { type = slot3, pos = slot4 }, 12026, function (slot0) if slot0.result == 0 then function slot1() slot0:removeBuildShipByIndex(slot0) if Ship.New(slot2.ship):isMetaShip() and not slot0.virgin and Player.isMetaShipNeedToTrans(slot0.configId) then if MetaCharacterConst.addReMetaTransItem(slot0) then slot0:setReMetaSpecialItemVO(slot1) end else slot3:addShip(slot0) end slot0:setBuildShipState() slot2 = getProxy(PlayerProxy).getData(slot1) if slot0:getRarity() >= 4 and not slot2:GetCommonFlag(GAME_RESTOREVIEW_ALREADY) then pg.SdkMgr.GetInstance():StoreReview() pg.SdkMgr.GetInstance():sendNotification(GAME.COMMON_FLAG, { flagID = GAME_RESTOREVIEW_ALREADY }) end if slot5 and not slot0.virgin and slot0:getRarity() < 4 then slot4:sendNotification(GAME.SKIP_SHIP_DONE) slot6(slot0) else slot4:sendNotification(GAME.GET_SHIP_DONE, { ship = slot0, quitCallBack = slot6, canSkipBatch = slot6, isBatch = slot8 }) end end if slot8 then slot8(slot1, slot9.type) else slot1() end else pg.TipsMgr.GetInstance():ShowTips(errorTip("ship_getShip", slot0.result)) end end) end return class("GetShipCommand", pm.SimpleCommand)
function onUse(player, item, fromPosition, target, toPosition, isHotkey) if player:getStorageValue(Storage.QuestChests.BananaPalm) == 1 then player:sendTextMessage(MESSAGE_EVENT_ADVANCE, 'The banana palm is empty.') else player:sendTextMessage(MESSAGE_EVENT_ADVANCE, 'You have found a banana.') player:addItem(2676, 1) player:setStorageValue(Storage.QuestChests.BananaPalm, 1) end return true end
Initialize = function() startTime = os.time() end Update = function() local sessionTime = os.time() - startTime local hours = sessionTime / 3600.0 local minutes = (hours % 1) * 60.0 return SKIN:Bang(('[!SetOption "SessionTime" "Text" "%02d:%02d"]'):format(math.floor(hours), math.floor(minutes))) end
function inventorypostinit(Inventory, inst) Inventory.OriginalDropEverything = Inventory.DropEverything; function Inventory:DropEverything(ondeath, keepequip) if inst:HasTag("player") then else return Inventory:OriginalDropEverything(ondeath, keepequip); end; end; end; AddComponentPostInit("inventory", inventorypostinit);
local config = import 'micro/config' local function wantwords(ft) return ft == 'markdown' or ft == 'asciidoc' end local function appendsep(s, a) if s ~= '' then s = s .. ' | ' end return s .. a end function onBufferOpen(b) if wantwords(b:FileType()) then local format = config.GetGlobalOption 'statusformatr' local add = '$(textcount.words) Words' if not string.find(format, add) then b:SetOption('statusformatr', appendsep(format, add)) end end end
#!/usr/bin/env lua -------------------------------------------------------------------------------- -- wrap.lua bundle begins -- version: 2020-02-03 8ef0a41 -- content sha256: 55fa8110a1 -------------------------------------------------------------------------------- do do local _ENV = _ENV package.preload[ "argparse" ] = function( ... ) _ENV = _ENV; -- The MIT License (MIT) -- Copyright (c) 2013 - 2015 Peter Melnichenko -- 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 function deep_update(t1, t2) for k, v in pairs(t2) do if type(v) == "table" then v = deep_update({}, v) end t1[k] = v end return t1 end -- A property is a tuple {name, callback}. -- properties.args is number of properties that can be set as arguments -- when calling an object. local function class(prototype, properties, parent) -- Class is the metatable of its instances. local cl = {} cl.__index = cl if parent then cl.__prototype = deep_update(deep_update({}, parent.__prototype), prototype) else cl.__prototype = prototype end if properties then local names = {} -- Create setter methods and fill set of property names. for _, property in ipairs(properties) do local name, callback = property[1], property[2] cl[name] = function(self, value) if not callback(self, value) then self["_" .. name] = value end return self end names[name] = true end function cl.__call(self, ...) -- When calling an object, if the first argument is a table, -- interpret keys as property names, else delegate arguments -- to corresponding setters in order. if type((...)) == "table" then for name, value in pairs((...)) do if names[name] then self[name](self, value) end end else local nargs = select("#", ...) for i, property in ipairs(properties) do if i > nargs or i > properties.args then break end local arg = select(i, ...) if arg ~= nil then self[property[1]](self, arg) end end end return self end end -- If indexing class fails, fallback to its parent. local class_metatable = {} class_metatable.__index = parent function class_metatable.__call(self, ...) -- Calling a class returns its instance. -- Arguments are delegated to the instance. local object = deep_update({}, self.__prototype) setmetatable(object, self) return object(...) end return setmetatable(cl, class_metatable) end local function typecheck(name, types, value) for _, type_ in ipairs(types) do if type(value) == type_ then return true end end error(("bad property '%s' (%s expected, got %s)"):format(name, table.concat(types, " or "), type(value))) end local function typechecked(name, ...) local types = {...} return {name, function(_, value) typecheck(name, types, value) end} end local multiname = {"name", function(self, value) typecheck("name", {"string"}, value) for alias in value:gmatch("%S+") do self._name = self._name or alias table.insert(self._aliases, alias) end -- Do not set _name as with other properties. return true end} local function parse_boundaries(str) if tonumber(str) then return tonumber(str), tonumber(str) end if str == "*" then return 0, math.huge end if str == "+" then return 1, math.huge end if str == "?" then return 0, 1 end if str:match "^%d+%-%d+$" then local min, max = str:match "^(%d+)%-(%d+)$" return tonumber(min), tonumber(max) end if str:match "^%d+%+$" then local min = str:match "^(%d+)%+$" return tonumber(min), math.huge end end local function boundaries(name) return {name, function(self, value) typecheck(name, {"number", "string"}, value) local min, max = parse_boundaries(value) if not min then error(("bad property '%s'"):format(name)) end self["_min" .. name], self["_max" .. name] = min, max end} end local actions = {} local option_action = {"action", function(_, value) typecheck("action", {"function", "string"}, value) if type(value) == "string" and not actions[value] then error(("unknown action '%s'"):format(value)) end end} local option_init = {"init", function(self) self._has_init = true end} local option_default = {"default", function(self, value) if type(value) ~= "string" then self._init = value self._has_init = true return true end end} local add_help = {"add_help", function(self, value) typecheck("add_help", {"boolean", "string", "table"}, value) if self._has_help then table.remove(self._options) self._has_help = false end if value then local help = self:flag() :description "Show this help message and exit." :action(function() print(self:get_help()) os.exit(0) end) if value ~= true then help = help(value) end if not help._name then help "-h" "--help" end self._has_help = true end end} local Parser = class({ _arguments = {}, _options = {}, _commands = {}, _mutexes = {}, _require_command = true, _handle_options = true }, { args = 3, typechecked("name", "string"), typechecked("description", "string"), typechecked("epilog", "string"), typechecked("usage", "string"), typechecked("help", "string"), typechecked("require_command", "boolean"), typechecked("handle_options", "boolean"), typechecked("action", "function"), typechecked("command_target", "string"), add_help }) local Command = class({ _aliases = {} }, { args = 3, multiname, typechecked("description", "string"), typechecked("epilog", "string"), typechecked("target", "string"), typechecked("usage", "string"), typechecked("help", "string"), typechecked("require_command", "boolean"), typechecked("handle_options", "boolean"), typechecked("action", "function"), typechecked("command_target", "string"), add_help }, Parser) local Argument = class({ _minargs = 1, _maxargs = 1, _mincount = 1, _maxcount = 1, _defmode = "unused", _show_default = true }, { args = 5, typechecked("name", "string"), typechecked("description", "string"), option_default, typechecked("convert", "function", "table"), boundaries("args"), typechecked("target", "string"), typechecked("defmode", "string"), typechecked("show_default", "boolean"), typechecked("argname", "string", "table"), option_action, option_init }) local Option = class({ _aliases = {}, _mincount = 0, _overwrite = true }, { args = 6, multiname, typechecked("description", "string"), option_default, typechecked("convert", "function", "table"), boundaries("args"), boundaries("count"), typechecked("target", "string"), typechecked("defmode", "string"), typechecked("show_default", "boolean"), typechecked("overwrite", "boolean"), typechecked("argname", "string", "table"), option_action, option_init }, Argument) function Argument:_get_argument_list() local buf = {} local i = 1 while i <= math.min(self._minargs, 3) do local argname = self:_get_argname(i) if self._default and self._defmode:find "a" then argname = "[" .. argname .. "]" end table.insert(buf, argname) i = i+1 end while i <= math.min(self._maxargs, 3) do table.insert(buf, "[" .. self:_get_argname(i) .. "]") i = i+1 if self._maxargs == math.huge then break end end if i < self._maxargs then table.insert(buf, "...") end return buf end function Argument:_get_usage() local usage = table.concat(self:_get_argument_list(), " ") if self._default and self._defmode:find "u" then if self._maxargs > 1 or (self._minargs == 1 and not self._defmode:find "a") then usage = "[" .. usage .. "]" end end return usage end function actions.store_true(result, target) result[target] = true end function actions.store_false(result, target) result[target] = false end function actions.store(result, target, argument) result[target] = argument end function actions.count(result, target, _, overwrite) if not overwrite then result[target] = result[target] + 1 end end function actions.append(result, target, argument, overwrite) result[target] = result[target] or {} table.insert(result[target], argument) if overwrite then table.remove(result[target], 1) end end function actions.concat(result, target, arguments, overwrite) if overwrite then error("'concat' action can't handle too many invocations") end result[target] = result[target] or {} for _, argument in ipairs(arguments) do table.insert(result[target], argument) end end function Argument:_get_action() local action, init if self._maxcount == 1 then if self._maxargs == 0 then action, init = "store_true", nil else action, init = "store", nil end else if self._maxargs == 0 then action, init = "count", 0 else action, init = "append", {} end end if self._action then action = self._action end if self._has_init then init = self._init end if type(action) == "string" then action = actions[action] end return action, init end -- Returns placeholder for `narg`-th argument. function Argument:_get_argname(narg) local argname = self._argname or self:_get_default_argname() if type(argname) == "table" then return argname[narg] else return argname end end function Argument:_get_default_argname() return "<" .. self._name .. ">" end function Option:_get_default_argname() return "<" .. self:_get_default_target() .. ">" end -- Returns label to be shown in the help message. function Argument:_get_label() return self._name end function Option:_get_label() local variants = {} local argument_list = self:_get_argument_list() table.insert(argument_list, 1, nil) for _, alias in ipairs(self._aliases) do argument_list[1] = alias table.insert(variants, table.concat(argument_list, " ")) end return table.concat(variants, ", ") end function Command:_get_label() return table.concat(self._aliases, ", ") end function Argument:_get_description() if self._default and self._show_default then if self._description then return ("%s (default: %s)"):format(self._description, self._default) else return ("default: %s"):format(self._default) end else return self._description or "" end end function Command:_get_description() return self._description or "" end function Option:_get_usage() local usage = self:_get_argument_list() table.insert(usage, 1, self._name) usage = table.concat(usage, " ") if self._mincount == 0 or self._default then usage = "[" .. usage .. "]" end return usage end function Argument:_get_default_target() return self._name end function Option:_get_default_target() local res for _, alias in ipairs(self._aliases) do if alias:sub(1, 1) == alias:sub(2, 2) then res = alias:sub(3) break end end res = res or self._name:sub(2) return (res:gsub("-", "_")) end function Option:_is_vararg() return self._maxargs ~= self._minargs end function Parser:_get_fullname() local parent = self._parent local buf = {self._name} while parent do table.insert(buf, 1, parent._name) parent = parent._parent end return table.concat(buf, " ") end function Parser:_update_charset(charset) charset = charset or {} for _, command in ipairs(self._commands) do command:_update_charset(charset) end for _, option in ipairs(self._options) do for _, alias in ipairs(option._aliases) do charset[alias:sub(1, 1)] = true end end return charset end function Parser:argument(...) local argument = Argument(...) table.insert(self._arguments, argument) return argument end function Parser:option(...) local option = Option(...) if self._has_help then table.insert(self._options, #self._options, option) else table.insert(self._options, option) end return option end function Parser:flag(...) return self:option():args(0)(...) end function Parser:command(...) local command = Command():add_help(true)(...) command._parent = self table.insert(self._commands, command) return command end function Parser:mutex(...) local options = {...} for i, option in ipairs(options) do assert(getmetatable(option) == Option, ("bad argument #%d to 'mutex' (Option expected)"):format(i)) end table.insert(self._mutexes, options) return self end local max_usage_width = 70 local usage_welcome = "Usage: " function Parser:get_usage() if self._usage then return self._usage end local lines = {usage_welcome .. self:_get_fullname()} local function add(s) if #lines[#lines]+1+#s <= max_usage_width then lines[#lines] = lines[#lines] .. " " .. s else lines[#lines+1] = (" "):rep(#usage_welcome) .. s end end -- This can definitely be refactored into something cleaner local mutex_options = {} local vararg_mutexes = {} -- First, put mutexes which do not contain vararg options and remember those which do for _, mutex in ipairs(self._mutexes) do local buf = {} local is_vararg = false for _, option in ipairs(mutex) do if option:_is_vararg() then is_vararg = true end table.insert(buf, option:_get_usage()) mutex_options[option] = true end local repr = "(" .. table.concat(buf, " | ") .. ")" if is_vararg then table.insert(vararg_mutexes, repr) else add(repr) end end -- Second, put regular options for _, option in ipairs(self._options) do if not mutex_options[option] and not option:_is_vararg() then add(option:_get_usage()) end end -- Put positional arguments for _, argument in ipairs(self._arguments) do add(argument:_get_usage()) end -- Put mutexes containing vararg options for _, mutex_repr in ipairs(vararg_mutexes) do add(mutex_repr) end for _, option in ipairs(self._options) do if not mutex_options[option] and option:_is_vararg() then add(option:_get_usage()) end end if #self._commands > 0 then if self._require_command then add("<command>") else add("[<command>]") end add("...") end return table.concat(lines, "\n") end local margin_len = 3 local margin_len2 = 25 local margin = (" "):rep(margin_len) local margin2 = (" "):rep(margin_len2) local function make_two_columns(s1, s2) if s2 == "" then return margin .. s1 end s2 = s2:gsub("\n", "\n" .. margin2) if #s1 < (margin_len2-margin_len) then return margin .. s1 .. (" "):rep(margin_len2-margin_len-#s1) .. s2 else return margin .. s1 .. "\n" .. margin2 .. s2 end end function Parser:get_help() if self._help then return self._help end local blocks = {self:get_usage()} if self._description then table.insert(blocks, self._description) end local labels = {"Arguments:", "Options:", "Commands:"} for i, elements in ipairs{self._arguments, self._options, self._commands} do if #elements > 0 then local buf = {labels[i]} for _, element in ipairs(elements) do table.insert(buf, make_two_columns(element:_get_label(), element:_get_description())) end table.insert(blocks, table.concat(buf, "\n")) end end if self._epilog then table.insert(blocks, self._epilog) end return table.concat(blocks, "\n\n") end local function get_tip(context, wrong_name) local context_pool = {} local possible_name local possible_names = {} for name in pairs(context) do if type(name) == "string" then for i = 1, #name do possible_name = name:sub(1, i - 1) .. name:sub(i + 1) if not context_pool[possible_name] then context_pool[possible_name] = {} end table.insert(context_pool[possible_name], name) end end end for i = 1, #wrong_name + 1 do possible_name = wrong_name:sub(1, i - 1) .. wrong_name:sub(i + 1) if context[possible_name] then possible_names[possible_name] = true elseif context_pool[possible_name] then for _, name in ipairs(context_pool[possible_name]) do possible_names[name] = true end end end local first = next(possible_names) if first then if next(possible_names, first) then local possible_names_arr = {} for name in pairs(possible_names) do table.insert(possible_names_arr, "'" .. name .. "'") end table.sort(possible_names_arr) return "\nDid you mean one of these: " .. table.concat(possible_names_arr, " ") .. "?" else return "\nDid you mean '" .. first .. "'?" end else return "" end end local ElementState = class({ invocations = 0 }) function ElementState:__call(state, element) self.state = state self.result = state.result self.element = element self.target = element._target or element:_get_default_target() self.action, self.result[self.target] = element:_get_action() return self end function ElementState:error(fmt, ...) self.state:error(fmt, ...) end function ElementState:convert(argument) local converter = self.element._convert if converter then local ok, err if type(converter) == "function" then ok, err = converter(argument) else ok = converter[argument] end if ok == nil then self:error(err and "%s" or "malformed argument '%s'", err or argument) end argument = ok end return argument end function ElementState:default(mode) return self.element._defmode:find(mode) and self.element._default end local function bound(noun, min, max, is_max) local res = "" if min ~= max then res = "at " .. (is_max and "most" or "least") .. " " end local number = is_max and max or min return res .. tostring(number) .. " " .. noun .. (number == 1 and "" or "s") end function ElementState:invoke(alias) self.open = true self.name = ("%s '%s'"):format(alias and "option" or "argument", alias or self.element._name) self.overwrite = false if self.invocations >= self.element._maxcount then if self.element._overwrite then self.overwrite = true else self:error("%s must be used %s", self.name, bound("time", self.element._mincount, self.element._maxcount, true)) end else self.invocations = self.invocations + 1 end self.args = {} if self.element._maxargs <= 0 then self:close() end return self.open end function ElementState:pass(argument) argument = self:convert(argument) table.insert(self.args, argument) if #self.args >= self.element._maxargs then self:close() end return self.open end function ElementState:complete_invocation() while #self.args < self.element._minargs do self:pass(self.element._default) end end function ElementState:close() if self.open then self.open = false if #self.args < self.element._minargs then if self:default("a") then self:complete_invocation() else if #self.args == 0 then if getmetatable(self.element) == Argument then self:error("missing %s", self.name) elseif self.element._maxargs == 1 then self:error("%s requires an argument", self.name) end end self:error("%s requires %s", self.name, bound("argument", self.element._minargs, self.element._maxargs)) end end local args = self.args if self.element._maxargs <= 1 then args = args[1] end if self.element._maxargs == 1 and self.element._minargs == 0 and self.element._mincount ~= self.element._maxcount then args = self.args end self.action(self.result, self.target, args, self.overwrite) end end local ParseState = class({ result = {}, options = {}, arguments = {}, argument_i = 1, element_to_mutexes = {}, mutex_to_used_option = {}, command_actions = {} }) function ParseState:__call(parser, error_handler) self.parser = parser self.error_handler = error_handler self.charset = parser:_update_charset() self:switch(parser) return self end function ParseState:error(fmt, ...) self.error_handler(self.parser, fmt:format(...)) end function ParseState:switch(parser) self.parser = parser if parser._action then table.insert(self.command_actions, {action = parser._action, name = parser._name}) end for _, option in ipairs(parser._options) do option = ElementState(self, option) table.insert(self.options, option) for _, alias in ipairs(option.element._aliases) do self.options[alias] = option end end for _, mutex in ipairs(parser._mutexes) do for _, option in ipairs(mutex) do if not self.element_to_mutexes[option] then self.element_to_mutexes[option] = {} end table.insert(self.element_to_mutexes[option], mutex) end end for _, argument in ipairs(parser._arguments) do argument = ElementState(self, argument) table.insert(self.arguments, argument) argument:invoke() end self.handle_options = parser._handle_options self.argument = self.arguments[self.argument_i] self.commands = parser._commands for _, command in ipairs(self.commands) do for _, alias in ipairs(command._aliases) do self.commands[alias] = command end end end function ParseState:get_option(name) local option = self.options[name] if not option then self:error("unknown option '%s'%s", name, get_tip(self.options, name)) else return option end end function ParseState:get_command(name) local command = self.commands[name] if not command then if #self.commands > 0 then self:error("unknown command '%s'%s", name, get_tip(self.commands, name)) else self:error("too many arguments") end else return command end end function ParseState:invoke(option, name) self:close() if self.element_to_mutexes[option.element] then for _, mutex in ipairs(self.element_to_mutexes[option.element]) do local used_option = self.mutex_to_used_option[mutex] if used_option and used_option ~= option then self:error("option '%s' can not be used together with %s", name, used_option.name) else self.mutex_to_used_option[mutex] = option end end end if option:invoke(name) then self.option = option end end function ParseState:pass(arg) if self.option then if not self.option:pass(arg) then self.option = nil end elseif self.argument then if not self.argument:pass(arg) then self.argument_i = self.argument_i + 1 self.argument = self.arguments[self.argument_i] end else local command = self:get_command(arg) self.result[command._target or command._name] = true if self.parser._command_target then self.result[self.parser._command_target] = command._name end self:switch(command) end end function ParseState:close() if self.option then self.option:close() self.option = nil end end function ParseState:finalize() self:close() for i = self.argument_i, #self.arguments do local argument = self.arguments[i] if #argument.args == 0 and argument:default("u") then argument:complete_invocation() else argument:close() end end if self.parser._require_command and #self.commands > 0 then self:error("a command is required") end for _, option in ipairs(self.options) do local name = option.name or ("option '%s'"):format(option.element._name) if option.invocations == 0 then if option:default("u") then option:invoke(name) option:complete_invocation() option:close() end end local mincount = option.element._mincount if option.invocations < mincount then if option:default("a") then while option.invocations < mincount do option:invoke(name) option:close() end elseif option.invocations == 0 then self:error("missing %s", name) else self:error("%s must be used %s", name, bound("time", mincount, option.element._maxcount)) end end end for i = #self.command_actions, 1, -1 do self.command_actions[i].action(self.result, self.command_actions[i].name) end end function ParseState:parse(args) for _, arg in ipairs(args) do local plain = true if self.handle_options then local first = arg:sub(1, 1) if self.charset[first] then if #arg > 1 then plain = false if arg:sub(2, 2) == first then if #arg == 2 then self:close() self.handle_options = false else local equals = arg:find "=" if equals then local name = arg:sub(1, equals - 1) local option = self:get_option(name) if option.element._maxargs <= 0 then self:error("option '%s' does not take arguments", name) end self:invoke(option, name) self:pass(arg:sub(equals + 1)) else local option = self:get_option(arg) self:invoke(option, arg) end end else for i = 2, #arg do local name = first .. arg:sub(i, i) local option = self:get_option(name) self:invoke(option, name) if i ~= #arg and option.element._maxargs > 0 then self:pass(arg:sub(i + 1)) break end end end end end end if plain then self:pass(arg) end end self:finalize() return self.result end function Parser:error(msg) io.stderr:write(("%s\n\nError: %s\n"):format(self:get_usage(), msg)) os.exit(1) end -- Compatibility with strict.lua and other checkers: local default_cmdline = rawget(_G, "arg") or {} function Parser:_parse(args, error_handler) return ParseState(self, error_handler):parse(args or default_cmdline) end function Parser:parse(args) return self:_parse(args, self.error) end local function xpcall_error_handler(err) return tostring(err) .. "\noriginal " .. debug.traceback("", 2):sub(2) end function Parser:pparse(args) local parse_error local ok, result = xpcall(function() return self:_parse(args, function(_, err) parse_error = err error(err, 0) end) end, xpcall_error_handler) if ok then return true, result elseif not parse_error then error(result, 0) else return false, parse_error end end return function(...) return Parser(default_cmdline[0]):add_help(true)(...) end end end do local _ENV = _ENV package.preload[ "common.utils.array.add" ] = function( ... ) _ENV = _ENV; --- Creates a new array that has items from all argument arrays added in sequence. --- concat would be a better name, but there already is table.concat that does something else. ---@generic TItem ---@vararg TItem[] ---@return TItem[] local function add (...) local result = {} local arrays = { ... } for arrayIndex = 1, #arrays do local array = arrays[arrayIndex] for elementIndex = 1, #array do result[#result + 1] = array[elementIndex] end end return result end return add end end do local _ENV = _ENV package.preload[ "common.utils.array.findOneMatching" ] = function( ... ) _ENV = _ENV; --- Returns the first item matching the predicate. ---@generic TItem ---@param items TItem[] ---@param predicate fun(item:TItem):boolean ---@return TItem|nil local function findOneMatching (items, predicate) for _, item in ipairs(items) do if predicate(item) then return item end end end return findOneMatching end end do local _ENV = _ENV package.preload[ "common.utils.array.map" ] = function( ... ) _ENV = _ENV; -- https://en.wikibooks.org/wiki/Lua_Functional_Programming/Functions ---@generic TSource, TResult ---@param array TSource[] ---@param func fun(item:TSource):TResult ---@return TResult[] local function map (array, func) local new_array = {} for index, value in ipairs(array) do new_array[index] = func(value) end return new_array end return map end end do local _ENV = _ENV package.preload[ "common.utils.compat.pairs" ] = function( ... ) _ENV = _ENV; -- adds __pairs support to Lua 5.1 if not _ENV then local realPairs = pairs -- luacheck: ignore pairs pairs = function (tbl) local mt = getmetatable(tbl) if type(mt) == "table" and mt.__pairs then return mt.__pairs(tbl) else return realPairs(tbl) end end end end end do local _ENV = _ENV package.preload[ "common.utils.string.replaceVars" ] = function( ... ) _ENV = _ENV; ---@param str string ---@param vars table<string, string> local function replaceVars (str, vars) local result = str:gsub("({([^}]+)})", function (whole, key) return vars[key] or whole end) return result end return replaceVars end end do local _ENV = _ENV package.preload[ "common.utils.table.OrderedMap" ] = function( ... ) _ENV = _ENV; -- Penlight's OrderedMap adds over 150 KB of Lua code. This class implements some of its functionality. local getValueKey = require "common.utils.table.getValueKey" local concat = table.concat local function iterateOrderedMap (om, key) if key == nil then key = om._keys[1] else local keyIndex = getValueKey(om._keys, key) if not keyIndex then return nil end key = om._keys[keyIndex + 1] end return key, om[key] end local OrderedMap = {} OrderedMap.__index = OrderedMap function OrderedMap.new (t) local self = setmetatable({ _keys = {} }, OrderedMap) if t then self:update(t) end return self end function OrderedMap:update (t) if #t > 0 then for _, pair in ipairs(t) do local k, v = next(pair) if not k then error("Empty pair (key is null).") end self[k] = v end else for k, v in pairs(t) do self[k] = v end end return self end function OrderedMap:__pairs () return iterateOrderedMap, self, nil end function OrderedMap._ipairs () error("Not implemented!") end function OrderedMap:__newindex (k, v) local keys = self._keys if not getValueKey(keys, v) then keys[#keys + 1] = k end rawset(self, k, v) end function OrderedMap:__tostring () -- for debugging and unit testing local keys = self._keys local buf = { "{" } for i = 1, #keys do local k = keys[i] local v = self[k] buf[#buf + 1] = k buf[#buf + 1] = "=" if type(v) == "number" then buf[#buf + 1] = v else buf[#buf + 1] = '"' .. tostring(v) .. '"' end if i < #keys then buf[#buf + 1] = "," end end buf[#buf + 1] = "}" return concat(buf) end return setmetatable({}, { __call = function(_, t) return OrderedMap.new(t) end, __index = OrderedMap }) end end do local _ENV = _ENV package.preload[ "common.utils.table.assign" ] = function( ... ) _ENV = _ENV; -- Copies values of source tables into the target table and returns the target table -- (like JavaScript's Object.assign) ---@generic TTargetTable, TCopiedTable ---@param targetTable TTargetTable ---@vararg TCopiedTable ---@return TTargetTable | TCopiedTable local function assign (targetTable, ...) local sourceTables = { ... } for i = 1, #sourceTables do for key, value in pairs(sourceTables[i]) do targetTable[key] = value end end return targetTable end return assign end end do local _ENV = _ENV package.preload[ "common.utils.table.getKeys" ] = function( ... ) _ENV = _ENV; ---@generic TKey ---@param tbl table<TKey, any> ---@return TKey[] local function getKeys (tbl) local keys = {} for key, _ in pairs(tbl) do keys[#keys + 1] = key end return keys end return getKeys end end do local _ENV = _ENV package.preload[ "common.utils.table.getValueKey" ] = function( ... ) _ENV = _ENV; ---@generic TKey, TValue ---@param tbl table<TKey, TValue> ---@param valueToFind TValue ---@return TValue local function getValueKey (tbl, valueToFind) for key, value in pairs(tbl) do if value == valueToFind then return key end end return nil end return getValueKey end end do local _ENV = _ENV package.preload[ "dkjson" ] = function( ... ) _ENV = _ENV; -- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 Version 2.5 For the documentation see the corresponding readme.txt or visit <http://dkolf.de/src/dkjson-lua.fsl/>. You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. Copyright (C) 2010-2013 David Heiko Kolf Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local strmatch = string.match local concat = table.concat local json = { version = "dkjson 2.5" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function replace(str, o, n) local i, j = strfind (str, o, 1, true) if i then return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1) else return str end end -- locale independent num2str and str2num functions local decpoint, numfilter local function updatedecpoint () decpoint = strmatch(tostring(0.5), "([^05+])") -- build a filter that can be used to remove group separators numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+" end updatedecpoint() local function num2str (num) return replace(fsub(tostring(num), numfilter, ""), decpoint, ".") end local function str2num (str) local num = tonumber(replace(str, ".", decpoint)) if not num then updatedecpoint() num = tonumber(replace(str, ".", decpoint)) end return num end local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder, state) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder, state) end local function appendcustom(res, buffer, state) local buflen = state.bufferlen if type (res) == 'string' then buflen = buflen + 1 buffer[buflen] = res end return buflen end local function exception(reason, value, state, buffer, buflen, defaultmessage) defaultmessage = defaultmessage or reason local handler = state.exception if not handler then return nil, defaultmessage else state.bufferlen = buflen local ret, msg = handler (reason, value, state, defaultmessage) if not ret then return nil, msg or defaultmessage end return appendcustom(ret, buffer, state) end end function json.encodeexception(reason, value, state, defaultmessage) return quotestring("<" .. defaultmessage .. ">") end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder, state) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return exception('reference cycle', value, state, buffer, buflen) end tables[value] = true state.bufferlen = buflen local ret, msg = valtojson (value, state) if not ret then return exception('custom encoder failed', value, state, buffer, buflen, msg) end tables[value] = nil buflen = appendcustom(ret, buffer, state) elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = num2str (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return exception('reference cycle', value, state, buffer, buflen) end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder, state) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder, state) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder, state) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder, state) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return exception ('unsupported type', value, state, buffer, buflen, "type '" .. valtype .. "' is not supported by JSON.") end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} state.buffer = buffer updatedecpoint() local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder, state) if not ret then error (msg, 2) elseif oldbuffer == buffer then state.bufferlen = ret return true else state.bufferlen = nil state.buffer = nil return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end local sub2 = strsub (str, pos, pos + 1) if sub2 == "\239\187" and strsub (str, pos + 2, pos + 2) == "\191" then -- UTF-8 Byte Order Mark pos = pos + 3 elseif sub2 == "//" then pos = strfind (str, "[\n\r]", pos + 2) if not pos then return nil end elseif sub2 == "/*" then pos = strfind (str, "*/", pos + 2) if not pos then return nil end pos = pos + 2 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = str2num (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") if g.version() == "0.11" then error "due to a bug in LPeg 0.11, it cannot be used for JSON matching" end local pegmatch = g.match local P, S, R = g.P, g.S, g.R local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local SingleLineComment = P"//" * (1 - S"\n\r")^0 local MultiLineComment = P"/*" * (1 - P"*/")^0 * P"*/" local Space = (S" \n\r\t" + P"\239\187\191" + SingleLineComment + MultiLineComment)^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json end end do local _ENV = _ENV package.preload[ "du.script-config.Autoconf" ] = function( ... ) _ENV = _ENV; local findOneMatching = require "common.utils.array.findOneMatching" local AutoconfSlot = require "du.script-config.AutoconfSlot" local insert, unpack = table.insert, unpack or table.unpack -- luacheck: ignore unpack ---@param name string local function createAutoconf (name) name = name or "Unnamed autoconf" local self = {} ---@class ScriptAutoconf ---@type ScriptAutoconfSlot[] local slots = { AutoconfSlot.new("unit", "control", nil, nil, true), AutoconfSlot.new("system", "system", nil, nil, true), AutoconfSlot.new("library", "library", nil, nil, true) } ---@param slotName string ---@param slotTypeName string ---@param slotClass string ---@param slotSelect string|nil function self.addSlot (slotName, slotTypeName, slotClass, slotSelect) local slot = AutoconfSlot.new(slotName, slotTypeName, slotClass, slotSelect) insert(slots, slot) return slot end ---@return ScriptAutoconfSlot[] function self.getSlots () return { unpack(slots) } end ---@param slotName string function self.getSlotByName (slotName) return findOneMatching(slots, function (slot) return slot.getName() == slotName end) end function self.getName () return name end ---@param newName string function self.setName (newName) name = newName end return self end return { new = createAutoconf } end end do local _ENV = _ENV package.preload[ "du.script-config.AutoconfSlot" ] = function( ... ) _ENV = _ENV; local Handler = require "du.script-config.Handler" local insert, unpack = table.insert, unpack or table.unpack -- luacheck: ignore unpack local function createAutoconfSlot (name, typeName, class, select, isBuiltin) local self = {} ---@class ScriptAutoconfSlot local handlers = {} ---@type ScriptHandler[] function self.getName () return name end function self.getTypeName () return typeName end function self.getClass () return class end function self.getSelect () return select end function self.getIsBuiltin () return isBuiltin end function self.addHandler (filterSignature, filterArguments, code) local handler = Handler.new(filterSignature, filterArguments, code) insert(handlers, handler) return handler end ---@return ScriptHandler[] function self.getHandlers () return { unpack(handlers) } end return self end return { new = createAutoconfSlot } end end do local _ENV = _ENV package.preload[ "du.script-config.Config" ] = function( ... ) _ENV = _ENV; local map = require "common.utils.array.map" local findOneMatching = require "common.utils.array.findOneMatching" local ConfigMethod = require "du.script-config.ConfigMethod" local ConfigSlot = require "du.script-config.ConfigSlot" local insert, unpack = table.insert, unpack or table.unpack -- luacheck: ignore unpack local function createConfig () local self = {} ---@class ScriptConfig local slots = {} ---@type ScriptConfigSlot[] local methods = {} ---@type ScriptConfigMethod[] ---@param slotKey number ---@param slotName string ---@param slotElementType string function self.addSlot (slotKey, slotName, slotElementType) local slot = ConfigSlot.new(slotKey, slotName, slotElementType) insert(slots, slot) return slot end ---@param signature string ---@param code string function self.addMethod (signature, code) local method = ConfigMethod.new(signature, code) insert(methods, method) return method end ---@return ScriptConfigSlot[] function self.getSlots () return { unpack(slots) } end function self.getSlotKeys () return map(slots, function (slot) return slot.getKey() end) end function self.getSlotByKey (slotKey) return findOneMatching(slots, function (slot) return slot.getKey() == slotKey end) end function self.getSlotByName (slotName) return findOneMatching(slots, function (slot) return slot.getName() == slotName end) end ---@return ScriptConfigMethod[] function self.getMethods () return { unpack(methods) } end return self end local function createDefaultConfig () local config = createConfig() for slotIndex = 1, 10 do config.addSlot(slotIndex - 1, "slot" .. slotIndex) end config.addSlot(-1, "unit", "control") config.addSlot(-2, "system", "system") config.addSlot(-3, "library", "library") return config end return { new = createConfig, default = createDefaultConfig } end end do local _ENV = _ENV package.preload[ "du.script-config.ConfigMethod" ] = function( ... ) _ENV = _ENV; ---@param signature string ---@param code string local function createConfigMethod (signature, code) local self = {} ---@class ScriptConfigMethod function self.getSignature () return signature end function self.getCode () return code end ---@param newSignature string function self.setSignature (newSignature) signature = newSignature end ---@param newCode string function self.setCode (newCode) code = newCode end return self end return { new = createConfigMethod } end end do local _ENV = _ENV package.preload[ "du.script-config.ConfigSlot" ] = function( ... ) _ENV = _ENV; local Handler = require "du.script-config.Handler" local insert, unpack = table.insert, unpack or table.unpack -- luacheck: ignore unpack ---@param key number ---@param name string ---@param elementType string local function createConfigSlot (key, name, elementType) local self = {} ---@class ScriptConfigSlot local handlers = {} ---@type ScriptHandler[] function self.getKey () return key end function self.getName () return name end function self.getElementType () return elementType end ---@param newName string function self.setName (newName) name = newName end ---@param newElementType string function self.setElementType (newElementType) elementType = newElementType end ---@param filterSignature string ---@param filterArguments string[] ---@param code string function self.addHandler (filterSignature, filterArguments, code) local handler = Handler.new(filterSignature, filterArguments, code) insert(handlers, handler) return handler end ---@return ScriptHandler[] function self.getHandlers () return { unpack(handlers) } end return self end return { new = createConfigSlot } end end do local _ENV = _ENV package.preload[ "du.script-config.Handler" ] = function( ... ) _ENV = _ENV; ---@param filterSignature string ---@param filterArguments string[] ---@param code string local function createHandler (filterSignature, filterArguments, code) local self = {} ---@class ScriptHandler function self.getFilterSignature () return filterSignature end function self.getFilterArguments () return filterArguments end function self.getCode () return code end ---@param newFilterSignature string function self.setFilterSignature (newFilterSignature) filterSignature = newFilterSignature end ---@param newFilterArguments string function self.setFilterArguments (newFilterArguments) filterArguments = newFilterArguments end ---@param newCode string function self.setCode (newCode) code = newCode end return self end return { new = createHandler } end end do local _ENV = _ENV package.preload[ "du.script-config.autoconfToObject" ] = function( ... ) _ENV = _ENV; local getValueKey = require "common.utils.table.getValueKey" local parseFilterSignature = require "du.script-config.parseFilterSignature" local OrderedMap = require "common.utils.table.OrderedMap" ---@param slot ScriptAutoconfSlot local function getSlotObject (slot) local slotObj = OrderedMap { class = slot.getClass() } if slot.getSelect() then slotObj.select = slot.getSelect() end return slotObj end ---@param slots ScriptAutoconfSlot[] local function getSlotsObject (slots) local slotsObj = OrderedMap() for _, slot in ipairs(slots) do if not slot.getIsBuiltin() then slotsObj[slot.getName()] = getSlotObject(slot) end end return slotsObj end ---@param handler ScriptHandler ---@param hasWildcardArgs boolean local function getHandlerObject (handler, hasWildcardArgs) local handlerObj = OrderedMap() local filterArguments = handler.getFilterArguments() if #filterArguments > 0 and not hasWildcardArgs then handlerObj.args = filterArguments end handlerObj.lua = handler.getCode() return handlerObj end ---@param slot ScriptAutoconfSlot local function getHandlersObjectForSlot (slot) local handlersObj = OrderedMap() for _, handler in ipairs(slot.getHandlers()) do local filterSignature = handler.getFilterSignature() local hasWildcardArgs = getValueKey(handler.getFilterArguments(), "*") local handlerKey if hasWildcardArgs then handlerKey = filterSignature else local eventName, _ = parseFilterSignature(filterSignature) handlerKey = eventName end handlersObj[handlerKey] = getHandlerObject(handler, hasWildcardArgs) end return handlersObj end ---@param slots ScriptAutoconfSlot[] local function getHandlersObject (slots) local handlersObj = OrderedMap() for _, slot in ipairs(slots) do if #slot.getHandlers() > 0 then handlersObj[slot.getName()] = getHandlersObjectForSlot(slot) end end return handlersObj end ---@param autoconf ScriptAutoconf local function autoconfToObject (autoconf) return OrderedMap { { name = autoconf.getName() }, { slots = getSlotsObject(autoconf.getSlots()) }, { handlers = getHandlersObject(autoconf.getSlots()) } } end return autoconfToObject end end do local _ENV = _ENV package.preload[ "du.script-config.autoconfToYaml" ] = function( ... ) _ENV = _ENV; local autoconfToObject = require "du.script-config.autoconfToObject" local objectToYaml = require "du.script-config.objectToYaml" return function (autoconf) return objectToYaml(autoconfToObject(autoconf)) end end end do local _ENV = _ENV package.preload[ "du.script-config.configToJson" ] = function( ... ) _ENV = _ENV; local configToObject = require "du.script-config.configToObject" local objectToJson = require "du.script-config.objectToJson" return function (config, indent) return objectToJson(configToObject(config), indent) end end end do local _ENV = _ENV package.preload[ "du.script-config.configToObject" ] = function( ... ) _ENV = _ENV; local map = require "common.utils.array.map" local insert = table.insert ---@param slot ScriptConfigSlot local function slotToObject (slot) return { name = slot.getName(), type = { methods = {}, events = {} }, _elementType = slot.getElementType() } end ---@param argument string local function filterArgumentToObject(argument) if argument == "*" then return { variable = argument } else return { value = argument } end end ---@param handler ScriptHandler ---@param handlerKey string ---@param slotKey number local function handlerToObject(handler, handlerKey, slotKey) return { key = handlerKey, filter = { slotKey = slotKey, signature = handler.getFilterSignature(), args = map(handler.getFilterArguments(), filterArgumentToObject) }, code = handler.getCode() } end ---@param method ScriptConfigMethod local function methodToObject(method) return { signature = method.getSignature(), code = method.getCode() } end ---@param config ScriptConfig local function configToObject (config) local obj = { slots = {}, handlers = {}, methods = {}, events = {} } local nextHandlerKey = 0 for _, slot in ipairs(config.getSlots()) do obj.slots[tostring(slot.getKey())] = slotToObject(slot) for _, handler in ipairs(slot.getHandlers()) do insert(obj.handlers, handlerToObject(handler, tostring(nextHandlerKey), slot.getKey())) nextHandlerKey = nextHandlerKey + 1 end end for _, method in ipairs(config.getMethods()) do insert(obj.methods, methodToObject(method)) end return obj end return configToObject end end do local _ENV = _ENV package.preload[ "du.script-config.objectToJson" ] = function( ... ) _ENV = _ENV; local json = require "dkjson" local insert = table.insert local function addNumericKeyOrder(keyorder) for key = 0, 200 do insert(keyorder, tostring(key)) end for key = -1, -20, -1 do insert(keyorder, tostring(key)) end end local function getJsonOptions(indent) local options = { indent = indent, keyorder = { "slots", "handlers", "methods", "events", -- root "name", "type", -- slot "slotKey", "signature", "args", -- handler filter "key", "filter", "code" -- handler } } addNumericKeyOrder(options.keyorder) return options end return function (obj, indent) return json.encode(obj, getJsonOptions(indent)) end end end do local _ENV = _ENV package.preload[ "du.script-config.objectToYaml" ] = function( ... ) _ENV = _ENV; -- Supports just enough of YAML syntax to write an Autoconf file. Won't work with most other objects. local concat = table.concat local rep = string.rep local indent = ' ' local firstCharsOfQuotedStrings = [['"[]{}>|*&!%#`@,?:-]] local function getIndent (indentLevel) return rep(indent, indentLevel) end local function write (buffer, str) buffer[#buffer + 1] = str end local function writeIndent (buffer, indentLevel) write(buffer, getIndent(indentLevel)) end local function writeSpace (buffer) write(buffer, " ") end local function writeNewline (buffer) write(buffer, "\n") end local function writeInlineString (buffer, str) local firstChar = str:sub(1, 1) local shouldQuote = firstCharsOfQuotedStrings:find(firstChar, 1, true) if shouldQuote then write(buffer, "'") end write(buffer, str) if shouldQuote then write(buffer, "'") end end local function writeMultilineString (buffer, indentLevel, str) writeIndent(buffer, indentLevel) write(buffer, str:gsub("\n", "%0" .. getIndent(indentLevel))) writeNewline(buffer) end local function writeInlineArray (buffer, arr) write(buffer, "[") for index, value in ipairs(arr) do local valueType = type(value) if valueType == "string" and not value:match("\n") then writeInlineString(buffer, value) else error("Array cannot be written. Cannot write element of type " .. valueType .. ".") end if index < #value then write(buffer, ",") end end write(buffer, "]") end local function writeTable (buffer, indentLevel, tbl) for key, value in pairs(tbl) do writeIndent(buffer, indentLevel) write(buffer, key .. ":") local valueType = type(value) if valueType == "table" then if value[1] then writeSpace(buffer) writeInlineArray(buffer, value) writeNewline(buffer) else writeNewline(buffer) writeTable(buffer, indentLevel + 1, value) end elseif valueType == "string" then if value:match("\n") then write(buffer, " |") writeNewline(buffer) writeMultilineString(buffer, indentLevel + 1, value) else writeSpace(buffer) writeInlineString(buffer, value) writeNewline(buffer) end else error("Table cannot be written. Cannot write value of type " .. valueType .. ".") end end end return function (obj) local buffer = {} writeTable(buffer, 0, obj) return concat(buffer) end end end do local _ENV = _ENV package.preload[ "du.script-config.parseFilterSignature" ] = function( ... ) _ENV = _ENV; local insert = table.insert ---@param filterSignature string ---@return string, string[] local function parseFilterSignature (filterSignature) local funName, funArgs = filterSignature:match("^([^(]+)%((.*)%)") local argNames = {} for argName in funArgs:gmatch("[^%s,]+") do insert(argNames, argName) end return funName, argNames end return parseFilterSignature end end do local _ENV = _ENV package.preload[ "wrap.fixes" ] = function( ... ) _ENV = _ENV; return { gc = [[ -- Garbage collection fix added by wrap.lua do -- Set GC pause. This more or less means by how many % memory use should increase before a garbage collection is started. Lua default is 200 local newPause = 110 local oldPause = collectgarbage("setpause", newPause) if oldPause < newPause then -- DU now has a different default GC pause which is even lower. Revert back to it. collectgarbage("setpause", oldPause) end end ]], require = [[ -- require() fix added by wrap.lua package = package or {} package.preload = package.preload or {} package.loaded = package.loaded or {} package.preload["__wrap_lua__require_test"] = function () return true end if not require or not pcall(require, "__wrap_lua__require_test") then function require (modname) if package.loaded[modname] then return package.loaded[modname] end if package.preload[modname] then local mod = package.preload[modname]() if mod == nil then mod = true end package.loaded[modname] = mod return mod end error("module '" .. modname .. "' not found in package.loaded or package.preload") end end ]] } end end do local _ENV = _ENV package.preload[ "wrap.getArgsForFilter" ] = function( ... ) _ENV = _ENV; local map = require "common.utils.array.map" local parseFilterSignature = require "du.script-config.parseFilterSignature" ---@param filterSignature string local function getArgsForFilter (filterSignature) local _, argNames = parseFilterSignature(filterSignature) return map(argNames, function () return "*" end) end return getArgsForFilter end end do local _ENV = _ENV package.preload[ "wrap.getEventHandlerCode" ] = function( ... ) _ENV = _ENV; local add = require "common.utils.array.add" local getHandlerCode = require "wrap.getHandlerCode" local parseFilterSignature = require "du.script-config.parseFilterSignature" ---@param templateString string ---@param scriptObject string ---@param callOperator string ---@param slotName string ---@param filterSignature string local function getEventHandlerCode (templateString, scriptObject, callOperator, slotName, filterSignature) local eventName, argNames = parseFilterSignature(filterSignature) local eventMethod = "on" .. eventName:gsub("^%l", string.upper) local eventArgsWithElement = add(argNames, { slotName }) return getHandlerCode(templateString, scriptObject, callOperator, eventMethod, eventArgsWithElement) end return getEventHandlerCode end end do local _ENV = _ENV package.preload[ "wrap.getHandlerCode" ] = function( ... ) _ENV = _ENV; local replaceVars = require "common.utils.string.replaceVars" local concat = table.concat ---@param templateString string ---@param scriptObject string ---@param callOperator string ---@param method string ---@param args string local function getHandlerCode (templateString, scriptObject, callOperator, method, args) local argsStr = concat(args, ",") local argsStrForPcall = (callOperator == ":" and (scriptObject .. ",") or "") .. argsStr return replaceVars(templateString, { scriptObject = scriptObject, callOperator = callOperator, method = method, argsStr = argsStr, argsStrForPcall = argsStrForPcall }) end return getHandlerCode end end do local _ENV = _ENV package.preload[ "wrap.getMethodCode" ] = function( ... ) _ENV = _ENV; local getHandlerCode = require "wrap.getHandlerCode" local parseFilterSignature = require "du.script-config.parseFilterSignature" ---@param templateString string ---@param scriptObject string ---@param callOperator string ---@param methodSignature string local function getEventHandlerCode (templateString, scriptObject, callOperator, methodSignature) local methodName, argNames = parseFilterSignature(methodSignature) return getHandlerCode(templateString, scriptObject, callOperator, methodName, argNames) end return getEventHandlerCode end end do local _ENV = _ENV package.preload[ "wrap.getSlotType" ] = function( ... ) _ENV = _ENV; local slotTypes = require "wrap.slotTypes" ---@param requiredSlotTypeName string|nil case-insensitive slot type name local function getSlotType (requiredSlotTypeName) if not requiredSlotTypeName then return nil end for slotTypeName, slotType in pairs(slotTypes) do if slotTypeName:lower() == requiredSlotTypeName:lower() then return slotType end end error("unknown slot type '" .. requiredSlotTypeName .. "'") end return getSlotType end end do local _ENV = _ENV package.preload[ "wrap.makeAutoconf" ] = function( ... ) _ENV = _ENV; local assign = require "common.utils.table.assign" local getArgsForFilter = require "wrap.getArgsForFilter" local getEventHandlerCode = require "wrap.getEventHandlerCode" local getSlotType = require "wrap.getSlotType" local replaceVars = require "common.utils.string.replaceVars" local Autoconf = require "du.script-config.Autoconf" local format = string.format return function (options) local scriptName = options.scriptName local startHandlerCode = options.startHandlerCode local scriptObjectName = options.scriptObjectName local callOperator = options.callOperator local slotDefinitions = options.slotDefinitions local defaultSlotDefinition = options.defaultSlotDefinition local methodSignatures = options.methodSignatures local template = options.template if defaultSlotDefinition then error("Default slot option cannot be used with YAML output.") end if #methodSignatures > 0 then error("Methods option cannot be used with YAML output.") end local autoconf = Autoconf.new(scriptName) local fullStartHandlerCode = replaceVars(template.startEventHandler, { scriptObject = scriptObjectName, startHandlerCode = startHandlerCode }) local unitSlot = autoconf.getSlotByName("unit") unitSlot.addHandler("start()", {}, fullStartHandlerCode) for _, slotDefinition in ipairs(slotDefinitions) do local slotName = slotDefinition.name local slotTypeName = slotDefinition.type local slotSelect = slotDefinition.select local slotType = getSlotType(slotTypeName) or {} if slotDefinition.class then slotType = assign({}, slotType, { class = slotDefinition.class }) end local slotClass = slotType.class or error(format("Slot type '%s' cannot be used with YAML output.", slotTypeName)) autoconf.addSlot(slotName, slotTypeName, slotClass, slotSelect) end for _, slot in ipairs(autoconf.getSlots()) do local slotName = slot.getName() local slotType = getSlotType(slot.getTypeName()) for _, filterSignature in ipairs(slotType and slotType.filters or {}) do local filterArgs = getArgsForFilter(filterSignature) local handlerCode = getEventHandlerCode(template.eventHandler, scriptObjectName, callOperator, slotName, filterSignature) slot.addHandler(filterSignature, filterArgs, handlerCode) end end return autoconf end end end do local _ENV = _ENV package.preload[ "wrap.makeConfig" ] = function( ... ) _ENV = _ENV; local getArgsForFilter = require "wrap.getArgsForFilter" local getEventHandlerCode = require "wrap.getEventHandlerCode" local getMethodCode = require "wrap.getMethodCode" local getSlotType = require "wrap.getSlotType" local replaceVars = require "common.utils.string.replaceVars" local Config = require "du.script-config.Config" return function (options) local startHandlerCode = options.startHandlerCode local scriptObjectName = options.scriptObjectName local callOperator = options.callOperator local slotDefinitions = options.slotDefinitions local defaultSlotDefinition = options.defaultSlotDefinition local methodSignatures = options.methodSignatures local template = options.template local config = Config.default() local fullStartHandlerCode = replaceVars(template.startEventHandler, { scriptObject = scriptObjectName, startHandlerCode = startHandlerCode }) local unitSlot = config.getSlotByName("unit") unitSlot.addHandler("start()", {}, fullStartHandlerCode) for slotIndex, slotDefinition in ipairs(slotDefinitions) do if slotDefinition.class then error("Slot option key 'class' cannot be used with JSON output.") end if slotDefinition.select then error("Slot option key 'select' cannot be used with JSON output.") end local slotName = slotDefinition.name local slotTypeName = slotDefinition.type local slot = config.getSlotByKey(slotIndex - 1) slot.setName(slotName) if slotTypeName then slot.setElementType(slotTypeName) end end for _, slot in ipairs(config.getSlots()) do local slotName = slot.getName() local slotTypeName = slot.getElementType() or defaultSlotDefinition and defaultSlotDefinition.type local slotType = getSlotType(slotTypeName) local filterSignatures = slotType and slotType.filters or {} for _, filterSignature in ipairs(filterSignatures) do local filterArgs = getArgsForFilter(filterSignature) local handlerCode = getEventHandlerCode(template.eventHandler, scriptObjectName, callOperator, slotName, filterSignature) slot.addHandler(filterSignature, filterArgs, handlerCode) end end for _, methodSignature in ipairs(methodSignatures) do local methodCode = getMethodCode(template.methodHandler, scriptObjectName, callOperator, methodSignature) config.addMethod(methodSignature, methodCode) end return config end end end do local _ENV = _ENV package.preload[ "wrap.slotTypes" ] = function( ... ) _ENV = _ENV; local add = require "common.utils.array.add" local types = { -- elements antigravityGenerator = { class = "AntiGravityGeneratorUnit" }, core = { class = "CoreUnit" }, databank = { class = "DataBank" }, fuelContainer = { class = "FuelContainer" }, industry = { class = "IndustryUnit", filters = { "completed()", "statusChanged(status)" } }, gyro = { class = "GyroUnit" }, radar = { class = "RadarUnit" }, pvpRadar = { class = "RadarPVPUnit" }, screen = { class = "ScreenUnit", filters = { "mouseDown(x,y)", "mouseUp(x,y)" } }, laserDetector = { class = "LaserDetectorUnit", filters = { "laserHit()", "laserRelease()" } }, receiver = { class = "ReceiverUnit", filters = { "receive(channel,message)" } }, weapon = { class = "WeaponUnit" }, -- abstract enterable = { filters = { "enter(id)", "leave(id)" } }, pressable = { filters = { "pressed()", "released()" } }, -- built-in control = { filters = { "stop()", "tick(timerId)" } }, system = { filters = { "actionStart(action)", "actionStop(action)", "actionLoop(action)", "update()", "flush()" }, }, library = { } } types.anything = { filters = add( types.enterable.filters, types.industry.filters, types.pressable.filters, types.laserDetector.filters, types.receiver.filters, types.screen.filters ) } types.pvpRadar.filters = types.enterable.filters types.radar.filters = types.enterable.filters return types end end do local _ENV = _ENV package.preload[ "wrap.templates" ] = function( ... ) _ENV = _ENV; return { copy = function (template) return { eventHandler = template.eventHandler, methodHandler = template.methodHandler, startEventHandler = template.startEventHandler } end, default = { eventHandler = "if {scriptObject}.{method} then {scriptObject}{callOperator}{method}({argsStr}) end", methodHandler = "if {scriptObject}.{method} then return {scriptObject}{callOperator}{method}({argsStr}) end", startEventHandler = "{startHandlerCode}" }, withErrorHandling = { eventHandler = [[ if not __wrap_lua__stopped and {scriptObject}.{method} then local ok, message = xpcall({scriptObject}.{method},__wrap_lua__traceback,{argsStrForPcall}) if not ok then __wrap_lua__error(message) end end]], methodHandler = [[ if {scriptObject}.{method} then local ret = { xpcall({scriptObject}.{method},__wrap_lua__traceback,{argsStrForPcall}) } if not ret[1] then __wrap_lua__error(ret[2]) end return table.unpack(ret, 2) end]], startEventHandler = [=[ -- error handling code added by wrap.lua __wrap_lua__stopped = false __wrap_lua__stopOnError = false __wrap_lua__rethrowErrorAlways = false __wrap_lua__rethrowErrorIfStopped = true __wrap_lua__printError = true __wrap_lua__showErrorOnScreens = true function __wrap_lua__error (message) if __wrap_lua__stopped then return end -- make the traceback more readable and escape HTML syntax characters message = tostring(message):gsub('"%-%- |STDERROR%-EVENTHANDLER[^"]*"', 'chunk'):gsub("&", "&amp;"):gsub("<", "&lt;"):gsub(">", "&gt;") local unit = unit or self or {} if __wrap_lua__showErrorOnScreens then for _, value in pairs(unit) do if type(value) == "table" and value.setCenteredText and value.setHTML then -- value is a screen if message:match("\n") then value.setHTML([[ <pre style="color: white; background-color: black; font-family: Consolas,monospace; font-size: 4vh; white-space: pre-wrap; margin: 1em"> Error: ]] .. message .. [[ </pre>]]) else value.setCenteredText(message) end end end end if __wrap_lua__printError and system and system.print then system.print("Error: " .. message:gsub("\n", "<br>")) end if __wrap_lua__stopOnError then __wrap_lua__stopped = true end if __wrap_lua__stopped and unit and unit.exit then unit.exit() end if __wrap_lua__rethrowErrorAlways or (__wrap_lua__stopped and __wrap_lua__rethrowErrorIfStopped) then error(message) end end -- in case traceback is removed or renamed __wrap_lua__traceback = traceback or (debug and debug.traceback) or function (arg1, arg2) return arg2 or arg1 end local ok, message = xpcall(function () -- script code {startHandlerCode} -- error handling code added by wrap.lua end, __wrap_lua__traceback) if not ok then __wrap_lua__error(message) if not {scriptObject} then {scriptObject} = {} end end]=] }, withErrorHandlingMinified = { eventHandler = [[ if not __wrap_lua__stopped and {scriptObject}.{method} then local a,b=xpcall({scriptObject}.{method},__wrap_lua__traceback,{argsStrForPcall}) if not a then __wrap_lua__error(b) end end]], methodHandler = [[ if {scriptObject}.{method} then local a={xpcall({scriptObject}.{method},__wrap_lua__traceback,{argsStrForPcall})} if not a[1] then __wrap_lua__error(a[2]) end return table.unpack(a, 2) end]], startEventHandler = [=[ __wrap_lua__stopped=false __wrap_lua__stopOnError=false __wrap_lua__rethrowErrorAlways=false __wrap_lua__rethrowErrorIfStopped=true __wrap_lua__printError=true __wrap_lua__showErrorOnScreens=true function __wrap_lua__error(a) if __wrap_lua__stopped then return end a=tostring(a):gsub('"%-%- |STDERROR%-EVENTHANDLER[^"]*"','chunk'):gsub("&","&amp;"):gsub("<","&lt;"):gsub(">","&gt;") local b=unit or self or {} if __wrap_lua__showErrorOnScreens then for _,c in pairs(b) do if type(c)=="table" and c.setCenteredText and c.setHTML then if a:match("\n") then c.setHTML([[ <pre style="color: white; background-color: black; font-family: Consolas,monospace; font-size: 4vh; white-space: pre-wrap; margin: 1em"> Error: ]]..a..[[ </pre>]]) else c.setCenteredText(a) end end end end if __wrap_lua__printError and system and system.print then system.print("Error: "..a:gsub("\n","<br>")) end if __wrap_lua__stopOnError then __wrap_lua__stopped=true end if __wrap_lua__stopped and b and b.exit then b.exit() end if __wrap_lua__rethrowErrorAlways or (__wrap_lua__stopped and __wrap_lua__rethrowErrorIfStopped) then error(a) end end __wrap_lua__traceback=traceback or (debug and debug.traceback) or function(a,b)return b or a end local a,b=xpcall(function() {startHandlerCode} end,__wrap_lua__traceback) if not a then __wrap_lua__error(b) if not {scriptObject} then {scriptObject} = {} end end ]=] } } end end end -- Lua script packager/configurator for DU -- Copyright (C) 2020 D. L., a.k.a dlbd, a.k.a hdparm require "common.utils.compat.pairs" local argparse = require "argparse" local fixes = require "wrap.fixes" local getKeys = require "common.utils.table.getKeys" local getValueKey = require "common.utils.table.getValueKey" local makeAutoconf = require "wrap.makeAutoconf" local makeConfig = require "wrap.makeConfig" local map = require "common.utils.array.map" local autoconfToYaml = require "du.script-config.autoconfToYaml" local configToJson = require "du.script-config.configToJson" local templates = require "wrap.templates" local format = string.format local concat, sort = table.concat, table.sort local function listSlotTypes () local slotTypes = require "wrap.slotTypes" local slotTypeNames = getKeys(slotTypes) sort(slotTypeNames) print("Slot types:") for _, slotTypeName in ipairs(slotTypeNames) do local filterSignatures = slotTypes[slotTypeName].filters or {} if #filterSignatures > 0 then local quotedFilterSignatures = map(filterSignatures, function (filterSignature) return format("%q", filterSignature) end) print(format("* Slot type %q adds event handlers for %s.", slotTypeName, concat(quotedFilterSignatures, ", "))) else print(format("* Slot type %q adds no event handlers.", slotTypeName)) end end os.exit(0) end local function checkOutputType (value) if not value then return "json" end if value ~= "json" and value ~= "yaml" then error(format('Invalid output type "%s". Must be "json" or "yaml".'), value) end return value end local function parseSlotOptions (options, slot) slot = slot or {} local validKeys = { "class", "select", "type" } local function isKeyValid (key) return getValueKey(validKeys, key) end local function addToSlot (key, value) if not isKeyValid(key) then error(format('Invalid key "%s" in slot options.', key)) end slot[key] = value end repeat local prevOptions = options options = options:gsub(",([^=,]+)=([^=]*)$", function (...) addToSlot(...) return "" end) until prevOptions == options local lastKey, lastValue = options:match("^([^=]+)=(.*)$") if not lastKey then error('Slot options must look like "key1=value1,key2=value".') else addToSlot(lastKey, lastValue) end return slot end local function parseSlot (slotDef) slotDef = tostring(slotDef) local name, options = slotDef:match("^([^:]+):?(.*)$") local slot = { name = name } if #options > 0 then parseSlotOptions(options, slot) end return slot end local function getArgs () local parser = argparse(arg[0], [[ This script generates a DU-compatible script configuration from a single .lua file. To use this script, structure your code like this: script = {} function script.onActionStart (actionName) -- handle the actionStart event: screen.setCenteredText("action start: " .. actionName) end function script.onActionStop (actionName) -- handle the actionStop event: screen.setCenteredText("action stop: " .. actionName) end function script.onStop() -- handle the unit stop event: screen.setCenteredText("goodbye") end This code will be placed inside the unit start handler. All other event handlers will be generated automatically and will call methods of the script object.]]) parser:argument("file", "The Lua file that contains script code.") :convert(io.open) parser:option("--output", [[ Output format. Valid values: "json", "yaml". Defaults to "json". JSON output can be pasted in-game by right-clicking on the control unit. YAML files the with .conf extension can be placed in data/lua/autoconf/custom.]]) :argname "<format>" :convert(checkOutputType) parser:option("--name", "Script name. Only used when outputting YAML.") :convert(tostring) parser:option("--slots", [[ Control unit slot names and, optionally, element types (to generate element type specific event handlers). When output format is YAML, "class" option can be used to link elements that do not have a type defined in this script, and the "select=all" option can be used to link all elements of that type or class. Unit, system and library slots are added automatically. Slot names default to slot1, slot2, ..., slot10.]]) :args "0-10" :argname "<slot_name>[:type=<slot_type>[,class=<slot_class>][,select=all]]" :convert(parseSlot) parser:option("--methods", [[ Methods to define on the control unit. This is not very useful and is only supported when outputting JSON.]]) :args "*" :argname "<method_signature>" :target "methodSignatures" parser:option("--object", "The name of the object containing the event handlers. Defaults to \"script\".") :argname "<script_object_name>" :convert(tostring) parser:option("--call-with", "Event handler function call operator. Valid values: \".\", \":\". Defaults to \".\".") :argname "<dot_or_colon>" :target "callOperator" parser:option("--default-slot", "Default slot options.") :argname "type=<slot_type>" :target "defaultSlot" :convert(parseSlotOptions) parser:flag("--fix-gc", [[ Adjust GC to run more frequently. This can help prevent memory overload errors.]]) :target "fixGC" parser:flag("--fix-require", [[ Replace non-working require() with a function that looks in package.preload and package.loaded. This is not necessary unless require() is disabled in-game again.]]) :target "fixRequire" parser:mutex( parser:flag("--handle-errors", "Add error handling code that displays errors on screen elements.") :target "handleErrors", parser:flag("--handle-errors-min", "Add minified error handling code that displays errors on screen elements.") :target "handleErrorsMin" ) parser:flag("--indent-json", "Indent the JSON output.") :target "indent" parser:flag("--list-slot-types", "Lists slot types supported by the --slots option.") :action(listSlotTypes) return parser:parse() end local args = getArgs() local startHandlerCode = args.file:read("*all") args.file:close() local template if args.handleErrors then template = templates.withErrorHandling elseif args.handleErrorsMin then template = templates.withErrorHandlingMinified else template = templates.default end template = templates.copy(template) if args.fixGC then template.startEventHandler = fixes.gc .. template.startEventHandler end if args.fixRequire then template.startEventHandler = fixes.require .. template.startEventHandler end local options = { scriptName = args.name, startHandlerCode = startHandlerCode, scriptObjectName = args.object or "script", callOperator = args.callOperator or ".", slotDefinitions = args.slots or {}, defaultSlotDefinition = args.defaultSlot or nil, methodSignatures = args.methodSignatures or {}, template = template } if args.output == "yaml" then if args.indent then error("--indent-json flag cannot be used with YAML output.") end local autoconf = makeAutoconf(options) io.write(autoconfToYaml(autoconf)) else local config = makeConfig(options) io.write(configToJson(config, args.indent)) end -------------------------------------------------------------------------------- -- wrap.lua bundle ends --------------------------------------------------------------------------------
object_mobile_walus_assistant = object_mobile_shared_walus_assistant:new { } ObjectTemplates:addTemplate(object_mobile_walus_assistant, "object/mobile/walus_assistant.iff")
require "us4l" local MakeUString = require "us4l.internals.MakeUString" --U{ cp, cp, cp } isn't implemented yet local function CpTextToUString ( txt ) local cp_list = {} for cp_txt in txt:gmatch("%x+") do cp_list[ #cp_list + 1 ] = tonumber( cp_txt, 16 ) end return MakeUString( cp_list ) end local unpack = table.unpack or unpack local tests = { { 2, 1, "ToNFC" }, { 2, 2, "ToNFC" }, { 2, 3, "ToNFC" }, { 4, 4, "ToNFC" }, { 4, 5, "ToNFC" }, { 3, 1, "ToNFD" }, { 3, 2, "ToNFD" }, { 3, 3, "ToNFD" }, { 5, 4, "ToNFD" }, { 5, 5, "ToNFD" }, { 4, 1, "ToNFKC" }, { 4, 2, "ToNFKC" }, { 4, 3, "ToNFKC" }, { 4, 4, "ToNFKC" }, { 4, 5, "ToNFKC" }, { 5, 1, "ToNFKD" }, { 5, 2, "ToNFKD" }, { 5, 3, "ToNFKD" }, { 5, 4, "ToNFKD" }, { 5, 5, "ToNFKD" } } local success = true local line_number = 0 for line in io.lines[[../UCD/NormalizationTest.txt]] do line_number = line_number + 1 if line:match("^%x") then print( string.format( "Executing test on line %i", line_number ) ) local columns = {} for column_txt in line:gmatch("[^;]+") do columns[ #columns+1 ] = CpTextToUString( column_txt ) if #columns == 5 then break end end for _, test_parms in ipairs( tests ) do local plain_col, trans_col, methname = unpack( test_parms ) local plain_s, trans_s = columns[ plain_col ], columns[ trans_col ] if plain_s ~= trans_s[ methname ]( trans_s ) then print( string.format( "On line %i, test c%i == %s( c%i ) failed", line_number, plain_col, methname, trans_col ) ) --print( string.format( "String c%i:\n%s", plain_col, plain_s:PrettyPrint() ) ) --print( string.format( "String %s( c%i ):\n%s", methname, trans_col, trans_s[methname]( trans_s ):PrettyPrint() ) ) success = false end end end end print( success and "All tests passed" or "Some tests failed" ) return success
dye = {} -- Make dye names and descriptions available globally dye.dyes = { {"white", "White"}, {"grey", "Grey"}, {"dark_grey", "Dark grey"}, {"black", "Black"}, {"violet", "Violet"}, {"blue", "Blue"}, {"cyan", "Cyan"}, {"dark_green", "Dark green"}, {"green", "Green"}, {"yellow", "Yellow"}, {"brown", "Brown"}, {"orange", "Orange"}, {"red", "Red"}, {"magenta", "Magenta"}, {"pink", "Pink"}, } -- Define items for _, row in ipairs(dye.dyes) do local name = row[1] local description = row[2] local groups = {dye = 1} groups["color_" .. name] = 1 minetest.register_craftitem("dye:" .. name, { inventory_image = "dye_" .. name .. ".png", description = description .. " Dye", groups = groups }) minetest.register_craft({ output = "dye:" .. name .. " 4", recipe = { {"group:flower,color_" .. name} }, }) end -- Manually add coal -> black dye minetest.register_craft({ output = "dye:black 4", recipe = { {"group:coal"} }, }) -- Manually add blueberries->violet dye minetest.register_craft({ output = "dye:violet 2", recipe = { {"default:blueberries"} }, }) -- Mix recipes local dye_recipes = { -- src1, src2, dst -- RYB mixes {"red", "blue", "violet"}, -- "purple" {"yellow", "red", "orange"}, {"yellow", "blue", "green"}, -- RYB complementary mixes {"yellow", "violet", "dark_grey"}, {"blue", "orange", "dark_grey"}, -- CMY mixes - approximation {"cyan", "yellow", "green"}, {"cyan", "magenta", "blue"}, {"yellow", "magenta", "red"}, -- other mixes that result in a color we have {"red", "green", "brown"}, {"magenta", "blue", "violet"}, {"green", "blue", "cyan"}, {"pink", "violet", "magenta"}, -- mixes with black {"white", "black", "grey"}, {"grey", "black", "dark_grey"}, {"green", "black", "dark_green"}, {"orange", "black", "brown"}, -- mixes with white {"white", "red", "pink"}, {"white", "dark_grey", "grey"}, {"white", "dark_green", "green"}, } for _, mix in pairs(dye_recipes) do minetest.register_craft({ type = "shapeless", output = 'dye:' .. mix[3] .. ' 2', recipe = {'dye:' .. mix[1], 'dye:' .. mix[2]}, }) end
display = {} print(display)
---@class src.app.fonts ---@field current love.Font ---@field normal love.Font ---@field bold love.Font local fonts = proto.set_name({}, "src.app.fonts") local glyphs = " _?!@#$%&\"'`*+-=~,.:;\\/|^<>[](){}0123456789" .. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" .. "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя" function fonts:init() local names = { "normal", "bold" } for _, name in ipairs(names) do self[name] = love.graphics.newImageFont( "res/img/fonts/" .. name .. ".png", glyphs, 1 ) end self:switch("bold") return self end ---@param name string function fonts:switch(name) self.current = self[name] love.graphics.setFont(self.current) end return fonts
local M = { [1] = { id = 1, test1 = {gold = 100,id = 10,man = true,name = test}, test2 = {10,11,123}, test4 = 12, test5 = {[1] = 12,[4] = 10}, test6 = true, test7 = {a = 11,b=3}, test8 = {year=2021,month=6,day=11,hour=12,min=00,sec=00}, test9 = { [1] = { desc = '1', hurtType = 1, icon = '1', id = 1, levels = {1,2}, skillType = 1, }, [2] = { desc = '2', hurtType = 2, icon = '2', id = 2, levels = {1,2}, skillType = 2, }, }, }, } return M
local HttpService = game:GetService("HttpService") local Promise local function requestAsync(requestFields) return Promise.new(function(resolve, reject) local response = HttpService:RequestAsync(requestFields) if response.Success then resolve(response) else reject(response) end end) end local HttpUtils = {} function HttpUtils.get(url, headers, body) return requestAsync( { Url = url, Method = "GET", Headers = headers, Body = body } ) end function HttpUtils.head(url, headers, body) return requestAsync( { Url = url, Method = "HEAD", Headers = headers, Body = body } ) end function HttpUtils.post(url, headers, body) return requestAsync( { Url = url, Method = "POST", Headers = headers, Body = body } ) end function HttpUtils.put(url, headers, body) return requestAsync( { Url = url, Method = "PUT", Headers = headers, Body = body } ) end function HttpUtils.delete(url, headers, body) return requestAsync( { Url = url, Method = "DELETE", Headers = headers, Body = body } ) end function HttpUtils.connect(url, headers, body) return requestAsync( { Url = url, Method = "CONNECT", Headers = headers, Body = body } ) end function HttpUtils.options(url, headers, body) return requestAsync( { Url = url, Method = "OPTIONS", Headers = headers, Body = body } ) end function HttpUtils.trace(url, headers, body) return requestAsync( { Url = url, Method = "TRACE", Headers = headers, Body = body } ) end function HttpUtils.path(url, headers, body) return requestAsync( { Url = url, Method = "PATH", Headers = headers, Body = body } ) end function HttpUtils.formatQueryStrings(baseUrl, queryStrings) local url = baseUrl local i = 1 for k,v in pairs(queryStrings) do if i == 1 then url ..= ("?%s=%s"):format(k, v) else url ..= ("&%s=%s"):format(k, v) end i += 1 end return url end function HttpUtils:start() Promise = self:Load("Cardinal.Promise") end return HttpUtils
-- Requiring all endpoint related test modules require "endpoints.EndpointTest" require "endpoints.BulkTest" require "endpoints.CountTest" require "endpoints.CountPercolateTest" require "endpoints.DeleteTest" require "endpoints.DeleteByQueryTest" require "endpoints.DeleteTemplateTest" require "endpoints.ExplainTest" require "endpoints.FieldStatsTest" require "endpoints.GetTemplateTest" require "endpoints.GetTest" require "endpoints.IndexTest" require "endpoints.InfoTest" require "endpoints.MGetTest" require "endpoints.MPercolateTest" require "endpoints.MSearchTest" require "endpoints.MTermVectorsTest" require "endpoints.MltTest" require "endpoints.PercolateTest" require "endpoints.PingTest" require "endpoints.PutTemplateTest" require "endpoints.ReIndexTest" require "endpoints.RenderSearchTemplateTest" require "endpoints.ScrollTest" require "endpoints.SearchTest" require "endpoints.SearchExistsTest" require "endpoints.SearchShardsTest" require "endpoints.SearchTemplateTest" require "endpoints.SuggestTest" require "endpoints.TermVectorsTest" require "endpoints.UpdateTest" require "endpoints.UpdateByQueryTest" require "endpoints.CatTest.init" require "endpoints.ClusterTest.init" require "endpoints.IndicesTest.init" require "endpoints.NodesTest.init" require "endpoints.SnapshotTest.init" require "endpoints.TasksTest.init"
local bitcoin = require "bitcoin" local shortport = require "shortport" local stdnse = require "stdnse" local table = require "table" description = [[ Extracts version and node information from a Bitcoin server ]] --- -- @usage -- nmap -p 8333 --script bitcoin-info <ip> -- -- @output -- PORT STATE SERVICE -- 8333/tcp open unknown -- | bitcoin-info: -- | Timestamp: Wed Nov 9 19:47:23 2011 -- | Network: main -- | Version: 0.4.0 -- | Node Id: DD5DFCBAAD0F882D -- |_ Lastblock: 152589 -- author = "Patrik Karlsson" license = "Same as Nmap--See http://nmap.org/book/man-legal.html" categories = {"discovery", "safe"} -- -- Version 0.1 -- -- Created 11/09/2011 - v0.1 - created by Patrik Karlsson <[email protected]> -- portrule = shortport.port_or_service(8333, "bitcoin", "tcp" ) action = function(host, port) local NETWORK = { [3652501241] = "main", [3669344250] = "testnet" } local bcoin = bitcoin.Helper:new(host, port, { timeout = 10000 }) local status = bcoin:connect() if ( not(status) ) then return "\n ERROR: Failed to connect to server" end local status, ver = bcoin:exchVersion() if ( not(status) ) then return "\n ERROR: Failed to extract version information" end bcoin:close() local result = {} table.insert(result, ("Timestamp: %s"):format(stdnse.format_timestamp(ver.timestamp))) table.insert(result, ("Network: %s"):format(NETWORK[ver.magic])) table.insert(result, ("Version: %s"):format(ver.ver)) table.insert(result, ("Node Id: %s"):format(ver.nodeid)) table.insert(result, ("Lastblock: %s"):format(ver.lastblock)) return stdnse.format_output(true, result) end
local meta = FindMetaTable( "Player" ) function meta:IsTyping() return self:GetNWBool("IsTyping") end
Object = require "libs.classic" Paddle = Object.extend(Object) MaxHeight = love.graphics.getHeight() function Paddle:new(x,y) self.x = x self.y = y self.width = 20 self.height = 120 self.speed = 180 end function Paddle:render() love.graphics.setColor(255,255,255) love.graphics.rectangle('fill', self.x-(self.width/2), self.y-(self.height/2), self.width, self.height) end function Paddle:update(dt) self.y = Clamp(0+self.height/2,self.y+dt*self.speed,MaxHeight-self.height/2) end function Paddle:charge(dt) end
local path = minetest.get_modpath("backpack").."/" dofile(path.."backpack_registration.lua") dofile(path.."backpack_logic.lua")
-- Test Scroll Inventory Asset do am.gfx_engine.asset(am.asset.new("main") :add_texture("data/textures/items/scroll.png")) end
require "keybow" -- Keybow MINI volume controls -- function setup() keybow.use_mini() keybow.auto_lights(true) end -- Key mappings -- -- fullscreen function handle_minikey_00(pressed) keybow.set_key(keybow.F11, pressed) end -- toggle video function handle_minikey_01(pressed) if pressed then keybow.set_modifier(keybow.LEFT_CTRL, keybow.KEY_DOWN) keybow.tap_key("e", pressed) keybow.set_modifier(keybow.LEFT_CTRL, keybow.KEY_UP) end end -- toggle mute function handle_minikey_02(pressed) if pressed then keybow.set_modifier(keybow.LEFT_CTRL, keybow.KEY_DOWN) keybow.tap_key("d", pressed) keybow.set_modifier(keybow.LEFT_CTRL, keybow.KEY_UP) end end
fx_version 'cerulean' game 'gta5' description 'NPC-Apartments' version '1.0.0' ui_page 'index.html' files { "index.html", "scripts.js", "css/style.css", } server_scripts { "server/apart_server.lua", "server/hotel_server.lua", "@mysql-async/lib/MySQL.lua" } client_scripts { "client/apart_client.lua", "client/hotel_client.lua" } client_script 'GUI.lua'
local CorePackages = game:GetService("CorePackages") local Rodux = require(CorePackages.Rodux) local Actions = script.Parent.Parent.Actions local OpenPlayerDropDown = require(Actions.OpenPlayerDropDown) local ClosePlayerDropDown = require(Actions.ClosePlayerDropDown) local RemovePlayer = require(Actions.RemovePlayer) local SetPlayerListVisibility = require(Actions.SetPlayerListVisibility) local defaultState = { isVisible = false, selectedPlayer = nil, } local PlayerDropDown = Rodux.createReducer(defaultState, { [SetPlayerListVisibility.name] = function(state, action) if not action.isVisible then return { isVisible = false, selectedPlayer = state.selectedPlayer, } end return state end, [OpenPlayerDropDown.name] = function(state, action) return { isVisible = true, selectedPlayer = action.selectedPlayer, } end, [ClosePlayerDropDown.name] = function(state, action) return { isVisible = false, selectedPlayer = state.selectedPlayer, } end, [RemovePlayer.name] = function(state, action) if action.player == state.selectedPlayer then return { isVisible = false, selectedPlayer = nil, } end return state end, }) return PlayerDropDown
----------------------------------- -- Area: Southern San d'Oria -- NPC: Lusiane -- Standard Merchant NPC ----------------------------------- local ID = require("scripts/zones/Southern_San_dOria/IDs") require("scripts/globals/npc_util") require("scripts/globals/quests") require("scripts/globals/shop") function onTrade(player,npc,trade) if player:getQuestStatus(SANDORIA, tpz.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED and npcUtil.tradeHas(trade, 532) then player:messageSpecial(ID.text.FLYER_REFUSED) end end function onTrigger(player,npc) local stock = { 17389, 496, 1, -- Bamboo Fishing Rod 17395, 9, 2, -- Lugworm 17390, 217, 2, -- Yew Fishing Rod 17396, 3, 3, -- Little Worm 5068, 110, 3, -- Scroll of Light Threnoldy 5066, 1265, 3, -- Scroll of Lightning Threnoldy 17391, 66, 3, -- Willow Fishing Rod } player:showText(npc, ID.text.LUSIANE_SHOP_DIALOG) tpz.shop.nation(player, stock, tpz.nation.SANDORIA) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
Locales ['sv'] = { ['voice'] = '~y~Röst: ~s~%s', ['normal'] = 'prata', ['shout'] = 'skrik', ['whisper'] = 'viska', }
ITEM.name = "Gagarin" ITEM.model = "models/kek1ch/spec_sold_outfit.mdl" ITEM.newModel = "models/nasca/stalker/male_gagarin.mdl" ITEM.description= "A Gagarin Suit." ITEM.longdesc = "A prototype suit intended for use by the military, seemingly an attempt to militarize the SEVA. PSZ-12 protective vest is of high quality, but the rest of the armor had to be downsized to keep the system's weight in check. It is a mystery how it ended up in the zone." ITEM.width = 2 ITEM.height = 3 ITEM.price = 48000 ITEM.busflag = "dev" ITEM.br = 0.4 ITEM.fbr = 7 ITEM.ar = 0.5 ITEM.far = 2 ITEM.isHelmet = true ITEM.isGasmask = true ITEM.radProt = 0.60 ITEM.repairCost = ITEM.price/100*1 ITEM.ballisticlevels = {"0","lll","lll","lll-a","lll-a"} ITEM.img = ix.util.GetMaterial("vgui/hud/berill7.png") ITEM.noBusiness = true ITEM.weight = 7.600 ITEM.miscslots = 4 ITEM.bodyGroups = { ["Closed-Cycle"] = 1, ["Shoulderpads"] = 1, } ITEM.newSkin = 0 ITEM.bodygroup = {0} ITEM.bodygroupsub = {0} ITEM.skincustom[1] = { name = "Skin 0", skingroup = 0, } ITEM.skincustom[2] = { name = "Skin 1", skingroup = 1, } ITEM.skincustom[3] = { name = "Skin 2", skingroup = 2, } ITEM.skincustom[4] = { name = "Skin 3", skingroup = 3, } ITEM.skincustom[5] = { name = "Skin 4", skingroup = 4, } ITEM.skincustom[6] = { name = "Skin 5", skingroup = 5, } ITEM.skincustom[7] = { name = "Skin 6", skingroup = 6, } ITEM.skincustom[8] = { name = "Skin 7", skingroup = 7, } ITEM.skincustom[9] = { name = "Skin 8", skingroup = 8, } ITEM.skincustom[10] = { name = "Skin 9", skingroup = 9, } ITEM.skincustom[11] = { name = "Skin 10", skingroup = 10, } ITEM.skincustom[12] = { name = "Skin 11", skingroup = 11, } ITEM.skincustom[13] = { name = "Skin 12", skingroup = 12, }
-- Button -- When pressed, prompt the user with a textbox -- Type inside, press enter to finish -- Unfocusing the textbox destroys it -- Creates a new free floating billboard with the text -- Will also maintain metadata of who wrote the message, the date/time, and a little avatar. -- List of all notes -- Clicking a note jumps to it in the game -- Let author edit -- Allow deleting notes -- Have all WorldMessages stored as Parts in the workspace -- When Studio boots up, create state out of all the WorldMessages' Value instances -- When a new "WorldMessage" tagged Part is added, add a new one -- When a WorldMessage tagged part is destroyed, remove it from the state -- When a WorldMessage is removed from the state, remove it from the game as well (link via IDs) local CoreGui = game:GetService("CoreGui") local CollectionService = game:GetService("CollectionService") local Roact = require(script.Parent.Lib.Roact) local Rodux = require(script.Parent.Lib.Rodux) local StoreProvider = require(script.Parent.Lib.RoactRodux).StoreProvider local Messages = require(script.Parent.Messages) local Reducer = require(script.Parent.Reducer) local Config = require(script.Parent.Config) local App = require(script.Parent.Components.App) local WorldMessages = require(script.Parent.Components.WorldMessages) local CreateMessage = require(script.Parent.Actions.CreateMessage) local DeleteMessage = require(script.Parent.Actions.DeleteMessage) local SetMessageBody = require(script.Parent.Actions.SetMessageBody) local toolbar = plugin:CreateToolbar(Config.DISPLAY_NAME) local store = Rodux.Store.new(Reducer) local function createWidget() local info = DockWidgetPluginGuiInfo.new( Enum.InitialDockState.Left, true ) local widgetName = Config.PLUGIN_NAME.."App" local widget = plugin:CreateDockWidgetPluginGui(widgetName, info) widget.Name = widgetName widget.Title = Config.DISPLAY_NAME widget.ZIndexBehavior = Enum.ZIndexBehavior.Sibling return widget end local function onMessagePartAdded(messagePart) Messages.runIfValid(messagePart, function() store:dispatch(CreateMessage(messagePart.Id.Value, messagePart.AuthorId.Value, messagePart.Time.Value)) store:dispatch(SetMessageBody(messagePart.Id.Value, messagePart.Body.Value)) -- TODO: Listen for changes to the message's Value instances and -- reconstruct if anything is edited manually. end) end local function onMessagePartRemoved(messagePart) Messages.runIfValid(messagePart, function() store:dispatch(DeleteMessage(messagePart.Id.Value)) end) end local function setupInitialState() for _, messagePart in pairs(CollectionService:GetTagged(Config.TAG_NAME)) do onMessagePartAdded(messagePart) end CollectionService:GetInstanceAddedSignal(Config.TAG_NAME):Connect(onMessagePartAdded) CollectionService:GetInstanceRemovedSignal(Config.TAG_NAME):Connect(onMessagePartRemoved) end local function createButtons(widget) local toggleAppView = toolbar:CreateButton( Config.DISPLAY_NAME, "View and edit the list of messages", "" ) toggleAppView.Click:Connect(function() widget.Enabled = not widget.Enabled end) widget:GetPropertyChangedSignal("Enabled"):Connect(function() toggleAppView:SetActive(widget.Enabled) end) end local function createInterface(widget) local billboardsRoot = Roact.createElement(StoreProvider, { store = store }, { Roact.createElement(WorldMessages) }) Roact.mount(billboardsRoot, CoreGui, Config.PLUGIN_NAME) local appRoot = Roact.createElement(StoreProvider, { store = store, }, { Roact.createElement(App, { plugin = plugin }) }) Roact.mount(appRoot, widget, "App") end local widget = createWidget() setupInitialState() createButtons(widget) createInterface(widget) print("loaded!")
-- [email protected] -- Entry point for git HTTP site implementation -- Copyright (c) 2020 Joshua 'joshuas3' Stockin -- <https://git.joshstock.in/resty-gitweb> -- This software is licensed under the MIT License. local puremagic = require("puremagic") local utils = require("utils/utils") local git = require("git/git") local parse_uri = require("utils/parse_uri") local parsed_uri = parse_uri() local view local content -- TODO: Rewrite app script completely if parsed_uri.repo == nil then content = require("pages/index")(CONFIG) else -- repo found local repo for _,r in pairs(CONFIG) do if parsed_uri.repo == r.name then repo = r break end end if repo then repo.loc = PRODUCTION and repo.location.prod or repo.location.dev repo.obj = git.repo.open(repo.loc) view = parsed_uri.parts[2] or "tree" local branch local res, status = pcall(function() -- if branch is real branch = git.find_rev(repo.obj, parsed_uri.parts[3]) -- if parts[3] is nil, defaults to "HEAD" end) if res then local res, status = pcall(function() -- effectively catch any errors, 404 if any if view == "tree" then -- directory display (with automatic README rendering) local path = parsed_uri.parts table.remove(path, 3) -- branch table.remove(path, 2) -- "tree" table.remove(path, 1) -- repo if #path > 0 then path = table.concat(path, "/").."/" else path = "" end content = require("pages/tree")(repo, repo.loc, branch, path) elseif view == "blob" then local path = parsed_uri.parts table.remove(path, 3) -- branch table.remove(path, 2) -- "tree" table.remove(path, 1) -- repo if #path > 0 then path = table.concat(path, "/") else path = "" end content = require("pages/blob")(repo, repo.loc, branch, path) elseif view == "raw" then local path = parsed_uri.parts table.remove(path, 3) -- branch table.remove(path, 2) -- "tree" table.remove(path, 1) -- repo if #path > 0 then path = table.concat(path, "/") else path = "" end content, is_binary = require("pages/raw")(repo, repo.loc, branch, path) if content then if is_binary then mimetype = puremagic.via_content(content.body, path) content.type = mimetype else content.type = "text/plain" end end elseif view == "log" then content = require("pages/log")(repo, repo.loc, branch, ngx.var.arg_n, ngx.var.arg_skip) elseif view == "refs" then content = require("pages/refs")(repo, repo.loc, branch) elseif view == "download" then content = require("pages/download")(repo, repo.loc, branch) elseif view == "commit" then content = require("pages/commit")(repo, repo.loc, parsed_uri.parts[3]) else error("bad view "..view) end end) -- pcall if res ~= true then if not PRODUCTION then ngx.say(res) ngx.say(status) end ngx.exit(ngx.HTTP_NOT_FOUND) return end elseif not PRODUCTION then -- branch doesn't exist, show an error in non-prod environments ngx.say(res) ngx.say(status) ngx.exit(ngx.HTTP_NOT_FOUND) end git.repo.free(repo.obj) end end if content ~= nil then -- TODO: HTML templates from files, static serving if view ~= "raw" then ngx.header.content_type = "text/html" ngx.say([[<!DOCTYPE html><html lang="en"><head>]]) ngx.say([[<link rel="stylesheet" href="https://raw.githubusercontent.com/necolas/normalize.css/master/normalize.css">]]) ngx.say( [[<style> @import url('https://fonts.googleapis.com/css?family=Fira+Sans:400,400i,700,700i&display=swap'); *{ box-sizing:border-box; } body{ color: #212121; font-family:'Fira Sans', sans-serif; padding-bottom:200px; line-height:1.4; max-width:1000px; margin:20px auto; } body>h2{ margin-top:5px; margin-bottom:0; } h3{ margin-bottom:4px; } td,th{ padding:2px 5px; border:1px solid #858585; text-align:left; vertical-align:top; } th{ border:1px solid #000; } table.files,table.log,table.blob{ width:100%; max-width:100%; } table{ border-collapse:collapse; overflow:auto; font-family: monospace; font-size:14px; line-height:1.2; } table.files td:first-child{ padding-right:calc(5px + 1em); } table.files td:not(:nth-child(2)), table.log td:not(:nth-child(4)){ width:1%; white-space:nowrap; } span.q{ text-decoration:underline; text-decoration-style:dotted; } .q:hover{ cursor:help; } th, tr:hover{ /*darker color for table head, hovered-over rows*/ background-color:#dedede; } div.markdown{ width:100%; padding:20px 50px; border:1px solid #858585; border-radius:6px; } img{ max-width:100%; } pre{ background-color:#eee; padding:15px; overflow-x:auto; border-radius:8px; } :not(pre)>code{ background-color:#eee; padding:2.5px; border-radius:4px; } div.blob.table { overflow-x: auto; border:1px solid #858585; border-top: none; } div.blob.header { font-family: monospace; font-size:14px; font-weight: bold; border:1px solid #000; background-color:#dedede; } div.blob.header span{ margin:0 4px; } table.blob { font-size:1em; width:100%; max-width:100%; line-height:1; } table.blob tr:hover { background-color: inherit; } table.blob td{ border:none; padding:1px 5px; } table.blob.binary td{ text-align:center; padding: 0; } table.blob.binary td>img, table.blob.binary td>video{ max-width:100%; max-height:600px; } table.blob.lines td:first-child{ text-align: right; padding-left:20px; user-select: none; color:#858585; max-width:1%; white-space:nowrap; } table.blob.lines td:first-child:hover{ color: #454545; } table.blob.lines td:nth-child(2){ width:100%; white-space:pre; } a{ text-decoration:none; color: #0077aa; display: inline-block; } a:hover{ text-decoration:underline; } center.index-banner h1.title { margin-top:40px; margin-bottom:0; } center.index-banner p.description { margin-top:8px; margin-bottom:30px; } div.repo-section .name { margin-bottom:0; } div.repo-section h3 { margin-top:10px; } div.repo-section .description { margin-top:8px; } div.repo-section .nav { margin-top:10px; } hr { margin: 20px 0; } </style>]]) ngx.say("</head><body>") if parsed_uri.repo then local arrow_left_circle = [[<img style="width:1.2em;height:1.2em;vertical-align:middle;margin-right:0.2em" src="https://joshstock.in/static/svg/arrow-left.svg"/>]] ngx.say("<a style=\"margin-left:-1.35em\" href=\"/\">"..arrow_left_circle.."<span style=\"vertical-align:middle\">Index</span></a>") end ngx.print(content:build()) ngx.say("</body></html>") else ngx.header.content_type = content.type ngx.print(content:build()) end ngx.exit(ngx.HTTP_OK) return else ngx.exit(ngx.HTTP_NOT_FOUND) -- default behavior return end
object_tangible_item_landing_gear = object_tangible_item_shared_landing_gear:new { } ObjectTemplates:addTemplate(object_tangible_item_landing_gear, "object/tangible/item/landing_gear.iff")
local pedlist = { { 2432.78,4802.78,34.82,128.22,0xFCFA9E1E,"A_C_Cow" }, { 2440.98,4794.38,34.66,128.22,0xFCFA9E1E,"A_C_Cow" }, { 2449.0,4786.67,34.65,128.22,0xFCFA9E1E,"A_C_Cow" }, { 2457.28,4778.75,34.52,128.22,0xFCFA9E1E,"A_C_Cow" }, { 2464.67,4770.23,34.38,128.22,0xFCFA9E1E,"A_C_Cow" }, --[[{ -309.77,6272.08,31.5,42.91,0xF161D212,"s_m_m_highsec_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1980.34,3049.59,50.44,151.16,0x61C81C85,"a_f_o_genstreet_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1308.46,315.35,82.0,15.18,0xD5BA52FF,"ig_roccopelosi","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -1062.06,-1663.29,4.57,97.97,0x26EF3426,"g_m_y_mexgoon_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 845.08,-901.74,25.26,277.03,0x0F977CEB,"s_m_y_chef_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 453.67,-601.26,28.6,271.75,0xEDA0082D,"ig_jimmyboston","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 903.66,-165.75,74.09,243.27,0xBE204C9B,"ig_joeminuteman","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 354.7,274.19,103.12,257.19,0xCDEF5408,"mp_s_m_armoured_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -841.71,5401.02,34.62,294.99,0x37FACDA6,"ig_money","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 24.49,-1347.31,29.5,271.34,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 2557.25,380.8,108.63,355.54,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1164.71,-322.72,69.21,98.92,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -706.11,-913.66,19.22,92.34,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -46.71,-1757.96,29.43,50.34,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 372.54,326.38,103.57,254.31,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -3242.27,999.97,12.84,354.9,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1727.86,6415.24,35.04,241.92,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 549.1,2671.31,42.16,95.92,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1960.1,3740.04,32.35,300.65,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 2678.1,3279.4,55.25,335.7,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1698.09,4922.92,42.07,328.31,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -1820.07,794.18,138.09,131.05,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1392.81,3606.47,34.99,200.07,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -2966.44,390.93,15.05,85.99,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -3038.95,584.55,7.91,16.82,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1134.2,-982.52,46.42,278.98,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1165.87,2710.83,38.16,181.59,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -1486.25,-378.0,40.17,132.59,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -1221.92,-908.29,12.33,34.77,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 160.56,6641.64,31.72,225.9,0x8B7D3766,"u_m_y_burgerdrug_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1692.2,3760.96,34.71,225.61,0x1A021B83,"s_m_m_cntrybar_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 253.78,-50.57,69.95,65.21,0x1A021B83,"s_m_m_cntrybar_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 842.46,-1035.24,28.2,357.31,0x1A021B83,"s_m_m_cntrybar_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -331.59,6085.03,31.46,222.94,0x1A021B83,"s_m_m_cntrybar_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -662.29,-933.6,21.83,179.34,0x1A021B83,"s_m_m_cntrybar_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -1304.08,-394.6,36.7,75.11,0x1A021B83,"s_m_m_cntrybar_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -1118.94,2699.81,18.56,220.65,0x1A021B83,"s_m_m_cntrybar_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 2568.04,292.65,108.74,359.32,0x1A021B83,"s_m_m_cntrybar_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -3173.56,1088.33,20.84,246.11,0x1A021B83,"s_m_m_cntrybar_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 22.55,-1105.53,29.8,160.13,0x1A021B83,"s_m_m_cntrybar_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 810.2,-2159.05,29.62,359.45,0x1A021B83,"s_m_m_cntrybar_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1773.4,3322.14,41.45,27.71,0xF06B849D,"s_m_m_autoshop_02","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -1083.3,-245.93,37.77,206.79,0x2F8845A3,"ig_barry","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -1564.01,-975.12,13.02,234.03,0xEF154C47,"ig_old_man2","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -1592.35,-1005.57,13.03,232.04,0x719D27F4,"ig_old_man1a","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 73.98,-1392.81,29.38,267.12,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -708.34,-152.77,37.42,119.8,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -164.54,-301.92,39.74,246.23,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 427.07,-806.19,29.5,91.2,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -823.1,-1072.3,11.33,208.54,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -1194.58,-767.5,17.32,212.84,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -1449.72,-238.91,49.82,44.85,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 5.79,6511.36,31.88,40.19,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1695.35,4823.03,42.07,97.63,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 127.31,-223.42,54.56,68.28,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 612.99,2761.83,42.09,269.46,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 1196.6,2711.64,38.23,177.03,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -3169.09,1044.05,20.87,64.38,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -1102.51,2711.51,19.11,219.7,0x5B3BD90D,"ig_kerrymcintosh","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -69.88,-1230.79,28.95,230.75,0xE497BBEF,"s_m_y_dealer_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 724.85,-1075.51,22.17,264.49,0x62CC28E2,"s_m_y_armymech_01","anim@heists@heist_corona@single_team","single_team_loop_boss" },]] { 313.91,-1996.1,21.77,48.12,0xE497BBEF,"s_m_y_dealer_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { 93.55,-1948.87,20.76,307.83,0xE497BBEF,"s_m_y_dealer_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, { -185.76,-1702.52,32.79,315.71,0xE497BBEF,"s_m_y_dealer_01","anim@heists@heist_corona@single_team","single_team_loop_boss" }, } ----------------------------------------------------------------------------------------------------------------------------------------- -- THREADPEDLIST ----------------------------------------------------------------------------------------------------------------------------------------- local localPeds = {} Citizen.CreateThread(function() while true do Citizen.Wait(1000) local ped = PlayerPedId() local x,y,z = table.unpack(GetEntityCoords(ped)) for k,v in pairs(pedlist) do local distance = GetDistanceBetweenCoords(x,y,z,v[1],v[2],v[3],true) if distance <= 10 then if localPeds[k] == nil then RequestModel(GetHashKey(v[6])) while not HasModelLoaded(GetHashKey(v[6])) do RequestModel(GetHashKey(v[6])) Citizen.Wait(10) end localPeds[k] = CreatePed(4,v[5],v[1],v[2],v[3]-1,v[4],false,true) SetEntityInvincible(localPeds[k],true) FreezeEntityPosition(localPeds[k],true) SetBlockingOfNonTemporaryEvents(localPeds[k],true) if v[7] ~= nil then RequestAnimDict(v[7]) while not HasAnimDictLoaded(v[7]) do RequestAnimDict(v[7]) Citizen.Wait(10) end TaskPlayAnim(localPeds[k],v[7],v[8],8.0,0.0,-1,1,0,0,0,0) end end else if localPeds[k] then DeleteEntity(localPeds[k]) localPeds[k] = nil end end end end end)
--[[ MTA Role Play (mta-rp.pl) Autorzy poniższego kodu: - Patryk Adamowicz <[email protected]> Discord: PatrykAdam#1293 Link do githuba: https://github.com/PatrykAdam/mtarp --]] local ware = {} ware.config = { getPack = Vector3(1129.097656, -1467.645508, 14.730888), randPos = { Vector3(0, 0, 0), Vector3(0, 0, 0), Vector3(0, 0, 0), }, maxCash = 150 } ware.marker = false ware.currentPack = false function ware.onMarkerHit() if getElementData(localPlayer, "player:jobsCash") > ware.config['maxCash'] then return exports.sarp_notify:addNotify("Wyczerpałeś limit dzienny w pracach dorywczych, wróć ponownie jutro.") end if getElementData(localPlayer, "player:jobs") ~= 1 then return exports.sarp_notify:addNotify("Aby rozpocząć pracę jako Magazynier musisz udać się do urzędu pracy oraz wybrać podaną prace.") end local vehicle = getPedOccupiedVehicle( localPlayer ) if not (vehicle and getElementData(vehicle, "vehicle:ownerType") == 3 and getElementData(vehicle, "vehicle:ownerID") == 1) then return exports.sarp_notify:addNotify("Aby rozpocząć tą prace, musisz znajdować się w pojeździe pracy dorywczej.") end --wybór wielkość paczki ware.currentPack = {ID = 3, marker = createMarker( ware.config['randPos'][Math.random(#ware.config['randPos'])], "cylinder", 2.0, 0, 255, 255, 130)} -- największa end function ware.onStart() ware.marker = createMarker( ware.config['getPack'], "cylinder", 3.0, 0, 255, 255, 130 ) setElementDimension( ware.marker, 0 ) setElementInterior( ware.marker, 0 ) addEventHandler( "onClientMarkerHit", ware.marker, ware.onMarkerHit ) end addEventHandler( "onClientResourceStart", resourceRoot, ware.onStart )
local COMMAND = Command.new('charattributemultiplier') COMMAND.name = 'CharAttributeMultiplier' COMMAND.description = 'command.char_attribute_multiplier.description' COMMAND.syntax = 'command.char_attribute_multiplier.syntax' COMMAND.permission = 'moderator' COMMAND.category = 'permission.categories.character_management' COMMAND.arguments = 4 COMMAND.player_arg = 1 COMMAND.aliases = { 'attmult', 'attmultiplier', 'attributemult', 'attributemultiplier', 'charattmult' } function COMMAND:get_description() return t(self.description, table.concat(Attributes.get_id_list(), ', ')) end function COMMAND:on_run(player, targets, attr_id, value, duration) local target = targets[1] local attribute = Attributes.find_by_id(attr_id) if attribute and attribute.multipliable then Flux.Player:broadcast('char_attribute_multiplier.message', { get_player_name(player), target:name(), attribute.name, value, duration }) target:attribute_multiplier(attr_id:to_id(), tonumber(value), tonumber(duration)) target:increase_attribute(attr_id:to_id(), 1) else player:notify('error.attribute_not_valid', attr_id) end end COMMAND:register()
local corp = { web = "www.google.com", --索引为字符串,key = "web", -- value = "www.google.com" telephone = "12345678", --索引为字符串 staff = {"Jack", "Scott", "Gary"}, --索引为字符串,值也是一个表 100876, --相当于 [1] = 100876,此时索引为数字 -- key = 1, value = 100876 100191, --相当于 [2] = 100191,此时索引为数字 [10] = 360, --直接把数字索引给出 ["city"] = "Beijing" --索引为字符串 } print(corp.web) -->output:www.google.com print(corp["telephone"]) -->output:12345678 print(corp[2]) -->output:100191 print(corp["city"]) -->output:"Beijing" print(corp.staff[1]) -->output:Jack print(corp[10]) -->output:360