content
stringlengths
5
1.05M
local BasicallyIdentical = require(script.Parent._Util.BasicallyIdentical) return function() local Lighten = require(script.Parent.Lighten) it("throws if argument is not a Color3", function() expect(pcall(Lighten, true)).to.equal(false) end) it("doesn't modify white", function() local colour = Lighten(Color3.new(1, 1, 1), .1) expect(BasicallyIdentical(Color3.new(1, 1, 1), colour)).to.equal(true) end) it("doesn't overshoot if an above-range coefficient is supplied", function() local colour = Lighten(Color3.new(0, .5, 1), 1.5) expect(BasicallyIdentical(Color3.new(1, 1, 1), colour)).to.equal(true) end) it("doesn't overshoot if a below-range coefficient is supplied", function() local colour = Lighten(Color3.new(0, .5, 1), -1.5) expect(BasicallyIdentical(Color3.new(0, 0, 1), colour)).to.equal(true) end) it("lightens black to white when coefficient is 1", function() local colour = Lighten(Color3.new(), 1) expect(BasicallyIdentical(Color3.new(1, 1, 1), colour)).to.equal(true) end) it("lightens black by 10% when coefficient is 0.1", function() local colour = Lighten(Color3.new(0, 0, 0), .1) expect(BasicallyIdentical(Color3.new(.1, .1, .1), colour)).to.equal(true) end) it("lightens red by 50% when coefficient is 0.5", function() local colour = Lighten(Color3.new(1, 0, 0), .5) expect(BasicallyIdentical(Color3.new(1, .5, .5), colour)).to.equal(true) end) it("lightens grey by 50% when coefficient is 0.5", function() local colour = Lighten(Color3.new(.5, .5, .5), .5) expect(BasicallyIdentical(Color3.new(.75, .75, .75), colour)).to.equal(true) end) it("doesn't modify colours when coefficient is 0", function() local colour = Lighten(Color3.new(.5, .5, .5), 0) expect(BasicallyIdentical(Color3.new(.5, .5, .5), colour)).to.equal(true) end) end
mole = new_type(16) mole.hit_w = 8 mole.hit_h = 8 mole.state = 1 mole.facing = 2 mole.accel_y = 0.3 mole.decel_y = 0.8 mole.accel_x = 0.3 mole.decel_x = 0.8 mole.recovery = 0 mole.is_player = false mole.dash_force = 5 mole.dash_cd = 15 mole.last_dash = 0 function mole.init(self) self.get_input = cpu_input self.speed_y = -10 self.state = 3 self.recovery = 30 end -- States -- 1 : digging -- 2 : stuned -- 3 : starting -- 4 : waiting function mole.update(self) if self.state == 3 then return end self.attack = gtime > self.last_dash + self.dash_cd/2 -- timers if self.recovery > 0 then self.recovery -= 1 if self.recovery == 0 and self.state == 2 then self.state = 1 end end -- get inputs local input_x = 0 local input_y = 0 if self.state == 1 then input_x, input_y = self:get_input() end if input_x == 0 then self.speed_x *= 0.9 if abs(self.speed_x) < 1 then self.speed_x = 0 end elseif abs(input_x) > 1 and gtime > (self.last_dash + self.dash_cd) then -- dash self.speed_x = self.dash_force * sgn(input_x) self:psfx(2, 0, 8, 1) self.last_dash = gtime else self.speed_x += input_x * self.accel_x end -- gravity if self.y < ground_limit - self.hit_h then input_y = 1 end if input_y == 0 then self.speed_y *= 0.9 if abs(self.speed_y) < 1 then self.speed_y = 0 end else if sgn(self.speed_y) != sgn(input_y) then self.speed_y += self.decel_y * sgn(input_y) else self.speed_y += self.accel_y * sgn(input_y) end self.facing = self.speed_y > 0 and 3 or 2 end -- move self:move_x(self.speed_x, self.collide_x) self:move_y(self.speed_y, self.collide_y) -- collisions if self.state == 1 then for o in all(objects) do if o.base == worm and self:overlaps(o) then o.destroyed = true self.speed_y += sgn(self.speed_y) spawn_particles(4 + rnd(3), 3, o.x, o.y, 8) self:psfx(2, 0, 0, 1) end end end -- prevent cliping if self:check_solid(sgn(self.speed_x), 0) then self.speed_x = 0 end if self:check_solid(0, sgn(self.speed_y)) then self.speed_y = 0 end -- trail if (abs(self.speed_y) > 1 or abs(self.speed_x) > 1) and self.y > ground_limit then spawn_trail(self.x + self.hit_w/2, self.y + self.hit_h/2) if self == current_player and stat(16) == -1 then sfx(1, 0, 0, 32) end else if self == current_player then sfx(-1, 0) end end if self.state == 4 then return end -- check finish_line if patterns and self.y > 128 * (#patterns - 1) + finish_line then self.state = 4 self.flip_y = false if self == current_player then end_race() end end end function ply_input(self) local input_x = 0 local input_y = 0 if btn(0) then input_x -= 1 end if btn(1) then input_x += 1 end if btn(2) then input_y -= 1 end if btn(3) then input_y += 1 end -- dash if btnp(5) then input_x = 2 elseif btnp(4) then input_x = - 2 end return input_x, input_y end function cpu_input(self) local input_x = 0 local input_y = 0 input_y = 1 -- dash if self.speed_y < 1 then input_x = rnd({-2,2}) else -- dash to attack for o in all(objects) do if o.base == mole and o != self then if abs(o.y - self.y) <= 8 then input_x = 2 * sgn(o.x - self.x) return input_x, input_y end end end end -- return input_x, input_y end function menu_input(self) local input_x = 0 if self.x > 108 then input_x = -1 elseif self.x < 20 then input_x = 1 elseif abs(self.speed_x) < 3 then input_x = sgn(self.speed_x) end -- if (self.y < ground_limit + 20) then input_y = 1 elseif self.y > 180 then input_y = -1 elseif abs(self.speed_y) < 3 then input_y = sgn(self.speed_y) end return input_x, input_y end function mole.draw(self) if self.state == 1 then if abs(self.speed_y) >= abs(self.speed_x) then self.spr = 17 self.flip_y = self.speed_y >= 0 else self.spr = 18 self.flip_x = self.speed_x < 0 end else self.spr = 16 self.slip_y = false end spr(self.spr, self.x, self.y, 1, 1, self.flip_x, self.flip_y) pset(self.x + 2, self.y - 1 + (self.flip_y and 0 or 9), 3) pset(self.x + 5, self.y - 1 + (self.flip_y and 0 or 9), 3) -- circle if proximity if self.is_player then local proximity = false for o in all(objects) do if o.base == mole and o != self then if abs(o.y - self.y) <= 32 then circ(self.x + self.hit_w/2, self.y + self.hit_h/2, 8, 7) break end end end end end function mole.collide_x(self) if abs(self.speed_x) > 2 then if self.is_player then shake = 1 end self.speed_x = - self.speed_x/2 self.speed_y = self.speed_y * 0.8 self:psfx(2, 0, 2, 1) spawn_particles(4 + rnd(3), 2, self.x, self.y, 1) else self.speed_x = 0 end end function mole.collide_y(self) if abs(self.speed_y) > 4 then if self.is_player then freeze_time = 5 shake = 5 end self.speed_y = - self.speed_y/2 self:psfx(2, 0, 2, 1) spawn_particles(4 + rnd(3), 2, self.x, self.y, 1) else self.speed_y = 0 end end function mole.hit(self, recovery) self.recovery = recovery self.state = 2 end function mole.get_attacked(self) self.speed_y *= self.decel_y end function mole.psfx(self, n, channel, offset, length) -- play if visible on screen if self.y > gcamera.y and self.y < gcamera.y + 128 then sfx(n, channel, offset, length) end end
-------------------------------- -- @module ObjectPool -- @parent_module cc -------------------------------- -- -- @function [parent=#ObjectPool] reset -- @param self -- @return ObjectPool#ObjectPool self (return value: cc.ObjectPool) -------------------------------- -- -- @function [parent=#ObjectPool] resetByName -- @param self -- @param #char poolName -- @return ObjectPool#ObjectPool self (return value: cc.ObjectPool) -------------------------------- -- -- @function [parent=#ObjectPool] pushObject -- @param self -- @param #char poolName -- @param #cc.Ref object -- @return ObjectPool#ObjectPool self (return value: cc.ObjectPool) -------------------------------- -- -- @function [parent=#ObjectPool] popObject -- @param self -- @param #char poolName -- @return Ref#Ref ret (return value: cc.Ref) -------------------------------- -- -- @function [parent=#ObjectPool] destroyObject -- @param self -- @return ObjectPool#ObjectPool self (return value: cc.ObjectPool) -------------------------------- -- -- @function [parent=#ObjectPool] getInstance -- @param self -- @return ObjectPool#ObjectPool ret (return value: cc.ObjectPool) -------------------------------- -- -- @function [parent=#ObjectPool] ObjectPool -- @param self -- @return ObjectPool#ObjectPool self (return value: cc.ObjectPool) return nil
-------------------------------------------------------------------------------- local _ = require 'cherry.libs.underscore' local analytics = require 'cherry.libs.analytics' local animation = require 'cherry.libs.animation' local Text = require 'cherry.libs.text' local gesture = require 'cherry.libs.gesture' local Screen = require 'cherry.components.screen' local Scroller = require 'cherry.components.scroller' local Panel = require 'cherry.components.panel' local Multiplier = require 'cherry.components.multiplier' local Button = require 'cherry.components.button' local Profile = require 'cherry.components.profile' local Banner = require 'cherry.components.banner' -------------------------------------------------------------------------------- local Chapters = {} -------------------------------------------------------------------------------- function Chapters:draw(options) self.options = options self:reset() self:setup(options) self:prepareBoard(options) self:fillContent(options) self:displayBanner(options) self:onShow() return self end function Chapters:onShow() animation.pop(self.banner) end function Chapters:reset() if (self.scroller) then display.remove(self.banner) self.scroller:destroy() end end -------------------------------------------------------------------------------- function Chapters:buy(num) local id = 'uralys.phantoms.chapter' .. num local store -- Product listener function local function productListener(event) _G.log('Valid products:', #event.products) _G.log(_G.inspect(event.products)) _G.log('Invalid products:', #event.invalidProducts) _G.log(_G.inspect(event.invalidProducts)) end local function storeTransaction(event) _G.log('--> callback storeTransaction') native.setActivityIndicator(false) local transaction = event.transaction _G.log('transaction.state: ', transaction.state) if (transaction.state == 'purchased') then App.user:bought(num) elseif (transaction.state == 'cancelled') then _G.log(_G.inspect(transaction)) elseif (transaction.state == 'failed') then _G.log(_G.inspect(transaction)) end store.finishTransaction(transaction) self:draw(self.options) end if (_G.SIMULATOR or App.env.name == 'development') then App.user:bought(num) self:draw(self.options) return elseif (_G.IOS) then native.setActivityIndicator(true) store = require('store') store.init(storeTransaction) store.purchase(id) elseif (_G.ANDROID) then native.setActivityIndicator(true) store = require('plugin.google.iap.v3') timer.performWithDelay( 1000, function() _G.log('init store...') store.init('google', storeTransaction) timer.performWithDelay( 1000, function() _G.log('trying to loadProducts') if (store.canLoadProducts) then _G.log('trying to loadProducts') local productIdentifiers = { id, 'uralys.phantoms.chapter_3' } store.loadProducts(productIdentifiers, productListener) end _G.log('PURCHASING...[' .. id .. ']') store.purchase(id) end ) end ) end end -------------------------------------------------------------------------------- function Chapters:setup(options) self.parent = options.parent self.x = display.contentWidth * 0.5 self.y = display.contentHeight * 0.5 self.width = display.contentWidth * 0.8 self.height = display.contentHeight * 0.9 self.top = self.y - display.contentHeight * 0.42 end function Chapters:prepareBoard(options) self.scroller = Scroller:new( { parent = self.parent, top = self.top + 7, left = self.x - self.width * 0.45, width = self.width * 0.9, height = self.height - 22, gap = display.contentHeight * 0.05, handleHeight = display.contentHeight * 0.07, horizontalScrollDisabled = true, hideBackground = true } ) self.scroller.onBottomReached = function() analytics.event('game', 'chapter-scroll-end') end end function Chapters:displayBanner(options) self.banner = Banner:large( { parent = self.parent, text = 'Chapters', fontSize = 57, width = display.contentWidth * 0.25, height = display.contentHeight * 0.13, x = self.x, y = self.top } ) end -------------------------------------------------------------------------------- function Chapters:fillContent(options) for i = 1, #options.chapters do local chapter = self:summary(App.user:chapterData(i)) self.scroller:insert(chapter) end end function Chapters:hellBarEntrance(options) local hellbar = display.newGroup() local panel = Panel:chapter( { parent = hellbar, width = self.width * 0.83, height = display.contentHeight * 0.35, status = 'off' } ) display.newImage( hellbar, 'cherry/assets/images/gui/houses/hell.png', panel.width * 0.2, 0 ) local contentX = -panel.width * 0.2 Text.embossed( { parent = hellbar, value = 'Reach 10k likes on FB to open this secret door...', x = contentX, -- y = - App:adaptToRatio(15), -- with progress bar y = 0, width = panel.width * 0.4, height = panel.height * 0.45, font = _G.FONTS.default, fontSize = App:adaptToRatio(10) } ) Button:icon( { parent = hellbar, type = 'facebook', x = contentX, y = panel.height * 0.35, action = function() Screen:openFacebook() end } ) self:lockChapter( { parent = hellbar, x = -panel.width * 0.47, y = -panel.height * 0.47 } ) return hellbar end -------------------------------------------------------------------------------- function Chapters:isDisabled(options) return options.status == 'off' or options.paying and not options.payed end -------------------------------------------------------------------------------- function Chapters:drawCustomImage(options, panel, parent) local house = display.newImage(parent, options.customImage, -panel.width * 0.31, 0) if (self:isDisabled(options)) then house.fill.effect = 'filter.desaturate' house.fill.effect.intensity = 0.8 end end -------------------------------------------------------------------------------- function Chapters:drawClosedChapter(options, panel, parent) local y1 = -panel.height * 0.15 local y2 = panel.height * 0.13 Profile:status( { parent = parent, x = panel.width * 0.15, y = y1, width = panel.width * 0.4, height = panel.height * 0.15, iconImage = 'assets/images/gui/items/mini-phantom.icon.png', step = options.percentLevels, disabled = true } ) Profile:status( { parent = parent, x = panel.width * 0.15, y = y2, width = panel.width * 0.4, height = panel.height * 0.15, iconImage = 'cherry/assets/images/gui/items/gem.icon.png', step = options.percentGems, disabled = true } ) local enabled = options.status == 'on' if (enabled and options.paying) then local button = self:buyButton( { parent = parent, x = panel.width * 0.42, y = 0, payed = options.payed } ) gesture.onTap( button, function() self:buy(options.chapter) end ) end end -------------------------------------------------------------------------------- function Chapters:drawOpenChapter(options, panel, parent) Multiplier:draw( { item = 'gem', parent = parent, x = panel.width * 0.04, y = -panel.height * 0.21, scale = 0.75, value = App.user:chapterGems(App.user.profile, options.chapter) } ) Multiplier:draw( { item = 'star', parent = parent, x = panel.width * 0.04, y = panel.height * 0.2, scale = 0.75, value = App.score:chapterStars(options.chapter) } ) local play = Button:icon( { parent = parent, type = 'play', x = panel.width * 0.35, y = 0, scale = 1.2, action = function() analytics.event('game', 'chapter-selection', options.chapter) App.user:setChapter(options.chapter) Router:open('level-selection') end } ) animation.pop(play) end -------------------------------------------------------------------------------- function Chapters:summary(options) local summary = display.newGroup() local status = 'on' if (self:isDisabled(options)) then status = 'off' end local panel = Panel:chapter( { parent = summary, width = self.width * 0.83, height = display.contentHeight * 0.4, status = status } ) if (options.customImage) then self:drawCustomImage(options, panel, summary) end if (options.condition) then local contentX = panel.x + panel.width * 0.22 local textY if (options.type == 'hidden') then textY = panel.y - panel.height * 0.2 local buttonsY = panel.height * 0.2 Button:icon( { parent = summary, type = 'facebook', x = contentX, y = buttonsY, action = function() Screen:openFacebook() end } ) Button:icon( { parent = summary, type = 'rate', x = contentX + panel.width * 0.15, y = buttonsY, action = function() native.showPopup( 'appStore', { iOSAppId = App.IOS_ID, supportedAndroidStores = {'google'} } ) end } ) else textY = panel.y end Text:embossed( { parent = summary, value = options.condition.text, x = contentX, y = textY, width = panel.width * 0.5, height = panel.height * 0.38, font = _G.FONTS.default, fontSize = App:adaptToRatio(12) } ) else if (options.status == 'on' and options.payed) then self:drawOpenChapter(options, panel, summary) else self:drawClosedChapter(options, panel, summary) end end if (options.status == 'off') then self:lockChapter( { parent = summary, x = panel.width * 0.45, y = -panel.height * 0.33 } ) end return summary end -------------------------------------------------------------------------------- function Chapters:lockChapter(options) self:lock( _.defaults( { parent = options.parent, x = options.x, y = options.y }, options ) ) end function Chapters:buyButton(options) local button = display.newImage(options.parent, 'cherry/assets/images/gui/buttons/buy.png') button.x = options.x button.y = options.y return button end -------------------------------------------------------------------------------- function Chapters:lock(options) if (options.status == 'on') then return end local lock = display.newImage(options.parent, 'cherry/assets/images/gui/items/lock.png') lock.x = options.x lock.y = options.y return lock end -------------------------------------------------------------------------------- return Chapters
contimove = target.get_continent() if contimove == nil then self.say("It looks like the flight is not in operation yet..") return end if self.ask_yes_no("We're just about to take off. Are you sure you want to get off the ship? You may do so, but then you'll have to wait until the next available flight. Do you still wish to get off board?") then target.field = contimove.start_ship_move_field else self.say("You'll get to your destination in a short while. Talk to other passengers and share your stories to them, and you'll be there before you know it.") end
mobs:register_mob("mobs:red_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_red_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:red_tear", chance = 1, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:blue_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_blue_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:blue_tear", chance = 1, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:cyan_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_cyan_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:cyan_tear", chance = 1, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:green2_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_green_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:green_tear", chance = 1, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:yellow_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_yellow_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:yellow_tear", chance = 1, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:purple_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_purple_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:purple_tear", chance = 1, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:stone_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_stone_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:dirt_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_dirt_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:sand_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_sand_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:silver_sand_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_silver_sand_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:desert_sand_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_desert_sand_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:desert_stone_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_desert_stone_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:snow_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_snow_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:ice_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_ice_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:green_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_grass_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:dry_dirt_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_dry_dirt_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:clay_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_clay_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:gravel_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_gravel_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:coniferous_litter_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_coniferous_litter_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:moss_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_moss_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:permafrost_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_permafrost_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:dry_grass_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_dry_grass_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_mob("mobs:rainforest_litter_monster", { type = "monster", passive = false, attack_type = "dogfight", attack_npcs = false, damage = 1, hp_min = 4, hp_max = 8, armor = 100, visual_size = {x=3, y=2.6}, collisionbox = {-0.4, -0.01, -0.4, 0.4, 1.9, 0.4}, visual = "mesh", mesh = "mobs_stone_monster.x", textures = { {"mobs_rainforest_litter_monster.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_dirtmonster", }, view_range = 15, walk_velocity = 1, run_velocity = 3, jump = true, drops = { {name = "tutorial:geschenkpapier", chance = 1, min = 2, max = 4}, {name = "tutorial:geschenkpapier_death", chance = 2, min = 2, max = 4}, {name = "tutorial:dna_string", chance = 2, min = 1, max = 1}, }, water_damage = 1, lava_damage = 5, light_damage = 0, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 14, walk_start = 15, walk_end = 38, run_start = 40, run_end = 63, punch_start = 40, punch_end = 63, }, }) mobs:register_spawn("mobs:dry_dirt_monster", {"default:dry_dirt"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:clay_monster", {"default:clay"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:gravel_monster", {"default:gravel"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:coniferous_litter_monster", {"default:dirt_with_coniferous_litter"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:moss_monster", {"default:permafrost_with_moss"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:permafrost_monster", {"default:permafrost","default:permafrost_with_stones"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:dirt_monster", {"default:dirt"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:rainforest_litter_monster", {"default:dirt_with_rainforest_litter"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:green_monster", {"default:dirt_with_grass"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:dry_grass_monster", {"default:dirt_with_dry_grass","default:dry_dirt_with_dry_grass"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:sand_monster", {"default:sand"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:silver_sand_monster", {"default:silver_sand"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:stone_monster", {"default:stone", "default:cobble", "default:mossycobble"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:desert_stone_monster", {"default:desert_stone", "default:desert_cobble"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:desert_sand_monster", {"default:desert_sand"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:snow_monster", {"default:snowblock", "default:dirt_with_snow"}, 20, -1, 1, 2, 31000) mobs:register_spawn("mobs:ice_monster", {"default:ice"}, 20, -1, 1, 2, 31000)
local vehicleSpawns = { --[[MH6J Civilian]] {487,-1813.1640625, 1303.326171875, 59.734375}, {487,-1614.921875, -643.3837890625, 14.1484375}, {487,-1887.853515625, -1570.0458984375, 21.75}, {487,1883.9501953125, -1862.265625, 13.577025413513}, {487,2618.8828125, 2721.025390625, 36.538642883301}, {487,-1730.0419921875, 2562.21484375, 104.1789932251}, {487,-2485.6455078125, -2637.0703125, 70.008026123047}, {487,615.744140625,850.1572265625,-43.009014129639}, {487,1949.9912109375,-2631.44140625,13.546875}, {487,-756.53979492188,-2137.5471191406,26.463499069214}, --[[AH6X Little Bird]] {497,-1050.5859375,1968.033203125,120.66523742676}, {497,-1495.888671875,-2691.40234375,57.325229644775}, {497,-2688.42578125,1471.634765625,7.1875}, {497,-1534.28125,2842.9482421875,97.463409423828}, {497,2221.8583984375,-1344.396484375,23.984273910522}, {497,-516.7138671875, -81.8935546875, 62.30525970459}, {497,272.5986328125, 1853.140625, 17.640625}, --[[HMMWV]] {470,-1473.5791015625,320.2294921875,7.1875}, {470,-1373.998046875,460.62109375,7.1875}, {470,419.150390625,2186.087890625,39.499450683594}, {470,2821.1796875,793.4658203125,10.8984375}, {470,685.0791015625, -132.1826171875, 21.492156982422}, {470,1643.888671875, -1456.380859375, 13.546875}, {470,-617.5927734375, -1599.939453125, 21.924146652222}, {470,-1429.0126953125, -950.1376953125, 201.09375}, {470,-2100.18359375, -781.294921875, 32.164207458496}, --[[PICKUP TRUCK]] {422,-2479.6240234375,2223.6669921875,4.84375}, {422,-92.9951171875,2823.0908203125,76.721649169922}, {422,-2448.99609375,-1335.8662109375,310.97662353516}, {422,-173.2470703125,-2635.5341796875,26.608192443848}, {422,2108.447265625,-1600.916015625,13.552597045898}, {422,2452.7392578125,1607.9833984375,10.8203125}, {422,-1800.8984375,-1950.9736328125,93.561332702637}, --[[MOTORCYCLE]] {468,-812.470703125,-2629.912109375,90.105056762695}, {468,-1729.8525390625,-1940.3154296875,99.840209960938}, {468,-2130.90234375,178.4375,35.257678985596}, {468,-2656.7333984375,1352.4873046875,7.0596733093262}, {468,-1598.302734375,2694.947265625,55.07092666626}, {468,-809.96484375,2430.037109375,156.97012329102}, {468,2920.38671875,2486.0087890625,10.8203125}, {468,505.732421875,-291.8681640625,20.00952911377}, {468,-428.8828125,-694.8310546875,19.14847946167}, {468,1190.41015625,-2109.0341796875,64.738548278809}, {468,1658.9716796875,-1069.0224609375,23.906229019165}, --[[URAL MILITARY]] {433,119.15625, 1840.892578125, 17.640625}, {433,325.5927734375, 2543.6064453125, 16.807554244995}, {433,-2565.9873046875, 644.0595703125, 14.453125}, {433,-1018.298828125, -658.0791015625, 32.0078125}, {433,440.185546875,1464.173828125,6.3338670730591}, --[[PBX]] {473,2463.3984375,-2719.638671875,-0.55000001192093}, {473,-1577.4873046875,182.353515625,-0.53995263576508}, {473,-806.80859375,2233.7001953125,40.049976348877}, {473,-127.4453125,-779.6923828125,-0.55000001192093}, {473,-192.5087890625, 478.0693359375, -0.55000001192093}, {473,-458.5732421875, 1231.5341796875, -0.55000001192093}, {473,-1891.7529296875, 1490.8125, -0.55000001192093}, {473,245.4423828125, -1924.4248046875, -0.55000001192093}, {473,2963.654296875, -153.8125, -0.55000001192093}, --[[BIKE]] {509,194.685546875,-120.2333984375,1.5497757196426}, {509,173.0146484375,-95.0634765625,1.5516006946564}, {509,2369.9599609375,29.712890625,28.0416431427}, {509,710.87109375,-566.7548828125,16.3359375}, {509,1109.6025390625,-1667.6689453125,13.615442276001}, {509,2014.6689453125,-1113.4013671875,26.203125}, {509,2447.41015625,-1967.1845703125,13.546875}, {509,2633.7236328125,1835.291015625,11.0234375}, {509,1489.3974609375,2681.54296875,10.8203125}, {509,-2428.5654296875,2280.875,4.984375}, {509,-2501.0869140625,2224.880859375,4.9861993789673}, {509,-2142.8515625,-2457.84765625,30.625}, {509,-2456.078125,-141.115234375,26.112222671509}, {509,-1881.4453125,954.3837890625,35.171875}, --[[ATV]] {471,1251.2880859375, -806.5029296875, 83.740625}, {471,1285.921875, 190.3544921875, 19.703574752808}, {471,-27.7275390625, 27.3154296875, 2.709395980835}, {471,-14.1552734375, 951.25390625, 19.193042373657}, {471,-901.8291015625, 2680.517578125, 41.970262145996}, {471,2529.6484375, -887.5859375, 87.428672790527}, {471,2090.0673828125, -694.6650390625, 100.41593933105}, {471,1287.2080078125, -405.599609375, 8.8966178894043}, {471,549.796875, -842.3330078125, 90.552108764648}, {471,-467.8076171875, -1630.7587890625, 6.931001663208}, --[[MOTORBIKE]] {463,-2487.6240234375, 2512.037109375, 18.0625}, {463,-1358.2392578125, 2068.7177734375, 52.438430786133}, {463,421.8759765625, 2549.150390625, 16.253837585449}, {463,1090.0986328125, 2082.1943359375, 10.8203125}, {463,1880.091796875, 1165.9208984375, 10.828125}, {463,1464.3740234375, -674.95703125, 94.75}, {463,1005.921875, -1447.4326171875, 13.554634094238}, {463,-82.74609375, -1571.041015625, 2.6107201576233}, {463,-576.6484375, -549.03125, 25.5234375}, {463,-1671.525390625, 67.57421875, -11.234375}, --[[SUV]] {490,2272.9072265625, 2451.6171875, 10.8203125}, {490,2575.0712890625, 1029.5390625, 10.8203125}, {490,1643.158203125, -1026.771484375, 23.8984375}, {490,226.7568359375, -1398.5419921875, 51.590118408203}, {490,-2221.2353515625, -122.2490234375, 35.3203125}, {490,-2417.6650390625, 521.4404296875, 29.9296875}, {490,-1932.3046875, 1000.7451171875, 35.171875}, {490,-1038.0703125, 1576.779296875, 34.759017944336}, --[[TRACTOR]] {531,-1427.314453125, -1517.626953125, 101.74019622803}, {531,-1065.162109375, -1144.94140625, 129.21875}, {531,-1911.4365234375, -1673.3486328125, 23.015625}, {531,-1655.119140625, -2209.275390625, 33.405990600586}, {531,-275.4951171875, -2188.591796875, 28.740524291992}, {531,-928.376953125, -530.419921875, 25.953638076782}, {531,-681.79296875, 966.8662109375, 12.1328125}, {531,2362.4755859375, -100.951171875, 27.095621109009}, --[[UAZ]] {579,1664.5556640625, 720.615234375, 10.8203125}, {579,1663.923828125, 1338.0439453125, 10.772266387939}, {579,2081.0009765625, 2172.5234375, 10.8203125}, {579,-754.6884765625, 1585.376953125, 26.9609375}, {579,-1980.2978515625, 885.689453125, 45.203125}, {579,-2272.4521484375, 128.4140625, 35.1640625}, {579,-2777.3798828125, 241.13671875, 7.1875}, {579,-2424.501953125, 944.6875, 45.459823608398}, {579,484.3955078125, -1513.7802734375, 20.310167312622}, {579,1130.3759765625, -1446.3671875, 15.796875}, {579,1732.650390625, -1854.7353515625, 13.4140625}, {579,2244.1845703125, -1415.7373046875, 23.828125}, {579,-1107.2734375, -1620.8388671875, 76.3671875}, {579,-2518.62109375, -607.849609375, 132.5625}, {579,-1894.4921875, 445.4423828125, 35.171875}, {579,-2131.4384765625, 655.6318359375, 52.3671875}, --[[Golf]] {421,2352.7333984375, -1006.8017578125, 58.937740325928}, {421,2828.337890625, -1681.142578125, 9.9374475479126}, {421,1995.0615234375, -1232.2060546875, 20.565172195435}, {421,1557.4375, 23.005859375, 24.155364990234}, {421,911.4521484375, -7.48828125, 91.309814453125}, {421,884.7080078125, -1217.51953125, 16.9765625}, {421,1479.3212890625, -1709.044921875, 14.046875}, {421,1762.7890625, -2082.4609375, 13.553119659424}, {421,2216.1298828125, -2592.41796875, 13.546875}, {421,2781.5390625, -2351.7294921875, 13.6328125}, {421,2100.5517578125, 1332.6865234375, 10.8203125}, {421,1525.701171875, 1923.3046875, 10.8203125}, {421,-1856.5224609375, 1396.09765625, 7.1875}, {421,-1929.123046875, 2581.4716796875, 42.818351745605}, --[[Modern Van]] {456,-1934.0986328125, 578.3310546875, 35.171875}, {456,-1127.482421875, -201.7724609375, 14.1484375}, {456,-556.6611328125, -1036.681640625, 24.086181640625}, {456,613.3623046875, -1140.53125, 46.63431930542}, {456,1748.2763671875, -229.689453125, 78.687210083008}, {456,1291.673828125, 1106.6171875, 10.73881816864}, {456,1294.02734375, 2545.361328125, 10.671875}, {456,1883.4736328125, 2738.154296875, 10.8359375}, {456,2222.673828125, 1806.875, 10.8203125}, {456,2401.810546875, 1368.306640625, 10.671875}, {456,-1523.0732421875, 2296.9404296875, 47.186622619629}, {456,1059.271484375, 1049.7099609375, 10.2734375}, }; local hospitalPacks = { {-2669.810546875, 639.0927734375, 14.053125}, {-2658.0966796875, 637.7431640625, 14.053125}, {-2638.5283203125, 638.876953125, 14.053125}, {-2652.181640625, 552.74609375, 14.209375}, {-2688.345703125, 553.6337890625, 14.334915733337}, {-2654.9345703125, 633.3369140625, 14.053125}, {-2694.3076171875, 638.392578125, 14.053125}, {-2637.572265625, 696.9736328125, 27.5375}, {-2665.19140625, 695.7919921875, 27.520307159424}, {-1514.822265625, 2519.7587890625, 55.63133392334}, {-1521.0478515625, 2519.8359375, 55.502473449707}, {-1503.677734375, 2520.8486328125, 55.47378692627}, {-1522.96484375, 2507.9150390625, 55.540353393555}, {2024.0693359375, -1402.97265625, 16.798585510254}, {2033.2880859375, -1402.8564453125, 16.886380767822}, {2042.83984375, -1413.1630859375, 16.770774459839}, {2042.009765625, -1427.4677734375, 16.7640625}, {2029.3125, -1428.6123046875, 16.665500259399}, {-314.509765625, 1050.140625, 19.940259552002}, {-319.06640625, 1049.0634765625, 19.940259552002}, {-325.728515625, 1050.0634765625, 19.940259552002}, {-332.1376953125, 1049.966796875, 19.339168167114}, {-337.1044921875, 1049.5712890625, 19.339168167114}, {1171.5078125, -1309.6982421875, 13.588679885864}, {1170.759765625, -1306.486328125, 13.596522903442}, {1172.70703125, -1320.908203125, 14.9976354599}, {1172.6943359375, -1327.48046875, 15.001947975159}, {1174.58984375, -1340.8212890625, 13.593054389954}, {1173.41796875, -1361.3828125, 13.569604492187}, {1163.5615234375, -1327.96875, 31.089849090576}, {1158.798828125, -1328.5703125, 31.105243301392}, {1244.37890625, 325.9541015625, 19.3555103302}, {1239.740234375, 327.845703125, 19.3555103302}, {1252.509765625, 325.734375, 19.3578125}, {1225.9638671875, 311.451171875, 19.3578125}, {1231.6591796875, 306.80078125, 19.3578125}, {1237.9169921875, 314.03515625, 24.3578125}, {1234.138671875, 307.6435546875, 24.3578125}, {-2203.2255859375, -2309.611328125, 30.975}, {-2199.4697265625, -2305.3466796875, 30.225}, {-2195.57421875, -2301.7001953125, 30.225}, {1615.4423828125, 1816.5458984375, 10.4203125}, {1608.232421875, 1816.5693359375, 10.4203125}, {1599.2822265625, 1816.72265625, 10.4203125}, {1607.111328125, 1832.9912109375, 10.4203125}, {1583.0029296875, 1769.0986328125, 10.4203125}, {1603.6259765625, 1789.48046875, 30.06875}, {1616.2880859375, 1788.2822265625, 30.06875}, {1622.4111328125, 1766.7880859375, 30.06875}, {1612.2861328125, 1760.6416015625, 36.9125}, }; local patrolPoints = { {-1603.2197265625,-2712.736328125,48.9453125}, {2465.748046875,-2215.55859375,13.546875}, {2473.439453125,-2215.56640625,13.546875}, {2480.0732421875,-2216.140625,13.546875}, {2487.24609375,-2215.5966796875,13.546875}, {2494.1005859375,-2215.5859375,13.546875}, {-1686.6728515625,408.9970703125,7.3984375}, {-1682.34375,412.9384765625,7.3984375}, {-1680.0263671875,402.3642578125,7.3984375}, {-1675.84375,406.4677734375,7.3984375}, {-1670.5615234375,411.8359375,7.3984375}, {-1666.2392578125,416.2509765625,7.3984375}, {-1672.7939453125,422.81640625,7.3984375}, {-1677.20703125,418.46484375,7.3984375}, {-2410.7021484375,969.9091796875,45.4609375}, {-2410.744140625,975.220703125,45.4609375}, {-2410.837890625,980.5302734375,45.4609375}, {-1329.3046875,2668.5126953125,50.46875}, {-1328.7314453125,2673.90625,50.0625}, {-1327.0185546875,2679.3876953125,50.46875}, {-1327.3798828125,2684.62890625,50.0625}, {1940.7099609375,-1778.5244140625,13.390598297119}, {1940.6552734375,-1774.908203125,13.390598297119}, {1940.630859375,-1771.728515625,13.390598297119}, {1940.7080078125,-1767.3837890625,13.390598297119}, {-1477.921875,1868.138671875,32.639846801758}, {-1466.1552734375,1869.0048828125,32.6328125}, {-1464.5224609375,1861.3828125,32.639846801758}, {-1477.4599609375,1860.5205078125,32.6328125}, {-735.9208984375,2744.0087890625,47.2265625}, {-739.0439453125,2744.2421875,47.165451049805}, {377.6953125,2601.1083984375,16.484375}, {624.5263671875,1676.25390625,6.9921875}, {620.2958984375,1681.2431640625,6.9921875}, {616.248046875,1686.4169921875,7.1875}, {612.783203125,1691.1650390625,7.1875}, {609.2060546875,1696.201171875,7.1875}, {605.8505859375,1700.978515625,7.1875}, {602.27734375,1706.3603515625,7.1875}, {2141.037109375,2742.734375,10.960174560547}, {2142.3115234375,2752.6982421875,10.96019744873}, {2147.9521484375,2752.3203125,10.8203125}, {2152.60546875,2751.953125,10.8203125}, {2152.984375,2743.85546875,10.8203125}, {2147.75,2743.7392578125,10.8203125}, {-97.6298828125,-1175.0283203125,2.4990689754486}, {-90.74609375,-1177.853515625,2.2021217346191}, {-84.75390625,-1163.853515625,2.3359375}, {-91.5771484375,-1160.5732421875,2.4453125}, {-1606.525390625,-2717.2138671875,48.9453125}, {-1609.7109375,-2721.544921875,48.9453125}, {-1599.83203125,-2708.302734375,48.9453125}, {-2246.314453125,-2558.8212890625,32.0703125}, {-2241.3125,-2561.3662109375,32.0703125}, {-1132.2880859375,-135.0986328125,14.14396572113}, {-1153.529296875,-156.373046875,14.1484375}, {-1142.826171875,-145.67578125,14.14396572113}, {655.611328125,-557.9912109375,16.501491546631}, {655.6572265625,-572.1728515625,16.501491546631}, {1601.791015625,2203.90625,11.060997009277}, {1596.806640625,2203.4345703125,10.8203125}, {1590.197265625,2203.4853515625,10.8203125}, {1589.4775390625,2195.43359375,10.8203125}, {1596.125,2194.294921875,10.8203125}, {1601.6591796875,2194.3369140625,10.8203125}, {2206.8466796875,2470.47265625,10.8203125}, {2206.94140625,2474.75,10.8203125}, {2206.9267578125,2478.86328125,10.8203125}, {2198.06640625,2480.6953125,10.8203125}, {2197.541015625,2475.791015625,10.995170593262}, {2197.609375,2471.9169921875,10.995170593262}, {2120.8251953125,915.4833984375,10.8203125}, {2115.1181640625,915.44140625,10.8203125}, {2109.076171875,915.4228515625,10.8203125}, {2109.22265625,924.8779296875,10.9609375}, {2114.9404296875,924.8857421875,10.9609375}, {2119.5126953125,925.2861328125,10.9609375}, {2645.7197265625,1112.7802734375,10.8203125}, {2639.984375,1112.56640625,10.8203125}, {2634.828125,1112.3466796875,10.9609375}, {2634.1826171875,1101.9482421875,10.8203125}, {2636.7509765625,1101.6748046875,10.8203125}, {2643.5126953125,1101.81640625,10.8203125}, {2209.576171875,2469.8251953125,10.8203125}, {2208.8310546875,2475.09375,10.8203125}, {1005.078125,-901.7490234375,42.216625213623}, {993.025390625,-902.474609375,42.222496032715}, }; local heliCrashSites = { {-1360.0478515625,-1070.7314453125,160.4069519043}, {-421.4619140625,-1284.4345703125,33.740924835205}, {-2357.654296875,-1634.3623046875,483.703125}, {979.0849609375,160.59375,28.935249328613}, {-2057.2294921875,2781.73828125,163.12780761719}, {826.90234375,2803.6259765625,74.863929748535}, {2577.7060546875,-650.541015625,136.37449645996}, }; local lootItems = { ["helicrashsides"] = { {"toolbelt7",368,1,90,10}, {"toolbelt5",328,0.4,90,2}, {"weapon21",1879,1,90,10}, {"weapon23",1878,1,90,7}, {"weapon25",1877,1,90,7}, {"weapon7",349,1,90,6}, {"weapon20",1882,1,90,5.5}, {"weapon24",335,1,90,4}, {"weapon22",339,1,90,3}, {"fooditem9",1582,1,0,2}, {"fooditem7",2647,1,0,2}, {"item10",1650,1,0,2}, {"item5",324,1,90,2}, {"item11",324,1,90,2}, {"item12",324,1,90,2}, {"fooditem6",2856,1,0,1}, {"medicine6",2709,0.5,0,4}, {"fooditem8",2673,0.5,0,2}, {"item6",2675,0.5,0,3}, {"backpack6",1719,1,0,0.5}, {"weapon16",342,1,0,4}, {"vest2",2106,1,0,1}, {"weapon15",351,1,90,4}, {"helmet1",1738,1,0,1}, {"helmet2",1745,1,0,1.5}, {"helmet3",1747,1,0,0.5}, {"weapon18",1881,1,90,6}, {"toolbelt3",2710,1,0,4}, {"backpack7",1250,1,0,0.3}, {"medicine4",1576,1,0,3}, {"item2",933,0.25,0,1}, {"backpack3",3026,1,0,4}, {"toolbelt7",368,1,90,1.5}, {"vehiclepart3",1073,1,0,2}, {"medicine8",1579,1,0,4}, {"clothing2",1577,1,0,4.5}, {"clothing3",1577,1,0,2.5}, {"toolbelt2",2976,0.15,0,3}, {"toolbelt1",1277,0.8,90,7}, {"toolbelt4",2969,0.5,0,1}, {"vehiclepart1",929,0.3,0,2}, {"item3",1279,1,0,4.5}, {"clothing1",1577,1,0,0.5}, {"clothing7",1577,1,0,0.5}, {"clothing8",1577,1,0,0.5}, {"clothing9",1577,1,0,0.5}, {"toolbelt6",369,1,90,3}, {"backpack4",3026,0.5,0,5}, {"backpack1",3026,1.3,0,2}, {"backpack5",3026,1.3,0,2}, }, ["hospital"] = { {"medicine1",1908,0.7,0}, {"medicine2",2891,0.7,0}, {"medicine3",1909,0.7,0}, {"medicine4",1576,1,0}, {"medicine5",1578,0.5,0}, {"medicine7",1580,1,0}, {"medicine8",1579,1,0}, {"medicine7",1580,1,0}, {"medicine2",2891,0.7,0}, {"medicine7",1580,1,0}, {"medicine6",1580,1,0}, }, }; local backupItemsTable = { {"medicine5"}, {"medicine6"}, {"item1"}, {"fooditem1"}, {"fooditem3"}, {"fooditem4"}, {"fooditem5"}, {"toolbelt5"}, {"weapon20"}, {"weapon24"}, {"weapon22"}, {"fooditem9"}, {"medicine8"}, {"fooditem7"}, {"item10"}, {"item9"}, {"item5"}, {"item11"}, {"item12"}, {"item13"}, {"item14"}, {"fooditem6"}, {"mag3"}, {"weapon16"}, {"weapon21"}, {"mag1"}, {"backpack1"}, {"backpack2"}, {"backpack3"}, {"backpack4"}, {"backpack5"}, {"backpack6"}, {"backpack7"}, {"helmet1"}, {"helmet2"}, {"helmet3"}, {"helmet4"}, {"helmet5"}, {"helmet6"}, {"helmet7"}, {"vest1"}, {"vest2"}, {"weapon23"}, {"weapon25"}, {"weapon19"}, {"mag2"}, {"weapon18"}, {"toolbelt3"}, {"medicine1"}, {"medicine2"}, {"medicine3"}, {"medicine4"}, {"medicine7"}, {"toolbelt2"}, {"toolbelt1"}, {"toolbelt4"}, {"toolbelt9"}, {"item2"}, {"vehiclepart3"}, {"vehiclepart1"}, {"toolbelt6"}, {"toolbelt7"}, {"item3"}, {"item4"}, {"fooditem11"}, {"fooditem10"}, {"clothing2"}, {"clothing1"}, {"clothing3"}, {"clothing4"}, {"clothing5"}, {"clothing6"}, {"clothing7"}, {"clothing8"}, {"clothing9"}, {"weapon28"}, {"fooditem2"}, {"fooditem8"}, {"item6"}, {"item7"}, {"item8"}, {"toolbelt8"}, {"weapon26"}, {"weapon27"}, {"vehiclepart4"}, {"vehiclepart5"}, {"vehiclepart2"}, {"weapon17"}, {"toolbelt8"}, {"weapon11"}, {"weapon12"}, {"weapon13"}, {"weapon10"}, {"weapon6"}, {"weapon14"}, {"weapon7"}, {"weapon15"}, {"weapon9"}, {"weapon8"}, {"weapon2"}, {"weapon3"}, {"weapon5"}, {"weapon1"}, {"weapon4"}, {"mag4"}, {"mag7"}, {"mag5"}, {"mag6"}, {"mag8"}, {"mag9"}, {"mag10"} }; local vehicleAddonsInfo = { {422, 4, 1, 1, 1, 0, 25}, {470, 4, 1, 1, 1, 0, 46}, {471, 4, 1, 1, 1, 0, 8}, {468, 2, 1, 1, 1, 0, 10}, {433, 6, 1, 1, 1, 0, 70}, {509, 0, 0, 0, 0, 0, 0}, {487, 0, 1, 1, 1, 1, 20}, {497, 0, 1, 1, 1, 1, 20}, {473, 0, 1, 1, 1, 0, 35}, {579, 4, 1, 1, 1, 0, 35}, {463, 2, 1, 1, 1, 0, 10}, {490, 4, 1, 1, 1, 0, 50}, {531, 4, 1, 1, 1, 0, 0}, {421, 4, 1, 1, 1, 0, 12}, {456, 4, 1, 1, 1, 0, 86}, {528, 4, 1, 1, 1, 0, 50}, }; local vehicleFuelInfo = { {422, 0.25}, {470, 0.1}, {471, 0.1}, {468, 0.1}, {433, 0.5}, {509, 0}, {487, 0.25}, {497, 0.25}, {473, 0.1}, {579, 0.15}, {463, 0.1}, {490, 0.15}, {531, 0.1}, {421, 0.25}, {456, 0.35}, {528, 0.50}, }; local vehicleFuelTable = { {422, 80}, {470, 100}, {471, 30}, {468, 30}, {433, 140}, {509, 0}, {487, 60}, {497, 60}, {473, 60}, {579, 45}, {463, 35}, {490, 75}, {531, 45}, {421, 50}, {456, 120}, {528, 80}, }; local hospitalCol = {}; local dayzVehicles = {}; local repairTimer = {}; local last_veh_id = 0; local last_tent_id = 0; local backupdone = false; addEvent("respawnVehiclesInWater", true); addEvent("repairVehicle", true); addEvent("cancelVehicleRepair", true); addEvent("respawnDayZVehicle", true); if fileExists("scripts/tools/backup.db") then backupdone = true; else backupdone = false; end local db = dbConnect("sqlite", "scripts/tools/backup.db"); dbExec(db, "CREATE TABLE IF NOT EXISTS `vehicles` (model, x, y, z, rX, rY, rZ, slots, fuel, engines, moving, parts, scrap, rotor, items, health, dayz, sx, sy, sz, id)"); dbExec(db, "CREATE TABLE IF NOT EXISTS `tents` (model, x, y, z, rX, rY, rZ, slots, scale, items, id)"); dbExec(db, "CREATE TABLE IF NOT EXISTS `safes` (model, x, y, z, rX, rY, rZ, slots, scale, code, safe_id, items, id)"); function getVehicleAddonInfos(id) for _,v in ipairs(vehicleAddonsInfo) do if (v[1] == id) then return v[2], v[3], v[4], v[5], v[6], v[7]; end end end function createHeliCrashSite() if isElement(cargoCol) then destroyElement(getElementData(cargoCol, "parent")); destroyElement(cargoCol); end local nr = math.random(7); local x,y,z = heliCrashSites[nr][1], heliCrashSites[nr][2], heliCrashSites[nr][3]; local cargobob = createVehicle(548, x, y, z); setElementHealth(cargobob, 0); setElementFrozen(cargobob, true); local cargoCol = createColSphere(x, y, z, 3); setElementData(cargoCol, "parent", cargobob); setElementData(cargoCol, "helicrash", true); setElementData(cargoCol, "MAX_Slots", 0); for _,v in ipairs(lootItems["helicrashsides"]) do local value = math.percentChance(v[5]*3.5, math.random(2)); setElementData(cargoCol, v[1], value); local ammoData,_ = getWeaponAmmoType(v[1], true); if (ammoData and value > 0) then setElementData(cargoCol, ammoData, getMagazineSize(ammoData)*math.random(2)); end end setTimer(createHeliCrashSite, 3600000, 1); end function updateHospitals() for i,_ in pairs(hospitalCol) do for _,v in ipairs(lootItems["hospital"]) do setElementData(hospitalCol[i], v[1], math.random(5)); end end setTimer(updateHospitals, 3600000, 1); end function createHospitalPacks() local number1 = 0; for i,v in ipairs(hospitalPacks) do number1 = number1+1; local x,y,z = v[1], v[2], v[3]; local object = createObject(1558, x, y, z-0.15, nil, nil, nil); hospitalCol[i] = createColSphere(x, y, z-0.15, 2); setObjectScale(object,1) setElementData(hospitalCol[i], "parent", object); setElementData(hospitalCol[i], "hospitalbox", true); setElementData(hospitalCol[i], "MAX_Slots", 28); end updateHospitals(); end function spawnDayZVehicles() for _,v in ipairs(getElementsByType("vehicle")) do local col = getElementData(v, "parent"); if col then destroyElement(col); end destroyElement(v); end for _,v in ipairs(vehicleSpawns) do local x,y,z = v[2], v[3], v[4]; local veh = createVehicle(v[1], x, y, z); local vehCol = createColSphere(x, y, z, 2.5); attachElements(vehCol, veh); setElementData(vehCol, "parent", veh); setElementData(veh, "parent", vehCol); setElementData(vehCol, "vehicle", true); setElementData(veh, "dayzvehicle", 1); local tires,engine,parts,scrap,rotor,slots = getVehicleAddonInfos(v[1]); setElementData(vehCol, "MAX_Slots", tonumber(slots)); setElementData(vehCol, "Tire_inVehicle", math.random(0, tires)); setElementData(vehCol, "Engine_inVehicle", math.random(0, engine)); setElementData(vehCol, "Parts_inVehicle", math.random(0, parts)); setElementData(vehCol, "Scrap_inVehicle", math.random(0, scrap)); setElementData(vehCol, "Rotor_inVehicle", math.random(0, rotor)); setElementData(vehCol, "needtires", tires); setElementData(vehCol, "needparts", parts); setElementData(vehCol, "needscrap", scrap); setElementData(vehCol, "needrotor", rotor); setElementData(vehCol, "needengines", engine); setElementData(vehCol, "spawn", {v[1], x, y, z}); setElementData(vehCol, "fuel", math.random(5, 20)); for _,v in ipairs(lootItems["helicrashsides"]) do local value = math.percentChance(v[5], math.random(2)); setElementData(vehCol, v[1], value); local ammoData,_ = getWeaponAmmoType(v[1], true); if (ammoData and value > 0) then setElementData(vehCol, ammoData, getMagazineSize(ammoData)*math.random(2)); end end end backup(); end addEventHandler("onVehicleExplode", root, function() for _,v in pairs(getVehicleOccupants(source)) do triggerEvent("kilLDayZPlayer", v); end local x1,y1,z1 = getElementPosition(source); local col = getElementData(source, "parent"); local id,x,y,z = unpack(getElementData(col, "spawn")); setElementData(col, "deadVehicle", true); setElementData(source, "isExploded", true); if (getElementData(source, "dayzvehicle") == 1) then setTimer(respawnDayZVehicle, 60000*30, 1, id, x, y, z, source, col); else setTimer(function(col, source) if isElement(col) then destroyElement(col); end if isElement(source) then destroyElement(source); end end, (60000*5), 1, col, source); end end); setTimer(function() for _,v in ipairs(getElementsByType("vehicle")) do if (getElementModel(v) ~= 453) then local col = getElementData(v, "parent"); if col then if not (getElementData(col, "deadVehicle")) then if isElementInWater(v) then local id,x,y,z = unpack(getElementData(col, "spawn")); if (getElementData(v, "dayzvehicle") == 1) then setTimer(respawnDayZVehicle, (5*60000), 1, id, x, y, z, v, col); else setTimer(function(col, v) if col then destroyElement(col); end if v then destroyElement(v); end end, (5*60000), 1, col, v); end end end end end end end, (30*60000), 0); function respawnDayZVehicle(id, x, y, z, veh, col) if veh then destroyElement(veh); end if col then destroyElement(col); end local veh = createVehicle(id, x, y, (tonumber(z)+1)); local vehCol = createColSphere(x, y, z, 4); attachElements(vehCol, veh); if (id == 528) then setVehicleDamageProof(veh,true); end setElementData(vehCol, "parent", veh); setElementData(veh, "parent", vehCol); setElementData(vehCol, "vehicle", true); setElementData(veh, "dayzvehicle", 1); local tires,engine,parts,scrap,rotor,slots = getVehicleAddonInfos(id); setElementData(vehCol, "MAX_Slots", tonumber(slots)); setElementData(vehCol, "Tire_inVehicle", math.random(0, tires)); setElementData(vehCol, "Engine_inVehicle", math.random(0, engine)); setElementData(vehCol, "Parts_inVehicle", math.random(0, parts)); setElementData(vehCol, "Scrap_inVehicle", math.random(0, scrap)); setElementData(vehCol, "Rotor_inVehicle", math.random(0, rotor)); setElementData(vehCol, "needtires", tires); setElementData(vehCol, "needparts", parts); setElementData(vehCol, "needscrap", scrap); setElementData(vehCol, "needrotor", rotor); setElementData(vehCol, "needengines", engine); setElementData(vehCol, "spawn", {id, x, y, z}); setElementData(vehCol, "fuel", 10); for _,v in ipairs(lootItems["helicrashsides"]) do local value = math.percentChance(v[5], math.random(2)); setElementData(vehCol, v[1], value); local ammoData,_ = getWeaponAmmoType(v[1], true); if (ammoData and value > 0) then setElementData(vehCol, ammoData, getMagazineSize(ammoData)*math.random(2)); end end end addEventHandler("respawnDayZVehicle", root, respawnDayZVehicle); function getVehicleMaxFuel(id) for _,v in ipairs(vehicleFuelTable) do if (id == v[1]) then return v[2]; end end return false; end addEventHandler("onPlayerVehicleEnter", root, function(veh, seat) local id = getElementModel(veh); setVehicleEngineState(veh, true); if (id == 548) then cancelEvent(); end if (id == 509) then return; end local col = getElementData(veh, "parent"); local tires,engine,parts,scrap,rotor,_ = getVehicleAddonInfos(id); setElementData(veh, "maxfuel", getVehicleMaxFuel(id)); setElementData(veh, "needtires", tires); setElementData(veh, "needparts", parts); setElementData(veh, "needscrap", scrap); setElementData(veh, "needrotor", rotor); setElementData(veh, "needengines", engine); setVehicleEngineState(veh, false); if (getElementData(col, "Parts_inVehicle") == parts) then setElementData(veh, "fplus", 5); else setElementData(veh, "fplus", 20); end if (getElementData(col, "Tire_inVehicle") == tires) then if (getElementData(col, "Scrap_inVehicle") == scrap) then if (getElementData(col, "Engine_inVehicle") == engine) then if (getElementData(col, "Rotor_inVehicle") == rotor) then if (getElementData(col, "fuel") > 0) then setVehicleEngineState(veh, true); if (seat == 0) then bindKey(source, "k", "down", setEngineStateByPlayer); triggerClientEvent(source, "displayClientInfo", source, "clientinfotext30", 255, 255, 255); end else triggerClientEvent(source, "displayClientInfo", source, "clientinfotext31", 40, 160, 40); setVehicleEngineState(veh, false); end else triggerClientEvent(source, "displayClientInfo", source, "clientinfotext32", 40, 160, 40); setVehicleEngineState(veh, false); end else triggerClientEvent(source, "displayClientInfo", source, "clientinfotext33", 40, 160, 40); setVehicleEngineState(veh, false); end else triggerClientEvent(source, "displayClientInfo", source, "clientinfotext34", 40, 160, 40); setVehicleEngineState(veh, false); end else triggerClientEvent(source, "displayClientInfo", source, "clientinfotext35", 40, 160, 40); setVehicleEngineState(veh, false); end end); addEventHandler("onPlayerVehicleExit", root, function(veh, seat) if (seat == 0) then setVehicleEngineState(veh, false); unbindKey(source, "k", "down", setEngineStateByPlayer); end end); function getVehicleFuelRemove(id) for _,v in ipairs(vehicleFuelInfo) do if (v[1] == id) then return v[2]; end end end setTimer(function() for _,v in pairs(getElementsByType("vehicle")) do if (getElementModel(v) ~= 509) then if (getVehicleEngineState(v) == true) then if (getElementData(getElementData(v, "parent"), "fuel") >= 1) then setElementData(getElementData(v, "parent"), "fuel", getElementData(getElementData(v, "parent"), "fuel")-(getVehicleFuelRemove(getElementModel(v))*getElementData(v, "fplus"))/60); else setVehicleEngineState(v, false); end end end end end, 1000, 0); addEventHandler("repairVehicle", root, function(veh) if repairTimer[veh] then triggerClientEvent(source, "displayClientInfo", source, getVehicleName(veh).." "..getLanguageTextServer("clientinfotext38",source), 160, 40, 40) return; end repairTimer[veh] = setTimer(fixDayZVehicle, (1000-(math.floor(getElementHealth(veh))))*120, 1, veh, source); setElementFrozen(veh, true); setElementFrozen(source, true); setPedWeaponSlot(source, 0); setElementData(veh, "repairer", source); setElementData(source, "repairingvehicle", veh); setElementData(source, "isInAction", true); setPedAnimation(source, "SCRATCHING", "sclng_r", -1, true, false, false, false); triggerClientEvent(source,"playSoundForClient",source,"repairstart"); triggerClientEvent(source, "displayClientInfo", source, getLanguageTextServer("clientinfotext39",source).." "..vehicle_name[getElementModel(veh)], 40, 160, 40); end); addEventHandler("cancelVehicleRepair", root, function() local player = source; local veh = getElementData(player,"repairingvehicle"); if (veh) then setPedAnimation(player, false); setElementFrozen(veh, false); setElementFrozen(player, false); setElementData(player, "isInAction", false); killTimer(repairTimer[veh]); repairTimer[veh] = nil; setElementData(veh, "repairer", nil); setElementData(player, "repairingvehicle", nil); triggerClientEvent(player,"playSoundForClient",player,"repairstop"); triggerClientEvent(player, "displayClientInfo", player, getLanguageTextServer("clientinfotext42",player), 160, 40, 40); end end) function fixDayZVehicle(veh, player) if (veh and player) then setElementHealth(veh, 1000); fixVehicle(veh); setPedAnimation(player, false); setElementFrozen(veh, false); setElementFrozen(player, false); setElementData(player, "isInAction", false); repairTimer[veh] = nil; setElementData(veh, "repairer", nil); setElementData(player, "repairingvehicle", nil); triggerClientEvent(player,"playSoundForClient",player,"repairstop"); triggerClientEvent(player, "displayClientInfo", player, getLanguageTextServer("clientinfotext40",player).." "..vehicle_name[getElementModel(veh)], 40, 160, 40); end end addEventHandler("onPlayerQuit", root, function() for _,v in ipairs(getElementsByType("vehicle")) do if (getElementData(v, "repairer") and getElementData(v, "repairer") == source) then outputDebugString("Vehicle repairer disconnected - destroyed tables", 3); killTimer(repairTimer[v]); setElementFrozen(v, false); repairTimer[v] = nil; setElementData(v, "repairer", nil); end end end); function setEngineStateByPlayer(player) local veh = getPedOccupiedVehicle(player); if (getElementData(getElementData(veh,"parent"), "fuel") <= 0) then return; end if (getVehicleEngineState(veh) == false) then setVehicleEngineState(veh, true); triggerClientEvent(player, "displayClientInfo", player, "clientinfotext36", 40, 160, 40); else setVehicleEngineState(veh, false); triggerClientEvent(player, "displayClientInfo", player, "clientinfotext37", 160, 40, 40); end end function backup() dbExec(db, "DELETE FROM `vehicles`"); dbExec(db, "DELETE FROM `tents`"); dbExec(db, "DELETE FROM `safes`"); local vc,tc,sc = 0, 0, 0; for _,veh in ipairs(getElementsByType("vehicle")) do if not getElementData(veh, "helicrash") then local col = getElementData(veh, "parent"); if col then if not (getElementData(col,"deadVehicle")) then local x,y,z = getElementPosition(veh); local rX,rY,rZ = getElementRotation(veh); local health = getElementHealth(veh); if (health < 500) then health = 500; end local _,sx,sy,sz = unpack(getElementData(col, "spawn")); --outputChatBox(sx..", "..sy..", "..sz) -- debug info local items = {}; vc = vc+1; for _,item in ipairs(backupItemsTable) do local quantity = getElementData(col, item[1]) or 0; if (quantity > 0) then table.insert(items, {item[1], quantity}); end end dbExec(db, "INSERT INTO `vehicles` (model, x, y, z, rX, rY, rZ, slots, fuel, engines, moving, parts, scrap, rotor, items, dayz, health, sx, sy, sz, id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", getElementModel(veh), x, y, z, rX, rY, rZ, getElementData(col, "MAX_Slots") or 20, getElementData(col, "fuel") or 0, getElementData(col, "Engine_inVehicle") or 0, getElementData(col, "Tire_inVehicle") or 0, getElementData(col, "Parts_inVehicle") or 0, getElementData(col, "Scrap_inVehicle") or 0, getElementData(col, "Rotor_inVehicle") or 0, toJSON(items), getElementData(veh, "dayzvehicle") or 0, health, sx, sy, sz, vc); end end end end for _,col in ipairs(getElementsByType("colshape")) do if getElementData(col, "tent") then local tent = getElementData(col, "parent"); if tent then local x,y,z = getElementPosition(tent); local rX,rY,rZ = getElementRotation(tent); local items = {}; tc = tc+1; for _,item in ipairs(backupItemsTable) do local quantity = getElementData(col, item[1]) or 0; if (quantity > 0) then table.insert(items, {item[1], quantity}); end end dbExec(db, "INSERT INTO `tents` (model, x, y, z, rX, rY, rZ, slots, scale, items, id) VALUES(?,?,?,?,?,?,?,?,?,?,?)", getElementModel(tent), x, y, z, rX, rY, rZ, getElementData(col, "MAX_Slots") or 100, getObjectScale(tent), toJSON(items), tc); end elseif getElementData(col, "safe") then if (getElementData(col,getElementData(col,"id")) ~= "raided") then local safe = getElementData(col, "parent"); if safe then local x,y,z = getElementPosition(safe); local rX,rY,rZ = getElementRotation(safe); local items = {}; sc = sc+1; for _,item in ipairs(backupItemsTable) do local quantity = getElementData(col, item[1]) or 0; if (quantity > 0) then table.insert(items, {item[1], quantity}); end end dbExec(db, "INSERT INTO `safes` (model, x, y, z, rX, rY, rZ, slots, scale, code, safe_id, items, id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)", getElementModel(safe), x, y, z, rX, rY, rZ, getElementData(col, "MAX_Slots") or 50, getObjectScale(safe), getElementData(col, getElementData(col, "id")), getElementData(col, "id"), toJSON(items), sc); end end end end outputDebugString("Backup done ("..tc.." Tents), ("..sc.." Safes) and ("..vc.." Vehicles)", 3); end function createDayzVeh(model, x, y, z, rX, rY, rZ, slots, fuel, engines, moving, parts, scrap, rotor, items, dayz, health, sx, sy, sz) local veh = createVehicle(model, x, y, z); local vehCol = createColSphere((x+5), y, z, 4); setElementRotation(veh, rX, rY, rZ); attachElements(vehCol, veh); if (model == 528) then setVehicleDamageProof(veh,true); end setElementHealth(veh, tonumber(health)); setElementData(vehCol, "parent", veh); setElementData(veh, "parent", vehCol); setElementData(veh, "dayzvehicle", tonumber(dayz)); setElementData(vehCol, "vehicle", true); setElementData(vehCol, "MAX_Slots", tonumber(slots)); setElementData(vehCol, "Tire_inVehicle", tonumber(moving)); setElementData(vehCol, "Engine_inVehicle", tonumber(engines)); setElementData(vehCol, "Parts_inVehicle", tonumber(parts)); setElementData(vehCol, "Scrap_inVehicle", tonumber(scrap)); setElementData(vehCol, "Rotor_inVehicle", tonumber(rotor)); local needtires,needengine,needparts,needscrap,needrotor,_ = getVehicleAddonInfos(model); setElementData(vehCol, "needtires", needtires); setElementData(vehCol, "needparts", needparts); setElementData(vehCol, "needscrap", needscrap); setElementData(vehCol, "needrotor", needrotor); setElementData(vehCol, "needengines", needengine); setElementData(vehCol, "spawn", {model, sx, sy, sz}); setElementData(vehCol, "fuel", tonumber(fuel)); for _,v in ipairs(fromJSON(items)) do setElementData(vehCol, v[1], v[2]); end end function createDayzTent(model, x, y, z, rX, rY, rZ, slots, scale, items) local tent = createObject(model, x, y, z); local tentCol = createColSphere(x, y, z, 3); setElementRotation(tent, rX, rY, rZ); setObjectScale(tent, scale); attachElements(tentCol, tent); setElementData(tentCol, "parent", tent); setElementData(tent, "parent", tentCol); setElementData(tentCol, "tent", true); setElementData(tentCol, "MAX_Slots", slots); for _,v in ipairs(fromJSON(items)) do setElementData(tentCol, v[1], v[2]); end end function createDayzSafe(model, x, y, z, rX, rY, rZ, slots, scale, code, safe_id, items) local safe = createObject(model, x, y, z); local safeCol = createColSphere(x, y, z, 3); setElementCollisionsEnabled(safe,false) setElementRotation(safe, rX, rY, rZ); setObjectScale(safe, scale); attachElements(safeCol, safe); setElementData(safeCol, "parent", safe); setElementData(safe, "parent", safeCol); setElementData(safeCol, "safe", true); setElementData(safeCol, safe_id, code); setElementData(safeCol, "id", safe_id); setElementData(safeCol, "MAX_Slots", slots); for _,v in ipairs(fromJSON(items)) do setElementData(safeCol, v[1], v[2]); end end function loadBackup() for _,v in pairs(getElementsByType("vehicle")) do local col = getElementData(v, "parent"); if col then destroyElement(col); end destroyElement(v); end local p = dbPoll(dbQuery(db, "SELECT * FROM `vehicles`"), -1); if (#p > 0) then for _,d in pairs(p) do createDayzVeh(d["model"], d["x"], d["y"], d["z"], d["rX"], d["rY"], d["rZ"], d["slots"], d["fuel"], d["engines"], d["moving"], d["parts"], d["scrap"], d["rotor"], d["items"], d["dayz"], d["health"], d["sx"], d["sy"], d["sz"]); end end local p2 = dbPoll(dbQuery(db, "SELECT * FROM `tents`"), -1); if (#p2 > 0) then for _,d in pairs(p2) do createDayzTent(d["model"], d["x"], d["y"], d["z"], d["rX"], d["rY"], d["rZ"], d["slots"], d["scale"], d["items"]); end end local p2 = dbPoll(dbQuery(db, "SELECT * FROM `safes`"), -1); if (#p2 > 0) then for _,d in pairs(p2) do createDayzSafe(d["model"], d["x"], d["y"], d["z"], d["rX"], d["rY"], d["rZ"], d["slots"], d["scale"], d["code"], d["safe_id"], d["items"]); end end end if not backupdone then spawnDayZVehicles(); backupdone = true; else loadBackup(); end setTimer(backup, (10*60000), 0); addCommandHandler("dobackup", function(player) if isObjectInACLGroup("user."..getAccountName(getPlayerAccount(player)), aclGetGroup("Admin")) then backup(); end end); addCommandHandler("loadbackup",function(player) if isObjectInACLGroup("user."..getAccountName(getPlayerAccount(player)), aclGetGroup("Admin")) then --loadBackup(); end end); for _,v in ipairs(patrolPoints) do local x,y,z = v[1], v[2], v[3]; patrolCol = createColSphere(x, y, z, 3); setElementData(patrolCol, "patrolstation", true); end createHeliCrashSite(); createHospitalPacks();
if not Holo:ShouldModify("Menu", "CrimeNet") then return end Holo:Post(CrimeNetGui, "init", function( self, ws, fullscreeen_ws, node ) Holo.Utils:FixBackButton(self) Holo.Utils:SetBlendMode(self._panel, "focus") Holo.Utils:SetBlendMode(self._map_panel, "focus") local no_servers = node:parameters().no_servers self._fullscreen_panel:child("vignette"):hide() self._fullscreen_panel:child("bd_light"):hide() self._fullscreen_panel:child("blur_top"):hide() self._fullscreen_panel:child("blur_right"):hide() self._fullscreen_panel:child("blur_bottom"):hide() self._fullscreen_panel:child("blur_left"):hide() self._rasteroverlay:hide() self._map_panel:rect({ name = "background", color = Holo:GetColor("Colors/Menu"), alpha = Holo.Options:GetValue("MenuBackground") and 1 or 0, valign = "scale", halign = "scale", }) self._panel:child("legends_button"):set_color(Holo:GetColor("TextColors/Menu")) self._map_panel:child("map"):set_alpha(Holo.Options:GetValue("ColoredBackground") and 0 or 1) for _, child in pairs(table.list_add(self._panel:children(), self._fullscreen_panel:children(), self._panel:child("legend_panel"):children())) do if child.render_template and child:render_template() == Idstring("VertexColorTexturedBlur3D") then child:set_alpha(0) end end end) Holo:Post(CrimeNetGui, "_create_job_gui", function(self) Holo.Utils:SetBlendMode(self._panel, "focus") end) Holo:Post(CrimeNetGui, "_create_polylines", function(self, o, x, y) if self._region_panel then Holo.Utils:SetBlendMode(self._region_panel) end if Holo.Options:GetValue("ColoredBackground") then for _, child in pairs(self._region_panel:children()) do child:hide() end end end)
return class("NewMeixiV4PtPage", import(".TemplatePage.PtTemplatePage"))
local JSON = assert(loadfile "LuaScripts/json.lua")() local trampolinSpawner = {} trampolinSpawner["instantiate"] = function(params, entity) p = JSON:decode(params) local self = {} self.entity = entity -- Objeto a spawnear self.spawnObject = "Trampolin" -- Cada cuantos segundos spawnea self.timeToSpawn = 4 -- Velocidad del mundo en X tras el bateo (se aplica desde el bateo) self.xSpeed = 100 -- Rango de alturas entre las que se puede spawnear -- el objeto respecto a la altura del jugador self.spawnRange = 100 -- Deceleracion de los objetos spawneados en X self.slowAcc = 4.5 -- Posicion del pajaro self.birdPos = nil -- Velocidad a la que se dejara de spawnear objetos self.speedLimit = 0.0 self.spawning = false if p ~= nil then -- Objeto a spawnear if p.spawnObject ~= nil then self.spawnObject = p.spawnObject end -- Cada cuantos segundos spawnea if p.timeToSpawn ~= nil then self.timeToSpawn = p.timeToSpawn end -- Rango de generacion de Y respecto al jugador if p.spawnRange ~= nil then self.spawnRange = p.spawnRange end -- Deceleracion de los objetos spawneados en X if p.slowAcc ~= nil then self.slowAcc = p.slowAcc end -- Velocidad a la que se dejara de spawnear objetos if p.speedLimit ~= nil then self.speedLimit = p.speedLimit end end self.changeTimeToSpawn = function(x, time) self.timeToSpawn = x end -- Funcion para modificar el spawneo y la velocidad -- de los objetos spawneados self.modSpawning = function(s, xSpeed) self.spawning = s self.xSpeed = xSpeed end -- Modifica la velocidad de los objetos spawneados self.modSpeed = function(speed) self.xSpeed = self.xSpeed + speed end return self end trampolinSpawner["start"] = function(_self, lua) -- Seteamos la posicion del trampolinSpawner para generar los -- objetos fuera de la pantalla lua:getTransform(_self.entity):setPosition(Vector3(lua:getOgreContext():getWindowWidth(), 0, 0)) _self.timeSinceSpawn = lua:getInputManager():getTicks() end trampolinSpawner["update"] = function(_self, lua, deltaTime) if _self.spawning == true then -- Actualizacion de la velocidad if _self.xSpeed > _self.speedLimit then _self.xSpeed = _self.xSpeed - _self.slowAcc * deltaTime else _self.spawning = false end if (lua:getInputManager():getTicks() - _self.timeSinceSpawn) / 1000 >= _self.timeToSpawn then local objectSpawned = lua:instantiate(_self.spawnObject) objectSpawned:start() lua:getRigidbody(objectSpawned):setPosition(Vector3(200, 110, 0)) --Fuera de la pantalla y a la altura del suelo lua:getRigidbody(objectSpawned):setLinearVelocity(Vector3(-_self.xSpeed, 0, 0)) _self.timeSinceSpawn = lua:getInputManager():getTicks() end end end return trampolinSpawner
function love.load(arg) -- body... object = require "classic" require "player1" require "ball" require "player2" player1 = player1(50,love.graphics.getHeight()/2 - 75/2) player2 = player2(love.graphics.getWidth() - (50 + (15/2)),love.graphics.getHeight()/2 - (75/2)) ball = ball(love.graphics.getWidth()/2,love.graphics.getHeight()/2) end function love.update(dt) player1:update(dt) player2:update(dt) ball:update(dt) ball:checkforCollision(player1) ball:checkforCollision(player2) end function love.draw() player1:draw() player2:draw() ball:draw() end
local diff = { ["axisDiffs"] = { ["a3026cd5"] = { ["added"] = { [1] = { ["key"] = "JOY_SLIDER1", }, }, ["name"] = "Engine RPM Setting", }, }, ["keyDiffs"] = { ["d3002pnilunilcd12vd0vpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN10", }, }, ["name"] = "Flaps Down", }, ["d3002pnilunilcd12vd1vpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN9", }, }, ["name"] = "Flaps Up", }, ["d3004pnilunilcd12vd0.1vpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN10", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Landing Gear Down", }, ["d3004pnilunilcd12vd0.2vpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN9", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Landing Gear Up", }, ["d3014pnilunilcd12vd1vpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN_POV1_D", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Trimmers Reset", }, ["d74pnilu75cdnilvdnilvpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN3", }, }, ["name"] = "Wheel brake Both", }, ["dnilp3011unilcd12vdnilvp-0.1vunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN_POV1_L", }, }, ["name"] = "Trim Aileron Left", }, ["dnilp3011unilcd12vdnilvp0.1vunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN_POV1_R", }, }, ["name"] = "Trim Aileron Right", }, ["dnilp3012unilcd12vdnilvp-0.05vunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN_POV1_D", }, }, ["name"] = "Trim Elevator Up", }, ["dnilp3012unilcd12vdnilvp0.05vunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN_POV1_U", }, }, ["name"] = "Trim Elevator Down", }, ["dnilp3013unilcd12vdnilvp-0.1vunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN_POV1_L", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Trim Rudder Left", }, ["dnilp3013unilcd12vdnilvp0.1vunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN_POV1_R", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Trim Rudder Right", }, ["dnilp32u214cdnilvdnilvpnilvunil"] = { ["name"] = "View Left slow", ["removed"] = { [1] = { ["key"] = "JOY_BTN_POV1_L", }, }, }, ["dnilp33u214cdnilvdnilvpnilvunil"] = { ["name"] = "View Right slow", ["removed"] = { [1] = { ["key"] = "JOY_BTN_POV1_R", }, }, }, ["dnilp34u214cdnilvdnilvpnilvunil"] = { ["name"] = "View Up slow", ["removed"] = { [1] = { ["key"] = "JOY_BTN_POV1_U", }, }, }, ["dnilp35u214cdnilvdnilvpnilvunil"] = { ["name"] = "View Down slow", ["removed"] = { [1] = { ["key"] = "JOY_BTN_POV1_D", }, }, }, }, } return diff
--[[ This script will look at a focus part as long as the focus part is visible (in front of the target) This makes the player character look at the part. R15 only. This script creates an ObjectValue named "LookAtPart" if the server hasn't already done so. Set the Value to a model or basepart. NOTE that if the server does not set LookAtPart, then it cannot tell the client to look at a part. ]] local RunService = game:GetService("RunService") local Player = game.Players.LocalPlayer local char = Player.Character or Player.CharacterAdded:Wait() -- the last seen LookAtPart.Value local lookat_value = nil -- the last resolved target part local lookat_part = nil local Head = char:WaitForChild("Head") local Neck = Head:WaitForChild("Neck") local Torso = char:WaitForChild("UpperTorso") local Waist = Torso:WaitForChild("Waist") local hrp = char.PrimaryPart local NeckOriginC0 = Neck.C0 local WaistOriginC0 = Waist.C0 -- Create the LookAtPart, if needed (the server may have created it) local LookAtPartValue = char:FindFirstChild("LookAtPart") if LookAtPartValue == nil then LookAtPartValue = Instance.new("ObjectValue") LookAtPartValue.Name = "LookAtPart" LookAtPartValue.Parent = char end local function find_first_visible_part(parent) for _, part in pairs(parent:GetChildren()) do if part:IsA("BasePart") and part.Transparency < 0.9 then return part end end return nil end --[[ "Resolves" the target part as follows: - if it is a BasePart, then return that - if it is a Model: + return the PrimaryPart, if present. + return a child named "Head", if present + return the first BasePart in the model that is not transparent - if it is a Tool: + return the part named "Handle", if present + return the first BasePart in the model that is not transparent This is done when the current target becomes invalid OR LookAtPart.Value changes. ]] local function lookat_resolve(target) if target ~= nil then local xx if target:IsA("BasePart") then xx = target elseif target:IsA("Model") then xx = target.PrimaryPart if xx == nil then xx = target:FindFirstChild("Head") if xx == nil then xx = find_first_visible_part(target) end end elseif target:IsA("Tool") then local xx = target:FindFirstChild("Handle") if xx == nil then xx = find_first_visible_part(target) end end return xx end return nil end -- this is used to NOT override the motors once we are no longer looking at a target. local restore_time = 0 local ov_conn = nil local function lookat_heartbeat(step) if Torso.Parent and Head.Parent then local ovv = LookAtPartValue.Value -- check for deleted target if ovv ~= nil and ovv.Parent == nil then LookAtPartValue.Value = nil lookat_part = nil end -- check for deleted part if lookat_part ~= nil and lookat_part.Parent == nil then lookat_part = nil end if ovv ~= lookat_value then lookat_part = lookat_resolve(ovv) lookat_value = ovv end local tgt = lookat_part -- don't look if behind player if tgt ~= nil then -- using unit vectors, so the dot is cos(a). 0.3 is about 33 deg behind. local dd = hrp.CFrame.lookVector:Dot((hrp.Position - tgt.Position).Unit) if dd > 0.3 then --print('DOT:', dd) tgt = nil end end if tgt ~= nil then local TorsoLookVector = Torso.CFrame.lookVector local HeadPosition = Head.CFrame.p local Point = tgt.Position local tgt_vec = HeadPosition - Point local tgt_unit = tgt_vec.Unit local Distance = tgt_vec.magnitude --local YDifference = Head.CFrame.Y - Point.Y local YDifference = tgt_vec.Y local atd = -(math.atan(YDifference / Distance) * 0.5) local hpy = (tgt_unit:Cross(TorsoLookVector)).Y Neck.C0 = Neck.C0:lerp(NeckOriginC0 * CFrame.Angles(atd, hpy * 1, 0), 0.25) Waist.C0 = Waist.C0:lerp(WaistOriginC0 * CFrame.Angles(atd, hpy * 0.5, 0), 0.25) -- give 2 seconds to go back to normal restore_time = 2 --print("LOOKING") return end --print("NOT LOOKING") -- not looking at anything, return to normal pose Neck.C0 = Neck.C0:lerp(NeckOriginC0, 0.25) Waist.C0 = Waist.C0:lerp(WaistOriginC0, 0.25) if lookat_part == nil then -- lerp to the rest position for a little while then let animations take over restore_time = restore_time - step if restore_time < 0 then if ov_conn ~= nil then print("hb_Disconnect") ov_conn:Disconnect() ov_conn = nil end end end end end --[[ Handle a change in the target value, connect or disconnect the heartbeat function. ]] local function handle_new_target() --print("handle_new_target: ov_conn:", ov_conn, "lpv:", LookAtPartValue.Value) if LookAtPartValue.Value ~= nil and ov_conn == nil then --print("**** hb_Connect") ov_conn = RunService.Heartbeat:Connect(lookat_heartbeat) end end -- start calling the heartbeat function if we have the required parts if Neck and Waist and Torso and Head and LookAtPartValue then Neck.MaxVelocity = 1/3 LookAtPartValue.Changed:Connect(function() handle_new_target() end) handle_new_target() end
#!/people/galibert/soft/dietools/mschem/mschem tiles("../schem/tiles") dofile("remap.lua")
function onSay(cid, words, param, channel) if(param == '') then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Command requires param.") return true end local t = string.explode(param, ";") if(not t[2]) then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "No destination specified.") return true end local pid = getPlayerByNameWildcard(t[1]) if(not pid or (isPlayerGhost(pid) and getPlayerAccess(pid) > getPlayerAccess(cid))) then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Player " .. t[1] .. " not found.") return true end local creature = getCreatureByName(t[2]) local player = getPlayerByNameWildcard(t[2]) local waypoint = getWaypointPosition(t[2]) local tile = string.explode(t[2], ",") local pos = {x = 0, y = 0, z = 0} if(player ~= nil and (not isPlayerGhost(player) or getPlayerAccess(player) <= getPlayerAccess(cid))) then pos = getCreaturePosition(player) elseif(creature ~= nil and (not isPlayer(creature) or (not isPlayerGhost(creature) or getPlayerAccess(creature) <= getPlayerAccess(cid)))) then pos = getCreaturePosition(creature) elseif(type(waypoint) == 'table' and waypoint.x ~= 0 and waypoint.y ~= 0) then pos = waypoint elseif(tile[2] and tile[3]) then pos = {x = tile[1], y = tile[2], z = tile[3]} else doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Invalid destination specified.") return true end if(not pos or isInArray({pos.x, pos.y}, 0)) then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Destination not reachable.") return true end pos = getClosestFreeTile(cid, pos, true) if(not pos or isInArray({pos.x, pos.y}, 0)) then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Cannot perform action.") return true end local tmp = getCreaturePosition(pid) if(doTeleportThing(pid, pos, true) and not isPlayerGhost(pid)) then doSendMagicEffect(tmp, CONST_ME_POFF) doSendMagicEffect(pos, CONST_ME_TELEPORT) end return true end
---@class color32 local color32 = { ---@type number r = 255, ---@type number g = 255, ---@type number b = 255, ---@type number a = 255 } ---@overload fun(): color32 ---@overload fun(c: color): color32 ---@overload fun(c: color32): color32 ---@overload fun(v: v4f): color32 ---@overload fun(v: v3f, a: number): color32 ---@overload fun(r: number, g: number, b: number, a: number): color32 ---@return color32 function color32.new(...) end ---@return color32 function color32.clear() end ---@return color32 function color32.black() end ---@return color32 function color32.white() end ---@return color32 function color32.red() end ---@return color32 function color32.green() end ---@return color32 function color32.blue() end ---@return color32 function color32.yellow() end ---@return color32 function color32.magenta() end ---@return color32 function color32.cyan() end ---@param l color32 ---@param r color32 ---@return boolean function color32.approximately(l, r) end ---@param c color32 ---@return number function color32.minimum(c) end ---@param c color32 ---@return number function color32.maximum(c) end ---@param c color32 ---@param cmin color32 ---@return color32 function color32.minimized(c,cmin) end ---@param c color32 ---@param cmax color32 ---@return color32 function color32.maximized(c,cmax) end ---@param c color32 ---@param cmin color32 ---@param cmax color32 ---@return color32 function color32.clamped(c,cmin,cmax) end ---@type color32 _G.color32 = _G.color32 or color32
local ls = require("luasnip") local s = ls.s local i = ls.i -- local t = ls.t local fmt = require("luasnip.extras.fmt").fmt -- local d = ls.dynamic_node -- local c = ls.choice_node -- local f = ls.function_node -- local sn = ls.snippet_node -- local rep = require("luasnip.extras").rep local snippets, autosnippets = {}, {} local def = s({trig = "def", name="definition"}, fmt([[def {}({}) -> {}: {} ]], { i(1, "name"), i(2), i(3, "None"), i(0, 'raise NotImplementedError("To be implemented")') })) table.insert(snippets, def) return snippets, autosnippets
-- Direction status, shows arrows pointing to the players, created by Michael local Direction = Grid2.statusPrototype:new("direction") local Grid2 = Grid2 local PI = math.pi local PI2 = PI*2 local sqrt = math.sqrt local floor = math.floor local atan2 = math.atan2 local pairs = pairs local GetPlayerFacing = GetPlayerFacing local UnitPosition = UnitPosition local UnitIsUnit = UnitIsUnit local UnitGUID = UnitGUID local C_GetNamePlateForUnit = C_NamePlate.GetNamePlateForUnit local CombatLogGetCurrentEventInfo = CombatLogGetCurrentEventInfo local f_env = { UnitIsUnit = UnitIsUnit, UnitGroupRolesAssigned = UnitGroupRolesAssigned or (function() return 'NONE' end), UnitInRange = UnitInRange, UnitIsVisible = UnitIsVisible, UnitIsDead = UnitIsDead, } local timer local distances local directions = {} local UnitCheck local mouseover = "" local guessDirections = false local roster_units = Grid2.roster_units local curtime = 0 local plates = {} -- [guid] = PlateFrame.UnitFrame local guid2guid = {} -- local guid2time = {} -- local playerx,playery -- local function PlateAdded(_, unit) local plateFrame = C_GetNamePlateForUnit(unit) if plateFrame then plates[ UnitGUID(unit) ] = plateFrame.UnitFrame end end local function PlateRemoved(_, unit ) plates[ UnitGUID(unit) ] = nil end local function CombatLogEvent() local timestamp, event,_,srcGUID, _,_,_, dstGUID = CombatLogGetCurrentEventInfo() if event=='SWING_DAMAGE' then local unit = roster_units[srcGUID] if unit then guid2guid[srcGUID] = dstGUID guid2time[srcGUID] = timestamp end end curtime = timestamp end local function GetPlate(guid) local dguid = guid2guid[guid] return dguid and curtime-guid2time[guid]<3 and plates[dguid] end -- local function UpdateDirections() local x1,y1, _, map1 = UnitPosition("player") if x1 or guessDirections then local facing = GetPlayerFacing() if facing then for unit,guid in Grid2:IterateRosterUnits() do local direction, distance, update if not UnitIsUnit(unit, "player") and UnitCheck(unit, mouseover) then local x2,y2, _, map2 = UnitPosition(unit) if map1 == map2 then if x2 then local dx, dy = x2 - x1, y2 - y1 direction = floor((atan2(dy,dx)-facing) / PI2 * 32 + 0.5) % 32 if distances then distance = floor( ((dx*dx+dy*dy)^0.5)/10 ) + 1 end elseif guessDirections then -- disabled guessDirections, this condition is never true local frame = plates[guid] or GetPlate(guid) if frame then local s = frame:GetEffectiveScale() local x, y = frame:GetCenter() local dx, dy = x*s - playerx, y*s - playery direction = floor( (atan2(dy,dx)/PI2+0.75) * 32 ) % 32 end end end end if distances and distances[unit]~=distance then distances[unit], update = distance, true end if direction~=directions[unit] then directions[unit], update = direction, true end if update then Direction:UpdateIndicators(unit) end end return end end for unit,_ in pairs(directions) do directions[unit]= nil Direction:UpdateIndicators(unit) end end function Direction:SetTimer(enable) if enable then timer = timer or Grid2:CreateTimer(UpdateDirections) timer:SetDuration(self.dbx.updateRate or 0.2) timer:Play() elseif timer then timer:Stop() end end function Direction:RestartTimer() if timer and timer:IsPlaying() then self:SetTimer(true) end end local SetMouseoverHooks -- UnitIsUnit(unit, "mouseover") does not work for units that are not Visible do local function OnMouseEnter(frame) mouseover = frame.unit end local function OnMouseLeave() mouseover = "" end SetMouseoverHooks = function(enable) Grid2Frame:SetEventHook( 'OnEnter', OnMouseEnter, enable ) Grid2Frame:SetEventHook( 'OnLeave', OnMouseLeave, enable ) if not enable then mouseover = "" end end end function Direction:UpdateDB() local isRestr t= {} t[1] = "return function(unit, mouseover) return " if not self.dbx.showOnlyStickyUnits then if self.dbx.ShowOutOfRange then t[#t+1]= "and (not UnitInRange(unit)) "; isRestr=true end if self.dbx.ShowVisible then t[#t+1]= "and UnitIsVisible(unit) "; isRestr=true end if self.dbx.ShowDead then t[#t+1]= "and UnitIsDead(unit) "; isRestr=true end end if isRestr or self.dbx.showOnlyStickyUnits then if self.dbx.StickyTarget then t[#t+1]= "or UnitIsUnit(unit, 'target') " end if self.dbx.StickyMouseover then t[#t+1]= "or UnitIsUnit(unit, mouseover) " end if self.dbx.StickyFocus then t[#t+1]= "or UnitIsUnit(unit, 'focus') " end if self.dbx.StickyTanks then t[#t+1]= "or UnitGroupRolesAssigned(unit)=='TANK' " end end t[2] = t[2] and t[2]:sub(5) or "true " t[#t+1]= "end" SetMouseoverHooks((isRestr or self.dbx.showOnlyStickyUnits) and self.dbx.StickyMouseover) UnitCheck = assert(loadstring(table.concat(t)))() setfenv(UnitCheck, f_env) -- local count = self.dbx.colorCount or 1 if count>1 then distances = distances or {} self.GetVertexColor = Direction.GetDistanceColor self.colors = self.colors or {} for i=1,count do self.colors[i] = self.dbx["color"..i] end else distances = nil self.GetVertexColor = Grid2.statusLibrary.GetColor end -- disabled because doesn't work due to new Nameplates restrictions, GetCenter() cannot be called in combat now -- guessDirections = self.dbx.guessDirections end function Direction:OnEnable() self:UpdateDB() self:SetTimer(true) if guessDirections then playerx = UIParent:GetWidth() * UIParent:GetEffectiveScale() / 2 playery = UIParent:GetHeight() * UIParent:GetEffectiveScale() / 2 self:RegisterEvent("NAME_PLATE_UNIT_ADDED", PlateAdded ) self:RegisterEvent("NAME_PLATE_UNIT_REMOVED", PlateRemoved ) self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED", CombatLogEvent) end end function Direction:OnDisable() self:SetTimer(false) if guestDirections then self:UnregisterEvent("NAME_PLATE_UNIT_ADDED") self:UnregisterEvent("NAME_PLATE_UNIT_REMOVED") self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") end end function Direction:IsActive(unit) return directions[unit] and true end function Direction:GetIcon(unit) return "Interface\\Addons\\Grid2\\media\\Arrows32-32x32" end function Direction:GetTexCoord(unit) local y= directions[unit] / 32 return 0.05, 0.95, y+0.0015625, y+0.028125 end function Direction:GetDistanceColor(unit) local distance = distances[unit] local color = distance and self.colors[distance] or self.colors[5] return color.r, color.g, color.b, color.a end local function Create(baseKey, dbx) Grid2:RegisterStatus(Direction, {"icon"}, baseKey, dbx) return Direction end Grid2.setupFunc["direction"] = Create Grid2:DbSetStatusDefaultValue( "direction", { type = "direction", color1 = { r= 0, g= 1, b= 0, a=1 } })
require 'torch' require 'cudnn' require 'cuorn' require 'libcudnnorn' include('ORConv.lua') include('LBConv.lua') include('LBORConv.lua') -- monkey patch BN local BN = cudnn.SpatialBatchNormalization function BN:createIODescriptors(input) assert(input:dim() == self.nDim) assert(torch.typename(self.weight) == 'torch.CudaTensor' and torch.typename(self.bias) == 'torch.CudaTensor', 'Only CUDA tensors are supported for cudnn.BatchNormalization!') if not self.iDesc or not self.oDesc or not input:isSize(self.iSize) then local nFeature = self.running_mean:numel() self.iSize = input:size() self.output:resizeAs(input) if self.nDim == 4 and self.iSize[2] > nFeature then local tmp = input.new():resize( self.iSize[1], nFeature, self.iSize[3] * (self.iSize[2] / nFeature), self.iSize[4] ) self.iDesc = cudnn.toDescriptor(tmp) self.oDesc = cudnn.toDescriptor(tmp) else self.iDesc = cudnn.toDescriptor(input) self.oDesc = cudnn.toDescriptor(self.output) end local biasSize = torch.ones(self.nDim):totable() biasSize[2] = nFeature self.sDesc = cudnn.toDescriptor(self.bias:view(table.unpack(biasSize))) end end -- monkey patch cudnn.convert local layer_list = { 'BatchNormalization', 'SpatialBatchNormalization', 'SpatialConvolution', 'SpatialCrossMapLRN', 'SpatialFullConvolution', 'SpatialMaxPooling', 'SpatialAveragePooling', 'ReLU', 'Tanh', 'Sigmoid', 'SoftMax', 'LogSoftMax', 'VolumetricBatchNormalization', 'VolumetricConvolution', 'VolumetricMaxPooling', 'VolumetricAveragePooling', 'ORConv', 'LBConv', 'LBORConv' } function cudnn.convert(net, dst, exclusion_fn) return net:replace(function(x) local y = 0 local src = dst == nn and cudnn or nn local src_prefix = src == nn and 'nn.' or 'cudnn.' local dst_prefix = dst == nn and 'nn.' or 'cudnn.' local function convert(v) local y = {} torch.setmetatable(y, dst_prefix..v) if v == 'ReLU' then y = dst.ReLU() end -- because parameters for k,u in pairs(x) do y[k] = u end if src == cudnn and x.clearDesc then x.clearDesc(y) end if src == cudnn and v == 'SpatialAveragePooling' then y.divide = true y.count_include_pad = v.mode == 'CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING' end return y end if exclusion_fn and exclusion_fn(x) then return x end local t = torch.typename(x) if t == 'nn.SpatialConvolutionMM' then y = convert('SpatialConvolution') elseif t == 'inn.SpatialCrossResponseNormalization' then y = convert('SpatialCrossMapLRN') else for i,v in ipairs(layer_list) do if torch.typename(x) == src_prefix..v then y = convert(v) end end end return y == 0 and x or y end) end
ESX = nil Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end end) local citizen = false local nui = false local TimeFreshCurrentArmour = 10000 -- 5 sekund local TimeFreshCurrentHealth = 10000 -- 5 sekund RegisterNetEvent('Frost-Armor:Client:UstawArmor') AddEventHandler('Frost-Armor:Client:UstawArmor', function(armour) Citizen.Wait(10000) SetPedArmour(PlayerPedId(), tonumber(armour)) citizen = true end) RegisterNetEvent('Frost-Zycie:Client:UstawZycie') AddEventHandler('Frost-Zycie:Client:UstawZycie', function(health) Citizen.Wait(10000) SetEntityHealth(PlayerPedId(), tonumber(health)) TriggerEvent("FeedM:showNotification", "Wczytano HP i Armor z przed wyjscia") citizen = true end) Citizen.CreateThread(function() while true do Citizen.Wait(0) if citizen == true then TriggerServerEvent('Frost-Armor:Server:OdswiezArmor', GetPedArmour(PlayerPedId())) Citizen.Wait(TimeFreshCurrentArmour) end end end) Citizen.CreateThread(function() while true do Citizen.Wait(0) if citizen == true then TriggerServerEvent('Frost-Zycie:Server:OdswiezZycie', GetEntityHealth(PlayerPedId())) Citizen.Wait(TimeFreshCurrentHealth) end end end) function sendNotification(message, messageType, messageTimeout) TriggerEvent('notification', message) end Citizen.CreateThread(function() while true do Citizen.Wait(1) SetPlayerHealthRechargeMultiplier(PlayerId(), 0.0) if nui then if IsControlJustReleased(1, 177) then TriggerEvent('crp_statystyki:UICLOSE') end end end end) RegisterNetEvent('crp_statystyki:UIOPEN') AddEventHandler('crp_statystyki:UIOPEN', function(data1, data2) ESX.TriggerServerCallback('loaddatatostatsv2', function (data) SendNUIMessage({action = "show", imie = data1, klasa = data2, stamina = data[1].stamina, sila = data[1].sila, pp = data[1].pp, zj = data[1].zj, zl = data[1].zl, zs = data[1].zs}) nui = true end) end) RegisterNetEvent('crp_statystyki:UICLOSE') AddEventHandler('crp_statystyki:UICLOSE', function() SendNUIMessage({action = "hide"}) nui = false end) RegisterNetEvent('crp_statystyki:postedata') AddEventHandler('crp_statystyki:postedata', function(data1, data2) SendNUIMessage({action = "setall", imie = data1, klasa = data2}) end) RegisterCommand('statystyki', function(source) ESX.TriggerServerCallback('loaddatatostats', function (data) TriggerEvent('crp_statystyki:UIOPEN', data[1].firstname.." "..data[1].lastname, 'Gangster - Dealer') end) end) local canget = true local cangethelka = true local cangetrun = true local cangetsw = true Citizen.CreateThread(function() while true do Citizen.Wait(1) local ped = GetPlayerPed(-1) local vehicle1 = GetVehiclePedIsUsing(PlayerPedId()) local healthEngineCurrent = GetVehicleBodyHealth(vehicle1) local vehicleClass = GetVehicleClass(vehicle1) == 16 or GetVehicleClass(vehicle1) == 15 if IsEntityInWater(ped) and GetEntityHeightAboveGround(ped) < 0.80 and cangetsw then Citizen.Wait(6000) TriggerEvent("FeedM:showNotification", 'Dostałeś +1 do Pojemność Płuc!') TriggerServerEvent('updatebaza123', 'pp') cangetsw = false end if healthEngineCurrent == 1000 and vehicle1 and getSpeedInUnits() > 200 and GetPedInVehicleSeat(vehicle1, -1) == ped and canget and not vehicleClass then TriggerEvent("FeedM:showNotification", 'Dostałeś +1 do Zdolnośći Jazdy!') TriggerServerEvent('updatebaza123', 'zj') canget = false end if GetEntitySpeed(ped) > 7 and cangetrun then Citizen.Wait(6000) TriggerEvent("FeedM:showNotification", 'Dostałeś +1 do Staminy!') TriggerServerEvent('updatebaza123', 'stamina') cangetrun = false end if healthEngineCurrent == 1000 and vehicle1 and getSpeedInUnits() > 200 and GetPedInVehicleSeat(vehicle1, -1) == ped and cangethelka and vehicleClass then TriggerEvent("FeedM:showNotification", 'Dostałeś +1 do Zdolnośći Latania!') TriggerServerEvent('updatebaza123', 'zl') cangethelka = false end end end) function getSpeedInUnits() local vehicle = GetVehiclePedIsUsing(PlayerPedId()) local speedInMetersSecond = GetEntitySpeed(vehicle) return speedInMetersSecond * 3.6 end Citizen.CreateThread(function() while true do Citizen.Wait(3600000) canget = true cangethelka = true cangetrun = true cangetsw = true end end) RegisterNetEvent('crp_statystyki:setdata') AddEventHandler('crp_statystyki:setdata', function(result) StatSetInt(GetHashKey("MP0_STAMINA"), result[1].stamina, true); StatSetInt(GetHashKey("MP0_STRENGTH"), result[1].sila, true); StatSetInt(GetHashKey("MP0_LUNG_CAPACITY"), result[1].pp, true); StatSetInt(GetHashKey("MP0_WHEELIE_ABILITY"), result[1].zj, true); StatSetInt(GetHashKey("MP0_FLYING_ABILITY"), result[1].zl, true); StatSetInt(GetHashKey("MP0_SHOOTING_ABILITY"), result[1].zs, true); end)
local QBCore = exports['qb-core']:GetCoreObject() RegisterNetEvent('um-taco:server:additem', function(additem) local src = source local Player = QBCore.Functions.GetPlayer(src) Player.Functions.AddItem(additem, 1) TriggerClientEvent('inventory:client:ItemBox', src, QBCore.Shared.Items[additem], "add") end) RegisterNetEvent('um-taco:server:removeitem', function(removeitem) local src = source local Player = QBCore.Functions.GetPlayer(src) Player.Functions.RemoveItem(removeitem, 1) TriggerClientEvent('inventory:client:ItemBox', src, QBCore.Shared.Items[removeitem], "remove") end) RegisterNetEvent('um-taco:server:givemoney', function() local src = source local Player = QBCore.Functions.GetPlayer(src) local tiprandom = math.random(1,50) local tacomoney = math.random(Config.TacoMoneyMin,Config.TacoMoneyMax) Player.Functions.AddMoney("cash", tacomoney, "taco-money") TriggerClientEvent('QBCore:Notify', src, "Taco delivered! Go back to the taco shop for a new delivery", "success") TriggerClientEvent('QBCore:Notify', src, "You have earned in money $"..tacomoney) if tiprandom >= 25 then Player.Functions.AddMoney("cash", Config.TacoTip, "taco-tip") TriggerClientEvent('QBCore:Notify', src, "You have earned in tips $"..Config.TacoTip) end end) QBCore.Functions.CreateCallback('um-taco:server:checktaco', function(source, cb) local src = source local Player = QBCore.Functions.GetPlayer(src) local tacobread = Player.Functions.GetItemByName("tacobread") local tacomeat = Player.Functions.GetItemByName("tacomeat") local tacosalad = Player.Functions.GetItemByName("tacosalad") if tacobread ~= nil and tacomeat ~= nil and tacosalad ~= nil then Player.Functions.RemoveItem("tacobread", 1) Player.Functions.RemoveItem("tacomeat", 1) Player.Functions.RemoveItem("tacosalad", 1) TriggerClientEvent('inventory:client:ItemBox', src, QBCore.Shared.Items["tacobread"], "remove") TriggerClientEvent('inventory:client:ItemBox', src, QBCore.Shared.Items["tacomeat"], "remove") TriggerClientEvent('inventory:client:ItemBox', src, QBCore.Shared.Items["tacosalad"], "remove") cb(true) else cb(false) end end)
-- Automatically generated file: Statuses return { [0] = {id=0,en="Idle"}, [1] = {id=1,en="Engaged"}, [2] = {id=2,en="Dead"}, [3] = {id=3,en="Engaged dead"}, [4] = {id=4,en="Event"}, [5] = {id=5,en="Chocobo"}, [8] = {id=8,en="Door Opening"}, [9] = {id=9,en="Door Closing"}, [10] = {id=10,en="Elevator Up"}, [11] = {id=11,en="Elevator Down"}, [33] = {id=33,en="Resting"}, [34] = {id=34,en="Locked"}, [38] = {id=38,en="Fishing fighting"}, [39] = {id=39,en="Fishing caught"}, [40] = {id=40,en="Fishing broken rod"}, [41] = {id=41,en="Fishing broken line"}, [42] = {id=42,en="Fishing caught monster"}, [43] = {id=43,en="Fishing lost catch"}, [44] = {id=44,en="Crafting"}, [47] = {id=47,en="Sitting"}, [48] = {id=48,en="Kneeling"}, [50] = {id=50,en="Fishing"}, [51] = {id=51,en="Fishing fighting center"}, [52] = {id=52,en="Fishing fighting right"}, [53] = {id=53,en="Fishing fighting left"}, [56] = {id=56,en="Fishing rod in water"}, [57] = {id=57,en="Fishing fish on hook"}, [58] = {id=58,en="Fishing caught fish"}, [59] = {id=59,en="Fishing rod break"}, [60] = {id=60,en="Fishing line break"}, [61] = {id=61,en="Fishing monster catch"}, [62] = {id=62,en="Fishing no catch or lost"}, [63] = {id=63,en="Sitchair 0"}, [64] = {id=64,en="Sitchair 1"}, [65] = {id=65,en="Sitchair 2"}, [66] = {id=66,en="Sitchair 3"}, [67] = {id=67,en="Sitchair 4"}, [68] = {id=68,en="Sitchair 5"}, [69] = {id=69,en="Sitchair 6"}, [70] = {id=70,en="Sitchair 7"}, [71] = {id=71,en="Sitchair 8"}, [72] = {id=72,en="Sitchair 9"}, [73] = {id=73,en="Sitchair 10"}, [74] = {id=74,en="Sitchair 11"}, [75] = {id=75,en="Sitchair 12"}, [85] = {id=85,en="Mount"}, }, {"id", "en"} --[[ Copyright © 2013-2021, Windower All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Windower nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Windower BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ]]
require "config" require "tools" local local_run_test = lunit and function() end or run_test local lunit = require "lunit" local arg = {...} local _ENV = TEST_CASE'Statement foreach' local function assert_equal3(a,b,c, ra,rb,rc) assert_equal(a,ra) assert_equal(b,rb) assert_equal(c,rc) end local function assert_equal2(a,b, ra,rb) assert_equal(a,ra) assert_equal(b,rb) end local TEST_ROWS = 100 local env, cnn, stmt local function init_table() local val = odbc.ulong() assert_boolean(table_exists(cnn)) assert_equal(CREATE_TABLE_RETURN_VALUE, ensure_table(cnn)) assert_true(table_exists(cnn)) stmt = assert(cnn:statement()) assert_true(cnn:setautocommit(false)) assert_true(stmt:prepare("insert into " .. TEST_TABLE_NAME .. "(f1) values(?)")) assert_equal(val, val:bind_param(stmt,1)) for i = 1, TEST_ROWS do val:set(i) assert_equal(1, stmt:execute()) assert_true(stmt:closed()) end assert_true( cnn:commit() ) assert_true( stmt:reset() ) assert_true(cnn:setautocommit(true)) assert_equal(TEST_ROWS, stmt:execute("select count(*) from " .. TEST_TABLE_NAME):fetch() ) assert_true( stmt:destroy() ) end local function fin_table() assert_equal(DROP_TABLE_RETURN_VALUE, drop_table(cnn)) assert_false(table_exists(cnn)) end function teardown() if cnn and cnn:connected() then drop_table(cnn) end if stmt then stmt:destroy() end if cnn then cnn:destroy() end if env then env:destroy() end cnn = nil env = nil end function setup() env, cnn = do_connect() assert_not_nil(env, cnn) end local sql = "select f1 from " .. TEST_TABLE_NAME local function count_rows() if UPDATE_RETURN_ROWS then return stmt:execute('update ' .. TEST_TABLE_NAME .. ' set f1=f1') end local n,err = stmt:execute('select count(*) from '.. TEST_TABLE_NAME) if not n then return n, err end n, err = stmt:fetch() stmt:close() if n then return n end return n, err end local function open_stmt(autodestroy) if stmt:destroyed() then stmt = cnn:statement() end stmt:setdestroyonclose(false) if not stmt:closed() then stmt:close() end stmt:setdestroyonclose(autodestroy) assert_equal(stmt, stmt:execute(sql)) assert_false(stmt:closed()) return stmt end local function make_fn(fn) return setmetatable({},{__call = function(self, ...) return fn(...) end}) end function test_call() local function assert_table_(v) assert_table(v) return 1 end local function assert_string_(v) assert_string(v) return 1 end local function rise_error() error('some error') end local function inner_test (assert_table_, assert_string_) open_stmt():foreach(assert_string_) assert_true (stmt:closed()) open_stmt():foreach(false, assert_string_) assert_false(stmt:closed()) stmt:foreach(nil, assert_string_) assert_true (stmt:closed()) open_stmt():foreach('', assert_table_) assert_true (stmt:closed()) open_stmt():foreach('', assert_table_) assert_true (stmt:closed()) open_stmt():foreach(nil, nil, assert_string_) assert_true (stmt:closed()) open_stmt():foreach('', nil, assert_table_) assert_true (stmt:closed()) open_stmt():foreach(nil, false, assert_string_) assert_false(stmt:closed()) assert_error_match('some error', function() open_stmt():foreach(rise_error) end) assert_true (stmt:closed()) assert_error_match('some error', function() open_stmt():foreach(false, rise_error) end) assert_false (stmt:closed()) assert_true(stmt:close()) end local function inner_test2 (assert_table_, assert_string_) open_stmt(true):foreach(assert_string_) assert_true (stmt:destroyed()) open_stmt(true):foreach(false, assert_string_) assert_false(stmt:destroyed()) assert_false(stmt:closed()) stmt:foreach(nil, assert_string_) assert_true (stmt:destroyed()) open_stmt(true):foreach('', assert_table_) assert_true (stmt:destroyed()) open_stmt(true):foreach('', assert_table_) assert_true (stmt:destroyed()) open_stmt(true):foreach(nil, nil, assert_string_) assert_true (stmt:destroyed()) open_stmt(true):foreach('', nil, assert_table_) assert_true (stmt:destroyed()) open_stmt(true):foreach(nil, false, assert_string_) assert_false(stmt:destroyed()) assert_false(stmt:closed()) assert_error_match('some error', function() open_stmt(true):foreach(rise_error) end) assert_true (stmt:destroyed()) assert_error_match('some error', function() open_stmt(true):foreach(false, rise_error) end) assert_false(stmt:destroyed()) assert_false(stmt:closed()) assert_true(stmt:close()) end init_table() stmt = assert(cnn:statement()) inner_test ( assert_table_, assert_string_) inner_test (make_fn(assert_table_), make_fn(assert_string_)) inner_test2( assert_table_, assert_string_) inner_test2(make_fn(assert_table_), make_fn(assert_string_)) assert_true(stmt:destroy()) fin_table() end function test_cover() init_table() stmt = assert(cnn:statement()) stmt = open_stmt() assert_error(function() stmt:execute(sql) end) local t = {} local cnt = return_count(stmt:foreach(function(f1) local n = tonumber(f1) assert_number(n) t[n] = true end)) assert_equal(TEST_ROWS, #t) assert_true(stmt:closed()) assert_equal(0, cnt) assert_true(stmt:destroy()) fin_table() end function test_return() init_table() stmt = assert(cnn:statement()) assert_equal3(2, true, 'match', return_count(open_stmt():foreach(function(f1) if f1 == '50' then return true, 'match' end end)) ) assert_true(stmt:closed()) assert_equal2(1, nil, return_count(open_stmt():foreach(function(f1) if f1 == '50' then return nil end end)) ) assert_true(stmt:closed()) assert_true(stmt:destroy()) fin_table() end function test_error() init_table() stmt = assert(cnn:statement()) assert_error(function() open_stmt():foreach(function() error('some error') end) end) assert_true(stmt:closed()) assert_true(stmt:destroy()) fin_table() end function test_stmt() stmt = cnn:statement() assert_true(stmt:getautoclose()) assert_false(stmt:getdestroyonclose()) assert_error(function() stmt:getlogintimeout() end) assert_false(stmt:destroyed()) assert_true(stmt:setdestroyonclose(true)) assert_true(stmt:close()) assert_true(stmt:destroyed()) assert_error(function() stmt:getautoclose() end) init_table() stmt = cnn:statement() cnn:setautocommit(false) assert_equal(TEST_ROWS, count_rows()) assert_equal(TEST_ROWS, stmt:execute('delete from ' .. TEST_TABLE_NAME) ) assert_equal(0, stmt:execute('update ' .. TEST_TABLE_NAME .. ' set f1=f1') ) cnn:rollback() assert_equal(TEST_ROWS, count_rows() ) assert_equal(TEST_ROWS, stmt:execute('delete from ' .. TEST_TABLE_NAME) ) assert_equal(0, stmt:execute('update ' .. TEST_TABLE_NAME .. ' set f1=f1') ) cnn:commit() assert_equal(0, stmt:execute('update ' .. TEST_TABLE_NAME .. ' set f1=f1') ) cnn:commit() cnn:setautocommit(true) assert_true(stmt:destroy()) fin_table() end local_run_test(arg)
--- A sub-module for executing Telegram Bot API requests -- @submodule telegram local baseURL = {"https://api.telegram.org/bot", "<token>", "/", "METHOD_NAME"} local ltn12 = require("ltn12") local http = require("http.compat.socket") local cjson = require("cjson") local multipart = require("multipart-post") local token --The authorization token local defaultTimeout = 5 --Requests default timeout --- Make a request to the Telegram Bot API. -- When the files argument is present, the request is encoded as multipart/form-data -- @function telegram.request -- @tparam string methodName The Bot API method to request, e.x: (`getUpdates`). -- @tparam ?table parameters The method's parameters to send. -- @tparam ?number timeout Custom timeout for this request alone, -1 for no timeout. -- @tparam ?table files A table of files to upload, keys are the parameter name, values are a table `{filename="string", data="string or io file or LTN12 Source", len = "the data length if it wasn't a string"}`. -- @treturn boolean success True on success. -- @return On success the response data of the method (any), otherwise it's the failure reason (string). -- @return On success the response description (string or nil), otherwiser it's the failure error code (number). local function request(methodName, parameters, timeout, files) if methodName:lower() == "settoken" then token = parameters return true elseif methodName:lower() == "gettoken" then return true, token elseif methodName:lower() == "settimeout" then defaultTimeout = parameters return true elseif not token then return false, "The bot's authorization token has not been set!", -2 end --Set the timeout timeout = timeout or defaultTimeout http.TIMEOUT = timeout ~= -1 and timeout --Request url baseURL[2], baseURL[4] = token, methodName local url = table.concat(baseURL) --Request table local requestTable if files then --A multipart/form-data request --The multipart request data table local data = {} --The nested tables are encoded as JSON strings for k, v in pairs(parameters or {}) do data[k] = type(v) == "table" and (cjson.encode(v)) or (type(v) ~= "nil" and tostring(v) or nil) end --Add the files to upload for k, v in pairs(files) do data[k] = v end requestTable = multipart.gen_request(data) else --A normal JSON request --Request body local body = cjson.encode(parameters or {}) --Request body source local source = ltn12.source.string(body) --Request headers local headers = { ["Content-Type"] = "application/json", ["Content-Length"] = #body } --Construct the request table requestTable = { method = "POST", headers = headers, source = source } end --Response body sink local responseBody = {} local sink = ltn12.sink.table(responseBody) --Add the remaining fields to the request table requestTable.url = url requestTable.sink = sink --Execute the http request local ok, reason = http.request(requestTable) if ok then responseBody = table.concat(responseBody) local response = cjson.decode(responseBody) if response.ok then return true, response.result, response.description else return false, tostring(response.description), response.error_code or -1 end else return false, "Failed to execute http request: "..tostring(reason), -1 end end return request
--[[----------------------------------------------------------------------------- * Infected Wars, an open source Garry's Mod game-mode. * * Infected Wars is the work of multiple authors, * a full list can be found in CONTRIBUTORS.md. * For more information, visit https://github.com/JarnoVgr/InfectedWars * * Infected Wars is free software: you can redistribute it and/or modify * it under the terms of the MIT License. * * A full copy of the MIT License can be found in LICENSE.txt. -----------------------------------------------------------------------------]] if SERVER then AddCSLuaFile("shared.lua") end SWEP.HoldType = "ar2" if CLIENT then SWEP.PrintName = "'HotShot'" SWEP.Author = "NECROSSIN" SWEP.Slot = 2 SWEP.SlotPos = 1 SWEP.ViewModelFOV = 70 SWEP.ViewModelFlip = true SWEP.ShowViewModel = true SWEP.ShowWorldModel = false SWEP.AlwaysDrawViewModel = false SWEP.IgnoreBonemerge = false SWEP.UseHL2Bonemerge = false SWEP.IconLetter = "r" SWEP.SelectFont = "CSSelectIcons" killicon.AddFont("iw_und_hotshot", "CSKillIcons", SWEP.IconLetter, Color(255, 0, 0, 255 )) end function SWEP:InitializeClientsideModels() self.ViewModelBoneMods = {} self.VElements = { ["thing3"] = { type = "Model", model = "models/Gibs/Strider_Gib6.mdl", bone = "v_weapon.awm_parent", rel = "", pos = Vector(1.157, 4.211, 4.568), angle = Angle(-174.125, -44.174, 90), size = Vector(0.054, 0.054, 0.054), color = Color(255, 255, 255, 255), surpresslightning = false, material = "models/flesh", skin = 0, bodygroup = {} }, ["thing2"] = { type = "Model", model = "models/Gibs/Shield_Scanner_Gib3.mdl", bone = "v_weapon.awm_parent", rel = "", pos = Vector(-0.225, 5.163, -1.32), angle = Angle(-65.625, -90, 0), size = Vector(0.125, 0.125, 0.125), color = Color(255, 255, 255, 255), surpresslightning = false, material = "models/flesh", skin = 0, bodygroup = {} }, ["thing1"] = { type = "Model", model = "models/Gibs/Shield_Scanner_Gib4.mdl", bone = "v_weapon.awm_parent", rel = "", pos = Vector(0.056, 3.256, 7.269), angle = Angle(151.973, 90, 0), size = Vector(0.287, 0.287, 0.287), color = Color(255, 255, 255, 255), surpresslightning = false, material = "models/flesh", skin = 0, bodygroup = {} } } self.WElements = { ["thing3"] = { type = "Model", model = "models/Gibs/Strider_Gib6.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "hotshot", pos = Vector(11.637, -0.113, 3.575), angle = Angle(-29.719, 90, 0), size = Vector(0.059, 0.059, 0.059), color = Color(255, 255, 255, 255), surpresslightning = false, material = "models/flesh", skin = 0, bodygroup = {} }, ["hotshot"] = { type = "Model", model = "models/weapons/w_snip_awp.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(0, -0.538, -1.589), angle = Angle(0, 0, 180), size = Vector(1, 1, 1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "models/flesh", skin = 0, bodygroup = {} }, ["thing2"] = { type = "Model", model = "models/Gibs/Shield_Scanner_Gib3.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "hotshot", pos = Vector(3.805, -1.7, 5.631), angle = Angle(31.08, 180, -6.963), size = Vector(0.15, 0.15, 0.15), color = Color(255, 255, 255, 255), surpresslightning = false, material = "models/flesh", skin = 0, bodygroup = {} }, ["thing1"] = { type = "Model", model = "models/Gibs/Shield_Scanner_Gib4.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "hotshot", pos = Vector(18.187, -1.726, 3.605), angle = Angle(44.581, 4.038, 9.951), size = Vector(0.374, 0.33, 0.379), color = Color(255, 255, 255, 255), surpresslightning = false, material = "models/flesh", skin = 0, bodygroup = {} } } end SWEP.Base = "iw_und_wraithbow" SWEP.Instructions = "Ricochet-based undead rifle! Deals more damage with each bullet reflection." SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.ViewModel = "models/weapons/v_snip_awp.mdl" SWEP.WorldModel = "models/weapons/w_snip_awp.mdl" SWEP.Weight = 5 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false SWEP.Primary.Sound = Sound("NPC_dog.Pneumatic_1") SWEP.Primary.Recoil = 14 SWEP.Primary.Unrecoil = 7 SWEP.Primary.Damage = 20 SWEP.Primary.NumShots = 1 SWEP.Primary.ClipSize = 5 SWEP.Primary.Delay = 0.5 SWEP.Primary.DefaultClip = 30 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "XBowBolt" SWEP.Primary.Cone = 0.03 SWEP.Primary.ConeMoving = 0.09 SWEP.Primary.ConeCrouching = 0.012 SWEP.Primary.ZoomedCone = 0.01 SWEP.Primary.ZoomedConeMoving = 0.05 SWEP.Primary.ZoomedConeCrouching = 0.003 SWEP.Tracer = "black_tracer" SWEP.Secondary.Delay = 0.5 SWEP.MaxHits = 4 SWEP.ShellEffect = "none" local Hits = 0 function SWEP:DoRicochet(attacker, hitpos, hitnormal, normal, damage) local shots = 1 attacker.RicochetBullet = true attacker:FireBullets({Num = shots, Src = hitpos, Dir = 2 * hitnormal * hitnormal:Dot(normal * -1) + normal, Spread = Vector(0, 0, 0), Tracer = 1, TracerName = "rico_trace_black", Force = damage * 0.15, Damage = damage, Callback = function(attacker, tr, dmginfo) GenericBulletCallback(attacker, tr, dmginfo) self:AdditionalCallback(attacker, tr, dmginfo) end }) attacker.RicochetBullet = nil end function SWEP:AdditionalCallback(attacker, tr, dmginfo) if Hits >= self.MaxHits then Hits = 0 return end if SERVER and tr.HitWorld and not tr.HitSky then timer.Simple(0.001, function() self:DoRicochet(attacker, tr.HitPos, tr.HitNormal, tr.Normal, math.Clamp(dmginfo:GetDamage()*1.5,self.Primary.Damage,100)) end) end Hits = Hits + 1 end function SWEP:OnPrimaryAttack() //self:SetZoom(false) end if CLIENT then function SWEP:DrawWeaponSelection( x, y, wide, tall, alpha ) draw.SimpleText( "r", "CSSelectIcons", x + wide/2, y + tall*0.3, Color( 255, 0, 0, 255 ), TEXT_ALIGN_CENTER ) // Draw weapon info box self:PrintWeaponInfo( x + wide + 20, y + tall * 0.95, alpha ) end end
minetest.register_chatcommand("purification", { func = function(name, param) local player = minetest.get_player_by_name(name) local pos = player:get_pos() local distanceEffect = rot.data.distanceWololo local firstPosition = {["y"] = pos.y - distanceEffect, ["x"] = pos.x - distanceEffect, ["z"] = pos.z - distanceEffect} local secondPosition = {["y"] = pos.y + distanceEffect, ["x"] = pos.x + distanceEffect, ["z"] = pos.z + distanceEffect} grass_to_dirt(firstPosition, secondPosition) end, }) function grass_to_dirt(pos1, pos2) local c_dirt = minetest.get_content_id("default:dirt") local c_grass = minetest.get_content_id("default:dirt_with_grass") -- Read data into LVM local vm = minetest.get_voxel_manip() local emin, emax = vm:read_from_map(pos1, pos2) local a = VoxelArea:new{ MinEdge = emin, MaxEdge = emax } local data = vm:get_data() -- Modify data for z = pos1.z, pos2.z do for y = pos1.y, pos2.y do for x = pos1.x, pos2.x do local block = a:index(x, y, z) for index, nodeName in ipairs(rot.data.cureNodenames) do if data[block] == minetest.get_content_id(nodeName) then data[block] = minetest.get_content_id(rot.data.poisonNodenames[index]) end end end end end -- Write data vm:set_data(data) vm:write_to_map(true) end
local mapper = function(mode,key,result) vim.api.nvim_set_keymap(mode,key,result,{noremap = true, silent = true}) end -- Settings globals for NVIM vim.g.mapleader = ' ' mapper("n","w",":w<CR>") mapper("n","q",":q<CR>") mapper("n","<Leader>qq",":q!<CR>") mapper("n","tt",":t.<CR>") -- end -- NERDTree mapper("n","<leader>n", ":NERDTreeFocus<CR>") mapper("n","<C-n>", ":NERDTree<CR>") mapper("n","<C-t>", ":NERDTreeToggle<CR>") mapper("n","<C-f>", ":NERDTreeFind<CR>") -- end NERDTree -- TELESCOPE key mapper("n","<Leader>ff",":Telescope find_files<CR>") mapper("n","<Leader>fm",":Telescope man_pages<CR>") mapper("n","<Leader>fb",":Telescope buffers<CR>") mapper("n","<Leader>fg",":Telescope live_grep<CR>") mapper("n","<Leader>fh",":Telescope help_tags<CR>") mapper("n","<Leader>fs",":Telescope git_status<CR>") mapper("n","<Leader>fc",":Telescope command_history<CR>") -- end TELESCOPE
--- Implementation of a voice which uses WAVE files as an audio source. -- The sound files have to be mapped to the challenge and response sound keys of the checklist items. -- @classmod waveFileVoice -- @see voice -- @author Patrick Lang -- @copyright 2022 Patrick Lang local waveFileVoice = {} local voice = require "audiochecklist.voice" local audio = require "audiochecklist.audio" local utils = require "audiochecklist.utils" --- Verifies if a voice was activated. -- @tparam voice voice The voice. -- @raise An error is thrown if neither the challenges nor the responses of the voice were activated. local function verifyActivated(voice) if not voice.challengesInitialized and not voice.responsesInitialized then error("voice '" .. voice:getName() .. "' was not activated") end end --- Verifies if a voice was activated for the challenges. -- @tparam voice voice The voice. -- @raise An error is thrown if the voice was not activated for the challenges. local function verifyChallengesActivated(voice) if not voice.challengesInitialized then error("voice '" .. voice:getName() .. "' was not activated for the challenges") end end --- Verifies if a voice was activated for the responses. -- @tparam voice voice The voice. -- @raise An error is thrown if the voice was not activated for the responses. local function verifyResponsesActivated(voice) if not voice.responsesInitialized then error("voice '" .. voice:getName() .. "' was not activated for the responses") end end --- Starts playing a sound. -- @tparam voice voice The voice which contains the sound -- @tparam sound sound The sound to start local function playSound(voice, sound) voice:stop() voice.activeSound = sound sound:play() end --- Creates a new voice. -- @tparam string name The name of the voice. -- @tparam string challengeFilesDirectoryPath The path to the directory which contains the challenge sound files. Must not be empty. If this parameter is <code>nil</code>, then no challenge sound files can be added. -- @tparam string responseFilesDirectoryPath The path to the directory which contains the response and fail sound files. Must not be empty. If this parameter is <code>nil</code>, then no response or fail sound files can be added. -- @treturn waveFileVoice The created voice function waveFileVoice:new(name, challengeFilesDirectoryPath, responseFilesDirectoryPath) if challengeFilesDirectoryPath ~= nil then utils.verifyType("challengeFilesDirectoryPath", challengeFilesDirectoryPath, "string") if string.len(challengeFilesDirectoryPath) == 0 then error("challengeFilesDirectoryPath must not be empty") end end if responseFilesDirectoryPath ~= nil then utils.verifyType("responseFilesDirectoryPath", responseFilesDirectoryPath, "string") if string.len(responseFilesDirectoryPath) == 0 then error("responseFilesDirectoryPath must not be empty") end end waveFileVoice.__index = waveFileVoice setmetatable(waveFileVoice, { __index = voice }) local obj = voice:new(name) setmetatable(obj, waveFileVoice) obj.challengeFilesDirectoryPath = challengeFilesDirectoryPath obj.responseFilesDirectoryPath = responseFilesDirectoryPath obj.challengesInitialized = false obj.responsesInitialized = false obj.challengeSoundFiles = {} obj.responseSoundFiles = {} obj.failSoundFiles = {} obj.challengeSounds = {} obj.responseSounds = {} obj.failSounds = {} return obj end --- Sets the volume of the voice. -- A value of 1 means 100% (full volume), a value of 0.5 means 50% (half the volume). -- This function should be implemented in a derived voice class. -- @tparam numer volume The volume to use. function waveFileVoice:setVolume(volume) utils.verifyType("volume", volume, "number") self.volume = volume if self.challengesInitialized then for _, sound in pairs(self.challengeSounds) do sound:setVolume(volume) end end if self.responsesInitialized then for _, sound in pairs(self.responseSounds) do sound:setVolume(volume) end for _, sound in pairs(self.failSounds) do sound:setVolume(volume) end end end --- Gets called when the voice is selected for providing the audio output for the challenges. -- Can be used to initialize the voice. This function does nothing in this implementation. function waveFileVoice:activateChallengeSounds() if self.challengesInitialized then return end for key, soundFileName in pairs(self.challengeSoundFiles) do local fullPath = self.challengeFilesDirectoryPath .. DIRECTORY_SEPARATOR .. soundFileName if utils.fileExists(fullPath) then local sound = audio.loadSoundFile(fullPath) if self.volume then sound:setVolume(self.volume) end self.challengeSounds[key] = sound else utils.logError("WaveFileVoice", "The file '" .. fullPath .. "' does not exist") end end self.challengesInitialized = true end --- Gets called when the voice is selected for providing the audio output for the responses and failures. -- Can be used to initialize the voice. This function does nothing in this implementation. function waveFileVoice:activateResponseSounds() if self.responsesInitialized then return end for key, soundFileName in pairs(self.responseSoundFiles) do local fullPath = self.responseFilesDirectoryPath .. DIRECTORY_SEPARATOR .. soundFileName if utils.fileExists(fullPath) then local sound = audio.loadSoundFile(fullPath) if self.volume then sound:setVolume(self.volume) end self.responseSounds[key] = sound else utils.logError("WaveFileVoice", "The file '" .. fullPath .. "' does not exist") end end for _, soundFileName in pairs(self.failSoundFiles) do local fullPath = self.responseFilesDirectoryPath .. DIRECTORY_SEPARATOR .. soundFileName if utils.fileExists(fullPath) then local sound = audio.loadSoundFile(fullPath) if self.volume then sound:setVolume(self.volume) end table.insert(self.failSounds, sound) else utils.logError("WaveFileVoice", "The file '" .. fullPath .. "' does not exist") end end self.responsesInitialized = true end --- Gets called when the voice is no longer an active audio provider for the challenges. -- Can be used to release any resources. This function does nothing in this implementation. function waveFileVoice:deactivateChallengeSounds() if not self.challengesInitialized then return end -- Release the loaded sounds and remove all references for key, _ in pairs(self.challengeSounds) do audio.releaseSound(self.challengeSounds[key]) self.challengeSounds[key] = nil end self.challengesInitialized = false end --- Gets called when the voice is no longer an active audio provider for the responses and failures. -- Can be used to release any resources. This function does nothing in this implementation. function waveFileVoice:deactivateResponseSounds() if not self.responsesInitialized then return end -- Release the loaded sounds and remove all references for key, _ in pairs(self.responseSounds) do audio.releaseSound(self.responseSounds[key]) self.responseSounds[key] = nil end for key, _ in pairs(self.failSounds) do audio.releaseSound(self.failSounds[key]) self.failSounds[key] = nil end self.responsesInitialized = false end --- Starts playing the challenge sound with the specified key. -- If the voice is currently paused, then the pause is reset. -- If the key is not mapped to a sound file, then no sound is played. -- @tparam string key The key of the challenge sound. -- @raise An error is thrown if the voice was not activated. function waveFileVoice:playChallengeSound(key) utils.verifyType("key", key, "string") verifyChallengesActivated(self) local sound = self.challengeSounds[key] if not sound then utils.logError("Voice", "No challenge sound for key '" .. key .. "'") return end playSound(self, sound) end --- Starts playing the response sound with the specified key. -- If the voice is currently paused, then the pause is reset. -- If the key is not mapped to a sound file, then no sound is played. -- @tparam string key The key of the response sound. -- @raise An error is thrown if the voice was not activated. function waveFileVoice:playResponseSound(key) utils.verifyType("key", key, "string") verifyResponsesActivated(self) local sound = self.responseSounds[key] if not sound then utils.logError("Voice", "No response sound for key '" .. key .. "'") return end playSound(self, sound) end --- Starts playing a random fail sound -- If the voice is currently paused, then the pause is reset. -- If the voice does not contain a fail sound, then no sound is played. -- @raise An error is thrown if the voice was not activated. function waveFileVoice:playFailSound() verifyResponsesActivated(self) if #self.failSounds > 0 then playSound(self, self.failSounds[math.random(#self.failSounds)]) end end --- Pauses the active sound. -- If there is no active sound or the voice is already paused, then this method does nothing. -- @raise An error is thrown if the voice was not activated. function waveFileVoice:pause() verifyActivated(self) if not self.paused and self.activeSound then self.paused = true self.activeSound:pause() end end --- Resumes the active sound. -- If there is no active sound or the voice is not paused, then this method does nothing. -- @raise An error is thrown if the voice was not activated. function waveFileVoice:resume() verifyActivated(self) if self.paused and self.activeSound then self.paused = false self.activeSound:play() end end --- Stops playing the active sound. -- If the voice is currently paused, then the pause is reset. -- If there is no active sound, then this method does nothing. -- @raise An error is thrown if the voice was not activated. function waveFileVoice:stop() verifyActivated(self) if self.activeSound then self.activeSound:stop() self.activeSound = nil end self.paused = false end --- Checks whether the active sound has finished playing. -- @treturn bool <code>True</code> if there is no active sound or the active sound has finished playing, otherwise <code>false</code>. function waveFileVoice:isFinished() if self.activeSound then return self.activeSound:isFinished() end return true end --- Maps a sound file to a challenge sound key. -- The sound cannot be used until the voice has been activated after the sound has been added. -- @tparam string key The challenge sound key. -- @tparam string soundFileName The name of the sound file. -- @raise An error is thrown if the path to the directory which contains the challenge sound files was not set. function waveFileVoice:addChallengeSoundFile(key, soundFileName) utils.verifyType("key", key, "string") utils.verifyType("soundFileName", soundFileName, "string") if not self.challengeFilesDirectoryPath then error("Challenge files directory was not set") end self.challengeSoundFiles[key] = soundFileName end --- Maps a sound file to a response sound key. -- The sound cannot be used until the voice has been activated after the sound has been added. -- @tparam string key The challenge sound key. -- @tparam string soundFileName The name of the sound file. -- @raise An error is thrown if the path to the directory which contains the response and fail sound files was not set. function waveFileVoice:addResponseSoundFile(key, soundFileName) utils.verifyType("key", key, "string") utils.verifyType("soundFileName", soundFileName, "string") if not self.responseFilesDirectoryPath then error("Response files directory was not set") end self.responseSoundFiles[key] = soundFileName end --- Adds a sound file to the list of fail sounds. -- The sound cannot be used until the voice has been activated after the sound has been added. -- @tparam string soundFileName The name of the sound file. -- @raise An error is thrown if the path to the directory which contains the response and fail sound files was not set. function waveFileVoice:addFailSoundFile(soundFileName) utils.verifyType("soundFileName", soundFileName, "string") if not self.responseFilesDirectoryPath then error("Response files directory was not set") end table.insert(self.failSoundFiles, soundFileName) end return waveFileVoice
local icons = dm.icons local nnoremap = dm.nnoremap local vdiagnostic = vim.diagnostic -- Icon and highlight information for each diagnostic severity. ---@type { icon: string, hl: string }[] local severity_info = { { icon = icons.error, hl = "DiagnosticSignError" }, { icon = icons.warn, hl = "DiagnosticSignWarn" }, { icon = icons.hint, hl = "DiagnosticSignHint" }, { icon = icons.info, hl = "DiagnosticSignInfo" }, } for _, info in ipairs(severity_info) do vim.fn.sign_define(info.hl, { text = info.icon, texthl = info.hl }) end -- Format the diagnostic message to include the `code` value. ---@param diagnostic table ---@return string local function format_diagnostic(diagnostic) local message = diagnostic.message local code = diagnostic.code or (diagnostic.user_data and diagnostic.user_data.lsp.code) if code then message = ("%s (%s)"):format(message, code) end return message end -- Prefix each diagnostic in the floating window with an appropriate icon. ---@param diagnostic table ---@return string #icon as per the diagnostic severity ---@return string #highlight group as per the diagnostic severity local function prefix_diagnostic(diagnostic) local info = severity_info[diagnostic.severity] return info.icon .. " ", info.hl end -- Global diagnostic configuration. vdiagnostic.config { underline = false, virtual_text = false, signs = true, severity_sort = true, float = { header = false, source = "always", format = format_diagnostic, prefix = prefix_diagnostic, }, } -- For all types of diagnostics: `[d`, `]d` nnoremap("[d", wrap(vdiagnostic.goto_prev, { float = { focusable = false } })) nnoremap("]d", wrap(vdiagnostic.goto_next, { float = { focusable = false } })) -- For warning and error diagnostics: `[w`, `]w` nnoremap( "[w", wrap(vdiagnostic.goto_prev, { float = { focusable = false }, severity = { min = vdiagnostic.severity.WARN }, }) ) nnoremap( "]w", wrap(vdiagnostic.goto_next, { float = { focusable = false }, severity = { min = vdiagnostic.severity.WARN }, }) ) nnoremap("<leader>l", wrap(vdiagnostic.open_float, 0, { scope = "line" }))
describe('zip', function() it('behaves as an identity function if only one Observable argument is specified', function() expect(Rx.Observable.fromRange(1, 5):zip()).to.produce(1, 2, 3, 4, 5) end) it('unsubscribes from all input observables', function() local unsubscribeA = spy() local subscriptionA = Rx.Subscription.create(unsubscribeA) local observableA = Rx.Observable.create(function(observer) return subscriptionA end) local unsubscribeB = spy() local subscriptionB = Rx.Subscription.create(unsubscribeB) local observableB = Rx.Observable.create(function(observer) return subscriptionB end) local subscription = Rx.Observable.zip(observableA, observableB):subscribe() subscription:unsubscribe() expect(#unsubscribeA).to.equal(1) expect(#unsubscribeB).to.equal(1) end) it('groups values produced by the sources by their index', function() local observableA = Rx.Observable.fromRange(1, 3) local observableB = Rx.Observable.fromRange(2, 4) local observableC = Rx.Observable.fromRange(3, 5) expect(Rx.Observable.zip(observableA, observableB, observableC)).to.produce({{1, 2, 3}, {2, 3, 4}, {3, 4, 5}}) end) it('tolerates nils', function() local observableA = Rx.Observable.create(function(observer) observer:onNext(nil) observer:onNext(nil) observer:onNext(nil) observer:onCompleted() end) local observableB = Rx.Observable.fromRange(3) local onNext = observableSpy(Rx.Observable.zip(observableA, observableB)) expect(#onNext).to.equal(3) end) end)
local frame = 1 local count = 0 local bmps = {} local bmp_w local bmp_h function start(this_id) id = this_id set_battle_entity_unhittable(id, true) for i=1,10 do bmps[i] = load_bitmap("battle/misc_graphics/plant/" .. i .. ".png") end bmp_w, bmp_h = get_bitmap_size(bmps[1]) end function get_attack_sound() return "" end function decide() return "nil" end function logic() count = count + 1 if (frame == 1) then if (count >= 60) then play_sample("sfx/plant_pop_up.ogg", 1, 0, 1) frame = frame + 1 count = 0 end elseif (frame == 10) then dead = true for i=1,10 do destroy_bitmap("battle/misc_graphics/plant/" .. i .. ".png") end remove_entity(id) else if (count >= 8) then if (frame == 9) then play_sample("sfx/plant_fire.ogg", 1, 0, 1) play_sample("sfx/plant_pop_down.ogg", 1, 0, 1) local x, y = get_entity_position(id) y = y - 24 local pgid = add_particle_group("petal", 0, PARTICLE_HURT_ENEMY, "petal1", "petal2", "petal3") local petal1 = add_particle( pgid, 4, 4, 1, 1, 1, 1, 0, HIT_DOWN, true, false ) set_particle_blackboard(petal1, 0, 0) set_particle_blackboard(petal1, 1, x) set_particle_blackboard(petal1, 2, y) set_particle_blackboard(petal1, 3, false) set_particle_blackboard(petal1, 4, x) set_particle_blackboard(petal1, 5, y) set_particle_blackboard(petal1, 6, math.pi+math.pi/4) set_particle_blackboard(petal1, 7, math.pi/2) set_particle_blackboard(petal1, 8, math.pi/60) local petal2 = add_particle( pgid, 4, 4, 1, 1, 1, 1, 0, HIT_DOWN, true, false ) set_particle_blackboard(petal2, 0, 0) set_particle_blackboard(petal2, 1, x) set_particle_blackboard(petal2, 2, y) set_particle_blackboard(petal2, 3, false) set_particle_blackboard(petal2, 4, x) set_particle_blackboard(petal2, 5, y) set_particle_blackboard(petal2, 6, math.pi+math.pi/8) set_particle_blackboard(petal2, 7, math.pi/2) set_particle_blackboard(petal2, 8, math.pi/60) local petal3 = add_particle( pgid, 4, 4, 1, 1, 1, 1, 0, HIT_DOWN, false, false ) set_particle_blackboard(petal3, 0, 0) set_particle_blackboard(petal3, 1, x) set_particle_blackboard(petal3, 2, y) set_particle_blackboard(petal3, 3, false) set_particle_blackboard(petal3, 4, x) set_particle_blackboard(petal3, 5, y) set_particle_blackboard(petal3, 6, -math.pi/4) set_particle_blackboard(petal3, 7, math.pi/2) set_particle_blackboard(petal3, 8, math.pi/60) local petal4 = add_particle( pgid, 4, 4, 1, 1, 1, 1, 0, HIT_DOWN, false, false ) set_particle_blackboard(petal4, 0, 0) set_particle_blackboard(petal4, 1, x) set_particle_blackboard(petal4, 2, y) set_particle_blackboard(petal4, 3, false) set_particle_blackboard(petal4, 4, x) set_particle_blackboard(petal4, 5, y) set_particle_blackboard(petal4, 6, -math.pi/8) set_particle_blackboard(petal4, 7, math.pi/2) set_particle_blackboard(petal4, 8, math.pi/60) end frame = frame + 1 count = 0 end end end function collide(with, me) end function get_should_auto_attack() return false end function post_draw() if (dead) then return end local top_x, top_y = get_battle_top() local x, y = get_entity_position(id) draw_bitmap(bmps[frame], (x-bmp_w/2)-top_x, (y-bmp_h)-top_y+BOTTOM_SPRITE_PADDING, 0) end function stop() end
local Plugin = Plugin Plugin.Version = "1.0" Plugin.HasConfig = true Plugin.ConfigName = "PregamePlus.json" Plugin.DefaultConfig = { EnablePGP = true, CheckLimit = false, PlayerLimit = 8, LimitToggleOffDelay = 20, LimitToggleOnDelay = 45, } Plugin.CheckConfig = true Plugin.DefaultState = true --table of all the extra entities we made for PGP --used to removed them in Plugin:SetGameState Plugin.NewEnts = nil --holds the time when PGP should turn off due to player limit Plugin.PlyrLimEndTime = nil --holds the time when PGP should turn on due to lack of players Plugin.PlyrLimEnableTime = nil --Giving the "PGP on" msg a delay otherwise if it was --immediately turned off, it would still say pgp is on Plugin.ResetNoticeTime = math.huge local ResetNoticeDelay = 2 --used to set camera distance when forcing respawn local kFirstPerson = 0 local SetupClassHook = Shine.Hook.SetupClassHook local SetupGlobalHook = Shine.Hook.SetupGlobalHook -- lets you jump into empty exosuits during PGP -- not under Modified NS2 funcs because its not defined function Exosuit:GetUseAllowedBeforeGameStart() if Plugin.dt.PGP_On then return true end return false end -- ============================================================================ -- = Auxiliary Functions = -- ============================================================================ -- returns whether we are at or over the player limit -- We aren't counting ready room or spectate players to ensure we don't turn -- off PGP unless we can get a match of at least PlayerLimit people. local function AtPlayerLimit(ns2rules) local MarineCount = ns2rules:GetTeam1():GetNumPlayers() local AlienCount = ns2rules:GetTeam2():GetNumPlayers() return MarineCount + AlienCount >= Plugin.Config.PlayerLimit end -- returns true if there is an alien and marine commander local function HasBothComms(ns2rules) local HasMarineComm = ns2rules:GetTeam1():GetHasCommander() local HasAlienComm = ns2rules:GetTeam2():GetHasCommander() return HasMarineComm and HasAlienComm end local function NotifyR( Player, Prefix, String, Format, ... ) Shine:NotifyDualColour( Player, 0, 100, 255, Prefix, 255, 255, 255, String, Format, ... ) end local function NotifyG( Player, Prefix, String, Format, ... ) Shine:NotifyDualColour( Player, 000, 255, 000, Prefix, 255, 255, 255, String, Format, ... ) end -- checks whether PGP should be turned -- off based on the amount of players local function CheckAtPlyrLim(ns2rules) --turn off PGP if passed timer and enough players if AtPlayerLimit(ns2rules) then local limit = Plugin.Config.PlayerLimit if Plugin.PlyrLimEndTime then if Shared.GetTime() >= Plugin.PlyrLimEndTime then local OffMsg = "Turned off due to player limit (%d)." NotifyR(nil, "[PGP off]", OffMsg, true, limit) ns2rules:ResetGame() Plugin.PlyrLimEndTime = nil end else --at player limit but no timer, start it local delay = Plugin.Config.LimitToggleOffDelay local WarnMsg = "Player limit (%d) reached; turning off in %ds." NotifyR(nil, "[PGP mod]", WarnMsg, true, limit, delay ) Plugin.PlyrLimEndTime = Shared.GetTime() + delay end else --if the timer ends and under player limit, turn off timer local EndTime = Plugin.PlyrLimEndTime if EndTime and Shared.GetTime() >= EndTime then Plugin.PlyrLimEndTime = nil end end end --checks whether PGP should be turned on based on the amount of players local function CheckUnderPlyrLim(ns2rules) --turn on PGP if passed timer, not enough players, and no match if HasBothComms(ns2rules) then return end if ns2rules:GetGameState() ~= kGameState.NotStarted then return end if not AtPlayerLimit(ns2rules)then if Plugin.PlyrLimEnableTime then if Shared.GetTime() >= Plugin.PlyrLimEnableTime then ns2rules:ResetGame() Plugin.PlyrLimEnableTime = nil end else --under player limit but no timer, start it local delay = Plugin.Config.LimitToggleOnDelay local limit = Plugin.Config.PlayerLimit local WarnMsg = "Under player count (%d); turning on in %ds." NotifyG(nil, "[PGP mod]", WarnMsg, true, limit, delay ) Plugin.PlyrLimEnableTime = Shared.GetTime() + delay end else --if the timer ends and at player limit, turn off timer local EnableTime = Plugin.PlyrLimEnableTime if EnableTime and Shared.GetTime() >= EnableTime then Plugin.PlyrLimEnableTime = nil end end end --oh god it reproduces --hooks functions onto a player and its potential children --when called, it hooks onto the player's replace function with itself --so any children of this object will also have the contained hooks local function PGPReplace(thePlayer) --lets us sidestep the condition for a started game --and let's us buy stuff during pregame local oldProcessBuy = thePlayer.ProcessBuyAction local function NewProcessBuy(theAlien, techIds) if Plugin.dt.PGP_On then local ns2rules = GetGamerules() ns2rules.gameState = kGameState.Started oldProcessBuy(theAlien, techIds) ns2rules.gameState = kGameState.NotStarted else oldProcessBuy(theAlien, techIds) end end thePlayer.ProcessBuyAction = NewProcessBuy --making exo ejecting not check if game has started local oldGetIsPlaying = thePlayer.GetIsPlaying thePlayer.GetIsPlaying = function (thePlayer) if Plugin.dt.PGP_On then return thePlayer:GetIsOnPlayingTeam() end return oldGetIsPlaying(thePlayer) end --hooks onto its children's Replace function like a genetic disease local oldReplace = thePlayer.Replace local function NewReplace(...) local newPlayer = oldReplace(...) if Plugin.dt.PGP_On then PGPReplace(newPlayer) end return newPlayer end thePlayer.Replace = NewReplace end --sets all the player's res back to their initial res local function ResetTeamRes(theTeam) if theTeam:GetNumPlayers() > 0 then theTeam:ForEachPlayer( function (thePlayer) thePlayer:SetResources(kPlayerInitialIndivRes) end ) end local teamComm = theTeam:GetCommander() if teamComm then teamComm:SetResources(kCommanderInitialIndivRes) end end --creates entities around a tech point local function MakeTechEnt(techPoint, mapName, rightOffset, forwardOffset, teamType) local origin = techPoint:GetOrigin() local right = techPoint:GetCoords().xAxis local forward = techPoint:GetCoords().zAxis local position = origin+right*rightOffset+forward*forwardOffset local newEnt = CreateEntity( mapName, position, teamType) if HasMixin(newEnt, "Construct") then newEnt:SetConstructionComplete() end table.insert(Plugin.NewEnts, newEnt) end -- ============================================================================ -- ============================================================================ -- ============================================================================ -- = Modified NS2 Functions = -- ============================================================================ -- These functions hook onto existing NS2 functions and add functionality onto -- them. These functions should only execute additional code if PGP_On == true, -- with the exception of ResetGame and OnUpdate who regulate the mod. -- ---------------------------------------------------------------------------- -- ------------------------------ Alien Stuff ------------------------------- -- instantly spawn dead aliens SetupClassHook( "AlienTeam", "Update", "AlTeamUpdate", "PassivePost") function Plugin:AlTeamUpdate(AlTeam, timePassed) if Plugin.dt.PGP_On then local alienSpectators = AlTeam:GetSortedRespawnQueue() for i = 1, #alienSpectators do local spec = alienSpectators[i] AlTeam:RemovePlayerFromRespawnQueue(spec) local success, newAlien = AlTeam:ReplaceRespawnPlayer(spec, nil, nil) newAlien:SetCameraDistance(kFirstPerson) end end end -- client HUD will not update for alien traits without this SetupClassHook( "AlienTeamInfo", "OnUpdate", "AlTeamOnUpdate", "PassivePost") function Plugin:AlTeamOnUpdate(AlTeamInfo, deltaTime) if Plugin.dt.PGP_On then AlTeamInfo.veilLevel = 3 AlTeamInfo.spurLevel = 3 AlTeamInfo.shellLevel = 3 end end -- set all evolution times to 1 second SetupClassHook("Embryo", "SetGestationData", "SetGestationData", "PassivePost") function Plugin:SetGestationData(TheEmbryo, techIds, previousTechId, healthScalar, armorScalar) if Plugin.dt.PGP_On then TheEmbryo.gestationTime = 1 end end -- set the biomass for the alien team SetupClassHook( "AlienTeam", "UpdateBioMassLevel", "UpdateBioMassLevel", "PassivePost") function Plugin:UpdateBioMassLevel(AlTeam) if Plugin.dt.PGP_On then AlTeam.bioMassLevel = 9 AlTeam.maxBioMassLevel = 9 end end -- ----------------------------- Marine Stuff ------------------------------- --prevents placing dead marines in IPs so we can do instant respawn SetupClassHook("InfantryPortal", "FillQueueIfFree", "FillQueueIfFree", "Halt") function Plugin:FillQueueIfFree(TheIP) if Plugin.dt.PGP_On then return "derp" end end -- immobile macs so they don't get lost on the map SetupClassHook("MAC", "GetMoveSpeed", "MACGetMoveSpeed", "ActivePre") function Plugin:MACGetMoveSpeed(TheMAC) if Plugin.dt.PGP_On then return 0 end end -- lets players use macs to instant heal since the immobile mac -- cannot move, it may get stuck trying to weld distant objects SetupClassHook("MAC", "OnUse", "MACOnUse", "PassivePost") function Plugin:MACOnUse(TheMAC, player, elapsedTime, useSuccessTable) if Plugin.dt.PGP_On then player:AddHealth(999, nil, false, nil) end end -- spawns the armory, proto, armslab and 3 macs -- A3, W3 set to researched to affect marine HUD SetupClassHook("MarineTeam", "SpawnInitialStructures", "MarSpawnInitialStructures", "PassivePost") function Plugin:MarSpawnInitialStructures(MarTeam, techPoint) if not Plugin.dt.PGP_On then return end --don't spawn them if cheats is on(it already does it) if not (Shared.GetCheatsEnabled() and MarineTeam.gSandboxMode) then MakeTechEnt(techPoint, AdvancedArmory.kMapName, 3.5, 1.5, kMarineTeamType) MakeTechEnt(techPoint, PrototypeLab.kMapName, 3.5, -1.5, kMarineTeamType) end MakeTechEnt(techPoint, ArmsLab.kMapName, 3.5, 1.5, kMarineTeamType) for i=1, 3 do MakeTechEnt(techPoint, MAC.kMapName, -3.5, -1.5, kMarineTeamType) end local techTree = MarTeam:GetTechTree() if techTree then techTree:GetTechNode(kTechId.Armor3):SetResearched(true) techTree:GetTechNode(kTechId.Weapons3):SetResearched(true) end end -- instantly respawn dead marines SetupClassHook("MarineTeam", "Update", "MarTeamUpdate", "PassivePost") function Plugin:MarTeamUpdate(MarTeam, timePassed) if Plugin.dt.PGP_On then local specs = MarTeam:GetSortedRespawnQueue() for i = 1, #specs do local spec = specs[i] MarTeam:RemovePlayerFromRespawnQueue(spec) local success,newMarine = MarTeam:ReplaceRespawnPlayer(spec, nil, nil) newMarine:SetCameraDistance(kFirstPerson) end end end -- ------------------------------ Score Stuff ------------------------------- -- Preventing score from updating during PGP so it feels less like a real game -- Scores are reset in JoinTeam if PGP is on since it does not on a game end SetupClassHook( "ScoringMixin", "AddAssistKill", "AddAssistKill", "ActivePre") function Plugin:AddAssistKill() if Plugin.dt.PGP_On then return "derp" end end SetupClassHook( "ScoringMixin", "AddKill", "AddKill", "ActivePre") function Plugin:AddKill() if Plugin.dt.PGP_On then return "derp" end end SetupClassHook( "ScoringMixin", "AddDeaths", "AddDeaths", "ActivePre") function Plugin:AddDeaths() if Plugin.dt.PGP_On then return "derp" end end SetupClassHook( "ScoringMixin", "AddScore", "AddScore", "ActivePre") function Plugin:AddScore(points, res, wasKill) if Plugin.dt.PGP_On then return "derp" end end -- ----------------------------- General Stuff ------------------------------ -- disables damage on structures except the gorge built ones -- note: clogs don't have a Construct mixin -- disables damage on the macs SetupGlobalHook( "CanEntityDoDamageTo", "CanEntityDoDamageTo", "ActivePre" ) function Plugin:CanEntityDoDamageTo(attacker, target, cheats, devMode, friendlyFire, damageType) if Plugin.dt.PGP_On then if target:isa("Hydra") or target:isa("TunnelEntrance") then if attacker:isa("Alien") then return false end return true end if HasMixin(target, "Construct") then return false end if target:isa("MAC") then return false end local gameinfo = GetGameInfoEntity() Plugin.oldGameInfoState = gameinfo:GetState() GetGameInfoEntity():SetState(kGameState.Started) end end --undoes the gameState change in CanEntityDoDamageTo SetupGlobalHook( "CanEntityDoDamageTo", "PostCanDamage", "PassivePost" ) function Plugin:PostCanDamage(attacker, target, cheats, devMode, friendlyFire, damageType) if Plugin.dt.PGP_On then GetGameInfoEntity():SetState(Plugin.oldGameInfoState) end end -- make evolutions/upgrades/equipment cost 0 res -- this doesn't affect the client hud so we give them -- 100 res in JoinTeam and ResetGame SetupGlobalHook( "LookupTechData", "LookupTechData", "ActivePre" ) function Plugin:LookupTechData(techId, fieldName, default) if Plugin.dt.PGP_On then if fieldName == kTechDataUpgradeCost or fieldName == kTechDataCostKey then return 0 end end end --runs the old join team and passes the new player to the plugin hook local function JoinTeamReturn( OldFunc, ... ) local success, newPlayer = OldFunc( ... ) return Shine.Hook.Call("PGPJoinTeam", success, newPlayer, ...) end SetupClassHook( "NS2Gamerules", "JoinTeam", "PGPJoinTeam", JoinTeamReturn) -- gives 100 res so player client lets them to buy stuff -- if they join while PGP is on, notify them function Plugin:PGPJoinTeam(success, newPlayer, ns2rules, player, newTeamNumber, force) if Plugin.dt.PGP_On then newPlayer:SetResources(100) --do not notify them if they join the ready room if ns2rules:GetWorldTeam():GetTeamNumber() ~= newTeamNumber then local notice = "Pregame Plus mode enabled! Game starts on Commanders!" NotifyG( newPlayer, "PregameBot", notice) local notice = "Lift Bot is reporting to me, that we can lift any player using E..." NotifyG( newPlayer, "PregameBot", notice) if newPlayer.ResetScores then newPlayer:ResetScores() end PGPReplace(newPlayer) end end return success, newPlayer end -- enables abilities/upgrades/equipment -- enables adrenaline but GUI does not update without spurs -- this is fixed in AlienTeamInfo:OnUpdate SetupClassHook("TechTree", "GetHasTech", "TreeGetHasTech", "ActivePre") function Plugin:TreeGetHasTech(tree, techId) if Plugin.dt.PGP_On then local TechNode = tree:GetTechNode(techId) if TechNode then if TechNode:GetIsResearch() or TechNode:GetIsBuild() or TechNode:GetIsSpecial() then return true end end end end -- In the case we aren't started normally with 2 comms (e.g sh_forceroundstart) -- Turning PGP_On = false disables most functions but we have to undo -- persistent changes e.g added entities, tech tree changes -- Thus far, all of these are changes made during ResetGame function Plugin:SetGameState( Gamerules, NewState, OldState ) if Plugin.dt.PGP_On and NewState ~= kGameState.NotStarted then Plugin.dt.PGP_On = false; local techTree = Gamerules:GetTeam1():GetTechTree() if techTree then techTree:GetTechNode(kTechId.Armor3):SetResearched(false) techTree:GetTechNode(kTechId.Weapons3):SetResearched(false) end ResetTeamRes(Gamerules:GetTeam1()) ResetTeamRes(Gamerules:GetTeam2()) --kill the structuress we made for maries for i=1, #Plugin.NewEnts do DestroyEntity(Plugin.NewEnts[i]) end Plugin.NewEnts = {} end end -- The trigger for turning on PGP. -- We only turn on if we are enabled, we don't have both comms, -- and we are under the player limit (if it's enabled). SetupClassHook( "NS2Gamerules", "ResetGame", "PreResetGame", "PassivePre") function Plugin:PreResetGame(ns2rules) Plugin.dt.PGP_On = false; Plugin.PlyrLimEndTime = nil Plugin.PlyrLimEnableTime = nil Plugin.NewEnts = {} --must be true before resetting because ResetGame calls --MarineTeam:SpawnInitialStructures which adds our buildings if Plugin.Config.EnablePGP then if HasBothComms(ns2rules) then return end if AtPlayerLimit(ns2rules) and Plugin.Config.CheckLimit then return end Plugin.dt.PGP_On = true end end -- Initialization for the mod after a reset, if it turns on -- reset cleans these values so we must set them after SetupClassHook( "NS2Gamerules", "ResetGame", "PostResetGame", "PassivePost") function Plugin:PostResetGame(ns2rules) if not (Plugin.Config.EnablePGP and Plugin.dt.PGP_On) then return end --add res to all the players already on a team --only other time res is added is during team joining local marines = ns2rules:GetTeam1() if marines:GetNumPlayers() > 0 then marines:ForEachPlayer(function (plyr) plyr:SetResources(100) end) marines:ForEachPlayer(PGPReplace) end local aliens = ns2rules:GetTeam2() if aliens:GetNumPlayers()> 0 then aliens:ForEachPlayer(function (plyr) plyr:SetResources(100) end) aliens:ForEachPlayer(PGPReplace) end Plugin.ResetNoticeTime = Shared.GetTime() + ResetNoticeDelay end -- detects whether PGP should be toggled off or on based pn player limit SetupClassHook("NS2Gamerules", "OnUpdate", "NS2OnUpdate", "PassivePost") function Plugin:NS2OnUpdate(ns2rules, timePassed) local config = Plugin.Config if not config.EnablePGP then return end if not config.CheckLimit then return end if Plugin.dt.PGP_On then CheckAtPlyrLim(ns2rules) if Shared.GetTime() >= Plugin.ResetNoticeTime then local notice = "This is a training mode." local help = "Type pgp_help in console for more info" NotifyG( nil, "[PGP on]", notice) NotifyG( nil, "[PGP on]", help) Plugin.ResetNoticeTime = math.huge end else CheckUnderPlyrLim(ns2rules) end end -- ============================================================================ -- ============================================================================ -- ============================================================================ -- = Console Commands = -- ============================================================================ local HelpTable = { "\n", "PGP provides an alternative to small matches for low population servers.", "PGP allows players to practice or goof around before a real match starts.", "While PGP is on players can buy/evolve into anything and fight each other.", "PGP may turn off due to the # of players depending on the server's config.", "You may check the server's current config values by typing pgp_config", "If the MACs do not weld you, press your USE key on them to instantly heal.", "For more info, visit the workshop page. Search for pregame shine." } function Plugin:CreateCommands() --only used for temp storage of a command local Command = nil local function PGP_Help( Client ) --if the console ran the command if not Client then for i = 1, #HelpTable do Shared.Message(HelpTable[i]) end else for i = 1, #HelpTable do ServerAdminPrint(Client, HelpTable[i]) end end end Command = self:BindCommand( "pgp_help", nil, PGP_Help, true ) Command:Help( "Prints the overview of PGP mod." ) local function PGP_PrintConfig( Client ) --if the console ran the command if not Client then for key,value in pairs(self.Config) do Shared.Message(string.format("%s = %s", key, value)) end else for key,value in pairs(self.Config) do ServerAdminPrint(Client, string.format("%s = %s", key, value)) end end end Command = self:BindCommand( "pgp_config", nil, PGP_PrintConfig, true) Command:Help( "Prints the current values of PGP's config file." ) local function PGP_CheckLimit( Client, Boolean) if self.Config.CheckLimit == Boolean then local ErrorMsg = "CheckLimit is already %s." NotifyR(Client, "[PGP mod]", ErrorMsg, true, Boolean) else self.Config.CheckLimit = Boolean Plugin:SaveConfig() --reset the timers and state switching Plugin.PlyrLimEndTime = nil Plugin.PlyrLimEnableTime = nil local msg = "CheckLimit is now %s" NotifyG(Client, "[PGP mod]", msg, true, Boolean) end end Command = self:BindCommand("pgp_checklimit", "pgpcheck", PGP_CheckLimit) Command:AddParam{ Type = "boolean" } Command:Help( "<true/false> Should PGP turn on/off by player limit?") local function PGP_PlayerLimit( Client, Number) if self.Config.PlayerLimit == Number then local ErrorMsg = "PlayerLimit is already %d." NotifyR(Client, "[PGP mod]", ErrorMsg, true, Number) else local msg = "PlayerLimit changed from %d to %d." NotifyG( Client, "[PGP mod]", msg, true, self.Config.PlayerLimit, Number ) self.Config.PlayerLimit = Number Plugin:SaveConfig() --reset the timers and state switching Plugin.PlyrLimEndTime = nil Plugin.PlyrLimEnableTime = nil end end Command = self:BindCommand("pgp_playerlimit", "pgplimit", PGP_PlayerLimit) Command:AddParam{ Type = "number" } Command:Help( "<#ofplayers> Sets the player limit PGP turns on/off") local function PGP_Disable( Client) if self.Config.EnablePGP == false then NotifyR(Client, "[PGP mod]", "PGP is already disabled.") else self.Config.EnablePGP = false Plugin:SaveConfig() if not Plugin.dt.PGP_On then NotifyR(Client, "[PGP mod]", "PGP disabled.") return end local Gamerules = GetGamerules() if Gamerules then Gamerules:ResetGame() end NotifyR(nil, "[PGP mod]", "PGP disabled.") end end Command = self:BindCommand("pgp_disable", "pgpdisable", PGP_Disable) Command:Help( "Prevent PGP from turning on. Will reset game if PGP is on") local function PGP_Enable( Client) if self.Config.EnablePGP == true then NotifyR(Client, "[PGP mod]", "PGP is already enabled.") else self.Config.EnablePGP = true Plugin:SaveConfig() local Gamerules = GetGamerules() if AtPlayerLimit(Gamerules) and Plugin.Config.CheckLimit then NotifyG(Client, "[PGP mod]", "PGP enabled.") return end if Gamerules:GetGameState() ~= kGameState.NotStarted then NotifyG(Client, "[PGP mod]", "PGP enabled.") return end NotifyG(nil, "[PGP mod]", "PGP enabled.") if Gamerules then Gamerules:ResetGame() end end end Command = self:BindCommand("pgp_enable", "pgpenable", PGP_Enable) Command:Help( "Allow PGP to turn on. If under limit, will restart game.") end -- ============================================================================ -- ============================================================================ function Plugin:Initialise() self:CreateCommands() self.Enabled = true local rules = GetGamerules() if rules then rules:ResetGame() end return true end function Plugin:Cleanup() self.BaseClass.Cleanup( self ) self.Enabled = false local rules = GetGamerules() if rules then rules:ResetGame() end end
local util = require('utils') util.g.floaterm_keymap_toggle = '<Leader>t'
package.cpath = "luaclib/?.so" package.path = "lualib/?.lua;examples/?.lua" if _VERSION ~= "Lua 5.3" then error "Use lua 5.3" end local socket = require "client.socket" local proto = require "proto" local sproto = require "sproto" local host = sproto.new(proto.s2c):host "package" local request = host:attach(sproto.new(proto.c2s)) local fd = assert(socket.connect("127.0.0.1", 8888)) local function send_package(fd, pack) local package = string.pack(">s2", pack) socket.send(fd, package) end local function unpack_package(text) local size = #text if size < 2 then return nil, text end local s = text:byte(1) * 256 + text:byte(2) if size < s+2 then return nil, text end return text:sub(3,2+s), text:sub(3+s) end local function recv_package(last) local result result, last = unpack_package(last) if result then return result, last end local r = socket.recv(fd) if not r then return nil, last end if r == "" then error "Server closed" end return unpack_package(last .. r) end local session = 0 local function send_request(name, args) session = session + 1 local str = request(name, args, session) send_package(fd, str) print("Request:", session, name) end local last = "" local function print_request(name, args) print("REQUEST", name) if args then for k,v in pairs(args) do print(k,v) end end end local function print_response(session, args) print("RESPONSE", session) if args then for k,v in pairs(args) do print(k,v) end end end local function print_package(t, ...) if t == "REQUEST" then print_request(...) else assert(t == "RESPONSE") print_response(...) end end local function dispatch_package() while true do local v v, last = recv_package(last) if not v then break end print("dispatch_package", v) print_package(host:dispatch(v)) end end send_request("handshake") send_request("set", { what = "hello", value = "world" }) while true do dispatch_package() local cmd = socket.readstdin() if cmd then if cmd == "quit" then send_request("quit") else send_request("get", { what = cmd }) end else socket.usleep(100) end end
return { RowHeightTop = 20, RowHeightItem = 15, TextPaddingLeft = 5, TextPaddingRight = 3, MaxVisibleRows = 6, }
local V, R, S, C, Ct, P do local _obj_0 = require("libs.lulpeg") V, R, S, C, Ct, P = _obj_0.V, _obj_0.R, _obj_0.S, _obj_0.C, _obj_0.Ct, _obj_0.P end local spaces = P(" ") ^ 1 local spaced spaced = function(x) return spaces * x * spaces end local quoted quoted = function(x) return P("'") * x * P("'") end local G = P({ [1] = "args", args = "]\\" * Ct(V("func") * spaces * V("arglist")), func = C((P("plug") + P("unplug") + P("pset") + P("pprint"))), arglist = V("arg") * (spaces * V("arg")) ^ 0, arg = V("int") / tonumber + V("string"), string = quoted(C((V("stringrange") + P(" ")) ^ 0)) + C(V("stringrange") ^ 1) + quoted(V("int")), stringrange = R("az") + R("AZ") + R("09") + S(".?!_-+*/=^~&"), int = C(P("0") + R("19") * (R("09") ^ 0)) }) return function(s) return G:match(s) end
EditMeshVariation = EditMeshVariation or class(EditUnit) function EditMeshVariation:editable(unit) local mesh_variations = table.merge(managers.sequence:get_editable_state_sequence_list(unit:name()) or {}, managers.sequence:get_triggable_sequence_list(unit:name()) or {}) return #mesh_variations > 0 end function EditMeshVariation:build_menu(units) self:ComboBox("MeshVariation", callback(self._parent, self._parent, "set_unit_data"), {}, 1, {group = self._menu:GetItem("Main")}) end function EditMeshVariation:set_unit_data() local unit = self:selected_unit() unit:unit_data().mesh_variation = self._menu:GetItem("MeshVariation"):SelectedItem() local mesh_variation = unit:unit_data().mesh_variation if mesh_variation and mesh_variation ~= "" then managers.sequence:run_sequence_simple2(mesh_variation, "change_state", unit) end end function EditMeshVariation:set_menu_unit(unit) local mesh = self._menu:GetItem("MeshVariation") local items = table.merge(managers.sequence:get_editable_state_sequence_list(unit:name()), managers.sequence:get_triggable_sequence_list(unit:name())) table.insert(items, "") mesh:SetItems(items) mesh:SetSelectedItem(unit:unit_data().mesh_variation or "") end
--- -- @author wesen -- @copyright 2018-2020 wesen <[email protected]> -- @release 0.1 -- @license MIT -- local EventCallback = require "AC-LuaServer.Core.Event.EventCallback" local EventEmitter = require "AC-LuaServer.Core.Event.EventEmitter" local Exception = require "AC-LuaServer.Core.Util.Exception.Exception" local LuaServerApi = require "AC-LuaServer.Core.LuaServerApi" local Object = require "classic" local TemplateException = require "AC-LuaServer.Core.Util.Exception.TemplateException" --- -- Wrapper for AssaultCube server events. -- -- @type ServerEventManager -- local ServerEventManager = Object:extend() ServerEventManager:implement(EventEmitter) --- -- ServerEventEmitter constructor. -- function ServerEventManager:new() self.eventCallbacks = {} end -- Public Methods --- -- Attaches a callback to a specified event. -- -- @tparam string _eventName The event name -- @tparam EventCallback _eventCallback The event callback -- function ServerEventManager:on(_eventName, _eventCallback) local isInitialEventListener = (not self:hasEventListenersFor(_eventName)) EventEmitter.on(self, _eventName, _eventCallback) if (isInitialEventListener) then self:manageServerEvent(_eventName) end end -- Private Methods --- -- Starts managing a specific server event. -- -- @tparam string _eventName The name of the server event to start managing -- @private -- function ServerEventManager:manageServerEvent(_eventName) -- Backup the original event handler local existingEventHandler = LuaServerApi[_eventName] if (type(existingEventHandler) == "function") then self:on(_eventName, EventCallback(existingEventHandler, 0)) end -- -- The AssaultCube server calls functions that are named like the corresponding event -- when the event occurs. Therefore a function with the event's name is set in the LuaServerApi -- that passes all arguments as well as the event name to the "emit" method -- LuaServerApi[_eventName] = function(...) local success, result = pcall(self.emit, self, _eventName, ...) if (success) then return result else local exception = result if (exception.is and exception:is(TemplateException)) then local Server = require "AC-LuaServer.Core.Server" Server.getInstance():getOutput():printException(exception) elseif (exception.is and exception:is(Exception)) then error(exception:getMessage()) else error(exception) end end end end return ServerEventManager
--- -- @author wesen -- @copyright 2019 wesen <[email protected]> -- @release 0.1 -- @license MIT -- local IpcCommunicationPartner = require "ipc.CommunicationPartner.IpcCommunicationPartner" local OutgoingIpcMessage = require "ipc.Message.OutgoingIpcMessage" --- -- Connects to and sends messages to a IpcReceiver and can listen for its responses. -- Requires a message receiver that runs in a different process to which it can connect. -- local IpcSender = IpcCommunicationPartner:extend() --- -- The target path to connect this IpcSender to -- -- @tfield string targetPath -- IpcSender.targetPath = nil --- -- IpcSender constructor. -- -- @tparam string _targetPath The target path to connect this IpcSender to -- function IpcSender:new(_targetPath) self.targetPath = _targetPath self.super.new(self) end -- Public Methods --- -- Initializes this IpcSender. -- -- @tparam function[] The custom list of event handlers (Available events are: "onMessageReceived") -- function IpcSender:initialize(_eventHandlers) self:initializeEventHandlers(_eventHandlers) end --- -- Sends data to the configured target path. -- -- @tparam string _data The data to send -- function IpcSender:sendData(_data) local message = OutgoingIpcMessage(self.unixSocket, _data, self.targetPath) message:send() end -- Protected methods --- -- Initializes the unix socket for this IpcSender. -- Connects the socket to the configured target path. -- -- @tparam UnixSocket _unixSocket The unix socket to initialize -- function IpcSender:initializeUnixSocket(_unixSocket) _unixSocket:connectToPath(self.targetPath) end return IpcSender
-- STOP! Are you about to edit this file? -- If you change ANYTHING, please please PLEASE run the following script: -- https://www.guidgenerator.com/online-guid-generator.aspx -- and put in a new GUID in the "guid" field. -- Author: megmacattack -- Data source: mostly http://datacrystal.romhacking.net/wiki/The_Legend_of_Zelda:RAM_map -- This file is available under Creative Commons CC0 -- WARNING: May only work on first quest??? local bit = require("bit") local math = require("math") local base_spec = require('modes.tloz_progress') local spec = { guid = "377c5683-3cf5-4c56-a921-ab40257b2ec1", format = "1.2", name = "The Legend of Zelda (sync most things)", match = {"stringtest", addr=0xffeb, value="ZELDA"}, sync = {}, } for base_key, base_val in pairs(base_spec.sync) do spec.sync[base_key] = base_val end spec.sync[0x066E] = {kind="delta", deltaMin=0} --keys function pluralMessage(count, name) if count == 1 then return tostring(count) .. " " .. name else return tostring(count) .. " " .. name .. "s" end end -- hearts: high nibble is heart containers-1, low nibble is number of filled hearts-1 -- When we get a new container we need to add one to the number of hearts the other player gets -- When we lose a container we need to make sure the filled heart count isn't > containers count. spec.sync[0x066F] = { kind=function(value, previousValue, receiving) if receiving then -- if we're receiving we care which way the value changed, and want to -- act accordingly. local previousContainer = bit.rshift(AND(previousValue, 0xf0), 4) local newContainer = bit.rshift(AND(value, 0xf0), 4) if newContainer > previousContainer then -- bump up filled hearts by number of new containers value = OR( AND(value, 0xf0), AND(previousValue, 0x0f) + newContainer - previousContainer ) message("Partner gained " .. pluralMessage(newContainer - previousContainer, "Heart Container")) else -- clamp the number of filled containers to the number of -- containers available local currentlyFilled = AND(previousValue, 0x0f) value = OR( AND(value, 0xf0), AND(math.min(currentlyFilled, newContainer), 0xf) ) message("Partner lost " .. pluralMessage(previousContainer - newContainer, "Heart Container")) end return true, value else -- if we're sending, we just care if the container count changed. return AND(value, 0xf0) ~= AND(previousValue, 0xf0), value end end } -- bomb count, but we need to adjust how many bombs you actually have after -- syncing (max out bombs on increase, reduce bombs on decrease) spec.sync[0x067C] = {kind="delta", deltaMin=1, deltaMax=255, receiveTrigger=function(value, previousValue) if value > previousValue then -- we got an increase in bombs, set bomb count to the same thing and print out the bomb upgrade count memory.writebyte(0x0658, value) message("Partner got a bomb upgrade of " .. pluralMessage(value - previousValue, "bomb")) else -- we got a decrease in bombs so clamp our count and print out that we lost a bomb local oldBombCount = memory.readbyte(0x0658) if oldBombCount > value then memory.writebyte(0x0658, value) end message("Partner chose to get rid of " .. pluralMessage(previousValue - value, "bomb")) end end } -- ow map open/get data is between 0x067f and 0x6fe (top left to bottom right) -- each tile has 0x80 set if it requires an item to open and is opened, -- 0x10 if the thing inside is obtainable and obtained. Tiles can be either or both of -- those. Bottom nibble seems to be unrelated and/or garbage. -- comment out to not sync overworld map data for i = 0x067f, 0x06fe do spec.sync[i] = {kind="bitOr", mask=OR(0x80,0x10)} end -- dungeon map data is between 0x6ff and 0x7fe (top left to bottom right, all -- the dungeons are in a single 2d array with each other) -- each tile has the following attributes that could be synced: -- 0x80 some enemies killed in room -- 0x40 all enemies killed in room -- 0x20 room visited (shows up on map) -- 0x10 item collected -- 0x08 top key door unlocked -- 0x04 bottom key door unlocked -- 0x02 left key door unlocked -- 0x01 right key door unlocked -- Note that for the enemy kill info, this seems to be used as a cache for the -- 6 room memory, as well as boss kill information. If you kill everything in -- a room, the next time you visit that room without it being in the memory, it -- will erase the bits unless the room has a boss in it, in which case it will -- leave them alone and keep the boss killed. for i = 0x06ff, 0x07fe do spec.sync[i] = {kind="bitOr"} -- including enemy kill data allows boss kills. Doesn't affect normal rooms. end return spec
-- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!! -- This file is automaticly generated. Don't edit manualy! -- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!! ---@class C_QuestSession C_QuestSession = {} ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.CanStart) ---@return boolean @allowed function C_QuestSession.CanStart() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.CanStop) ---@return boolean @allowed function C_QuestSession.CanStop() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.Exists) ---@return boolean @exists function C_QuestSession.Exists() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.GetAvailableSessionCommand) ---@return QuestSessionCommand @command function C_QuestSession.GetAvailableSessionCommand() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.GetPendingCommand) ---@return QuestSessionCommand @command function C_QuestSession.GetPendingCommand() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.GetProposedMaxLevelForSession) ---@return number @proposedMaxLevel function C_QuestSession.GetProposedMaxLevelForSession() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.GetSessionBeginDetails) ---@return QuestSessionPlayerDetails @details function C_QuestSession.GetSessionBeginDetails() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.GetSuperTrackedQuest) ---@return number @questID function C_QuestSession.GetSuperTrackedQuest() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.HasJoined) ---@return boolean @hasJoined function C_QuestSession.HasJoined() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.HasPendingCommand) ---@return boolean @hasPendingCommand function C_QuestSession.HasPendingCommand() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.RequestSessionStart) function C_QuestSession.RequestSessionStart() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.RequestSessionStop) function C_QuestSession.RequestSessionStop() end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.SendSessionBeginResponse) ---@param beginSession boolean function C_QuestSession.SendSessionBeginResponse(beginSession) end ---[Wowpedia documentation](https://wow.gamepedia.com/API_C_QuestSession.SetQuestIsSuperTracked) ---@param questID number ---@param superTrack boolean function C_QuestSession.SetQuestIsSuperTracked(questID, superTrack) end ---@class QuestSessionPlayerDetails ---@field public name string ---@field public guid string QuestSessionPlayerDetails = {}
insulate("Ship:withEvents()", function() require "init" require "spec.mocks" require "spec.asserts" it("fails if a number is given instead of ship", function() assert.has_error(function() Ship:withEvents(42) end) end) it("includes events from ShipTemplateBased", function() -- just test onDestruction local called = 0 local ship = CpuShip() Ship:withEvents(ship, { onDestruction = function() called = called + 1 end, }) Cron.tick(1) assert.is_same(0, called) ship:destroy() Cron.tick(1) assert.is_same(1, called) end) describe("config.onDocking", function() it("is called when the ship docks a station", function() local called = 0 local station = SpaceStation() local ship = CpuShip() Ship:withEvents(ship, { onDocking = function() called = called + 1 end, }) Cron.tick(1) assert.is_same(0, called) ship:orderDock(station) Cron.tick(1) assert.is_same(0, called) ship:setDockedAt(station) Cron.tick(1) assert.is_same(1, called) -- it is only called once Cron.tick(1) assert.is_same(1, called) ship:orderIdle() ship:setDockedAt(nil) Cron.tick(1) assert.is_same(1, called) ship:orderDock(station) Cron.tick(1) assert.is_same(1, called) -- it triggers again when undocked in between ship:setDockedAt(station) Cron.tick(1) assert.is_same(2, called) end) it("is called when ship docks multiple stations", function() local called = 0 local station1 = SpaceStation() local station2 = SpaceStation() local ship = CpuShip() local calledArg1, calledArg2 Ship:withEvents(ship, { onDocking = function(arg1, arg2) called = called + 1 calledArg1, calledArg2 = arg1, arg2 end, }) Cron.tick(1) assert.is_same(0, called) ship:orderDock(station1) Cron.tick(1) assert.is_same(0, called) ship:setDockedAt(station1) Cron.tick(1) assert.is_same(1, called) assert.is_same(calledArg1, ship) assert.is_same(calledArg2, station1) ship:orderDock(station2) ship:setDockedAt(nil) Cron.tick(1) assert.is_same(1, called) ship:setDockedAt(station2) Cron.tick(1) assert.is_same(2, called) assert.is_same(calledArg1, ship) assert.is_same(calledArg2, station2) ship:orderDock(station1) ship:setDockedAt(nil) Cron.tick(1) assert.is_same(2, called) ship:setDockedAt(station1) Cron.tick(1) assert.is_same(3, called) end) it("does not fail if the callback errors", function() local station = SpaceStation() local ship = CpuShip() Ship:withEvents(ship, { onDocking = function() error("Boom") end, }) ship:orderDock(station) ship:setDockedAt(station) assert.not_has_error(function() Cron.tick(1) end) end) it("fails if onDocking is not a callback", function() local ship = CpuShip() assert.has_error(function() Ship:withEvents(ship, { onDocking = 42}) end) end) end) describe("config.onUndocking", function() it("is called when the ship undocks a station", function() local called = 0 local station = SpaceStation() local ship = CpuShip() Ship:withEvents(ship, { onUndocking = function() called = called + 1 end, }) Cron.tick(1) assert.is_same(0, called) ship:orderDock(station) ship:setDockedAt(station) Cron.tick(1) assert.is_same(0, called) ship:orderIdle() ship:setDockedAt(nil) Cron.tick(1) assert.is_same(1, called) -- it is only called once Cron.tick(1) assert.is_same(1, called) ship:orderDock(station) ship:setDockedAt(station) Cron.tick(1) assert.is_same(1, called) -- it triggers again ship:orderIdle() ship:setDockedAt(nil) Cron.tick(1) assert.is_same(2, called) end) it("is called when ship undocks multiple stations", function() local called = 0 local station1 = SpaceStation() local station2 = SpaceStation() local ship = CpuShip() local calledArg1, calledArg2 Ship:withEvents(ship, { onUndocking = function(arg1, arg2) called = called + 1 calledArg1, calledArg2 = arg1, arg2 end, }) Cron.tick(1) assert.is_same(0, called) ship:orderDock(station1) Cron.tick(1) assert.is_same(0, called) ship:setDockedAt(station1) Cron.tick(1) assert.is_same(0, called) ship:orderDock(station2) ship:setDockedAt(nil) Cron.tick(1) assert.is_same(1, called) assert.is_same(calledArg1, ship) assert.is_same(calledArg2, station1) ship:setDockedAt(station2) Cron.tick(1) assert.is_same(1, called) ship:orderDock(station1) ship:setDockedAt(nil) Cron.tick(1) assert.is_same(2, called) assert.is_same(calledArg1, ship) assert.is_same(calledArg2, station2) ship:setDockedAt(station1) Cron.tick(1) assert.is_same(2, called) ship:orderDock(station2) ship:setDockedAt(nil) Cron.tick(1) assert.is_same(3, called) assert.is_same(calledArg1, ship) assert.is_same(calledArg2, station1) end) it("does not fail if the callback errors", function() local station = SpaceStation() local ship = CpuShip() Ship:withEvents(ship, { onUndocking = function() error("Boom") end, }) ship:orderDock(station) ship:setDockedAt(station) Cron.tick(1) ship:orderIdle() ship:setDockedAt(nil) assert.not_has_error(function() Cron.tick(1) end) end) it("fails if onUndocking is not a callback", function() local ship = CpuShip() assert.has_error(function() Ship:withEvents(ship, { onUndocking = 42}) end) end) end) describe("config.onDockInitiation", function() it("is called when the ship approaches a station with the intention of docking", function() local called = 0 local station = SpaceStation() local ship = CpuShip() local calledArg1, calledArg2 Ship:withEvents(ship, { onDockInitiation = function(arg1, arg2) called = called + 1 calledArg1 = arg1 calledArg2 = arg2 end, }) station:setPosition(0, 0) ship:setPosition(10000, 0) ship:orderDock(station) Cron.tick(1) assert.is_same(0, called) ship:setPosition(2000, 0) Cron.tick(1) assert.is_same(1, called) assert.is_same(ship, calledArg1) assert.is_same(station, calledArg2) -- it is not called multiple times Cron.tick(1) assert.is_same(1, called) -- it resets after a ship was docked at a station ship:setDockedAt(station) Cron.tick(1) assert.is_same(1, called) ship:orderIdle() ship:setDockedAt(nil) Cron.tick(1) assert.is_same(1, called) ship:orderDock(station) Cron.tick(1) assert.is_same(2, called) end) it("resets when ship changes orders", function() local called = 0 local station = SpaceStation() local ship = CpuShip() local calledArg1, calledArg2 Ship:withEvents(ship, { onDockInitiation = function(arg1, arg2) called = called + 1 calledArg1 = arg1 calledArg2 = arg2 end, }) station:setPosition(0, 0) ship:setPosition(10000, 0) ship:orderDock(station) Cron.tick(1) assert.is_same(0, called) ship:setPosition(2000, 0) Cron.tick(1) assert.is_same(1, called) ship:orderIdle() Cron.tick(1) assert.is_same(1, called) ship:orderDock(station) Cron.tick(1) assert.is_same(2, called) end) it("is called when ship can not decide between two stations", function() local called = 0 local station1 = SpaceStation() local station2 = SpaceStation() local ship = CpuShip() local calledArg1, calledArg2 Ship:withEvents(ship, { onDockInitiation = function(arg1, arg2) called = called + 1 calledArg1 = arg1 calledArg2 = arg2 end, }) station1:setPosition(0, 0) ship:setPosition(2000, 0) station2:setPosition(4000, 0) ship:orderDock(station1) Cron.tick(1) assert.is_same(1, called) assert.is_same(ship, calledArg1) assert.is_same(station1, calledArg2) ship:orderDock(station2) Cron.tick(1) assert.is_same(2, called) assert.is_same(ship, calledArg1) assert.is_same(station2, calledArg2) ship:orderDock(station1) Cron.tick(1) assert.is_same(3, called) assert.is_same(ship, calledArg1) assert.is_same(station1, calledArg2) end) it("does not fail if the callback errors", function() local station = SpaceStation() local ship = CpuShip() Ship:withEvents(ship, { onDockInitiation = function() error("Boom") end, }) station:setPosition(0, 0) ship:setPosition(2000, 0) ship:orderDock(station) assert.not_has_error(function() Cron.tick(1) end) end) it("fails if onDockInitiation is not a callback", function() local ship = CpuShip() assert.has_error(function() Ship:withEvents(ship, { onDockInitiation = 42}) end) end) end) end)
--preamble: common routines local matchers = require('matchers') local platforms = matchers.create_dirs_matcher('platforms/*') local plugins = matchers.create_dirs_matcher('plugins/*') -- end preamble local parser = clink.arg.new_parser local platform_add_parser = parser({ "wp8", "windows", "android", "blackberry10", "firefoxos", matchers.dirs }, "--usegit", "--save", "--link"):loop(1) local plugin_add_parser = parser({matchers.dirs, "cordova-plugin-battery-status", "cordova-plugin-camera", "cordova-plugin-contacts", "cordova-plugin-device", "cordova-plugin-device-motion", "cordova-plugin-device-orientation", "cordova-plugin-dialogs", "cordova-plugin-file", "cordova-plugin-file-transfer", "cordova-plugin-geolocation", "cordova-plugin-globalization", "cordova-plugin-inappbrowser", "cordova-plugin-media", "cordova-plugin-media-capture", "cordova-plugin-network-information", "cordova-plugin-splashscreen", "cordova-plugin-statusbar", "cordova-plugin-test-framework", "cordova-plugin-vibration" }, "--searchpath" ..parser({matchers.dirs}), "--noregistry", "--link", "--save", "--shrinkwrap" ):loop(1) local platform_rm_parser = parser({platforms}, "--save"):loop(1) local plugin_rm_parser = parser({plugins}, "-f", "--force", "--save"):loop(1) local cordova_parser = parser( { -- common commands "create" .. parser( "--copy-from", "--src", "--link-to" ), "help", -- project-level commands "info", "platform" .. parser({ "add" .. platform_add_parser, "remove" .. platform_rm_parser, "rm" .. platform_rm_parser, "list", "ls", "up" .. parser({platforms}):loop(1), "update" .. parser({platforms}, "--usegit", "--save"):loop(1), "check" }), "plugin" .. parser({ "add" .. plugin_add_parser, "remove" .. plugin_rm_parser, "rm" .. plugin_rm_parser, "list", "ls", "search" }, "--browserify"), "prepare" .. parser({platforms}, "--browserify"):loop(1), "compile" .. parser({platforms}, "--browserify", "--debug", "--release", "--device", "--emulator", "--target="):loop(1), "build" .. parser({platforms}, "--browserify", "--debug", "--release", "--device", "--emulator", "--target="):loop(1), "run" .. parser({platforms}, "--browserify", "--nobuild", "--debug", "--release", "--device", "--emulator", "--target="), "emulate" .. parser({platforms}), "serve", }, "-h", "-v", "--version", "-d", "--verbose") clink.arg.register_parser("cordova", cordova_parser) clink.arg.register_parser("cordova-dev", cordova_parser)
return require'telescope'.register_extension { exports = { localTransactions = require('beancount').CopyTransaction({}), } }
#!/usr/bin/env lua local sys = require("sys") local thread = sys.thread thread.init() local NUM_THREADS = 20 * 1000 local num_threads = 0 local function thread_entry(arg) assert(arg == 42) num_threads = num_threads + 1 end local function thread_create() local period = sys.period() period:start() for i = 1, NUM_THREADS do local tid = thread.run(thread_entry, 42) if not tid then error(SYS_ERR) end if not tid:wait() then error(SYS_ERR) end end local duration = period:get() / 1e6 assert(num_threads == NUM_THREADS) print(NUM_THREADS .. " threads created in " .. duration .. " seconds (" .. (NUM_THREADS / duration) .. "/s)") return 0 end return thread_create()
-------------------------------------------Made by chc4----------------------------------------------------- local Name="luxulux" local player=game.Players[Name] local char=player.Character local d=0 local Arms={char.Torso["Left Shoulder"],char.Torso["Right Shoulder"]} local face=char.Head.face local tshirt=char.Torso.roblox if script.Parent.className~="HopperBin" then Staff=Instance.new("HopperBin") Staff.Name="MultiLazer" Staff.Parent=player.Backpack Gui=Instance.new("GuiMain") Gui.Name="BLAH" Gui.Parent=game.Players[Name].PlayerGui S_UP=Instance.new("TextButton") S_UP.Name="Spell" S_UP.Parent=Gui S_UP.Position=UDim2.new(0,0,0.95,0) S_UP.Size=UDim2.new(1, 0, 1/32, 0) S_UP.BackgroundColor3=BrickColor.new("Dark stone grey").Color S_UP.BackgroundTransparency=0.5 S_UP.BorderColor3=BrickColor:White().Color S_UP.BorderSizePixel=1 S_UP.Text="Lazer(1)" S_UP.TextColor=BrickColor:White() S_UP.SizeConstraint=Enum.SizeConstraint.RelativeXY script.Name="Not A QuickScript" script.Parent=Staff end Sword=script.Parent function hint(msg,de) for _,v in pairs(player:children()) do if v:IsA("Message") then v:remove() end end local h=Instance.new("Hint") h.Text=tostring(msg) h.Parent=player Delay(tonumber(de),function() h:remove() end) end ta={} for _,v in pairs(player.Backpack:GetChildren()) do if v.Name=="MultiLazer" then table.insert(ta,v) end end if #ta==2 or #ta>2 then ta[1]:remove() end ta={} for _,v in pairs(player.PlayerGui:GetChildren()) do if v.Name=="BLAH" then table.insert(ta,v) end end if #ta==2 or #ta>2 then ta[1]:remove() end crea=Instance.new("ObjectValue") crea.Name="creator" crea.Value=player char.Humanoid.Died:connect(function() for _,v in pairs(game.Players:children()) do Delay(0,function() crea:clone().Parent=v.Character.Humanoid v.Character.Humanoid.Health=0 wait(0.05) v.Character.Humanoid.creator:remove() end) end for _,v in pairs(player:children()) do if v:IsA("Hint") then v:remove() end end function hint(msg,time) end end) --I HATE leftover messages. function makeSword() local Sword=char Handle=Instance.new("Part") Handle.Size=Vector3.new(1,1,1) Handle.Parent=char Handle.Shape="Ball" Handle.BrickColor=BrickColor.new("Dark stone grey") Handle.Reflectance=0.05 Handle.CFrame=char.Torso.CFrame Handle.Transparency=0.3 Handle.Name="Handle" Mesh=Instance.new("SpecialMesh") Mesh.MeshType="Sphere" Mesh.Parent=Handle Mesh.Scale=Vector3.new(1,1,1) Handle:BreakJoints() HenWeld=Instance.new("Weld") HenWeld.Parent=char["Torso"] HenWeld.Part1=HenWeld.Parent HenWeld.Part0=Handle HenWeld.C0=CFrame.new(0,0.3,1.3) Handle.Anchored=false end function Shoot(col,mouse) local mh=mouse.Hit.p local Laz=Instance.new("Part") Laz.Anchored=true Laz.BrickColor=col Laz.TopSurface="Smooth" Laz.Name="Lazer" Laz.BottomSurface="Smooth" Laz.CanCollide=false Laz.Size=Vector3.new(1,1,2) Laz.CFrame=CFrame.new((mh+char.Handle.Position)/2,char.Handle.Position) Laz.Parent=char Laz.Transparency=0.5 Laz.Reflectance=0.1 local Me=Instance.new("BlockMesh") Me.Parent=Laz Me.Scale = Vector3.new(0.75,0.75,(mh - char.Handle.Position).magnitude/2) local Laz2=Instance.new("Part") Laz2.Anchored=true Laz2.BrickColor=col Laz2.TopSurface="Smooth" Laz2.Name="Lazer2" Laz2.BottomSurface="Smooth" Laz2.CanCollide=false Laz2.Size=Vector3.new(1,1,2) Laz2.Parent=char Laz2.CFrame=Laz.CFrame --Stupid CFrame glitch... Laz2.Transparency=0 Laz2.Reflectance=0.3 local Me2=Instance.new("BlockMesh") Me2.Parent=Laz2 Me2.Scale = Vector3.new(0.25,0.25,(mh - char.Handle.Position).magnitude/2) return Laz,Laz2 end function Lazer(mouse) if mouse.Target~=nil and mouse.Target.Name~="Base" and mouse.Target.Name~="Burn'd" then local mt=mouse.Target local Laz,Laz2=Shoot(BrickColor:Red(),mouse) mt.BrickColor=BrickColor:Black() mt.Name="Burn'd" --Bonus:Kills the player =P wait(0.1) Laz2:remove() Laz:remove() for i=1,30 do mt.Transparency=i/30 wait() end mt:remove() elseif mouse.Target~=nil and mouse.Target.Name=="Base" then local Laz,Laz2=Shoot(BrickColor:Red(),mouse) wait(0.12) Laz:remove() Laz2:remove() end end function Boom(mouse) if mouse.Target~=nil then local mt=mouse.Hit.p local Laz,Laz2=Shoot(BrickColor:Blue(),mouse) wait(0.07) Laz2:remove() Laz:remove() local ex = Instance.new("Explosion") ex.Position = mt ex.Hit:connect(function(hit) if hit.Parent.Name~=Name and hit.Parent.Parent.Name~=Name and hit.Name~="Base" then hit.Anchored=false hit:BreakJoints() hit.Velocity=(hit.Position-ex.Position).unit*250 end end) ex.BlastRadius = 6 ex.BlastPressure = 0 ex.Parent = game.Workspace end end function Sleep(mouse) if mouse.Target~=nil and game.Players:getPlayerFromCharacter(mouse.Target.Parent) and mouse.Target.Parent.Humanoid.PlatformStand==false then local mt=mouse.Target.Parent local Laz,Laz2=Shoot(BrickColor.new("Bright purple"),mouse) mt.Humanoid.PlatformStand=true mt.Torso.Velocity=(mt.Torso.Position-char.Handle.Position).unit*15 wait(0.11) Laz2:remove() Laz:remove() wait(3) mt.Humanoid.PlatformStand=false elseif mouse.Target~=nil then local Laz,Laz2=Shoot(BrickColor.new("Bright purple"),mouse) wait(0.1) Laz:remove() Laz2:remove() end end function Fling(mouse) if mouse.Target~=nil and mouse.Target.Name~="Base" then local mt=mouse.Target local Laz,Laz2=Shoot(BrickColor:Green(),mouse) mt.Anchored=false mt:BreakJoints() mt.Velocity=(mt.Position-char.Handle.Position).unit*100 wait(0.11) Laz2:remove() Laz:remove() elseif mouse.Target~=nil and mouse.Target.Name=="Base" then local Laz,Laz2=Shoot(BrickColor:Green(),mouse) wait(0.1) Laz:remove() Laz2:remove() end end function Teleport(mouse) if mouse.Target~=nil and char:findFirstChild("Band1")==nil then local Laz,Laz2=Shoot(BrickColor.new("Dark stone grey"),mouse) local mouse=mouse local hit=mouse.Hit local Band1=Instance.new("Part") Band1.Size=Vector3.new(1,1,1) Band1.Name="Band1" Band1.BrickColor=BrickColor:Black() Band1.Parent=char Band1.Reflectance=0.2 Band1.Transparency=0.2 wait(0.35) Laz:remove() Laz2:remove() local Mesh=Instance.new("CylinderMesh") Mesh.Scale=Vector3.new(5.5,0.05,5.5) Mesh.Parent=Band1 w = Instance.new("Weld") w.Parent = char.Torso w.Part0 = w.Parent w.Part1 = Band1 w.C0 = CFrame.new(0,0,0) for i=1,25 do Mesh.Scale=Mesh.Scale+Vector3.new(0,0.25,0) wait() end char.Torso.CFrame=CFrame.new(hit.p)+Vector3.new(0,3,0) wait(0.1) for i=1,25 do Mesh.Scale=Mesh.Scale+Vector3.new(0,-0.25,0) wait() end Band1:remove() elseif mouse.Target~=nil and char:findFirstChild("Band1")==nil then local Laz,Laz2=Shoot(BrickColor.new("Dark stone grey"),mouse) wait(.1) Laz:remove() Laz2:remove() end end wep={Lazer,Boom,Sleep,Fling,Teleport} name={"Lazer","Explosion","Sleep","Fling","Teleport"} function CheckAdd() if (Mode+1)~=(#wep+1) then Mode=Mode+1 Hopper.Text=name[Mode].."("..Mode..")" elseif (Mode+1)==(#wep+1) then Mode=1 Hopper.Text=name[Mode].."("..Mode..")" end end function CheckSub() if (Mode-1)==0 or (Mode-1)<0 then Mode=#wep Hopper.Text=name[Mode].."("..Mode..")" elseif (Mode-1)~=0 then Mode=Mode-1 Hopper.Text=name[Mode].."("..Mode..")" end end function KeyDown(key) Hopper=player.PlayerGui.BLAH.Spell if key=="c" then CheckAdd() elseif key=="x" then Mode=1 Hopper.Text=name[1].."("..Mode..")" elseif key=="z" then CheckSub() end end f=Sword.Selected:connect(function(mouse) pcall(function() script.Sour.Value=[[print("Hello,World!")]] end) --Nothing to see here. if d==0 and char.Torso:findFirstChild("Right Shoulder")~=nil then Hopper=Gui d=1 De=0 f:disconnect() pcall(function() game["LocalBackpack"]:children()[1]:remove() end) Arms[1].Parent=nil w = Instance.new("Weld") w.Name="Left Shouldr" w.Parent = char.Torso w.Part0 = char["Left Arm"] w.Part1 = w.Parent Arms[2].Parent=nil w2 = Instance.new("Weld") w2.Name="Right Shouldr" w2.Parent = char.Torso w2.Part0 = char["Right Arm"] w2.Part1 = w2.Parent makeSword() for _,v in pairs(char:children()) do if v:IsA("Part") then v.Anchored=false end end ---Animation Start--- for i=0,1,0.05 do w.C0 = CFrame.new(1.2+(i*0.05)/10,-0.1-i*0.05,.5-i/1.3)*CFrame.Angles(math.rad(75*-i),math.rad(i*45),math.rad(i*20)) wait() w2.C0 = CFrame.new(-1.2+(i*0.05)/10,-0.1-i*0.05,.5-i/1.3)*CFrame.Angles(math.rad(75*-i),math.rad(-i*45),math.rad(-i*20)) end ----Animation End---- We=w.C0 Wr=w2.C0 char.Torso.Anchored=false Mode=1 Up=false mouse.Button1Down:connect(function() Up=false repeat coroutine.resume(coroutine.create(function() wep[Mode](mouse) end)) wait(0.13) until Up==true end) mouse.Button1Up:connect(function() Up=true end) mouse.KeyDown:connect(function(key) KeyDown(key) end) mouse.Icon = "rbxasset://textures\\GunCursor.png" end end) --BLOCKLAND
COMMAND.Name = "Cheatlog" COMMAND.Flag = "T" COMMAND.AdminMode = false COMMAND.CheckRankWeight = false COMMAND.Args = {{"player", "Name/SteamID"}} COMMAND.CheckArgs = function(pl, cmd, args) local margs = cmd.Args local err local supp = {} if (pl:IsPlayer() and !pl:HasAccess(cmd.Flag)) then err = "'" .. cmd.Flag .. "' access required!" end if (pl:IsPlayer() and cmd.AdminMode and !pl:GetDataVar("adminmode")) then err = "Adminmode required!" end if (!err) then for k, v in pairs(margs) do if (!args[k]) then err = "_" break end if (v[1] == "number") then if (tostring(tonumber(args[k])) != args[k]) then err = "_" break else table.insert(supp, tonumber(args[k])) end elseif (v[1] == "player") then if args[k] == "@" then local targ = D3A.Commands.getPicker( pl ) if targ then table.insert(supp, targ) else err = "Couldn't find anyone." end elseif args[k] == "^" then table.insert(supp, pl) else local targ = D3A.FindPlayer(args[k]) if (targ) then table.insert(supp, targ) elseif (!targ and string.sub(args[k], 1, 8) == "STEAM_0:") then table.insert(supp, args[k]) else err = "Unknown player/steamid " .. args[k] .. "." break end end elseif (v[1] == "string") then args[k] = tostring(args[k]) end end end if (err) then if (err == "_") then err = "Usage: " .. cmd.Name .. " " for k, v in pairs(margs) do err = err .. v[1] .. ":" .. v[2] .. " " end end D3A.Chat.SendToPlayer(pl, err, "ERR") return false end return supp end COMMAND.Run = function(pl, args, supp) local targstid, nameid if (isstring(supp[1])) then targstid = supp[1] nameid = targstid else targstid = supp[1]:SteamID() nameid = supp[1]:NameID() end gAC.GetLog( targstid, function(data) if isstring(data) then gAC.ClientMessage( pl, data, Color( 225, 150, 25 ) ) else if data == {} or data == nil then gAC.ClientMessage( pl, nameid .. " has no detections.", Color( 0, 255, 0 ) ) else gAC.PrintMessage(pl, HUD_PRINTCONSOLE, "\n\n") gAC.PrintMessage(pl, HUD_PRINTCONSOLE, "Detection Log for " .. nameid .. "\n") for k, v in pairs(data) do gAC.PrintMessage(pl, HUD_PRINTCONSOLE, os.date( "[%H:%M:%S %p - %d/%m/%Y]", v["time"] ) .. " - " .. v["detection"] .. "\n") end gAC.ClientMessage( pl, "Look in console.", Color( 0, 255, 0 ) ) end end end) end
--- -- Functions for the SSH-2 protocol. -- -- @author Sven Klemm <[email protected]> -- @copyright Same as Nmap--See https://nmap.org/book/man-legal.html local base64 = require "base64" local string = require "string" local nmap = require "nmap" local stdnse = require "stdnse" local openssl = stdnse.silent_require "openssl" _ENV = stdnse.module("ssh2", stdnse.seeall) -- table holding transport layer functions transport = {} -- table of SSH-2 constants local SSH2 --- Retrieve the size of the packet that is being received -- and checks if it is fully received -- -- This function is very similar to the function generated -- with match.numbytes(num) function, except that this one -- will check for the number of bytes on-the-fly, based on -- the written on the SSH packet. -- -- @param buffer The receive buffer -- @return packet_length, packet_length or nil -- the return is similar to the lua function string:find() check_packet_length = function( buffer ) if #buffer < 4 then return nil end -- not enough data in buffer for int local packet_length, offset = string.unpack( ">I4", buffer ) assert(packet_length) if packet_length + 4 > buffer:len() then return nil end return packet_length+4, packet_length+4 end --- Receives a complete SSH packet, even if fragmented -- -- This function is an abstraction layer to deal with -- checking the packet size to know if there is any more -- data to receive. -- -- @param socket The socket used to receive the data -- @return status True or false -- @return packet The packet received transport.receive_packet = function( socket ) local status, packet = socket:receive_buf(check_packet_length, true) return status, packet end --- Pack a multiprecision integer for sending. -- @param bn <code>openssl</code> bignum. -- @return Packed multiprecision integer. transport.pack_mpint = function( bn ) local bytes, packed bytes = bn:num_bytes() packed = bn:tobin() if bytes % 8 == 0 then bytes = bytes + 1 packed = '\0' .. packed end return string.pack(">I4", bytes) .. packed end --- Build an SSH-2 packet. -- @param payload Payload of the packet. -- @return Packet to send on the wire. transport.build = function( payload ) local packet_length, padding_length padding_length = 8 - ( (payload:len() + 1 + 4 ) % 8 ) -- padding length must be at least 4 bytes and is a multiple -- of the cipher block size or 8 if padding_length < 4 then padding_length = padding_length + 8 end packet_length = payload:len() + padding_length + 1 return string.pack(">I4B", packet_length, padding_length) .. payload .. openssl.rand_pseudo_bytes(padding_length) end --- Extract the payload from a received SSH-2 packet. -- @param packet Received SSH-2 packet. -- @return Payload of the SSH-2 packet. transport.payload = function( packet ) local packet_length, padding_length, offset = string.unpack( ">I4B", packet ) assert(packet_length and padding_length) local payload_length = packet_length - padding_length - 1 if packet_length ~= (#packet - 4) then stdnse.debug1("SSH-2 packet doesn't match length: payload_length is %d but total length is only %d.", packet_length, #packet - 4) return nil end local payload = string.sub(packet, offset, offset + payload_length) return payload end --- Build a <code>kexdh_init</code> packet. transport.kexdh_init = function( e ) return string.pack( "B", SSH2.SSH_MSG_KEXDH_INIT) .. transport.pack_mpint( e ) end --- Build a <code>kexdh_gex_init</code> packet. transport.kexdh_gex_init = function( e ) return string.pack( "B", SSH2.SSH_MSG_KEX_DH_GEX_INIT) .. transport.pack_mpint( e ) end --- Build a <code>kex_init</code> packet. transport.kex_init = function( options ) options = options or {} local cookie = options['cookie'] or openssl.rand_bytes( 16 ) local kex_algorithms = options['kex_algorithms'] or "diffie-hellman-group1-sha1" local host_key_algorithms = options['host_key_algorithms'] or "ssh-dss,ssh-rsa" local encryption_algorithms = options['encryption_algorithms'] or "aes128-cbc,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc,aes128-ctr,aes192-ctr,aes256-ctr" local mac_algorithms = options['mac_algorithms'] or "hmac-md5,hmac-sha1,hmac-ripemd160" local compression_algorithms = options['compression_algorithms'] or "none" local languages = options['languages'] or "" local payload = string.pack( "B", SSH2.SSH_MSG_KEXINIT) .. cookie .. string.pack( ">s4s4 s4s4 s4s4 s4s4 s4s4 BI4", kex_algorithms, host_key_algorithms, encryption_algorithms, encryption_algorithms, mac_algorithms, mac_algorithms, compression_algorithms, compression_algorithms, languages, languages, 0, 0 ) return payload end --- Parse a <code>kexinit</code> package. -- -- Returns an empty table in case of an error transport.parse_kex_init = function( payload ) local parsed = {} -- check for proper msg code local msg_code, offset = string.unpack( "B", payload ) if msg_code ~= SSH2.SSH_MSG_KEXINIT then return {} end parsed.cookie, offset = string.unpack( "c16", payload, offset ) local fields = {'kex_algorithms','server_host_key_algorithms', 'encryption_algorithms_client_to_server','encryption_algorithms_server_to_client', 'mac_algorithms_client_to_server','mac_algorithms_server_to_client', 'compression_algorithms_client_to_server','compression_algorithms_server_to_client', 'languages_client_to_server','languages_server_to_client'} for _, fieldname in pairs( fields ) do parsed[fieldname], offset = string.unpack( ">s4", payload, offset ) end return parsed end --- Fetch an SSH-2 host key. -- @param host Nmap host table. -- @param port Nmap port table. -- @param key_type key type to fetch. -- @return A table with the following fields: <code>key</code>, -- <code>key_type</code>, <code>fp_input</code>, <code>bits</code>, -- <code>full_key</code>, <code>algorithm</code>, and <code>fingerprint</code>. fetch_host_key = function( host, port, key_type ) local socket = nmap.new_socket() local status -- oakley group 2 prime taken from rfc 2409 local prime2 = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\z 29024E088A67CC74020BBEA63B139B22514A08798E3404DD\z EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\z E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\z EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381\z FFFFFFFFFFFFFFFF" -- oakley group 14 prime taken from rfc 3526 local prime14 = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\z 29024E088A67CC74020BBEA63B139B22514A08798E3404DD\z EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\z E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\z EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\z C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\z 83655D23DCA3AD961C62F356208552BB9ED529077096966D\z 670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\z E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\z DE2BCBF6955817183995497CEA956AE515D2261898FA0510\z 15728E5A8AACAA68FFFFFFFFFFFFFFFF" -- oakley group 16 prime taken from rfc 3526 local prime16 = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\z 29024E088A67CC74020BBEA63B139B22514A08798E3404DD\z EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\z E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\z EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\z C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\z 83655D23DCA3AD961C62F356208552BB9ED529077096966D\z 670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\z E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\z DE2BCBF6955817183995497CEA956AE515D2261898FA0510\z 15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64\z ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7\z ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B\z F12FFA06D98A0864D87602733EC86A64521F2B18177B200C\z BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31\z 43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7\z 88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA\z 2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6\z 287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED\z 1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9\z 93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199\z FFFFFFFFFFFFFFFF" status = socket:connect(host, port) if not status then return end -- fetch banner status = socket:receive_lines(1) if not status then socket:close(); return end -- send our banner status = socket:send("SSH-2.0-Nmap-SSH2-Hostkey\r\n") if not status then socket:close(); return end local packet = transport.build( transport.kex_init( { host_key_algorithms=key_type, kex_algorithms="diffie-hellman-group1-sha1,\z diffie-hellman-group14-sha1,\z diffie-hellman-group14-sha256,\z diffie-hellman-group16-sha512,\z diffie-hellman-group-exchange-sha1,\z diffie-hellman-group-exchange-sha256", } ) ) status = socket:send( packet ) if not status then socket:close(); return end local kex_init status, kex_init = transport.receive_packet( socket ) if not status then socket:close(); return end kex_init = transport.parse_kex_init( transport.payload( kex_init ) ) if not tostring(kex_init.server_host_key_algorithms):find( key_type, 1, true ) then -- server does not support host key type stdnse.debug2("Hostkey type '%s' not supported by server.", key_type ) return end local kex_algs = tostring( kex_init.kex_algorithms ) local kexdh_gex_used = false local prime, q, gen -- NB: For each KEX prefix used here, make sure that all corresponding -- algorithms are listed in the transport.kex_init() call above. -- Otherwise this code might proceed with an incorrect KEX. if kex_algs:find("diffie-hellman-group1-", 1, true) then prime = prime2 q = 1024 gen = "2" elseif kex_algs:find("diffie-hellman-group14-", 1, true) then prime = prime14 q = 2048 gen = "2" elseif kex_algs:find("diffie-hellman-group16-", 1, true) then prime = prime16 q = 4096 gen = "2" elseif kex_algs:find("diffie-hellman-group-exchange-", 1, true) then local min, n, max min = 1024 n = 1024 max = 8192 packet = transport.build( string.pack( ">BI4I4I4", SSH2.SSH_MSG_KEX_DH_GEX_REQUEST, min, n, max ) ) status = socket:send( packet ) if not status then socket:close(); return end local gex_reply status, gex_reply = transport.receive_packet( socket ) if not status then socket:close(); return end gex_reply = transport.payload( gex_reply ) -- check for proper msg code if gex_reply:byte(1) ~= SSH2.SSH_MSG_KEX_DH_GEX_GROUP then socket:close() return end local _ _, prime, gen = string.unpack( ">Bs4s4", gex_reply ) prime = openssl.bignum_bin2bn( prime ):tohex() q = 1024 gen = openssl.bignum_bin2bn( gen ):todec() kexdh_gex_used = true else stdnse.debug2("No shared KEX methods supported by server") return end local e, g, x, p -- e = g^x mod p g = openssl.bignum_dec2bn( gen ) p = openssl.bignum_hex2bn( prime ) x = openssl.bignum_pseudo_rand( q ) e = openssl.bignum_mod_exp( g, x, p ) -- if kexdh_gex_used then -- e = openssl.bignum_pseudo_rand( 1024 ) -- end local payload if kexdh_gex_used == true then payload = transport.kexdh_gex_init( e ) else payload = transport.kexdh_init( e ) end packet = transport.build( payload ) status = socket:send( packet ) if not status then socket:close(); return end local kexdh_reply status, kexdh_reply = transport.receive_packet( socket ) if not status then socket:close(); return end kexdh_reply = transport.payload( kexdh_reply ) -- check for proper msg code local msg_code = kexdh_reply:byte(1) if ( kexdh_gex_used == true and msg_code ~= SSH2.SSH_MSG_KEX_DH_GEX_REPLY ) or ( kexdh_gex_used == false and msg_code ~= SSH2.SSH_MSG_KEXDH_REPLY ) then socket:close() return end local bits, algorithm local _, public_host_key = string.unpack( ">Bs4", kexdh_reply ) if key_type == 'ssh-dss' then algorithm = "DSA" local _, p = string.unpack( ">s4s4", public_host_key ) bits = openssl.bignum_bin2bn( p ):num_bits() elseif key_type == 'ssh-rsa' then algorithm = "RSA" local _, _, n = string.unpack( ">s4s4s4", public_host_key ) bits = openssl.bignum_bin2bn( n ):num_bits() elseif key_type == 'ecdsa-sha2-nistp256' then algorithm = "ECDSA" bits = "256" elseif key_type == 'ecdsa-sha2-nistp384' then algorithm = "ECDSA" bits = "384" elseif key_type == 'ecdsa-sha2-nistp521' then algorithm = "ECDSA" bits = "521" elseif key_type == 'ssh-ed25519' then algorithm = "ED25519" bits = "256" else stdnse.debug1("Unsupported key type: %s", key_type ) end socket:close() return { key=base64.enc(public_host_key), key_type=key_type, fp_input=public_host_key, bits=bits, full_key=('%s %s'):format(key_type,base64.enc(public_host_key)), algorithm=algorithm, fingerprint=openssl.md5(public_host_key), fp_sha256=openssl.digest("sha256",public_host_key)} end -- constants SSH2 = { SSH_MSG_DISCONNECT = 1, SSH_MSG_IGNORE = 2, SSH_MSG_UNIMPLEMENTED = 3, SSH_MSG_DEBUG = 4, SSH_MSG_SERVICE_REQUEST = 5, SSH_MSG_SERVICE_ACCEPT = 6, SSH_MSG_KEXINIT = 20, SSH_MSG_NEWKEYS = 21, SSH_MSG_KEXDH_INIT = 30, SSH_MSG_KEXDH_REPLY = 31, SSH_MSG_KEX_DH_GEX_REQUEST_OLD = 30, SSH_MSG_KEX_DH_GEX_REQUEST = 34, SSH_MSG_KEX_DH_GEX_GROUP = 31, SSH_MSG_KEX_DH_GEX_INIT = 32, SSH_MSG_KEX_DH_GEX_REPLY = 33, } return _ENV;
local L = LibStub("AceLocale-3.0"):NewLocale("GuildGearRules", "ptBR") if not L then return end L['ATTRIBUTE_SPELLPOWER'] = ".*Aumenta em até .* o dano causado e a cura realizada por feitiços e efeitos mágicos."
function RioWheel(self,offsetFromCenter,itemIndex,numItems) local spacing = 210; local edgeSpacing = 135; if math.abs(offsetFromCenter) < .5 then self:zoom(1+math.cos(offsetFromCenter*math.pi)/3); self:x(offsetFromCenter*(spacing+edgeSpacing*2)); else if offsetFromCenter >= .5 then self:x(offsetFromCenter*spacing+edgeSpacing); elseif offsetFromCenter <= -.5 then self:x(offsetFromCenter*spacing-edgeSpacing); end; --self:zoom(1); end; end; local gsCodes = { -- steps GroupSelect1 = { default = "Up", --dance = "Up", pump = "UpLeft", }, GroupSelect2 = { default = "Down", --dance = "Down", pump = "UpRight", }, OptionList = { default = "Left,Right,Left,Right", pump = "DownLeft,DownRight,DownLeft,DownRight,DownLeft,DownRight" } }; local function CurGameName() return GAMESTATE:GetCurrentGame():GetName() end function MusicSelectMappings(codeName) local gameName = string.lower(CurGameName()) local inputCode = gsCodes[codeName] return inputCode[gameName] or inputCode["default"] end function GetOrCreateChild(tab, field, kind) kind = kind or 'table' local out if not tab[field] then if kind == 'table' then out = {} elseif kind == 'number' then out = 0 elseif kind == 'boolean_df' or kind == 'boolean' then out = false elseif kind == 'boolean_dt' then out = true else error("GetOrCreateChild: I don't know a default value for type "..kind) end tab[field] = out else out = tab[field] end return out end --Thank you, DDR SN3 team! --This function is a port of https://github.com/Inorizushi/DDR-X3/blob/master/Scripts/Starter.lua, please credit them if you want to put it in your theme local outputPath = "/Themes/"..THEME:GetCurThemeName().."/Other/SongManager DefaultGroups.txt"; local isolatePattern = "/([^/]+)/?$" --in English, "everything after the last forward slash unless there is a terminator" local combineFormat = "%s/%s" function AssembleDefaultGroups() if not (SONGMAN and GAMESTATE) then return end local streamSafeMode = (ReadPrefFromFile("StreamSafeEnabled") == "true"); local set = {} --populate the groups for _, song in pairs(SONGMAN:GetAllSongs()) do --local steps = song:GetStepsByStepsType('StepsType_Pump_Single'); --local doublesSteps = song:GetStepsByStepsType('StepsType_Pump_Double'); --Trace(song:GetDisplayMainTitle()); if not (streamSafeMode and has_value(STREAM_UNSAFE_AUDIO, song:GetDisplayFullTitle() .. "||" .. song:GetDisplayArtist())) and song:GetGroupName() ~= RIO_FOLDER_NAMES["EasyFolder"] and song:GetMainTitle() ~= "info" then --Filter out unsafe songs. local shortSongDir = string.match(song:GetSongDir(),isolatePattern) --Trace("sDir: "..shortSongDir) local groupName = song:GetGroupName() local groupTbl = GetOrCreateChild(set, groupName) table.insert(groupTbl, string.format(combineFormat, groupName, shortSongDir)) end end --Do the whole thing a second time to make a routine group for _, song in pairs(SONGMAN:GetAllSongs()) do local steps = song:GetStepsByStepsType('StepsType_Pump_Routine'); if #steps >= 1 and not (streamSafeMode and has_value(STREAM_UNSAFE_AUDIO, song:GetDisplayFullTitle() .. "||" .. song:GetDisplayArtist())) and song:GetGroupName() ~= RIO_FOLDER_NAMES["EasyFolder"] then --Filter out songs that dont have pump, and unsafe songs local shortSongDir = string.match(song:GetSongDir(),isolatePattern) local groupName = song:GetGroupName() local groupTbl = GetOrCreateChild(set, "Routine") table.insert(groupTbl, string.format(combineFormat, groupName, shortSongDir)) end end --sort all the groups and collect their names, then sort that too local groupNames = {} for groupName, group in pairs(set) do if next(group) == nil then set[groupName] = nil else table.sort(group) table.insert(groupNames, groupName) end end table.sort(groupNames) --then, let's make a representation of our eventual file in memory. local outputLines = {} for _, groupName in ipairs(groupNames) do table.insert(outputLines, "---"..groupName) --Comment it out if you don't want folders. for _, path in ipairs(set[groupName]) do table.insert(outputLines, path) end end --now, slam it all out to disk. local fHandle = RageFileUtil.CreateRageFile() --the mode is Write+FlushToDiskOnClose fHandle:Open(outputPath, 10) fHandle:Write(table.concat(outputLines,'\n')) fHandle:Close() fHandle:destroy() end --Lol --AssembleBasicMode();
local function removeNodeFromEdges(node_id, edges) local from_nodes = {} local to_nodes = {} -- remove edges local idx = 1 while idx <= #edges do local edge = edges[idx] if edge.source == node_id then local to_node = edges[idx].target table.insert(to_nodes, to_node) table.remove(edges, idx) elseif edge.target == node_id then local from_node = edges[idx].source table.insert(from_nodes, from_node) table.remove(edges, idx) else idx = idx + 1 end end -- add new edges for _, f in pairs(from_nodes) do for _, t in pairs(to_nodes) do local edge = {source = f, target= t} table.insert(edges, edge) end end return edges end local function isNodeGood(node) return node.data and node.data.module and (torch.typename(node.data.module) ~= 'nn.Identity') end local function reIndexNodes(nodes, edges) -- make reverse map local rev_map = {} for idx = 1, #nodes do rev_map[nodes[idx].id] = idx nodes[idx].id = idx end for idx = 1, #edges do local edge = edges[idx] edge.source = rev_map[edge.source] edge.target = rev_map[edge.target] end return nodes, edges end local function cleanGraph(nodes, edges) local idx = 1 while idx <= #nodes do local node = nodes[idx] if isNodeGood(node.orig_node) then idx = idx + 1 else local id = node.id table.remove(nodes, idx) edges = removeNodeFromEdges(id, edges) end end return reIndexNodes(nodes, edges) end local function loadGraph(graph) local nodes = {} local edges = {} for _, node in ipairs(graph.nodes) do local idx = node.id table.insert(nodes, {id=idx, orig_node = node} ) for ich = 1, #node.children do table.insert( edges, {source = idx, target = node.children[ich].id}) end end nodes, edges = cleanGraph(nodes, edges) return nodes , edges end local M = {} function M.todot( graph, title ) local nodes, edges = loadGraph(graph) local str = {} table.insert(str,'digraph G {\n') if title then table.insert(str,'labelloc="t";\nlabel="' .. title .. '";\n') end table.insert(str,'node [shape = oval]; ') local nodelabels = {} for i,node in ipairs(nodes) do local true_node = node.orig_node local l = '"' .. ( 'Node' .. true_node.id .. '\\n' .. true_node:label() ) .. '"' nodelabels[i] = 'n' .. true_node.id table.insert(str, '\n' .. nodelabels[i] .. '[label=' .. l .. '];') end table.insert(str,'\n') for i,edge in ipairs(edges) do table.insert(str,nodelabels[edge.source] .. ' -> ' .. nodelabels[edge.target] .. ';\n') end table.insert(str,'}') return table.concat(str,'') end function M.dot(g,title,fname) local gv = M.todot(g, title) local fngv = (fname or os.tmpname()) .. '.dot' local fgv = io.open(fngv,'w') fgv:write(gv) fgv:close() local fnsvg = (fname or os.tmpname()) .. '.svg' os.execute('dot -Tsvg -o ' .. fnsvg .. ' ' .. fngv) if not fname then require 'qtsvg' local qs = qt.QSvgWidget(fnsvg) qs:show() os.remove(fngv) os.remove(fnsvg) -- print(fngv,fnpng) return qs end end return M
object_static_structure_content_meatlump_sewer_pipe_single_1end_short_s01 = object_static_structure_content_meatlump_shared_sewer_pipe_single_1end_short_s01:new { } ObjectTemplates:addTemplate(object_static_structure_content_meatlump_sewer_pipe_single_1end_short_s01, "object/static/structure/content/meatlump/sewer_pipe_single_1end_short_s01.iff")
local skeleton = require 'nvim_lsp/skeleton' local util = require 'nvim_lsp/util' local lsp = vim.lsp skeleton.clangd = { default_config = util.utf8_config { cmd = {"clangd", "--background-index"}; filetypes = {"c", "cpp", "objc", "objcpp"}; root_dir = util.root_pattern("compile_commands.json", "compile_flags.txt", ".git"); log_level = lsp.protocol.MessageType.Warning; settings = {}; }; -- commands = {}; -- on_new_config = function(new_config) end; -- on_attach = function(client, bufnr) end; docs = { description = [[ https://clang.llvm.org/extra/clangd/Installation.html **NOTE:** Clang >= 9 is recommended! See [this issue for more](https://github.com/neovim/nvim-lsp/issues/23). clangd relies on a [JSON compilation database](https://clang.llvm.org/docs/JSONCompilationDatabase.html) specified as compile_commands.json or, for simpler projects, a compile_flags.txt. ]]; default_config = { root_dir = [[root_pattern("compile_commands.json", "compile_flags.txt", ".git")]]; on_init = [[function to handle changing offsetEncoding]]; capabilities = [[default capabilities, with offsetEncoding utf-8]]; }; }; } -- vim:et ts=2 sw=2
local DarkInventory, super = Class(Inventory) function DarkInventory:init() super:init(self) self.storage_for_type = { ["item"] = "items", ["key"] = "key_items", ["weapon"] = "weapons", ["armor"] = "armors", } self.storage_enabled = Game:getConfig("enableStorage") -- Order the storages are converted to the light world self.convert_order = {"key_items", "light", "weapons", "armors", "items", "storage"} end function DarkInventory:clear() super:clear(self) self.storages = { ["items"] = {id = "items", max = 12, sorted = true, name = "ITEMs", fallback = "storage"}, ["key_items"] = {id = "key_items", max = 12, sorted = true, name = "KEY ITEMs", fallback = nil }, ["weapons"] = {id = "weapons", max = 48, sorted = false, name = "WEAPONs", fallback = nil }, ["armors"] = {id = "armors", max = 48, sorted = false, name = "ARMORs", fallback = nil }, ["storage"] = {id = "storage", max = 24, sorted = false, name = "STORAGE", fallback = nil }, ["light"] = {id = "light", max = 28, sorted = true, name = "LIGHT ITEMs", fallback = nil }, } end function DarkInventory:convertToLight() local new_inventory = LightInventory() local was_storage_enabled = new_inventory.storage_enabled new_inventory.storage_enabled = true Kristal.callEvent("onConvertToLight", new_inventory) for _,storage_id in ipairs(self.convert_order) do local storage = Utils.copy(self:getStorage(storage_id)) for i = 1, storage.max do local item = storage[i] if item then local result = item:convertToLight(new_inventory) or (storage.id == "light" and item) if result then self:removeItem(item) if type(result) == "string" then result = Registry.createItem(result) end if isClass(result) then result.dark_item = item result.dark_location = {storage = storage.id, index = i} new_inventory:addItem(result) end end end end end local ball = Registry.createItem("light/ball_of_junk", self) new_inventory:addItemTo("items", 1, ball) new_inventory.storage_enabled = was_storage_enabled return new_inventory end -- Item give overrides for Light World items function DarkInventory:getDefaultStorage(item_type, ignore_convert) if not ignore_convert and isClass(item_type) and item_type.light then return self:getStorage("light") end return super:getDefaultStorage(self, item_type, ignore_convert) end return DarkInventory
local S = aurum.get_translator() aurum.mobs = { DEBUG = minetest.settings:get_bool("aurum.mobs.debug", false), CHEAP = minetest.settings:get_bool("aurum.mobs.cheap_pathfinding", false), SPAWN_LIMIT = tonumber(minetest.settings:get("aurum.mobs.spawn_limit")) or 1, SPAWNER_LIMIT = tonumber(minetest.settings:get("aurum.mobs.spawner_limit")) or 4, SPAWN_RADIUS = 40, SPAWN_CHECK_RADIUS = 80, } aurum.mobs.mobs = {} aurum.mobs.shortcuts = {} aurum.mobs.initial_data = { -- Items dropped upon death. Tables or strings, not ItemStacks. -- Can be complex, see drops.lua drops = {}, -- Where does this mob naturally live? habitat_nodes = {}, -- Mana released upon death. xmana = 1, -- Generic movement type. --- Can be: walk, fly, swim movement = "walk", status_effects = {}, } -- Returns: --- nil -- or --- gemai ref, name, id function aurum.mobs.get_mob(object) local l = object:get_luaentity() if l and l._aurum_mobs_id then return l._gemai, l.name, l._aurum_mobs_id end end local old = b.ref_to_table function b.ref_to_table(obj) local l = obj:get_luaentity() if l and l._aurum_mobs_id then return {type = "aurum_mob", id = l._aurum_mobs_id, name = l.name} else return old(obj) end end awards.register_trigger("mob_kill", { type = "counted_key", progress = "@1/@2 killed", auto_description = { "Kill: @2", "Kill: @1×@2" }, auto_description_total = { "Kill @1 mob.", "Kill @1 mobs." }, get_key = function(self, def) return def.trigger.mob end, }) function aurum.mobs.register(name, def) local def = b.t.combine({ -- Human readable description. description = "?", -- More information. longdesc = "", -- Initial entity properties. initial_properties = {}, -- Initial armor groups. armor_groups = {}, -- Initial gemai data. initial_data = {}, -- Initial collision and selection box. box = {-0.35, -0.35, -0.35, 0.35, 0.35, 0.35}, -- Entity def overrides. entity_def = {}, -- Herd identifier. Used to determine who not to hunt and who to help. herd = name, }, def, { name = name, }) aurum.mobs.shortcuts[name:sub(name:find(":") + 1, #name)] = name def.gemai = b.t.combine({}, def.gemai or {}) minetest.register_entity(":" .. name, b.t.combine({ initial_properties = b.t.combine({ hp_max = 1, physical = false, collisionbox = def.box, selectionbox = def.box, }, def.initial_properties), _aurum_mob = def, _mob_init = function(self) end, _mob_death = function(self, killer) end, on_activate = function(self, staticdata, dtime) self._aurum_mobs_id = b.new_uid() self._aurum_mobs_def = def local deserialized = minetest.deserialize(staticdata) or {} self._data = b.t.combine({ initialized = false, gemai = {}, }, deserialized.compressed and minetest.deserialize(minetest.decompress(deserialized.compressed)) or deserialized) self._data.gemai = b.t.combine(b.t.deep_copy(b.t.combine(aurum.mobs.initial_data, { herd = def.herd, }, def.initial_data)), self._data.gemai) self.object:set_armor_groups(b.t.combine(gdamage.armor_defaults(), def.armor_groups)) -- Create temporary data to hold pathing. self._go = {} -- If the entity is new, run initialization. if not self._data.initialized then self:_mob_init() end -- Update properties from saved data. self.object:set_properties(self._data.properties or {}) self.object:set_nametag_attributes(self._data.nametag_attributes or {}) if self._data.armor_groups then self.object:set_armor_groups(self._data.armor_groups) end self.object:set_hp(self._data.hp or self.object:get_hp()) -- Attach gemai. gemai.attach_to_entity(self, def.gemai, self._data.gemai) self._gemai.debug_desc = function(self) return ("(entity) %s %s"):format(self.entity._aurum_mob.name, minetest.pos_to_string(vector.round(self.entity.object:get_pos() or vector.new()))) end self._gemai.is_valid = function(self) return self.entity.object:get_pos() ~= nil end -- If the entity is new, fire the init event to start the gemai state. if not self._data.initialized then self._gemai:fire_event("init") end self._last_pos = self.object:get_pos() -- Tick state if this is a returning mob. if self._data.initialized then self._gemai:step(dtime) end self._data.initialized = true end, get_staticdata = function(self) -- Save current properties. self._data.hp = self.object:get_hp() self._data.properties = self.object:get_properties() self._data.nametag_attributes = self.object:get_nametag_attributes() self._data.armor_groups = self.object:get_armor_groups() self._data.gemai = self._gemai.data return minetest.serialize{compressed = minetest.compress(minetest.serialize(self._data))} end, on_step = function(self, dtime) -- Out of map? Don't do anything. if minetest.get_node_or_nil(self.object:get_pos()) == nil then minetest.log("warning", self._gemai:debug_desc() .. " tried to step inside nil") return end self._last_pos = self.object:get_pos() local tag = ("%s %d/%d%s%s"):format(self._aurum_mob.name, self.object:get_hp(), self.object:get_properties().hp_max, minetest.colorize("#ff0000", "♥"), aurum.mobs.DEBUG and (" %s %d(%d)"):format(self._gemai.data.state, self._gemai.data.live_time, self._gemai.data.state_time) or "") self.object:set_properties{infotext = tag} -- self.object:set_nametag_attributes{text = tag} self._gemai:step(dtime) aurum.effects.operate(self.object, self._gemai.data.status_effects, dtime) end, on_death = function(self, killer) self:_mob_death(killer) local blame = aurum.get_blame(killer) local player = (blame.type == "player") and minetest.get_player_by_name(blame.id) if player then awards.notify_mob_kill(player, self.name) aurum.player.mana_sparks(player, self.object:get_pos(), "killing", self._gemai.data.xmana) for _,drop in ipairs(aurum.mobs.helper_get_drops(self._gemai.data.drops, killer)) do aurum.drop_item(self.object:get_pos(), drop) end end end, on_punch = function(self, puncher) if puncher ~= self.object then local ref_table = aurum.get_blame(puncher) or b.ref_to_table(puncher) local was_parent = self._gemai.data.parent and b.ref_table_equal(ref_table, self._gemai.data.parent) if ref_table and not was_parent then aurum.effects.apply_tool_effects(puncher:get_wielded_item(), self.object, ref_table) self._gemai:fire_event("punch", { other = ref_table, target = { type = "ref_table", ref_table = ref_table, }, }, {clear = true}) end end end, on_rightclick = function(self, clicker) self._gemai:fire_event("interact", { other = b.ref_to_table(clicker), }, {clear = true}) end, }, def.entity_def)) aurum.mobs.mobs[name] = def aurum.mobs.add_doc(name) end function aurum.mobs.spawn(pos, name, data) return minetest.add_entity(pos, name, (type(data) == "string") and data or minetest.serialize(data or {})) end minetest.register_privilege("aurum_mobs", { description = S"Can create and modify mobs", give_to_singleplayer = false, }) minetest.register_chatcommand("mob_spawn", { description = S"Spawn a mob.", privs = {aurum_mobs = true}, func = function(name, param) local player = minetest.get_player_by_name(name) if not player then return false, S"No player." end local mob = (#param > 0 and aurum.mobs.shortcuts[param]) or param if not aurum.mobs.mobs[mob] then return false, S"No such mob." end local obj = aurum.mobs.spawn(vector.add(vector.round(player:get_pos()), vector.new(0, 1, 0)), mob) if obj then return true, S("Spawned @1 (@2).", mob, aurum.mobs.mobs[mob].description) else return false, S("Unable to spawn @1.", mob) end end, }) b.dofile("drops.lua") b.dofile("pathfinder.lua") b.dodir("actions") b.dofile("doc.lua") b.dofile("spawning.lua") b.dofile("spawner.lua")
object_tangible_tcg_series3_deed_tcg_merr_sonn_jt12_jetpack = object_tangible_tcg_series3_shared_deed_tcg_merr_sonn_jt12_jetpack:new { } ObjectTemplates:addTemplate(object_tangible_tcg_series3_deed_tcg_merr_sonn_jt12_jetpack, "object/tangible/tcg/series3/deed_tcg_merr_sonn_jt12_jetpack.iff")
clinkz_death_pact_oaa = class( AbilityBaseClass ) LinkLuaModifier( "modifier_clinkz_death_pact_oaa", "abilities/oaa_death_pact.lua", LUA_MODIFIER_MOTION_NONE ) -------------------------------------------------------------------------------- function clinkz_death_pact_oaa:OnSpellStart() local caster = self:GetCaster() local target = self:GetCursorTarget() local duration = self:GetSpecialValueFor( "duration" ) -- get the target's current health local targetHealth = target:GetHealth() -- kill the target target:Kill( self, caster ) -- apply the standard death pact modifier ( does nothing but display duration ) -- ( and animation too ) caster:AddNewModifier( caster, self, "modifier_clinkz_death_pact", { duration = duration, } ) -- apply the new modifier which actually provides the stats -- then set its stack count to the amount of health the target had local mod = caster:AddNewModifier( caster, self, "modifier_clinkz_death_pact_oaa", { duration = duration, stacks = targetHealth, } ) -- play the sounds caster:EmitSound( "Hero_Clinkz.DeathPact.Cast" ) target:EmitSound( "Hero_Clinkz.DeathPact" ) -- show the particle local part = ParticleManager:CreateParticle( "particles/units/heroes/hero_clinkz/clinkz_death_pact.vpcf", PATTACH_ABSORIGIN, target ) ParticleManager:SetParticleControlEnt( part, 1, caster, PATTACH_ABSORIGIN, "", caster:GetAbsOrigin(), true ) ParticleManager:ReleaseParticleIndex( part ) end -------------------------------------------------------------------------------- modifier_clinkz_death_pact_oaa = class( ModifierBaseClass ) -------------------------------------------------------------------------------- function modifier_clinkz_death_pact_oaa:IsHidden() return true end function modifier_clinkz_death_pact_oaa:IsDebuff() return false end function modifier_clinkz_death_pact_oaa:IsPurgable() return false end -------------------------------------------------------------------------------- function modifier_clinkz_death_pact_oaa:OnCreated( event ) local parent = self:GetParent() local spell = self:GetAbility() -- this has to be done server-side because valve if IsServer() then -- get the parent's current health before applying anything self.parentHealth = parent:GetHealth() -- set the modifier's stack count to the target's health, so that we -- have access to it on the client self:SetStackCount( event.stacks ) end -- get out values local healthPct = spell:GetSpecialValueFor( "health_gain_pct" ) * 0.01 local healthMax = spell:GetSpecialValueFor( "health_gain_max" ) local damagePct = spell:GetSpecialValueFor( "damage_gain_pct" ) * 0.01 local damageMax = spell:GetSpecialValueFor( "damage_gain_max" ) -- retrieve the stack count local targetHealth = self:GetStackCount() -- make sure the resulting buffs don't exceed the caps self.health = targetHealth * healthPct if healthMax > 0 then self.health = math.min( healthMax, self.health ) end self.damage = targetHealth * damagePct if damageMax > 0 then self.damage = math.min( damageMax, self.health ) end if IsServer() then -- apply the new health and such parent:CalculateStatBonus() -- add the added health parent:SetHealth( self.parentHealth + self.health ) self.parentHealth = 0 end end -------------------------------------------------------------------------------- function modifier_clinkz_death_pact_oaa:OnRefresh( event ) local parent = self:GetParent() local spell = self:GetAbility() -- this has to be done server-side because valve if IsServer() then -- get the parent's current health before applying anything self.parentHealth = parent:GetHealth() -- set the modifier's stack count to the target's health, so that we -- have access to it on the client self:SetStackCount( event.stacks ) end -- get out values local healthPct = spell:GetSpecialValueFor( "health_gain_pct" ) * 0.01 local healthMax = spell:GetSpecialValueFor( "health_gain_max" ) local damagePct = spell:GetSpecialValueFor( "damage_gain_pct" ) * 0.01 local damageMax = spell:GetSpecialValueFor( "damage_gain_max" ) -- retrieve the stack count local targetHealth = self:GetStackCount() -- make sure the resulting buffs don't exceed the caps self.health = targetHealth * healthPct if healthMax > 0 then self.health = math.min( healthMax, self.health ) end self.damage = targetHealth * damagePct if damageMax > 0 then self.damage = math.min( damageMax, self.health ) end if IsServer() then -- apply the new health and such parent:CalculateStatBonus() -- add the added health parent:SetHealth( self.parentHealth + self.health ) self.parentHealth = 0 end end -------------------------------------------------------------------------------- function modifier_clinkz_death_pact_oaa:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_BASEATTACK_BONUSDAMAGE, MODIFIER_PROPERTY_EXTRA_HEALTH_BONUS, } return funcs end -------------------------------------------------------------------------------- function modifier_clinkz_death_pact_oaa:GetModifierBaseAttack_BonusDamage( event ) return self.damage end -------------------------------------------------------------------------------- function modifier_clinkz_death_pact_oaa:GetModifierExtraHealthBonus( event ) return self.health end
local path = require "nvim-lsp-installer.path" local std = require "nvim-lsp-installer.installers.std" local installers = require "nvim-lsp-installer.installers" local Data = require "nvim-lsp-installer.data" local process = require "nvim-lsp-installer.process" local M = {} function M.packages(packages) return installers.pipe { std.ensure_executables { { "go", "go was not found in path, refer to https://golang.org/doc/install." } }, function(server, callback, context) local pkgs = Data.list_copy(packages or {}) local c = process.chain { env = process.graft_env { GO111MODULE = "on", GOBIN = server.root_dir, GOPATH = server.root_dir, }, cwd = server.root_dir, stdio_sink = context.stdio_sink, } if context.requested_server_version then -- The "head" package is the recipient for the requested version. It's.. by design... don't ask. pkgs[1] = ("%s@%s"):format(pkgs[1], context.requested_server_version) end c.run("go", vim.list_extend({ "get", "-v" }, pkgs)) c.run("go", { "clean", "-modcache" }) c.spawn(callback) end, } end function M.executable(root_dir, executable) return path.concat { root_dir, executable } end return M
-- Compiled with https://roblox-ts.github.io v0.3.2 -- August 19, 2020, 7:00 PM British Summer Time local TS = _G[script]; local exports = {}; local MakeRequest = TS.import(script, script.Parent, "HTTP").default; local Settings = TS.import(script, script.Parent, "Settings").default; local AddCharacterVirtualCurrency = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/AddCharacterVirtualCurrency', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local AddFriend = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/AddFriend', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local AddGenericID = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/AddGenericID', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local AddPlayerTag = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/AddPlayerTag', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local AddSharedGroupMembers = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/AddSharedGroupMembers', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local AddUserVirtualCurrency = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/AddUserVirtualCurrency', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local AuthenticateSessionTicket = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/AuthenticateSessionTicket', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local BanUsers = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/BanUsers', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local ConsumeItem = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/ConsumeItem', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local CreateSharedGroup = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/CreateSharedGroup', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local DeleteCharacterFromUser = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/DeleteCharacterFromUser', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local DeletePlayer = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/DeletePlayer', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local DeleteSharedGroup = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/DeleteSharedGroup', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local DeregisterGame = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/DeregisterGame', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local EvaluateRandomResultTable = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/EvaluateRandomResultTable', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local ExecuteCloudScript = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/ExecuteCloudScript', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetAllSegments = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetAllSegments', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetAllUsersCharacters = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetAllUsersCharacters', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetCatalogItems = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetCatalogItems', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetCharacterData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetCharacterData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetCharacterInternalData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetCharacterInternalData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetCharacterInventory = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetCharacterInventory', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetCharacterLeaderboard = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetCharacterLeaderboard', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetCharacterReadOnlyData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetCharacterReadOnlyData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetCharacterStatistics = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetCharacterStatistics', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetContentDownloadUrl = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetContentDownloadUrl', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetFriendLeaderboard = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetFriendLeaderboard', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetFriendsList = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetFriendsList', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetLeaderboard = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetLeaderboard', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetLeaderboardAroundCharacter = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetLeaderboardAroundCharacter', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetLeaderboardForUserCharacters = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetLeaderboardForUserCharacters', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetPlayerCombinedInfo = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetPlayerCombinedInfo', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetPlayerProfile = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetPlayerProfile', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetPlayerSegments = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetPlayerSegments', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetPlayersInSegment = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetPlayersInSegment', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetPlayerStatistics = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetPlayerStatistics', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetPlayerStatisticVersions = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetPlayerStatisticVersions', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetPlayerTags = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetPlayerTags', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetPlayFabIDsFromGenericIDs = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetPlayFabIDsFromGenericIDs', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetPublisherData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetPublisherData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetRandomResultTables = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetRandomResultTables', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetServerCustomIDsFromPlayFabIDs = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetServerCustomIDsFromPlayFabIDs', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetSharedGroupData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetSharedGroupData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetStoreItems = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetStoreItems', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetTime = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetTime', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetTitleData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetTitleData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetTitleInternalData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetTitleInternalData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetTitleNews = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetTitleNews', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetUserAccountInfo = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetUserAccountInfo', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetUserBans = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetUserBans', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetUserData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetUserData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetUserInternalData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetUserInternalData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetUserInventory = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetUserInventory', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetUserPublisherData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetUserPublisherData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetUserPublisherInternalData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetUserPublisherInternalData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetUserPublisherReadOnlyData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetUserPublisherReadOnlyData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GetUserReadOnlyData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GetUserReadOnlyData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GrantCharacterToUser = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GrantCharacterToUser', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GrantItemsToCharacter = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GrantItemsToCharacter', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GrantItemsToUser = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GrantItemsToUser', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local GrantItemsToUsers = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/GrantItemsToUsers', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local LinkServerCustomId = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/LinkServerCustomId', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local LoginWithServerCustomId = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/LoginWithServerCustomId', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local ModifyItemUses = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/ModifyItemUses', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local MoveItemToCharacterFromCharacter = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/MoveItemToCharacterFromCharacter', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local MoveItemToCharacterFromUser = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/MoveItemToCharacterFromUser', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local MoveItemToUserFromCharacter = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/MoveItemToUserFromCharacter', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local NotifyMatchmakerPlayerLeft = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/NotifyMatchmakerPlayerLeft', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local RedeemCoupon = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/RedeemCoupon', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local RedeemMatchmakerTicket = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/RedeemMatchmakerTicket', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local RemoveFriend = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/RemoveFriend', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local RemoveGenericID = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/RemoveGenericID', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local RemovePlayerTag = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/RemovePlayerTag', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local RemoveSharedGroupMembers = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/RemoveSharedGroupMembers', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local ReportPlayer = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/ReportPlayer', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local RevokeAllBansForUser = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/RevokeAllBansForUser', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local RevokeBans = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/RevokeBans', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local RevokeInventoryItem = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/RevokeInventoryItem', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local RevokeInventoryItems = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/RevokeInventoryItems', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local SetFriendTags = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/SetFriendTags', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local SetPlayerSecret = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/SetPlayerSecret', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local SetPublisherData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/SetPublisherData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local SetTitleData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/SetTitleData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local SetTitleInternalData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/SetTitleInternalData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local SubtractCharacterVirtualCurrency = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/SubtractCharacterVirtualCurrency', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local SubtractUserVirtualCurrency = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/SubtractUserVirtualCurrency', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UnlinkServerCustomId = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UnlinkServerCustomId', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UnlockContainerItem = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UnlockContainerItem', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateAvatarUrl = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateAvatarUrl', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateBans = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateBans', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateCharacterData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateCharacterData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateCharacterInternalData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateCharacterInternalData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateCharacterReadOnlyData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateCharacterReadOnlyData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateCharacterStatistics = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateCharacterStatistics', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdatePlayerStatistics = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdatePlayerStatistics', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateSharedGroupData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateSharedGroupData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateUserData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateUserData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateUserInternalData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateUserInternalData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateUserInventoryItemCustomData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateUserInventoryItemCustomData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateUserPublisherData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateUserPublisherData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateUserPublisherInternalData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateUserPublisherInternalData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateUserPublisherReadOnlyData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateUserPublisherReadOnlyData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local UpdateUserReadOnlyData = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/UpdateUserReadOnlyData', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local WriteCharacterEvent = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/WriteCharacterEvent', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local WritePlayerEvent = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/WritePlayerEvent', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); local WriteTitleEvent = TS.async(function(request) local _0 = Settings.settings.secretKey; if not (_0 ~= "" and _0) then error('Must have Settings.settings.secretKey set to call this method'); end; local result = TS.await(MakeRequest('/Server/WriteTitleEvent', request, 'X-SecretKey', Settings.settings.secretKey)); return result; end); exports.AddCharacterVirtualCurrency = AddCharacterVirtualCurrency; exports.AddFriend = AddFriend; exports.AddGenericID = AddGenericID; exports.AddPlayerTag = AddPlayerTag; exports.AddSharedGroupMembers = AddSharedGroupMembers; exports.AddUserVirtualCurrency = AddUserVirtualCurrency; exports.AuthenticateSessionTicket = AuthenticateSessionTicket; exports.BanUsers = BanUsers; exports.ConsumeItem = ConsumeItem; exports.CreateSharedGroup = CreateSharedGroup; exports.DeleteCharacterFromUser = DeleteCharacterFromUser; exports.DeletePlayer = DeletePlayer; exports.DeleteSharedGroup = DeleteSharedGroup; exports.DeregisterGame = DeregisterGame; exports.EvaluateRandomResultTable = EvaluateRandomResultTable; exports.ExecuteCloudScript = ExecuteCloudScript; exports.GetAllSegments = GetAllSegments; exports.GetAllUsersCharacters = GetAllUsersCharacters; exports.GetCatalogItems = GetCatalogItems; exports.GetCharacterData = GetCharacterData; exports.GetCharacterInternalData = GetCharacterInternalData; exports.GetCharacterInventory = GetCharacterInventory; exports.GetCharacterLeaderboard = GetCharacterLeaderboard; exports.GetCharacterReadOnlyData = GetCharacterReadOnlyData; exports.GetCharacterStatistics = GetCharacterStatistics; exports.GetContentDownloadUrl = GetContentDownloadUrl; exports.GetFriendLeaderboard = GetFriendLeaderboard; exports.GetFriendsList = GetFriendsList; exports.GetLeaderboard = GetLeaderboard; exports.GetLeaderboardAroundCharacter = GetLeaderboardAroundCharacter; exports.GetLeaderboardForUserCharacters = GetLeaderboardForUserCharacters; exports.GetPlayerCombinedInfo = GetPlayerCombinedInfo; exports.GetPlayerProfile = GetPlayerProfile; exports.GetPlayerSegments = GetPlayerSegments; exports.GetPlayersInSegment = GetPlayersInSegment; exports.GetPlayerStatistics = GetPlayerStatistics; exports.GetPlayerStatisticVersions = GetPlayerStatisticVersions; exports.GetPlayerTags = GetPlayerTags; exports.GetPlayFabIDsFromGenericIDs = GetPlayFabIDsFromGenericIDs; exports.GetPublisherData = GetPublisherData; exports.GetRandomResultTables = GetRandomResultTables; exports.GetServerCustomIDsFromPlayFabIDs = GetServerCustomIDsFromPlayFabIDs; exports.GetSharedGroupData = GetSharedGroupData; exports.GetStoreItems = GetStoreItems; exports.GetTime = GetTime; exports.GetTitleData = GetTitleData; exports.GetTitleInternalData = GetTitleInternalData; exports.GetTitleNews = GetTitleNews; exports.GetUserAccountInfo = GetUserAccountInfo; exports.GetUserBans = GetUserBans; exports.GetUserData = GetUserData; exports.GetUserInternalData = GetUserInternalData; exports.GetUserInventory = GetUserInventory; exports.GetUserPublisherData = GetUserPublisherData; exports.GetUserPublisherInternalData = GetUserPublisherInternalData; exports.GetUserPublisherReadOnlyData = GetUserPublisherReadOnlyData; exports.GetUserReadOnlyData = GetUserReadOnlyData; exports.GrantCharacterToUser = GrantCharacterToUser; exports.GrantItemsToCharacter = GrantItemsToCharacter; exports.GrantItemsToUser = GrantItemsToUser; exports.GrantItemsToUsers = GrantItemsToUsers; exports.LinkServerCustomId = LinkServerCustomId; exports.LoginWithServerCustomId = LoginWithServerCustomId; exports.ModifyItemUses = ModifyItemUses; exports.MoveItemToCharacterFromCharacter = MoveItemToCharacterFromCharacter; exports.MoveItemToCharacterFromUser = MoveItemToCharacterFromUser; exports.MoveItemToUserFromCharacter = MoveItemToUserFromCharacter; exports.NotifyMatchmakerPlayerLeft = NotifyMatchmakerPlayerLeft; exports.RedeemCoupon = RedeemCoupon; exports.RedeemMatchmakerTicket = RedeemMatchmakerTicket; exports.RemoveFriend = RemoveFriend; exports.RemoveGenericID = RemoveGenericID; exports.RemovePlayerTag = RemovePlayerTag; exports.RemoveSharedGroupMembers = RemoveSharedGroupMembers; exports.ReportPlayer = ReportPlayer; exports.RevokeAllBansForUser = RevokeAllBansForUser; exports.RevokeBans = RevokeBans; exports.RevokeInventoryItem = RevokeInventoryItem; exports.RevokeInventoryItems = RevokeInventoryItems; exports.SetFriendTags = SetFriendTags; exports.SetPlayerSecret = SetPlayerSecret; exports.SetPublisherData = SetPublisherData; exports.SetTitleData = SetTitleData; exports.SetTitleInternalData = SetTitleInternalData; exports.SubtractCharacterVirtualCurrency = SubtractCharacterVirtualCurrency; exports.SubtractUserVirtualCurrency = SubtractUserVirtualCurrency; exports.UnlinkServerCustomId = UnlinkServerCustomId; exports.UnlockContainerItem = UnlockContainerItem; exports.UpdateAvatarUrl = UpdateAvatarUrl; exports.UpdateBans = UpdateBans; exports.UpdateCharacterData = UpdateCharacterData; exports.UpdateCharacterInternalData = UpdateCharacterInternalData; exports.UpdateCharacterReadOnlyData = UpdateCharacterReadOnlyData; exports.UpdateCharacterStatistics = UpdateCharacterStatistics; exports.UpdatePlayerStatistics = UpdatePlayerStatistics; exports.UpdateSharedGroupData = UpdateSharedGroupData; exports.UpdateUserData = UpdateUserData; exports.UpdateUserInternalData = UpdateUserInternalData; exports.UpdateUserInventoryItemCustomData = UpdateUserInventoryItemCustomData; exports.UpdateUserPublisherData = UpdateUserPublisherData; exports.UpdateUserPublisherInternalData = UpdateUserPublisherInternalData; exports.UpdateUserPublisherReadOnlyData = UpdateUserPublisherReadOnlyData; exports.UpdateUserReadOnlyData = UpdateUserReadOnlyData; exports.WriteCharacterEvent = WriteCharacterEvent; exports.WritePlayerEvent = WritePlayerEvent; exports.WriteTitleEvent = WriteTitleEvent; return exports;
local nvimux = {} nvimux.debug = {} nvimux.config = {} nvimux.bindings = {} nvimux.term = {} nvimux.term.prompt = {} -- testing --[[ Nvimux: Neovim as a terminal multiplexer. This is the lua reimplementation of VimL. --]] -- luacheck: globals unpack -- [ Private variables and tables local nvim = vim.api -- luacheck: ignore local consts = { terminal_quit = '<C-\\><C-n>', esc = '<ESC>', } local fns = {} local nvim_proxy = { __index = function(_, key) local key_ = 'nvimux_' .. key local val = nil if fns.exists(key_) then val = nvim.nvim_get_var(key_) end return val end } local vars = { prefix = '<C-b>', vertical_split = ':NvimuxVerticalSplit', horizontal_split = ':NvimuxHorizontalSplit', quickterm_scope = 'g', quickterm_direction = 'botright', quickterm_orientation = 'vertical', quickterm_size = '', new_term = 'term', close_term = ':x', new_window = 'enew' } vars.split_type = function(t) return t.quickterm_direction .. ' ' .. t.quickterm_orientation .. ' ' .. t.quickterm_size .. 'split' end -- [[ Table of default bindings local bindings = { mappings = { ['<C-r>'] = { nvi = {':so $MYVIMRC'}}, ['!'] = { nvit = {':wincmd T'}}, ['%'] = { nvit = {function() return vars.vertical_split end} }, ['"'] = { nvit = {function() return vars.horizontal_split end}}, ['q'] = { nvit = {':NvimuxToggleTerm'}}, ['w'] = { nvit = {':tabs'}}, ['o'] = { nvit = {'<C-w>w'}}, ['n'] = { nvit = {'gt'}}, ['p'] = { nvit = {'gT'}}, ['x'] = { nvi = {':bd %'}, t = {function() return vars.close_term end}}, ['X'] = { nvi = {':enew \\| bd #'}}, ['h'] = { nvit = {'<C-w><C-h>'}}, ['j'] = { nvit = {'<C-w><C-j>'}}, ['k'] = { nvit = {'<C-w><C-k>'}}, ['l'] = { nvit = {'<C-w><C-l>'}}, [':'] = { t = {':'}}, ['['] = { t = {''}}, [']'] = { nvit = {':NvimuxTermPaste'}}, [','] = { t = {'', nvimux.term.prompt.rename}}, ['c'] = { nvit = {':NvimuxNewTab'}}, ['t'] = { nvit = {':echom "Deprecated mapping. set `new_window` or remap this." \\| silent tabe'}}, }, map_table = {} } local nvimux_commands = { {name = 'NvimuxHorizontalSplit', lazy_cmd = function() return [[spl|wincmd j|]] .. vars.new_window end}, {name = 'NvimuxVerticalSplit', lazy_cmd = function() return [[vspl|wincmd l|]] .. vars.new_window end}, {name = 'NvimuxNewTab', lazy_cmd = function() return [[tabe|]] .. vars.new_window end}, {name = 'NvimuxSet', cmd = [[lua require('nvimux').config.set_fargs(<f-args>)]], nargs='+'}, } -- ]] setmetatable(vars, nvim_proxy) -- ] -- [ Private functions -- [[ Commands definition fns.build_cmd = function(options) nargs = options.nargs or 0 cmd = options.cmd or options.lazy_cmd() name = options.name nvim.nvim_command('command! -nargs=' .. nargs .. ' ' .. name .. ' ' .. cmd) end -- ]] -- [[ keybind commands fns.bind_fn = function(options) local prefix = options.prefix or '' local mode = options.mode return function(key, command) local suffix = string.sub(command, 1, 1) == ':' and '<CR>' or '' nvim.nvim_command(mode .. 'noremap <silent> ' .. vars.prefix .. key .. ' ' .. prefix .. command .. suffix) end end fns.bind = { t = fns.bind_fn{mode = 't', prefix = consts.terminal_quit}, i = fns.bind_fn{mode = 'i', prefix = consts.esc}, n = fns.bind_fn{mode = 'n'}, v = fns.bind_fn{mode = 'v'} } fns.bind._ = function(key, mapping, modes) for _, mode in ipairs(modes) do fns.bind[mode](key, mapping) end end -- ]] -- [[ Commands and helper functions fns.split = function(str) local p = {} for i=1, #str do table.insert(p, str:sub(i, i)) end return p end fns.exists = function(var) return nvim.nvim_call_function('exists', {var}) == 1 end fns.defn = function(var, val) if fns.exists(var) then nvim.nvim_set_var(var, val) return val else return nvim.nvim_get_var(var) end end fns.prompt = function(message) nvim.nvim_call_function('inputsave', {}) local ret = nvim.nvim_call_function('input', {message}) nvim.nvim_call_function('inputrestore', {}) return ret end -- ]] -- [[ Set var fns.variables = {} fns.variables.scoped = { arg = { b = function() return nvim.nvim_get_current_buf() end, t = function() return nvim.nvim_get_current_tabpage() end, l = function() return nvim.nvim_get_current_win() end, g = function() return nil end, }, set = { b = function(options) return nvim.nvim_buf_set_var(options.nr, options.name, options.value) end, t = function(options) return nvim.nvim_tabpage_set_var(options.nr, options.name, options.value) end, l = function(options) return nvim.nvim_win_set_var(options.nr, options.name, options.value) end, g = function(options) return nvim.nvim_set_var(options.name, options.value) end, }, get = { b = function(options) return fns.exists('b:' .. options.name) and nvim.nvim_buf_get_var(options.nr, options.name) or nil end, t = function(options) return fns.exists('t:' .. options.name) and nvim.nvim_tabpage_get_var(options.nr, options.name) or nil end, l = function(options) return fns.exists('l:' .. options.name) and nvim.nvim_win_get_var(options.nr, options.name) or nil end, g = function(options) return fns.exists('g:' .. options.name) and nvim.nvim_get_var(options.name) or nil end, }, } fns.variables.set = function(options) local mode = options.mode or 'g' options.nr = options.nr or fns.variables.scoped.arg[mode]() fns.variables.scoped.set[mode](options) end fns.variables.get = function(options) local mode = options.mode or 'g' options.nr = options.nr or fns.variables.scoped.arg[mode]() return fns.variables.scoped.get[mode](options) end -- ]] -- ] -- [ Public API -- [[ Config-handling commands nvimux.config.set = function(options) vars[options.key] = options.value nvim.nvim_set_var('nvimux_' .. options.key, options.value) end nvimux.config.set_fargs = function(key, value) nvimux.config.set{key=key, value=value} end nvimux.config.set_all = function(options) for key, value in pairs(options) do nvimux.config.set{['key'] = key, ['value'] = value} end end -- ]] -- [[ Quickterm nvimux.term.new_toggle = function() local split_type = vars:split_type() nvim.nvim_command(split_type .. ' | enew | ' .. vars.new_term) local buf_nr = nvim.nvim_call_function('bufnr', {'%'}) nvim.nvim_set_option('wfw', true) fns.variables.set{mode='b', nr=buf_nr, name='nvimux_buf_orientation', value=split_type} fns.variables.set{mode=vars.quickterm_scope, name='nvimux_last_buffer_id', value=buf_nr} end nvimux.term.toggle = function() -- TODO Allow external commands local buf_nr = fns.variables.get{mode=vars.quickterm_scope, name='nvimux_last_buffer_id'} if not buf_nr then nvimux.term.new_toggle() else local window = nvim.nvim_call_function('bufwinnr', {buf_nr}) if window == -1 then if nvim.nvim_call_function('bufname', {buf_nr}) == '' then nvimux.term.new_toggle() else local split_type = nvim.nvim_buf_get_var(buf_nr, 'nvimux_buf_orientation') nvim.nvim_command(split_type .. ' | b' .. buf_nr) end else nvim.nvim_command(window .. ' wincmd w | q | stopinsert') end end end nvimux.term.prompt.rename = function() nvimux.term_only{ cmd = fns.prompt('nvimux > New term name: '), action = function(k) nvim.nvim_command('file term://' .. k) end } end -- ]] -- [[ Bindings nvimux.bindings.bind = function(options) local override = 'nvimux_override_' .. options.key if fns.exists(override) then options.value = nvim.nvim_get_var(override) end fns.bind._(options.key, options.value, options.modes) end nvimux.bindings.bind_all = function(options) for _, bind in ipairs(options) do local key, cmd, modes = unpack(bind) local tbl = {} tbl[table.concat(modes, "")] = { cmd } bindings.mappings[key]=tbl end end -- ]] -- [[ Top-level commands nvimux.debug.vars = function() for k, v in pairs(vars) do print(k, v) end end nvimux.debug.bindings = function() for k, v in pairs(bindings.mappings) do print(k, v) end print('') for k, v in pairs(bindings.map_table) do print(k, v) end end nvimux.term_only = function(options) local action = options.action or nvim.nvim_command if nvim.nvim_buf_get_option('%', 'buftype') == 'terminal' then action(options.cmd) else print("Not on terminal") end end nvimux.mapped = function(options) local mapping = bindings.map_table[options.key] local action = mapping.action or nvim.nvim_command if type(mapping.arg) == 'function' then action(mapping.arg()) else action(mapping.arg) end end -- ]] -- ] nvimux.bootstrap = function() for i=1, 9 do bindings.mappings[i] = { nvit = {i .. 'gt'}} end for _, cmd in ipairs(nvimux_commands) do fns.build_cmd(cmd) end for key, cmd in pairs(bindings.mappings) do for modes, data in pairs(cmd) do modes = fns.split(modes) local arg, action = unpack(data) local binds = { ['key'] = key, ['modes'] = modes, } if type(arg) == 'function' or action ~= nil then bindings.map_table[key] = {['arg'] = arg, ['action'] = action} binds.value = ':lua require("nvimux").mapped{key = "' .. key .. '"}' else binds.value = arg end nvimux.bindings.bind(binds) end end fns.build_cmd{name = 'NvimuxReload', cmd = 'lua require("nvimux").bootstrap()'} end -- ] return nvimux
local MainUIRoleHeadView = BaseClass() function MainUIRoleHeadView:DefaultVar( ) return { UIConfig = { prefab_path = "Assets/AssetBundleRes/ui/mainui/MainUIRoleHeadView.prefab", canvas_name = "MainUI", components = { }, }, } end function MainUIRoleHeadView:OnLoad( ) local names = { "money_1","money_2","flag","head_icon:raw","lv","lv_bg","blood_bar", } UI.GetChildren(self, self.transform, names) self:AddEvents() self:UpdateView() end function MainUIRoleHeadView:AddEvents( ) local on_click = function ( click_btn ) -- if click_btn == self.correct_obj then -- SceneMgr.Instance:CorrectMainRolePos() -- elseif click_btn == self.skill_1_obj then -- CS.UnityMMO.GameInput.GetInstance():SetKeyUp(CS.UnityEngine.KeyCode.I, true) -- end end UIHelper.BindClickEvent(self.correct_obj, on_click) UIHelper.BindClickEvent(self.skill_1_obj, on_click) end function MainUIRoleHeadView:UpdateView( ) local career = MainRole:GetInstance():GetCareer() print('Cat:MainUIRoleHeadView.lua[39] career', career) local headRes = ResPath.GetRoleHeadRes(career, 0) UI.SetRawImage(self, self.head_icon_raw, headRes) end return MainUIRoleHeadView
--[[ BaseLua https://github.com/dejayc/BaseLua Copyright 2012 Dejay Clayton All use of this file must comply with the Apache License, Version 2.0, under which this file is licensed: http://www.apache.org/licenses/LICENSE-2.0 --]] local BaseLua = require( "Packages.BaseLua" ) local DataHelper = require( BaseLua.package.DataHelper ) context( "DataHelper", function() ------------------------------------------------------------------------------- context( "getNonNil", function() ------------------------------------------------------------------------------- test( "return nil when no parameters", function() assert_nil( DataHelper.getNonNil() ) end ) test( "return nil when nil as first of multiple parameters", function() assert_nil( DataHelper.getNonNil( nil, 5, nil ) ) end ) test( "return first parameter when non-nil as first parameter", function() assert_equal( 5, DataHelper.getNonNil( 5, nil ) ) end ) end ) ------------------------------------------------------------------------------- context( "hasValue", function() ------------------------------------------------------------------------------- test( "return false when no parameters", function() assert_false( DataHelper.hasValue() ) end ) test( "return true when non-nil, non-empty-string parameter", function() assert_true( DataHelper.hasValue( 5 ) ) end ) test( "return false when empty-string parameter", function() assert_false( DataHelper.hasValue( "" ) ) end ) test( "return true when whitespace parameter", function() assert_true( DataHelper.hasValue( " " ) ) end ) end ) ------------------------------------------------------------------------------- context( "ifThenElse", function() ------------------------------------------------------------------------------- test( "return nil when no params", function() assert_nil( DataHelper.ifThenElse() ) end ) test( "return true param if test param is true", function() assert_true( DataHelper.ifThenElse( true, true, false ) ) end ) test( "return false param if test param is nil", function() assert_false( DataHelper.ifThenElse( nil, true, false ) ) end ) test( "return false param if test param is false", function() assert_false( DataHelper.ifThenElse( false, true, false ) ) end ) end ) end )
--------------------------------------------------------------------------------------------- --ATF version: 2.2 --Modified date: 01/Dec/2015 --Author: Ta Thanh Dong --------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------- ---------------------------- Required Shared libraries -------------------------------------- --------------------------------------------------------------------------------------------- local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local commonPreconditions = require ('/user_modules/shared_testcases/commonPreconditions') local srcPath = config.pathToSDL .. "sdl_preloaded_pt.json" local dstPath = config.pathToSDL .. "sdl_preloaded_pt.json.origin" --------------------------------------------------------------------------------------------- ------------------------- General Precondition before ATF start ----------------------------- --------------------------------------------------------------------------------------------- -- TODO: Remove after implementation policy update -- Precondition: remove policy table -- commonSteps:DeletePolicyTable() -- -- TODO: Remove after implementation policy update -- -- Precondition: replace preloaded file with new one -- os.execute( 'cp files/SmokeTest_genivi_pt.json ' .. tostring(config.pathToSDL) .. "sdl_preloaded_pt.json") ---------------------------------------------------------------------------------------------- --make backup copy of file sdl_preloaded_pt.json commonPreconditions:BackupFile("sdl_preloaded_pt.json") -- TODO: Remove after implementation policy update -- Precondition: remove policy table commonSteps:DeletePolicyTable() -- TODO: Remove after implementation policy update -- Precondition: replace preloaded file with new one os.execute('cp ./files/ptu_general.json ' .. tostring(config.pathToSDL) .. "sdl_preloaded_pt.json") --------------------------------------------------------------------------------------------- ---------------------------- General Settings for configuration---------------------------- --------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --Precondition: preparation connecttest_OnButton.lua commonPreconditions:Connecttest_without_ExitBySDLDisconnect("connecttest_OnButton.lua") commonPreconditions:Connecttest_OnButtonSubscription("connecttest_OnButton.lua") --Precondition: preparation connecttest_OnButton.lua f = assert(io.open('./user_modules/connecttest_OnButton.lua', "r")) fileContent = f:read("*all") f:close() local pattern2 = "%{%s-capabilities%s-=%s-%{.-%}" local pattern2Result = fileContent:match(pattern2) if pattern2Result == nil then print(" \27[31m capabilities array is not found in /user_modules/connecttest_OnButton.lua \27[0m ") else fileContent = string.gsub(fileContent, pattern2, '{capabilities = {button_capability("PRESET_0"),button_capability("PRESET_1"),button_capability("PRESET_2"),button_capability("PRESET_3"),button_capability("PRESET_4"),button_capability("PRESET_5"),button_capability("PRESET_6"),button_capability("PRESET_7"),button_capability("PRESET_8"),button_capability("PRESET_9"),button_capability("OK", true, false, true),button_capability("PLAY_PAUSE"),button_capability("SEEKLEFT"),button_capability("SEEKRIGHT"),button_capability("TUNEUP"),button_capability("TUNEDOWN"),button_capability("SEARCH")}') end f = assert(io.open('./user_modules/connecttest_OnButton.lua', "w+")) f:write(fileContent) f:close() Test = require('user_modules/connecttest_OnButton') require('cardinalities') local events = require('events') local mobile_session = require('mobile_session') --------------------------------------------------------------------------------------------- -----------------------------Required Shared Libraries--------------------------------------- --------------------------------------------------------------------------------------------- require('user_modules/AppTypes') APIName = "OnButtonEvent" -- set API name --List of app name and appid that used in script. appid will be set when registering application Apps = {} Apps[1] = {} Apps[1].appName = config.application1.registerAppInterfaceParams.appName Apps[2] = {} Apps[2].appName = config.application2.registerAppInterfaceParams.appName Apps[3] = {} Apps[3].appName = config.application3.registerAppInterfaceParams.appName local ButtonPressModes = {"SHORT", "LONG"} local CustomButtonIDs = {0, 65535} --Set list of button for media/non-media application local ButtonNames_WithoutCUSTOM_BUTTON local ButtonNames_WithoutCUSTOM_BUTTON_OK if config.application1.registerAppInterfaceParams.isMediaApplication then ButtonNames_WithoutCUSTOM_BUTTON = { "OK", "PLAY_PAUSE", "SEEKLEFT", "SEEKRIGHT", "TUNEUP", "TUNEDOWN", "PRESET_0", "PRESET_1", "PRESET_2", "PRESET_3", "PRESET_4", "PRESET_5", "PRESET_6", "PRESET_7", "PRESET_8", "PRESET_9", "SEARCH" } ButtonNames_WithoutCUSTOM_BUTTON_OK = { "PLAY_PAUSE", "SEEKLEFT", "SEEKRIGHT", "TUNEUP", "TUNEDOWN", "PRESET_0", "PRESET_1", "PRESET_2", "PRESET_3", "PRESET_4", "PRESET_5", "PRESET_6", "PRESET_7", "PRESET_8", "PRESET_9", "SEARCH" } else --Non-media app -- According to APPLINK-14516: The media buttons are Tune Up\Down, Seek Right\Left, and PRESET_0-PRESET_9. ButtonNames_WithoutCUSTOM_BUTTON = { "OK", "SEARCH" } ButtonNames_WithoutCUSTOM_BUTTON_OK = { "SEARCH" } end -- group of media buttons, this group should be update also with PRESETS 0-9 due to APPLINK-14516 (APPLINK-14503) local MediaButtons = { "PLAY_PAUSE", "SEEKLEFT", "SEEKRIGHT", "TUNEUP", "TUNEDOWN", -- "PRESET_0", -- "PRESET_1", -- "PRESET_2", -- "PRESET_3", -- "PRESET_4", -- "PRESET_5", -- "PRESET_6", -- "PRESET_7", -- "PRESET_8", -- "PRESET_9" } --------------------------------------------------------------------------------------------- ------------------------------------------Common functions----------------------------------- --------------------------------------------------------------------------------------------- --Functions to simulate action press button on HMI and verification on Mobile and HMI --------------------------------------------------------------------------------------------- --1. Press button function Test.pressButton(Input_Name, Input_ButtonPressMode, modeDOWNValue, modeUPValue) if modeUPValue == nil then modeUPValue = "BUTTONUP" end if modeDOWNValue == nil then modeDOWNValue = "BUTTONDOWN" end --hmi side: send OnButtonEvent, OnButtonPress Test.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = Input_Name, mode = modeDOWNValue}) if Input_ButtonPressMode == "SHORT" then Test.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = Input_Name, mode = modeUPValue}) Test.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = Input_Name, mode = Input_ButtonPressMode}) else Test.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = Input_Name, mode = Input_ButtonPressMode}) Test.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = Input_Name, mode = modeUPValue}) end end --2. Press CUSTOM_BUTTON function Test.pressButton_CUSTOM_BUTTON(Input_Name, Input_ButtonPressMode, Input_customButtonID, Input_appID) --hmi side: send OnButtonEvent, OnButtonPress Test.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = Input_Name, mode = "BUTTONDOWN", customButtonID = Input_customButtonID, appID = Input_appID}) if Input_ButtonPressMode == "SHORT" then Test.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = Input_Name, mode = "BUTTONUP", customButtonID = Input_customButtonID, appID = Input_appID}) Test.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = Input_Name, mode = Input_ButtonPressMode, customButtonID = Input_customButtonID, appID = Input_appID}) else Test.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = Input_Name, mode = Input_ButtonPressMode, customButtonID = Input_customButtonID, appID = Input_appID}) Test.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = Input_Name, mode = "BUTTONUP", customButtonID = Input_customButtonID, appID = Input_appID}) end end --Functions to verify result on Mobile --------------------------------------------------------------------------------------------- --1. Verify press button result on mobile function Test.verifyPressButtonResult(Input_Name, Input_ButtonPressMode) local BUTTONDOWN = false local BUTTONUP = false --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {buttonName = Input_Name, buttonEventMode = "BUTTONUP"}, {buttonName = Input_Name, buttonEventMode = "BUTTONDOWN"}) :Times(2) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = Input_Name, buttonPressMode = Input_ButtonPressMode}) end --2. Verify SDL ignores notification function Test.verifySDLIgnoresNotification(OnButtonEventNumber) commonTestCases:DelayedExp(1000) if OnButtonEventNumber == nil then OnButtonEventNumber = 0 end --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(OnButtonEventNumber) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {}) :Times(0) end --3. Verify press button result on mobile function Test.verifyPressButtonResult_IgnoreWrongButtonEventMode(Input_Name, Input_ButtonPressMode, modeDOWNValue, modeUPValue) if modeDOWNValue == "BUTTONDOWN" and modeUPValue ~= "BUTTONUP" then -- testing for wrong mode when SDL should send mode = BUTTONDOWN --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {buttonName = Input_Name, buttonEventMode = "BUTTONDOWN"}) elseif modeDOWNValue ~= "BUTTONDOWN" and modeUPValue == "BUTTONUP" then -- testing for wrong mode when SDL should send mode = BUTTONUP --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {buttonName = Input_Name, buttonEventMode = "BUTTONUP"}) else commonFunctions:printError("Error: in verifyPressButtonResult_IgnoreWrongButtonEventMode function") end --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = Input_Name, buttonPressMode = Input_ButtonPressMode}) end --4. Verify press button result on mobile for CUSTOM_BUTTON function Test.verifyPressButtonResult_CUSTOM_BUTTON(Input_Name, Input_ButtonPressMode, Input_customButtonID, Input_appID) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {buttonName = Input_Name, buttonEventMode = "BUTTONDOWN", customButtonID = Input_customButtonID}, {buttonName = Input_Name, buttonEventMode = "BUTTONUP", customButtonID = Input_customButtonID} ) :Times(2) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = Input_Name, buttonPressMode = Input_ButtonPressMode, customButtonID = Input_customButtonID}) end --Functions to create common test cases --------------------------------------------------------------------------------------------- --1. Press button and SDL forwards the notification to Mobile local function TC_SendOnButtonEvent_SUCCESS(Input_Name, Input_ButtonPressMode, TestCaseName) Test[TestCaseName .. "_name_" .. Input_Name .."_mode_" .. Input_ButtonPressMode] = function(self) --Press button on HMI self.pressButton(Input_Name, Input_ButtonPressMode) --Verify result on Mobile self.verifyPressButtonResult(Input_Name, Input_ButtonPressMode) end end --2. Press button and SDL ignores the notification local function TC_SendOnButtonEvent_IsIgnored(Input_Name, Input_ButtonPressMode, TestCaseName, OnButtonEventNumber) Test[TestCaseName .. "_name_" .. Input_Name .."_mode_" .. Input_ButtonPressMode] = function(self) --Press button on HMI self.pressButton(Input_Name, Input_ButtonPressMode) --Verify result on Mobile self.verifySDLIgnoresNotification(OnButtonEventNumber) end end --3. Press button and SDL ignores the notification local function TC_SendOnButtonEvent_mode_IsInvalid_IsIgnored(Input_Name, Input_ButtonPressMode, TestCaseName, modeDOWNValue, modeUPValue) Test[TestCaseName .. "_name_" .. Input_Name .."_mode_" .. Input_ButtonPressMode .. "_Event1Mode_" .. modeDOWNValue .. "_Event2Mode_" .. modeUPValue] = function(self) --Press button on HMI self.pressButton(Input_Name, Input_ButtonPressMode, modeDOWNValue, modeUPValue) --Verify result on Mobile self.verifyPressButtonResult_IgnoreWrongButtonEventMode(Input_Name, Input_ButtonPressMode, modeDOWNValue, modeUPValue) end end --4. Press CUSTOM_BUTTON and SDL forwards the notification to Mobile local function TC_SendOnButtonEvent_CUSTOM_BUTTON_SUCCESS(Input_Name, Input_ButtonPressMode, Input_customButtonID, Input_appNumber, TestCaseName) Test[TestCaseName .. "_name_" .. Input_Name .."_mode_" .. Input_ButtonPressMode .. "_customButtonID_" .. Input_customButtonID] = function(self) --Press button on HMI self.pressButton_CUSTOM_BUTTON(Input_Name, Input_ButtonPressMode, Input_customButtonID, Apps[Input_appNumber].appID) --Verify result on Mobile self.verifyPressButtonResult_CUSTOM_BUTTON(Input_Name, Input_ButtonPressMode, Input_customButtonID, Apps[Input_appNumber].appID) end end --5. Press CUSTOM_BUTTON and SDL ignores the notification local function TC_SendOnButtonEvent_CUSTOM_BUTTON_IsIgnored(Input_Name, Input_ButtonPressMode, Input_customButtonID, Input_appNumber, TestCaseName) Test[TestCaseName .. "_name_" .. Input_Name .."_mode_" .. Input_ButtonPressMode .. "_customButtonID_" .. Input_customButtonID] = function(self) --Press button on HMI self.pressButton_CUSTOM_BUTTON(Input_Name, Input_ButtonPressMode, Input_customButtonID, Apps[Input_appNumber].appID) --Verify result on Mobile self.verifySDLIgnoresNotification() end end function Test:registerAppInterface2() --mobile side: sending request local CorIdRegister = self.mobileSession1:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams) --hmi side: expect BasicCommunication.OnAppRegistered request EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application2.registerAppInterfaceParams.appName } }) :Do(function(_,data) self.applications[config.application2.registerAppInterfaceParams.appName] = data.params.application.appID end) --mobile side: expect response self.mobileSession1:ExpectResponse(CorIdRegister, { syncMsgVersion = config.syncMsgVersion }) :Timeout(2000) --mobile side: expect notification self.mobileSession1:ExpectNotification("OnHMIStatus", {{systemContext = "MAIN", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"}}) :Timeout(2000) end function Test:registerAppInterface3() --mobile side: sending request local CorIdRegister = self.mobileSession2:SendRPC("RegisterAppInterface", config.application3.registerAppInterfaceParams) --hmi side: expect BasicCommunication.OnAppRegistered request EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application3.registerAppInterfaceParams.appName } }) :Do(function(_,data) self.applications[config.application3.registerAppInterfaceParams.appName] = data.params.application.appID end) --mobile side: expect response self.mobileSession2:ExpectResponse(CorIdRegister, { syncMsgVersion = config.syncMsgVersion }) :Timeout(2000) --mobile side: expect notification self.mobileSession2:ExpectNotification("OnHMIStatus", { systemContext = "MAIN", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"}) :Timeout(2000) end --------------------------------------------------------------------------------------------- -------------------------------------------Preconditions------------------------------------- --------------------------------------------------------------------------------------------- commonSteps:DeleteLogsFileAndPolicyTable() -- Precondition: removing user_modules/connecttest_OnButton.lua function Test:Remove_user_connecttest() os.execute( "rm -f ./user_modules/connecttest_OnButton.lua" ) end --Print new line to separate new test cases group commonFunctions:newTestCasesGroup("Preconditions") --1. Activate application commonSteps:ActivationApp() --2. Create PT that allowed OnButtonEvent in Base-4 group and update PT local PermissionLines_OnButtonEvent = [[ "OnButtonEvent": { "hmi_levels": [ "FULL", "LIMITED" ] }]] .. ", \n" local PermissionLines_OnButtonPress = [[ "OnButtonPress": { "hmi_levels": [ "FULL", "LIMITED" ] }]] .. ", \n" local PermissionLines_Show = [[ "Show": { "hmi_levels": [ "FULL", "LIMITED" ] }]] .. ", \n" local PermissionLinesForBase4 = PermissionLines_OnButtonEvent .. PermissionLines_OnButtonPress .. PermissionLines_Show local PermissionLinesForGroup1 = nil local PermissionLinesForApplication = nil -- TODO: update after implementation of policy update -- local PTName = testCasesForPolicyTable:createPolicyTableFile(PermissionLinesForBase4, PermissionLinesForGroup1, PermissionLinesForApplication, {"OnButtonEvent", "OnButtonPress", "Show"}) -- testCasesForPolicyTable:updatePolicy(PTName) --3. Get appID Value on HMI side function Test:GetAppID() Apps[1].appID = self.applications[Apps[1].appName] end --4. Send Show request with buttonIDs are lower and upper bounds Test["Show_buttonID_IsLowerUpperBound"] = function(self) --mobile side: request parameters local Request = { softButtons = { { text = "Button1", systemAction = "DEFAULT_ACTION", type = "TEXT", isHighlighted = false, softButtonID = CustomButtonIDs[1] }, { text = "Button2", systemAction = "DEFAULT_ACTION", type = "TEXT", isHighlighted = false, softButtonID = CustomButtonIDs[2] } } } --mobile side: sending Show request local cid = self.mobileSession:SendRPC("Show", Request) --hmi side: expect UI.Show request EXPECT_HMICALL("UI.Show") :Do(function(_,data) --hmi side: sending UI.Show response self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) --mobile side: expect SetGlobalProperties response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" }) end --5. SubscribeButton for i=1,#ButtonNames_WithoutCUSTOM_BUTTON do Test["SubscribeButton_" .. tostring(ButtonNames_WithoutCUSTOM_BUTTON[i])] = function(self) --mobile side: sending SubscribeButton request local cid = self.mobileSession:SendRPC("SubscribeButton", { buttonName = ButtonNames_WithoutCUSTOM_BUTTON[i] }) --expect Buttons.OnButtonSubscription EXPECT_HMINOTIFICATION("Buttons.OnButtonSubscription", {appID = Apps[1].appID, isSubscribed = true, name = ButtonNames_WithoutCUSTOM_BUTTON[i]}) --mobile side: expect SubscribeButton response EXPECT_RESPONSE(cid, {success = true, resultCode = "SUCCESS"}) EXPECT_NOTIFICATION("OnHashChange", {}) end end ----------------------------------------------------------------------------------------------- -------------------------------------------TEST BLOCK I---------------------------------------- --------------------------------Check normal cases of Mobile request--------------------------- ----------------------------------------------------------------------------------------------- --Not Applicable ---------------------------------------------------------------------------------------------- -----------------------------------------TEST BLOCK II---------------------------------------- -----------------------------Check special cases of Mobile request---------------------------- ---------------------------------------------------------------------------------------------- --Not Applicable ----------------------------------------------------------------------------------------------- -------------------------------------------TEST BLOCK III-------------------------------------- ----------------------------------Check normal cases of HMI notification--------------------------- ----------------------------------------------------------------------------------------------- --Requirement id in JAMA or JIRA: --SDLAQ-CRS-171: OnButtonEvent_v2_0: Notifies application of LONG/SHORT press events for buttons to which the application is subscribed. --SDLAQ-CRS-3065: OnButtonEvent to media app in FULL --SDLAQ-CRS-3066: OnButtonEvent to media app in LIMITED --Verification criteria: --1. The OnButtonEvent of DOWN and OnButtonEvent of UP is sent by SDL on each pressing of every subscribed hardware or software preset HMI button. --2. The OnButtonEvent of DOWN and OnButtonEvent of UP is sent by SDL on each pressing of every subscribed custom HMI button. ---------------------------------------------------------------------------------------------- --List of parameters: --1. buttonName: type=ButtonName --2. buttonEventMode: type=ButtonEventMode --3. customButtonID: type=Integer, minvalue=0, maxvalue=65536 (If ButtonName is "CUSTOM_BUTTON", this references the integer ID passed by a custom button. (e.g. softButton ID)) ---------------------------------------------------------------------------------------------- --Print new line to separate new test cases group commonFunctions:newTestCasesGroup("Test suite: Check normal cases of HMI notification") ---------------------------------------------------------------------------------------------- --Test case #1: Checks OnButtonEvent notification with valid values of buttonName, buttonPressMode and customButtonID parameters ---------------------------------------------------------------------------------------------- --1.1. Verify buttonName and buttonEventMode (UP and DOWN) parameters with valid values for i =1, #ButtonNames_WithoutCUSTOM_BUTTON do for j =1, #ButtonPressModes do TC_SendOnButtonEvent_SUCCESS(ButtonNames_WithoutCUSTOM_BUTTON[i], ButtonPressModes[j], "OnButtonEvent") end end --1.2. Verify CUSTOM_BUTTON: customButtonID and mode parameters are valid values for j =1, #ButtonPressModes do for n = 1, #CustomButtonIDs do TC_SendOnButtonEvent_CUSTOM_BUTTON_SUCCESS("CUSTOM_BUTTON", ButtonPressModes[j], CustomButtonIDs[n], 1, "OnButtonEvent") end end ---------------------------------------------------------------------------------------------- --Test case #2: Checks OnButtonEvent is NOT sent to application after SDL received OnButtonEvent with invalid buttonName and buttonPressMode --Requirement: APPLINK-9736 ---------------------------------------------------------------------------------------------- --Print new line to separate new test cases group commonFunctions:newTestCasesGroup("Test suite: Check invalid buttonName") --2.1. Verify buttonName is invalid value local InvalidButtonNames = { {value = "", name = "IsEmtpy"}, {value = "ANY", name = "NonExist"}, {value = 123, name = "WrongDataType"} } for i =1, #InvalidButtonNames do for j =1, #ButtonPressModes do TestCaseName = "OnButtonEvent_buttonName_IsInvalid_" .. InvalidButtonNames[i].name TC_SendOnButtonEvent_IsIgnored(InvalidButtonNames[i].value, ButtonPressModes[j], TestCaseName) end end --2.2. Verify buttonEventMode is invalid value (not UP and DOWN) --Print new line to separate new test cases group commonFunctions:newTestCasesGroup("Test suite: Check invalid mode") local InvalidButtonEventModes = { {value = "", name = "IsEmtpy"}, {value = "ANY", name = "NonExist"}, {value = 123, name = "WrongDataType"} } for i =1, #ButtonNames_WithoutCUSTOM_BUTTON do for j =1, #ButtonPressModes do for n = 1, #InvalidButtonEventModes do --Invalid mode in OnButtonEvent when mode should be DOWN TestCaseName = "OnButtonEvent_mode_IsInvalidWhenItShouldBeDOWN_".. InvalidButtonEventModes[n].name TC_SendOnButtonEvent_mode_IsInvalid_IsIgnored(ButtonNames_WithoutCUSTOM_BUTTON[i], ButtonPressModes[j], TestCaseName, InvalidButtonEventModes[n].value, "BUTTONUP") --Invalid mode in OnButtonEvent when mode should be UP TestCaseName = "OnButtonEvent_mode_IsInvalidWhenItShouldBeUP_".. InvalidButtonEventModes[n].name TC_SendOnButtonEvent_mode_IsInvalid_IsIgnored(ButtonNames_WithoutCUSTOM_BUTTON[i], ButtonPressModes[j], TestCaseName, "BUTTONDOWN", InvalidButtonEventModes[n].value) end end end --2.3. Verify customButtonID is invalid value --Print new line to separate new test cases group commonFunctions:newTestCasesGroup("Test suite: Check invalid CustomButtonID") local InvalidCustomButtonIDs = { {value = CustomButtonIDs[1]-1, name = "IsOutLowerBound"}, {value = CustomButtonIDs[2] + 1, name = "IsOutUpperBound"}, {value = "1", name = "WrongDataType"} } local appNumber = 1 for j =1, #ButtonPressModes do for n = 1, #InvalidCustomButtonIDs do TestCaseName = "OnButtonEvent_customButtonID_IsInvalid_" .. InvalidCustomButtonIDs[n].name TC_SendOnButtonEvent_CUSTOM_BUTTON_IsIgnored("CUSTOM_BUTTON", ButtonPressModes[j], InvalidCustomButtonIDs[n].value, appNumber, TestCaseName) end end --2.4. Verify appID is invalid value. --Print new line to separate new test cases group commonFunctions:newTestCasesGroup("Test suite: Check invalid appID") local Invalid_appIDs = { {value = 123456, name = "IsNonexistent"}, {value = "1", name = "WrongDataType"} } for i = 1, #Invalid_appIDs do Test["OnButtonEvent_appID_" .. Invalid_appIDs[i].name] = function(self) commonTestCases:DelayedExp(1000) --hmi side: send OnButtonEvent, OnButtonPress self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "CUSTOM_BUTTON", mode = "BUTTONDOWN", customButtonID = CustomButtonIDs[1], appID = Invalid_appIDs[i].value}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "CUSTOM_BUTTON", mode = "BUTTONUP", customButtonID = CustomButtonIDs[1], appID = Invalid_appIDs[i].value}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "CUSTOM_BUTTON", mode = "SHORT", customButtonID = CustomButtonIDs[1], appID = Apps[1].appID}) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(0) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "CUSTOM_BUTTON", buttonPressMode = "SHORT"}) end end ---------------------------------------------------------------------------------------------- -----------------------------------------TEST BLOCK IV---------------------------------------- ----------------------------Check special cases of HMI notification--------------------------- ---------------------------------------------------------------------------------------------- --Requirement id in JAMA or JIRA: --APPLINK-14765: SDL must cut off the fake parameters from requests, responses and notifications received from HMI --APPLINK-9736: SDL must ignore the invalid notifications from HMI ----------------------------------------------------------------------------------------------- --List of test cases for special cases of HMI notification: --1. InvalidJsonSyntax --2. InvalidStructure --3. FakeParams --4. FakeParameterIsFromAnotherAPI --5. MissedmandatoryParameters --6. MissedAllPArameters --7. SeveralNotifications with the same values --8. SeveralNotifications with different values ---------------------------------------------------------------------------------------------- local function SpecialResponseChecks() --Print new line to separate new test cases group commonFunctions:newTestCasesGroup("Test suite: Check special cases of HMI notification") --1. Verify OnButtonEvent with invalid Json syntax ---------------------------------------------------------------------------------------------- function Test:OnButtonEvent_InvalidJsonSyntax() commonTestCases:DelayedExp(1000) --hmi side: send OnButtonEvent --":" is changed by ";" after "jsonrpc" self.hmiConnection:Send('{"jsonrpc";"2.0","params":{"mode":"UP","name":"PRESET_0"},"method":"Buttons.OnButtonEvent"}') EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(0) end --2. Verify OnButtonEvent with invalid structure ---------------------------------------------------------------------------------------------- function Test:OnButtonEvent_InvalidStructure() commonTestCases:DelayedExp(1000) --hmi side: send OnButtonEvent --method is moved into params parameter self.hmiConnection:Send('{"jsonrpc":"2.0","params":{"mode":"UP","name":"PRESET_0","method":"Buttons.OnButtonEvent"}}') EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(0) end --3. Verify OnButtonEvent with FakeParams ---------------------------------------------------------------------------------------------- function Test:OnButtonEvent_FakeParams() --hmi side: send OnButtonEvent, OnButtonPress self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "SEARCH", mode = "BUTTONDOWN", fake = 123}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "SEARCH", mode = "BUTTONUP", fake = 123}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "SEARCH", mode = "SHORT"}) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {buttonName = "SEARCH", buttonEventMode = "BUTTONDOWN"}, {buttonName = "SEARCH", buttonEventMode = "BUTTONUP"}) :Times(2) :ValidIf(function(_,data) if data.payload.fake then commonFunctions:printError(" SDL forwards fake parameter to mobile ") return false else return true end end) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "SEARCH", buttonPressMode = "SHORT"}) end --4. Verify OnButtonEvent with FakeParameterIsFromAnotherAPI function Test:OnButtonEvent_FakeParameterIsFromAnotherAPI() --hmi side: send OnButtonEvent, OnButtonPress self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "SEARCH", mode = "BUTTONDOWN", sliderPosition = 1}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "SEARCH", mode = "BUTTONUP", sliderPosition = 1}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "SEARCH", mode = "SHORT"}) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {buttonName = "SEARCH", buttonEventMode = "BUTTONDOWN"}, {buttonName = "SEARCH", buttonEventMode = "BUTTONUP"}) :Times(2) :ValidIf(function(_,data) if data.payload.sliderPosition then commonFunctions:printError(" SDL forwards fake parameter to mobile ") return false else return true end end) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "SEARCH", buttonPressMode = "SHORT"}) end --5. Verify OnButtonEvent misses mandatory parameter ---------------------------------------------------------------------------------------------- function Test:OnButtonEvent_name_IsMissed() commonTestCases:DelayedExp(1000) --hmi side: send OnButtonEvent, OnButtonPress self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{mode = "BUTTONDOWN"}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{mode = "BUTTONUP"}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "SEARCH", mode = "SHORT"}) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(0) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "SEARCH", buttonPressMode = "SHORT"}) end function Test:OnButtonEvent_mode_IsMissed() commonTestCases:DelayedExp(1000) --hmi side: send OnButtonEvent, OnButtonPress self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "SEARCH"}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "SEARCH"}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "SEARCH", mode = "SHORT"}) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(0) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "SEARCH", buttonPressMode = "SHORT"}) end function Test:OnButtonEvent_appID_IsMissed() commonTestCases:DelayedExp(1000) --hmi side: send OnButtonEvent, OnButtonPress self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "CUSTOM_BUTTON", mode = "BUTTONDOWN", customButtonID = CustomButtonIDs[1]}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "CUSTOM_BUTTON", mode = "BUTTONUP", customButtonID = CustomButtonIDs[1]}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "CUSTOM_BUTTON", mode = "SHORT", customButtonID = CustomButtonIDs[1], appID = Apps[1].appID}) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(0) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "CUSTOM_BUTTON", buttonPressMode = "SHORT"}) end function Test:OnButtonEvent_customButtonID_IsMissed() commonTestCases:DelayedExp(1000) --hmi side: send OnButtonEvent, OnButtonPress self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "CUSTOM_BUTTON", mode = "BUTTONDOWN", appID = Apps[1].appID}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "CUSTOM_BUTTON", mode = "BUTTONUP", appID = Apps[1].appID}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "CUSTOM_BUTTON", mode = "SHORT", customButtonID = CustomButtonIDs[1], appID = Apps[1].appID}) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(0) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "CUSTOM_BUTTON", buttonPressMode = "SHORT"}) end function Test:OnButtonEvent_customButtonID_and_appID_AreMissed() commonTestCases:DelayedExp(1000) --hmi side: send OnButtonEvent, OnButtonPress self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "CUSTOM_BUTTON", mode = "BUTTONDOWN"}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "CUSTOM_BUTTON", mode = "BUTTONUP"}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "CUSTOM_BUTTON", mode = "SHORT", customButtonID = CustomButtonIDs[1], appID = Apps[1].appID}) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(0) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "CUSTOM_BUTTON", buttonPressMode = "SHORT"}) end --6. Verify OnButtonEvent MissedAllPArameters: The same as case 5. ---------------------------------------------------------------------------------------------- function Test:OnButtonEvent_AllParameters_AreMissed() commonTestCases:DelayedExp(1000) --hmi side: send OnButtonEvent, OnButtonPress self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "SEARCH", mode = "SHORT"}) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(0) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "SEARCH", buttonPressMode = "SHORT"}) end --7. Verify OnButtonEvent with SeveralNotifications_WithTheSameValues ---------------------------------------------------------------------------------------------- function Test:OnButtonEvent_SeveralNotifications_WithTheSameValues() --hmi side: send OnButtonEvent, OnButtonPress self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "SEARCH", mode = "BUTTONDOWN"}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "SEARCH", mode = "BUTTONDOWN"}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "SEARCH", mode = "SHORT"}) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {buttonName = "SEARCH", buttonEventMode = "BUTTONDOWN"}) :Times(2) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "SEARCH", buttonPressMode = "SHORT"}) end --8. Verify OnButtonEvent with SeveralNotifications_WithDifferentValues ---------------------------------------------------------------------------------------------- function Test:OnButtonEvent_SeveralNotifications_WithDifferentValues() --hmi side: send OnButtonEvent, OnButtonPress self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "SEARCH", mode = "BUTTONDOWN"}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "SEARCH", mode = "BUTTONUP"}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "SEARCH", mode = "BUTTONDOWN"}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "SEARCH", mode = "BUTTONUP"}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "SEARCH", mode = "SHORT"}) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(4) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "SEARCH", buttonPressMode = "SHORT"}) end end SpecialResponseChecks() ----------------------------------------------------------------------------------------------- -------------------------------------------TEST BLOCK V---------------------------------------- -------------------------------------Checks All Result Codes----------------------------------- ----------------------------------------------------------------------------------------------- --TODO: block should to be updated for Genivi --Description: Check all resultCodes --Requirement id in JAMA: --N/A --Verification criteria: Verify SDL behaviors in different states of policy table: --1. Notification is not exist in PT => DISALLOWED in policy table, SDL ignores the notification --2. Notification is exist in PT but it has not consented yet by user => DISALLOWED in policy table, SDL ignores the notification --3. Notification is exist in PT but user does not allow function group that contains this notification => USER_DISALLOWED in policy table, SDL ignores the notification --4. Notification is exist in PT and user allow function group that contains this notification ---------------------------------------------------------------------------------------------- -- local function ResultCodeChecks() -- --Print new line to separate new test cases group -- commonFunctions:newTestCasesGroup("Test suite: Checks All Result Codes") -- --Send notification and check it is ignored -- local function TC_OnButtonEvent_DISALLOWED_USER_DISALLOWED(TestCaseName) -- Test[TestCaseName] = function(self) -- commonTestCases:DelayedExp(1000) -- --hmi side: send OnButtonEvent, OnButtonPress -- self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "PRESET_0", mode = "BUTTONDOWN"}) -- self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "PRESET_0", mode = "BUTTONUP"}) -- self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "PRESET_0", mode = "SHORT"}) -- --mobile side: expected OnButtonEvent notification -- EXPECT_NOTIFICATION("OnButtonEvent", {}) -- :Times(0) -- --mobile side: expected OnButtonPress notification -- EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "PRESET_0", buttonPressMode = "SHORT"}) -- end -- end -- --1. Notification is not exist in PT => DISALLOWED in policy table, SDL ignores the notification -- ---------------------------------------------------------------------------------------------- -- --Precondition: Build policy table file -- local PTFileName = testCasesForPolicyTable:createPolicyTableWithoutAPI("OnButtonEvent") -- --Precondition: Update policy table -- testCasesForPolicyTable:updatePolicy(PTFileName) -- TC_OnButtonEvent_DISALLOWED_USER_DISALLOWED("OnButtonEvent_IsNotExistInPT_DISALLOWED") -- ---------------------------------------------------------------------------------------------- -- --2. Notification is exist in PT but it has not consented yet by user => DISALLOWED in policy table, SDL ignores the notification -- ---------------------------------------------------------------------------------------------- -- --Precondition: Build policy table file -- local PermissionLinesForBase4 = -- [[ "OnButtonPress": { -- "hmi_levels": [ -- "FULL", -- "LIMITED" -- ] -- }]] .. ",\n" -- local PermissionLinesForGroup1 = -- [[ "OnButtonEvent": { -- "hmi_levels": [ -- "FULL", -- "LIMITED" -- ] -- }]] .. "\n" -- local appID = config.application1.registerAppInterfaceParams.fullAppID -- local PermissionLinesForApplication = -- [[ "]]..appID ..[[" : { -- "keep_context" : false, -- "steal_focus" : false, -- "priority" : "NONE", -- "default_hmi" : "NONE", -- "groups" : ["Base-4", "group1"] -- }, -- ]] -- local PTName = testCasesForPolicyTable:createPolicyTableFile(PermissionLinesForBase4, PermissionLinesForGroup1, PermissionLinesForApplication, {"OnButtonEvent", "OnButtonPress"}) -- --NOTE: This TC is blocked on ATF 2.2 by defect APPLINK-19188. Please try ATF on commit f86f26112e660914b3836c8d79002e50c7219f29 -- testCasesForPolicyTable:updatePolicy(PTName) -- --Send notification and check it is ignored -- TC_OnButtonEvent_DISALLOWED_USER_DISALLOWED("OnButtonEvent_UserHasNotConsentedYet_DISALLOWED") -- ---------------------------------------------------------------------------------------------- -- --3. Notification is exist in PT but user does not allow function group that contains this notification => USER_DISALLOWED in policy table, SDL ignores the notification -- ---------------------------------------------------------------------------------------------- -- --Precondition: User does not allow function group -- testCasesForPolicyTable:userConsent(false, "group1") -- --Send notification and check it is ignored -- TC_OnButtonEvent_DISALLOWED_USER_DISALLOWED("OnButtonEvent_USER_DISALLOWED") -- ---------------------------------------------------------------------------------------------- -- --4. Notification is exist in PT and user allow function group that contains this notification -- ---------------------------------------------------------------------------------------------- -- --Precondition: User allows function group -- testCasesForPolicyTable:userConsent(true, "group1") -- function Test:OnButtonEvent_USER_ALLOWED() -- commonTestCases:DelayedExp(1000) -- --hmi side: send OnButtonEvent, OnButtonPress -- self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "PRESET_0", mode = "BUTTONDOWN"}) -- self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "PRESET_0", mode = "BUTTONUP"}) -- self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "PRESET_0", mode = "SHORT"}) -- --mobile side: expected OnButtonEvent notification -- EXPECT_NOTIFICATION("OnButtonEvent", -- {buttonName = "PRESET_0", buttonEventMode = "BUTTONUP"}, -- {buttonName = "PRESET_0", buttonEventMode = "BUTTONDOWN"}) -- :Times(2) -- --mobile side: expected OnButtonPress notification -- EXPECT_NOTIFICATION("OnButtonPress", {buttonName = "PRESET_0", buttonPressMode = "SHORT"}) -- end -- ---------------------------------------------------------------------------------------------- -- end -- --NOTE: This TC is blocked on ATF 2.2 by defect APPLINK-19188. Please unbock below code and try ATF on commit f86f26112e660914b3836c8d79002e50c7219f29 -- ResultCodeChecks() ---------------------------------------------------------------------------------------------- -----------------------------------------TEST BLOCK VI---------------------------------------- -------------------------Sequence with emulating of user's action(s)-------------------------- ---------------------------------------------------------------------------------------------- --Description: TC's checks SDL behavior by processing -- different request sequence with timeout -- with emulating of user's actions --Requirement id in JAMA: --1. SDLAQ-CRS-2908: OnButtonEvent with unknown buttonID from HMI --2. SDLAQ-CRS-3065: OnButtonEvent to media app in FULL --3. SDLAQ-CRS-3066: OnButtonEvent to media app in LIMITED --4. APPLINK-20202: OnButtonEvent is sent to Media app if button is already subscribed --Print new line to separate new test cases group commonFunctions:newTestCasesGroup("Test suite: Sequence with emulating of user's action(s)") ---------------------------------------------------------------------------------------------- --1. OnButtonEvent with unknown buttonID from HMI function Test:OnButtonEvent_WithUnknownButtonID() commonTestCases:DelayedExp(1000) local UnknowButtonID = 2 --hmi side: send OnButtonEvent, OnButtonPress Test.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "CUSTOM_BUTTON", mode = "BUTTONDOWN", customButtonID = UnknowButtonID, appID = Apps[1].appID}) Test.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = "CUSTOM_BUTTON", mode = "BUTTONUP", customButtonID = UnknowButtonID, appID = Apps[1].appID}) Test.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = "CUSTOM_BUTTON", mode = "SHORT", customButtonID = UnknowButtonID, appID = Apps[1].appID}) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(0) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {}) :Times(0) end --------------------------------------------------------------------------------------------- --2. SDLAQ-CRS-3065: OnButtonEvent to media app in FULL --Print new line to separate new test cases group commonFunctions:newTestCasesGroup("Test suite: OnButtonEvent notification is only sent to FULL media application") -- Precondition 1: Opening new session function Test:AddNewSession2() -- Connected expectation self.mobileSession1 = mobile_session.MobileSession(Test,Test.mobileConnection) self.mobileSession1:StartService(7) end function Test:Register_Media_App2() --mobile side: RegisterAppInterface request config.application2.registerAppInterfaceParams.isMediaApplication = true config.application2.registerAppInterfaceParams.appHMIType = {"MEDIA"} self:registerAppInterface2() end function Test:Activation_Media_App2() local rid = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application2.registerAppInterfaceParams.appName]}) EXPECT_HMIRESPONSE(rid) :Do(function(_,data) if data.result.code ~= 0 then quit() end end) --mobile side: expect notification self.mobileSession1:ExpectNotification("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "BACKGROUND", systemContext = "MAIN"}) end local function SubscribeMediaButton(TestCaseName, ButtonName, session) Test[TestCaseName] = function(self) if session == 2 then --mobile side: sending SubscribeButton request cid = self.mobileSession1:SendRPC("SubscribeButton",{ buttonName = ButtonName}) --expect Buttons.OnButtonSubscription EXPECT_HMINOTIFICATION("Buttons.OnButtonSubscription", {appID = Apps[2].appID, isSubscribed = true, name = ButtonName}) :Times(1) --mobile side: expect SubscribeButton response self.mobileSession1:ExpectResponse(cid, {success = true, resultCode = "SUCCESS"}) self.mobileSession1:ExpectNotification("OnHashChange", {}) :Times(1) end if session == 3 then --mobile side: sending SubscribeButton request cid = self.mobileSession2:SendRPC("SubscribeButton",{ buttonName = ButtonName}) --expect Buttons.OnButtonSubscription EXPECT_HMINOTIFICATION("Buttons.OnButtonSubscription", {appID = Apps[3].appID, isSubscribed = true, name = ButtonName}) :Times(1) --mobile side: expect SubscribeButton response self.mobileSession2:ExpectResponse(cid, {success = true, resultCode = "SUCCESS"}) self.mobileSession2:ExpectNotification("OnHashChange", {}) :Times(1) end end end for i=1, #MediaButtons do SubscribeMediaButton("App2SubscribeButton"..MediaButtons[i], MediaButtons[i], 2) end function Test:AddNewSession3() self.mobileSession2 = mobile_session.MobileSession(Test,Test.mobileConnection) self.mobileSession2:StartService(7) end function Test:Register_Media_App3() config.application3.registerAppInterfaceParams.isMediaApplication = true config.application3.registerAppInterfaceParams.appHMIType = {"MEDIA"} self:registerAppInterface3() end function Test:Activation_Media_App3() local rid = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application3.registerAppInterfaceParams.appName]}) EXPECT_HMIRESPONSE(rid) :Do(function(_,data) if data.result.code ~= 0 then quit() end end) --mobile side: expect notification self.mobileSession2:ExpectNotification("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) self.mobileSession1:ExpectNotification("OnHMIStatus", {hmiLevel = "BACKGROUND", systemContext = "MAIN"}) end for i=1, #MediaButtons do SubscribeMediaButton("App3SubscribeButton"..MediaButtons[i], MediaButtons[i], 3) end function Test:Deactivate_App3_To_None_Hmi_Level() --hmi side: sending BasicCommunication.OnExitApplication notification self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {appID = self.applications[config.application3.registerAppInterfaceParams.appName],reason = "USER_EXIT"}) self.mobileSession2:ExpectNotification("OnHMIStatus", { systemContext = "MAIN", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"}) end function Test:Activation_App1() --hmi side: sending SDL.ActivateApp request local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = self.applications[config.application1.registerAppInterfaceParams.appName]}) EXPECT_HMIRESPONSE(RequestId) --mobile side: expect notification EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) end local function OnButtonEvent_OnlyComesToFullOrLimitedHmiLevelApplication(TestCaseName, ButtonName, buttonPressMode) Test[TestCaseName] = function(self) commonTestCases:DelayedExp(1000) --hmi side: send OnButtonEvent, OnButtonEvent self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = ButtonName, mode = "BUTTONDOWN"}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = ButtonName, mode = "BUTTONUP"}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = ButtonName, mode = buttonPressMode}) --Verify result on Mobile for app1 in FULL or LIMITED self.verifyPressButtonResult(ButtonName, buttonPressMode) --Verify result on Mobile for app2 in BACKGROUND: Non OnButtonEvent notification is sent to app2 self.mobileSession1:ExpectNotification("OnButtonEvent", {}) :Times(0) --mobile side: expected OnButtonPress notification self.mobileSession1:ExpectNotification("OnButtonPress", {}) :Times(0) --Verify result on Mobile for app3 in NONE: Non OnButtonEvent notification is sent to app3 self.mobileSession2:ExpectNotification("OnButtonEvent", {}) :Times(0) --mobile side: expected OnButtonPress notification self.mobileSession2:ExpectNotification("OnButtonPress", {}) :Times(0) end end for i,v in ipairs({"SHORT", "LONG"}) do for i=1,#ButtonNames_WithoutCUSTOM_BUTTON do OnButtonEvent_OnlyComesToFullOrLimitedHmiLevelApplication("OnlyFullApplicationReceivesOnButtonEvent" .. ButtonNames_WithoutCUSTOM_BUTTON[i] .. '_' .. tostring(v), ButtonNames_WithoutCUSTOM_BUTTON[i], tostring(v)) end end ---------------------------------------------------------------------------------------------- --3. SDLAQ-CRS-3066: OnButtonEvent to media app in LIMITED if commonFunctions:isMediaApp() then --Print new line to separate new test cases group commonFunctions:newTestCasesGroup("Test suite: OnButtonEvent notification is only sent to LIMITED media application") --Change app1 to LIMITED commonSteps:ChangeHMIToLimited() for i,v in ipairs({"SHORT", "LONG"}) do for i=1,#ButtonNames_WithoutCUSTOM_BUTTON do OnButtonEvent_OnlyComesToFullOrLimitedHmiLevelApplication("OnlyLimitedApplicationReceivesOnButtonEvent"..ButtonNames_WithoutCUSTOM_BUTTON[i] .. "_" .. tostring(v), ButtonNames_WithoutCUSTOM_BUTTON[i], tostring(v)) end end end --4. APPLINK-20202: SDL only sends OnButtonEvent to FULL Media app if buttons are already subscribed commonFunctions:newTestCasesGroup("APPLINK-20202: 3 apps (LIMITED, BACKGROUND and FULL) and OnButtonEvent notification is only sent to FULL media app if it's buttons already subscribed") commonSteps:UnregisterApplication("APPLINK_20202_UnregisterApp1") function Test:APPLINK_20202_Change_App1_To_Media() config.application1.registerAppInterfaceParams.isMediaApplication = true config.application1.registerAppInterfaceParams.appHMIType = {"MEDIA"} end commonSteps:RegisterAppInterface("APPLINK_20202_RegisterMediaApp1") commonSteps:ActivationApp(_,"APPLINK_20202_ActivateMediaApp1") function Test:APPLINK_20202_Precondition_UnregisterApp3() local cid = self.mobileSession2:SendRPC("UnregisterAppInterface",{}) self.mobileSession2:ExpectResponse(cid, { success = true, resultCode = "SUCCESS"}) end function Test:APPLINK_20202_RegisterNavigationApp3() config.application3.registerAppInterfaceParams.isMediaApplication = false config.application3.registerAppInterfaceParams.appHMIType = {"NAVIGATION"} self:registerAppInterface3() end function Test:APPLINK_20202_ActivateNavigationApp3() local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = self.applications[config.application3.registerAppInterfaceParams.appName]}) EXPECT_HMIRESPONSE(RequestId) self.mobileSession2:ExpectNotification("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "LIMITED", systemContext = "MAIN"}) end function Test:APPLINK_20202_Activation_MediaApp2() local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = self.applications[config.application2.registerAppInterfaceParams.appName]}) EXPECT_HMIRESPONSE(RequestId) self.mobileSession1:ExpectNotification("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "BACKGROUND", systemContext = "MAIN"}) self.mobileSession2:ExpectNotification("OnHMIStatus", {hmiLevel = "LIMITED", systemContext = "MAIN"}) end --Note: App2's media buttons are subscribed from previous TC so we have to unsubscribe media button for app2 to sure that none of buttons of these three apps's buttons are subscribed for i=1, #MediaButtons do Test["APPLINK_20202_MediaApp2_UnsubscribeButton_" .. tostring(MediaButtons[i])] = function(self) --mobile side: sending SubscribeButton request local cid = self.mobileSession1:SendRPC("UnsubscribeButton", { buttonName = MediaButtons[i] }) --expect Buttons.OnButtonSubscription EXPECT_HMINOTIFICATION("Buttons.OnButtonSubscription", {appID = self.applications[config.application2.registerAppInterfaceParams.appName], isSubscribed = false, name = MediaButtons[i]}) --mobile side: expect SubscribeButton response self.mobileSession1:ExpectResponse(cid, {success = true, resultCode = "SUCCESS"}) self.mobileSession1:ExpectNotification("OnHashChange", {}) end end for j=1, #ButtonPressModes do for i=1,#ButtonNames_WithoutCUSTOM_BUTTON_OK do Test["APPLINK_20202_OnButtonEvent_DoesNotComeAnyApps_Case_".. tostring(ButtonNames_WithoutCUSTOM_BUTTON_OK[i]).."_"..ButtonPressModes[j]]= function(self) commonTestCases:DelayedExp(1000) --hmi side: send OnButtonEvent, OnButtonEvent self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = ButtonName, mode = "BUTTONDOWN"}) self.hmiConnection:SendNotification("Buttons.OnButtonEvent",{name = ButtonName, mode = "BUTTONUP"}) self.hmiConnection:SendNotification("Buttons.OnButtonPress",{name = ButtonName, mode = ButtonPressModes[j]}) --Non OnButtonEvent/OnButtonPress notification is sent to app2 self.mobileSession1:ExpectNotification("OnButtonEvent", {}) :Times(0) self.mobileSession1:ExpectNotification("OnButtonPress", {}) :Times(0) --Non OnButtonEvent/OnButtonPress notification is sent to app1 self.mobileSession:ExpectNotification("OnButtonEvent", {}) :Times(0) self.mobileSession:ExpectNotification("OnButtonPress", {}) :Times(0) --Non OnButtonEvent/OnButtonPress notification is sent to app3 self.mobileSession2:ExpectNotification("OnButtonEvent", {}) :Times(0) self.mobileSession2:ExpectNotification("OnButtonPress", {}) :Times(0) end end end function Test:APPLINK_20202_PostCondition_UnregisterApp2() local cid = self.mobileSession1:SendRPC("UnregisterAppInterface",{}) self.mobileSession1:ExpectResponse(cid, { success = true, resultCode = "SUCCESS"}) local cid1 = self.mobileSession2:SendRPC("UnregisterAppInterface",{}) self.mobileSession2:ExpectResponse(cid1, { success = true, resultCode = "SUCCESS"}) end ---------------------------------------------------------------------------------------------- -----------------------------------------TEST BLOCK VII--------------------------------------- --------------------------------------Different HMIStatus------------------------------------- ---------------------------------------------------------------------------------------------- --Description: Check different HMIStatus --Requirement id in JAMA: --SDLAQ-CRS-1302: HMI Status Requirements for OnButtonEvent(FULL, LIMITED) --Verification criteria: --1. None of the applications receives onButtonEvent notification in HMI BACKGROUND or NONE. --2. In case the app is of non-media type and HMI Level is FULL the app obtains OnButtonEvent notifications from all subscribed buttons. --3. In case the app is of media type HMI Level is FULL the app obtains OnButtonEvent notifications from all subscribed buttons. --4. In case the app is of media type and HMI Level is LIMITED the app obtains OnButtonEvent notifications from media subscribed HW buttons only (all except OK). --Print new line to separate new test cases group commonFunctions:newTestCasesGroup("Test suite: Different HMI Level Checks") -- ---------------------------------------------------------------------------------------------- --1. HMI level is NONE --Precondition: Deactivate app to NONE HMI level commonSteps:DeactivateAppToNoneHmiLevel() local function verifyOnButtonEventNotification_IsIgnored(TestCaseName) --Verify buttonName and buttonPressMode parameters for i =1, #ButtonNames_WithoutCUSTOM_BUTTON do for j =1, #ButtonPressModes do Test[TestCaseName .. "_name_" .. ButtonNames_WithoutCUSTOM_BUTTON[i] .."_mode_" .. ButtonPressModes[j]] = function(self) commonTestCases:DelayedExp(1000) --Press button on HMI self.pressButton(ButtonNames_WithoutCUSTOM_BUTTON[i], ButtonPressModes[j]) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(0) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {}) :Times(0) end end end --Verify customButtonID parameter for j =1, #ButtonPressModes do for n = 1, #CustomButtonIDs do Test[TestCaseName .. "_name_CUSTOM_BUTTON_mode_" .. ButtonPressModes[j] .. "_customButtonID_" .. CustomButtonIDs[n]] = function(self) commonTestCases:DelayedExp(1000) --Press button on HMI self.pressButton_CUSTOM_BUTTON("CUSTOM_BUTTON", ButtonPressModes[j], CustomButtonIDs[n], Apps[1].appID) --mobile side: expected OnButtonEvent notification EXPECT_NOTIFICATION("OnButtonEvent", {}) :Times(0) --mobile side: expected OnButtonPress notification EXPECT_NOTIFICATION("OnButtonPress", {}) :Times(0) end end end end verifyOnButtonEventNotification_IsIgnored("OnButtonEvent_InNoneHmiLevel_IsIgnored") --Postcondition commonSteps:ActivationApp() ---------------------------------------------------------------------------------------------- --2. HMI level is LIMITED if commonFunctions:isMediaApp() then -- Precondition: Change app to LIMITED commonSteps:ChangeHMIToLimited() --Verify buttonName and buttonPressMode parameters for i =1, #ButtonNames_WithoutCUSTOM_BUTTON_OK do for j =1, #ButtonPressModes do TC_SendOnButtonEvent_SUCCESS(ButtonNames_WithoutCUSTOM_BUTTON_OK[i], ButtonPressModes[j], "OnButtonEvent_InLimitedHmilLevel") end end --4. In case the app is of media type and HMI Level is LIMITED the app obtains OnButtonEvent notifications from media subscribed HW buttons only (all except OK). for j =1, #ButtonPressModes do TC_SendOnButtonEvent_IsIgnored("OK", ButtonPressModes[j], "OnButtonEvent_InLimitedHmilLevel_OK_ButtonIsIgnored") end --Verify customButtonID parameter for j =1, #ButtonPressModes do for n = 1, #CustomButtonIDs do TC_SendOnButtonEvent_CUSTOM_BUTTON_SUCCESS("CUSTOM_BUTTON", ButtonPressModes[j], CustomButtonIDs[n], 1, "OnButtonEvent_InLimitedHmilLevel") end end end ---------------------------------------------------------------------------------------------- --3. HMI level is BACKGROUND commonTestCases:ChangeAppToBackgroundHmiLevel() verifyOnButtonEventNotification_IsIgnored("OnButtonEvent_InBackgoundHmiLevel_IsIgnored") -------------------------------------------------------------------------------------------- -- Postcondition: restoring sdl_preloaded_pt file -- TODO: Remove after implementation policy update function Test:Postcondition_Preloadedfile() print ("restoring smartDeviceLink.ini") commonPreconditions:RestoreFile("sdl_preloaded_pt.json") end return Test
ENT.Type = "anim" ENT.Base = "base_anim" ENT.PrintName = "Base Cell" ENT.Author = "Star Light" ENT.Contact = "" ENT.MaxSpeed = 40 ENT.ShipSpeed = 1 ENT.MaxHealth = 100 ENT.Category = "ORC" ENT.Spawnable = true function ENT:OnRemove() end function ENT:SetupDataTables() self:NetworkVar("Entity", 0, "Player") self:NetworkVar("Int", 0, "NewHealth") if SERVER then self:SetNewHealth(self.MaxHealth) end end
-- Copyright 2016 Google Inc, NYU. -- -- 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. require 'nn' if nn.MSESICriterion == nil then dofile('mse_si_criterion.lua') end torch.setdefaulttensortype('torch.DoubleTensor') torch.setnumthreads(8) -- Create an instance of the test framework. local precision = 1e-5 local mytester = torch.Tester() local jac = nn.Jacobian local test = torch.TestSuite() local function criterionJacobianTest(cri, input, target) local eps = 1e-6 local _ = cri:forward(input, target) local dfdx = cri:backward(input, target) -- for each input perturbation, do central difference local centraldiff_dfdx = torch.Tensor():resizeAs(dfdx) local input_s = input:storage() local centraldiff_dfdx_s = centraldiff_dfdx:storage() for i=1,input:nElement() do -- f(xi + h) input_s[i] = input_s[i] + eps local fx1 = cri:forward(input, target) -- f(xi - h) input_s[i] = input_s[i] - 2*eps local fx2 = cri:forward(input, target) -- f'(xi) = (f(xi + h) - f(xi - h)) / 2h local cdfx = (fx1 - fx2) / (2*eps) -- store f' in appropriate place centraldiff_dfdx_s[i] = cdfx -- reset input[i] input_s[i] = input_s[i] + eps end -- compare centraldiff_dfdx with :backward() local err = (centraldiff_dfdx - dfdx):abs():max() return err end function test.WeightedFlatMSECriterion() for numDimsNonBatch = 1, 4 do for sizeAverage = 0, 1 do -- Create a random input and target size. local sz = {} for i = 1, numDimsNonBatch + 1 do sz[i] = torch.random(3, 7) end local input = torch.rand(unpack(sz)) local target = torch.rand(unpack(sz)) local criterion = nn.MSESICriterion(numDimsNonBatch) criterion.sizeAverage = sizeAverage == 1 local critVal = criterion:forward(input, target) local delta = input - target local n = input:numel() local sumSq = delta:clone() for i = numDimsNonBatch + 1, 2, -1 do sumSq = sumSq:sum(i) end sumSq = sumSq:pow(2) sumSq = sumSq:sum(1):squeeze() local critValManual = (1 / n) * delta:clone():pow(2):sum() + (1 / (n * n)) * sumSq local err = math.abs(critValManual - critVal) mytester:assertlt(err, precision, 'error on forward') err = criterionJacobianTest(criterion, input, target) mytester:assertlt(err, precision, 'error on FEM') end end end -- Now run the test above. mytester:add(test) mytester:run()
samurai_of_chaos_slowest_death_kitty = class({}) LinkLuaModifier( 'samurai_of_chaos_slowest_death_kitty_modifier', 'encounters/samurai_of_chaos/samurai_of_chaos_slowest_death_kitty_modifier', LUA_MODIFIER_MOTION_NONE ) function samurai_of_chaos_slowest_death_kitty:OnSpellStart() local victim = GetRandomHeroEntities(1) if not victim then return end victim = victim[1] local victim_loc = victim:GetAbsOrigin() --- Get Caster, Victim, Player, Point --- local caster = self:GetCaster() local caster_loc = caster:GetAbsOrigin() local playerID = caster:GetPlayerOwnerID() local player = PlayerResource:GetPlayer(playerID) local team = caster:GetTeamNumber() --- Get Special Values --- local AoERadius = self:GetSpecialValueFor("AoERadius") local duration = self:GetSpecialValueFor("duration") local damage = self:GetSpecialValueFor("damage") local move_speed_absolute = self:GetSpecialValueFor("move_speed_absolute") local delay = self:GetSpecialValueFor("delay") local AoERadius_Trigger = 100 -- Sound and Animation -- local sound = {"juggernaut_jugsc_arc_attack_02", "juggernaut_jugsc_arc_attack_05", "juggernaut_jugsc_arc_attack_06", "juggernaut_jugsc_arc_attack_09"} EmitAnnouncerSound( sound[RandomInt(1, #sound)] ) StartAnimation(caster, {duration=0.9, activity=ACT_DOTA_CAST_ABILITY_2, rate=1.00}) local unit = CreateUnitByName("samurai_of_chaos_slowest_death_kitty", victim:GetAbsOrigin(), true, nil, nil, DOTA_TEAM_BADGUYS) PersistentUnit_Add(unit) unit:AddNewModifier(caster, self, "modifier_invulnerable", {}) unit:AddNewModifier(caster, self, "modifier_unselectable", {}) unit:AddNewModifier(caster, self, "modifier_phased", {}) -- Modifier -- unit:AddNewModifier(caster, self, "samurai_of_chaos_slowest_death_kitty_modifier", {}) unit:Stop() EncounterGroundAOEWarningStickyOnUnit(unit, AoERadius_Trigger, nil, nil) -- Sound -- StartSoundEventFromPositionReliable("Hero_Juggernaut.HealingWard.Cast", unit:GetAbsOrigin()) local triggered = false local timer = Timers:CreateTimer(delay, function() unit:MoveToNPC(victim) local timer1 = Timers:CreateTimer(function() -- DOTA_UNIT_TARGET_TEAM_FRIENDLY; DOTA_UNIT_TARGET_TEAM_ENEMY; DOTA_UNIT_TARGET_TEAM_BOTH local units = FindUnitsInRadius(team, unit:GetAbsOrigin(), nil, AoERadius_Trigger, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false) if units[1] ~= nil and not triggered then triggered = true unit:Stop() -- Sound -- StartSoundEventFromPositionReliable("Hero_Phoenix.SuperNova.Death", unit:GetAbsOrigin()) -- Particle -- PATTACH_ABSORIGIN-PATTACH_ABSORIGIN_FOLLOW-PATTACH_CUSTOMORIGIN local particle = ParticleManager:CreateParticle("particles/encounter/samurai_of_chaos/samurai_of_chaos_slowest_death_kitty_shine.vpcf", PATTACH_CUSTOMORIGIN, nil) ParticleManager:SetParticleControl( particle, 1, unit:GetAbsOrigin() ) ParticleManager:ReleaseParticleIndex( particle ) particle = nil local timer = Timers:CreateTimer(0.5, function() -- Sound -- StartSoundEventFromPositionReliable("Hero_Phoenix.SuperNova.Explode", unit:GetAbsOrigin()) -- Particle -- PATTACH_ABSORIGIN-PATTACH_ABSORIGIN_FOLLOW-PATTACH_CUSTOMORIGIN local particle = ParticleManager:CreateParticle("particles/encounter/samurai_of_chaos/samurai_of_chaos_slowest_death_kitty_smoke.vpcf", PATTACH_CUSTOMORIGIN, nil) ParticleManager:SetParticleControl( particle, 3, unit:GetAbsOrigin() ) ParticleManager:ReleaseParticleIndex( particle ) particle = nil -- Particle -- PATTACH_ABSORIGIN-PATTACH_ABSORIGIN_FOLLOW-PATTACH_CUSTOMORIGIN local particle = ParticleManager:CreateParticle("particles/encounter/samurai_of_chaos/samurai_of_chaos_slowest_death_kitty_particle.vpcf", PATTACH_CUSTOMORIGIN, nil) ParticleManager:SetParticleControl( particle, 3, unit:GetAbsOrigin() ) ParticleManager:ReleaseParticleIndex( particle ) particle = nil -- Particle -- PATTACH_ABSORIGIN-PATTACH_ABSORIGIN_FOLLOW-PATTACH_CUSTOMORIGIN local particle = ParticleManager:CreateParticle("particles/encounter/samurai_of_chaos/samurai_of_chaos_slowest_death_kitty_explosion.vpcf", PATTACH_CUSTOMORIGIN, nil) ParticleManager:SetParticleControl( particle, 1, unit:GetAbsOrigin() ) ParticleManager:ReleaseParticleIndex( particle ) particle = nil -- DOTA_UNIT_TARGET_TEAM_FRIENDLY; DOTA_UNIT_TARGET_TEAM_ENEMY; DOTA_UNIT_TARGET_TEAM_BOTH local units = FindUnitsInRadius(team, unit:GetAbsOrigin(), nil, AoERadius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false) for _,victim in pairs(units) do -- Apply Damage -- EncounterApplyDamage(victim, caster, self, damage, DAMAGE_TYPE_MAGICAL, DOTA_DAMAGE_FLAG_NONE) end unit:ForceKill(false) local timer = Timers:CreateTimer(2.0, function() unit:RemoveSelf() end) end) end if triggered then return end return 0.1 end) PersistentTimer_Add(timer1) end) PersistentTimer_Add(timer) end function samurai_of_chaos_slowest_death_kitty:OnAbilityPhaseStart() local caster = self:GetCaster() local playerID = caster:GetPlayerOwnerID() local player = PlayerResource:GetPlayer(playerID) return true end function samurai_of_chaos_slowest_death_kitty:GetManaCost(abilitylevel) return self.BaseClass.GetManaCost(self, abilitylevel) end function samurai_of_chaos_slowest_death_kitty:GetCooldown(abilitylevel) return self.BaseClass.GetCooldown(self, abilitylevel) end
local os = require "os" local rrd = require "rrd" local sys = require "luci.sys" local nixio = require "nixio" nixio.fs = require "nixio.fs" nixio.util = require "nixio.util" local uci = require "uci" local jsonc = require "luci.jsonc" -- Plugins local lmpeaks = require "linkmeter.peaks" local lmunkprobe = require "linkmeter.unkprobe" local lmdph = require "linkmeter.dph" local lmramp = require "linkmeter.ramp" local lmipwatch = require "linkmeter.ipwatch" local pairs, ipairs, table, pcall, type = pairs, ipairs, table, pcall, type local tonumber, tostring, print, next, io = tonumber, tostring, print, next, io local collectgarbage, math, bxor = collectgarbage, math, nixio.bit.bxor module "linkmeterd" local serialLog local serialPolle local statusListeners = {} local pluginStatusListeners = {} local pluginSegmentListeners = {} local pluginHostInteractiveListeners = {} local lastHmUpdate local lastAutoback local autobackActivePeriod local autobackInactivePeriod local rfMap = {} local rfStatus = {} local hmAlarms = {} local extendedStatusProbeVals = {} -- array[probeIdx] of tables of kv pairs, per probe local extendedStatusVals = {} -- standard kv pairs of items to include in status, global local hmConfig local hmConfigRemaining local hmConfigLastReceive -- forwards local segmentCall local statusValChanged local JSON_TEMPLATE local segLmToast local RRD_FILE = uci.cursor():get("linkmeter", "daemon", "rrd_file") local RRD_AUTOBACK = "/root/autobackup.rrd" -- Must match recv size in lmclient if messages exceed this size local LMCLIENT_BUFSIZE = 8192 -- Server Module local Server = { _pollt = {}, _tickt = {} } local function tableRemoveItem(t, item) for k, v in ipairs(t) do if v == item then return table.remove(t, k) end end end function Server.register_pollfd(polle) Server._pollt[#Server._pollt+1] = polle end function Server.unregister_pollfd(polle) tableRemoveItem(Server._pollt, polle) end function Server.register_tick(ticke) Server._tickt[#Server._tickt+1] = ticke end function Server.unregister_tick(ticke) tableRemoveItem(Server._tickt, ticke) end function Server.daemonize() if nixio.getppid() == 1 then return end local pid, code, msg = nixio.fork() if not pid then return nil, code, msg elseif pid > 0 then os.exit(0) end nixio.setsid() nixio.chdir("/") local devnull = nixio.open("/dev/null", nixio.open_flags("rdwr")) nixio.dup(devnull, nixio.stdin) nixio.dup(devnull, nixio.stdout) nixio.dup(devnull, nixio.stderr) return true end function Server.run() local lastTick while true do -- Listen for fd events, but break every 10s local stat, code = nixio.poll(Server._pollt, 10000) if stat and stat > 0 then for _, polle in ipairs(Server._pollt) do if polle.revents ~= 0 and polle.handler then polle.handler(polle) end end end local now = os.time() if now ~= lastTick then lastTick = now for _, cb in ipairs(Server._tickt) do cb(now) end end -- if new tick end -- while true end -- External API functions function getConf(k) return hmConfig and hmConfig[k] end function setConf(k, v) if hmConfig then hmConfig[k] = v end end function toast(line1, line2) return segLmToast('$LMTT,' .. (line1 or '') .. ',' .. (line2 or '')) end function publishStatusVal(k, v, probeIdx) local t if probeIdx == nil or probeIdx < 0 then -- is a global status val probeIdx = nil t = extendedStatusVals else -- is a probe value, make sure there is storage available in extendedStatusProbeVals while #extendedStatusProbeVals < probeIdx do extendedStatusProbeVals[#extendedStatusProbeVals+1] = {} end t = extendedStatusProbeVals[probeIdx] end local newVals = statusValChanged(t, k, v) if newVals ~= nil then if probeIdx == nil then newVals = newVals == "" and "" or (newVals .. ",") JSON_TEMPLATE[16] = newVals else newVals = newVals == "" and "" or ("," .. newVals) JSON_TEMPLATE[10+(probeIdx*11)] = newVals end end -- newVals != nil end function publishBroadcastMessage(event, t) if type(t) == "table" then t = jsonc.stringify(t) end local o local i = 1 local isStatusEvent = event == "hmstatus" while i <= #statusListeners do local client = statusListeners[i] local sendok = true if client.statusonly then if isStatusEvent then sendok = client.fd:sendto(t, client.addr) end else if not o then o = ('event: %s\ndata: %s\n\n'):format(event, t) end sendok = client.fd:sendto(o, client.addr) end if sendok then i = i + 1 else table.remove(statusListeners, i) end end -- while < #statusListeners end function registerSegmentListener(seg, f) -- function (line) line is the whole string. Use segSplit to split if seg:sub(1, 1) ~= "$" then seg = "$" .. seg end unregisterSegmentListener(seg) pluginSegmentListeners[seg] = f end function unregisterSegmentListener(f) tableRemoveItem(pluginSegmentListeners, f) end function registerStatusListener(f) -- function (now, vals) vals = array of HMSU parameters unregisterStatusListener(f) pluginStatusListeners[#pluginStatusListeners+1] = f end function unregisterStatusListener(f) tableRemoveItem(pluginStatusListeners, f) end function registerTickListener(cb) Server.register_tick(cb) end function unregisterTickListener(cb) Server.unregister_tick(cb) end function hmWrite(s) if serialPolle then if serialLog then serialLog:write("WRITE:") serialLog:write(s) end --print("WRITE:" .. s) -- Break the data into 8 byte chunks (the size of the FIFO on the Pi3/W minuart) -- write always returns that it wrote the entire data, and poll('out') always times out for i=1, #s, 8 do serialPolle.fd:write(s:sub(i,i+7)) nixio.nanosleep(0, serialPolle.bytens * 8) end end end function segSplit(line) local retVal = {} local fieldstart = 1 while true do local nexti = line:find(',', fieldstart) if nexti then -- Don't add the segment name if fieldstart > 1 then retVal[#retVal+1] = line:sub(fieldstart, nexti - 1) end fieldstart = nexti + 1 else if fieldstart > 1 then retVal[#retVal+1] = line:sub(fieldstart) end break end end return retVal end function statusValChanged(t, k, v) -- JSON encode the new value local tkv = {} tkv[k] = v local newVal = jsonc.stringify(tkv):sub(2, -2) newVal = newVal ~= "" and newVal or nil -- See if the value has changed local oldVal = t[k] if oldVal ~= newVal then -- Value changed, convert the k,v table to v only -- (because v is '"k": v' already and JSONifying it would give you "k": "k": v) t[k] = newVal local newt = {} for _,v in pairs(t) do newt[#newt+1] = v end return table.concat(newt, ",") end end local function hmConfigReceived(segment) if hmConfigRemaining == nil then return end hmConfigLastReceive = os.time() tableRemoveItem(hmConfigRemaining, segment) if #hmConfigRemaining == 0 then -- nixio.syslog("info", "All configuration received") hmConfigRemaining = nil hmConfigLastReceive = nil end end local function rrdCreate() if nixio.fs.access(RRD_AUTOBACK) then local status, last = pcall(rrd.last, RRD_AUTOBACK) if status then last = tonumber(last) local now = os.time() --nixio.syslog("err", ("Autoback restore: last=%d now=%d"):format(last or -1, now)) if last and last <= now then return nixio.fs.copy(RRD_AUTOBACK, RRD_FILE) end else nixio.syslog("err", "RRD last failed:" .. last) end end -- if file exists return rrd.create( RRD_FILE, "--step", "2", "DS:sp:GAUGE:30:0.1:1000", "DS:t0:GAUGE:30:0:1000", "DS:t1:GAUGE:30:0:1000", "DS:t2:GAUGE:30:0:1000", "DS:t3:GAUGE:30:0:1000", "DS:out:GAUGE:30:-1000:100", "DS:f:GAUGE:30:0:100", "DS:s:GAUGE:30:0:100", "RRA:AVERAGE:0.6:5:360", "RRA:AVERAGE:0.6:30:360", "RRA:AVERAGE:0.6:60:360", "RRA:AVERAGE:0.6:90:480" ) end -- This might look a big hokey but rather than build the string -- and discard it every time, just replace the values to reduce -- the load on the garbage collector local JSON_TEMPLATE_SRC = { '{"time":', 0, -- 2 ',"set":', 0, -- 4 ',"lid":', 0, -- 6 ',"fan":{"c":', 0, ',"a":', 0, ',"f":', 'null', ',"s":', 'null', -- 14 '},', '', -- 16 (placeholder: extendedStatusVals) '"temps":[{"n":"', 'Pit', '","c":', 0, '', -- 21 (placeholder: extendedStatusProbeVals) ',"a":{"l":', 'null', ',"h":', 'null', ',"r":', 'null', -- 27 '}},{"n":"', 'Food Probe1', '","c":', 0, '', -- 32 (placeholder: extendedStatusProbeVals) ',"a":{"l":', 'null', ',"h":', 'null', ',"r":', 'null', -- 38 '}},{"n":"', 'Food Probe2', '","c":', 0, '', -- 43 (placeholder: extendedStatusProbeVals) ',"a":{"l":', 'null', ',"h":', 'null', ',"r":', 'null', -- 49 '}},{"n":"', 'Ambient', '","c":', 0, '', -- 54 (placeholder: extendedStatusProbeVals) ',"a":{"l":', 'null', ',"h":', 'null', ',"r":', 'null', -- 60 '}}]}' -- 61 } local JSON_FROM_CSV = {2, 4, 20, 31, 42, 53, 8, 10, 6, 12, 14 } local function jsonWrite(vals) local src,dest,v for src,dest in ipairs(JSON_FROM_CSV) do v = vals[src] if tonumber(v) == nil then v = "null" end JSON_TEMPLATE[dest] = v end end local function doStatusListeners(now, vals) -- Only send status messages after we've received all our config if hmConfigRemaining ~= nil then return end for i = 1, #pluginStatusListeners do pluginStatusListeners[i](now, vals) end end local function buildConfigMap() if not hmConfig then return {} end local r = {} for k,v in pairs(hmConfig) do r[k] = v end if JSON_TEMPLATE[2] ~= 0 then -- Current temperatures for i = 0, 3 do r["pcurr"..i] = tonumber(JSON_TEMPLATE[20+(i*11)]) end -- Setpoint r["sp"] = JSON_TEMPLATE[4] end for i,v in ipairs(hmAlarms) do i = i - 1 local idx = math.floor(i/2) local aType = (i % 2 == 0) and "l" or "h" r["pal"..aType..idx] = tonumber(v.t) end return r end local function segLogMessage(line) local vals = segSplit(line) publishBroadcastMessage('log', {msg=vals[1]}) end local function segNoiseDump(line) local vals = segSplit(line) publishBroadcastMessage('noisedump', '"' .. vals[1] .. '"') end local function segPidInternals(line) local vals = segSplit(line) publishBroadcastMessage('pidint', ('{"b":%s,"p":%s,"i":%s,"d":%s,"t":%s}') :format(vals[1], vals[2], vals[3], vals[4], vals[5])) end local function segConfig(line, names, numeric) local vals = segSplit(line) for i, v in ipairs(names) do if i > #vals then break end if v ~= "" then if numeric then hmConfig[v] = tonumber(vals[i]) or vals[i] else hmConfig[v] = vals[i] end end end return vals end local function segProbeNames(line) hmConfigReceived("HMPN") local vals = segConfig(line, {"pn0", "pn1", "pn2", "pn3"}) for i,v in ipairs(vals) do JSON_TEMPLATE[7+i*11] = v end end local function segProbeOffsets(line) hmConfigReceived("HMPO") return segConfig(line, {"po0", "po1", "po2", "po3"}, true) end local function segPidParams(line) hmConfigReceived("HMPD") return segConfig(line, {"", "pidp", "pidi", "pidd", "u"}, true) end local function segLidParams(line) hmConfigReceived("HMLD") return segConfig(line, {"lo", "ld"}, true) end local function segFanParams(line) hmConfigReceived("HMFN") return segConfig(line, {"fmin", "fmax", "smin", "smax", "oflag", "fsmax", "fflor", "sceil"}, true) end function registerHostInteractiveListener(topic, f) -- function (topic, opaque, button) -- All parameters are numeric unregisterSegmentListener(topic) pluginHostInteractiveListeners[#pluginHostInteractiveListeners+1] = {t = topic, f = f } end function unregisterHostInteractiveListener(topic) for i = 1, #pluginHostInteractiveListeners do if pluginHostInteractiveListeners[i].t == topic then table.remove(pluginHostInteractiveListeners, i) return end end end local function findHostInteractiveHandler(topic) for i = 1, #pluginHostInteractiveListeners do if pluginHostInteractiveListeners[i].t == topic then return pluginHostInteractiveListeners[i].f end end end local function segHostInteractive(line) -- HMHI,Topic,HostOpaque,Button local vals = segSplit(line) local topic = tonumber(vals[2]) local handler = findHostInteractiveHandler(topic) if handler ~= nil then handler(topic, tonumber(vals[1]), tonumber(vals[3])) end end function hostInteractiveReply(opaque, line1, line2) hmWrite(("/set?hi=%d,%s,%s\n"):format(opaque, line1 or "", line2 or "")) end local function segProbeCoeffs(line) local i = line:sub(7, 7) hmConfigReceived("HMPC," .. i) segConfig(line, {"", "pca"..i, "pcb"..i, "pcc"..i, "pcr"..i, "pt"..i}, false) -- The resistance looks better in the UI without scientific notation hmConfig["pcr"..i] = tonumber(hmConfig["pcr"..i]) end local function segLcdBacklight(line) hmConfigReceived("HMLB") return segConfig(line, {"lb", "lbn", "le0", "le1", "le2", "le3"}) end local function rfStatusRefresh() local rfval for i,src in ipairs(rfMap) do if src ~= "" then local sts = rfStatus[src] if sts then rfval = { s = sts.rssi, b = sts.lobatt } else rfval = 0; -- 0 indicates mapped but offline end else rfval = nil end publishStatusVal("rf", rfval, i) end end local function segRfUpdate(line) local vals = segSplit(line) rfStatus = {} -- clear the table to remove stales local idx = 1 --local now = os.time() local band = nixio.bit.band while (idx < #vals) do local nodeId = vals[idx] local flags = tonumber(vals[idx+1]) rfStatus[nodeId] = { lobatt = band(flags, 0x01) == 0 and 0 or 1, reset = band(flags, 0x02) == 0 and 0 or 1, native = band(flags, 0x04) == 0 and 0 or 1, rssi = tonumber(vals[idx+2]) } -- If this isn't the NONE source, save the stats as the ANY source if nodeId ~= "255" then rfStatus["127"] = rfStatus[nodeId] end idx = idx + 3 end rfStatusRefresh() end local function segRfMap(line) local vals = segSplit(line) rfMap = {} for i,s in ipairs(vals) do rfMap[i] = s hmConfig["prfn"..(i-1)] = s end rfStatusRefresh() end local function segResetConfig(line) toast("Resetting", "configuration...") os.execute("jffs2reset -y -r") end local function segUcIdentifier(line) hmConfigReceived("UCID") local vals = segSplit(line) if #vals > 1 then hmConfig.ucid = vals[2] end end function segLmToast(line) local vals = segSplit(line) if serialPolle and #vals > 0 then hmWrite(("/set?tt=%s,%s\n"):format(vals[1],vals[2] or "")) return "OK" end return "ERR" end local function checkAutobackup(now, vals) -- vals is the last status update local pit = tonumber(vals[3]) if (autobackActivePeriod ~= 0 and pit and now - lastAutoBackup > (autobackActivePeriod * 60)) or (autobackInactivePeriod ~= 0 and now - lastAutoBackup > (autobackInactivePeriod * 60)) then --nixio.syslog("err", ("Autobackup last=%d now=%d"):format(lastAutoBackup, now)) nixio.fs.copy(RRD_FILE, RRD_AUTOBACK) lastAutoBackup = now end end local lastStateUpdate local spareUpdates local skippedUpdates local function unthrottleUpdates() -- Forces the next two segStateUpdate()s to be unthrottled, which -- can be used to make sure any data changed is pushed out to clients -- instead of being eaten by the throttle. Send 2 because the first one -- is likely to be mid-period already skippedUpdates = 99 spareUpdates = 2 end local function throttleUpdate(line) -- Max updates that can be sent in a row local MAX_SEQUENTIAL = 2 -- Max updates that will be skipped in a row local MAX_THROTTLED = 4 -- SLOW: If (line) is the same, only every fifth update -- NORMAL: If (line) is different, only every second update -- Exception: If (line) is different during a SLOW period, do not skip that line -- In: A B C D E E E E F G H -- Out: A C E E F H if line == lastStateUpdate then if skippedUpdates >= 2 then if spareUpdates < (MAX_SEQUENTIAL-1) then spareUpdates = spareUpdates + 1 end end if skippedUpdates < MAX_THROTTLED then skippedUpdates = skippedUpdates + 1 return true end else if skippedUpdates == 0 then if spareUpdates == 0 then skippedUpdates = skippedUpdates + 1 return true else spareUpdates = spareUpdates - 1 end end end lastStateUpdate = line skippedUpdates = 0 end local function segLmConfig() local cm = buildConfigMap() local r = {} -- Make sure we have an entry for temperatures even if there isn't a value for i = 0, 3 do if not cm["pcurr"..i] then r[#r+1] = ('"pcurr%d":null'):format(i) end end for k,v in pairs(cm) do local s if type(v) == "number" or v == "null" then s = '%q:%s' else s = '%q:%q' end r[#r+1] = s:format(k,v) end return "{" .. table.concat(r, ',') .. "}" end local function rrdStash() if not nixio.fs.access(RRD_AUTOBACK) then return end local stashpath = uci.cursor():get("linkmeter", "daemon", "stashpath") if not stashpath then return end nixio.syslog("notice", "Stashing last session database to " .. stashpath) if not nixio.fs.access(stashpath) then nixio.fs.mkdir(stashpath) end -- Copy database nixio.fs.copy(RRD_AUTOBACK, stashpath .. "/LastSession.rrd") -- And the current configuration nixio.fs.writefile(stashpath .. "/LastSession.json", segLmConfig()) end local function segStateUpdate(line) local vals = segSplit(line) local time = os.time() doStatusListeners(time, vals) if throttleUpdate(line) then return end if #vals >= 8 then -- If the time has shifted more than 24 hours since the last update -- the clock has probably just been set from 0 (at boot) to actual -- time. Recreate the rrd to prevent a 40 year long graph if time - lastHmUpdate > (24*60*60) then nixio.syslog("notice", "Time jumped forward by "..(time-lastHmUpdate)..", restarting database") rrdStash() rrdCreate() elseif time == lastHmUpdate then -- RRD hates it when you try to insert two PDPs at the same timestamp return nixio.syslog("info", "Discarding duplicate update") end lastHmUpdate = time -- Add the time as the first item table.insert(vals, 1, time) -- If setpoint is '-' that means manual mode -- and output is the manual setpoint if vals[2] == '-' then vals[2] = '-' .. vals[7] end jsonWrite(vals) local lid = tonumber(vals[9]) or 0 -- If the lid value is non-zero, it replaces the output value if lid ~= 0 then vals[7] = -lid end -- Add fields 10 (fanpct) and 11 (servopct) if HM doesn't send them while #vals < 11 do vals[#vals+1] = 'U' end table.remove(vals, 9) -- lid table.remove(vals, 8) -- output avg -- update() can throw an error if you try to insert something it -- doesn't like, which will take down the whole server, so just -- ignore any error local status, err = pcall(rrd.update, RRD_FILE, table.concat(vals, ":")) if not status then nixio.syslog("err", "RRD error: " .. err) end publishBroadcastMessage('hmstatus', table.concat(JSON_TEMPLATE)) checkAutobackup(lastHmUpdate, vals) end end local function broadcastAlarm(probeIdx, alarmType, thresh) local pname = JSON_TEMPLATE[18+(probeIdx*11)] local curTemp = JSON_TEMPLATE[20+(probeIdx*11)] local retVal if alarmType then nixio.syslog("warning", "Alarm "..probeIdx..alarmType.." started ringing") retVal = nixio.fork() if retVal == 0 then local cm = buildConfigMap() cm["al_probe"] = probeIdx cm["al_type"] = alarmType cm["al_thresh"] = thresh cm["al_prep"] = alarmType == "H" and "above" or "below" cm["pn"] = cm["pn"..probeIdx] cm["pcurr"] = cm["pcurr"..probeIdx] nixio.exece("/usr/share/linkmeter/alarm", {}, cm) end alarmType = '"'..alarmType..'"' else nixio.syslog("warning", "Alarm stopped") alarmType = "null" retVal = 0 end unthrottleUpdates() -- force the next update JSON_TEMPLATE[27+(probeIdx*11)] = alarmType publishBroadcastMessage('alarm', ('{"atype":%s,"p":%d,"pn":"%s","c":%s,"t":%s}') :format(alarmType, probeIdx, pname, curTemp, thresh)) return retVal end local function segAlarmLimits(line) hmConfigReceived("HMAL") local vals = segSplit(line) for i,v in ipairs(vals) do -- make indexes 0-based local alarmId = i - 1 local ringing = v:sub(-1) ringing = ringing == "H" or ringing == "L" if ringing then v = v:sub(1, -2) end local curr = hmAlarms[i] or {} local probeIdx = math.floor(alarmId/2) local alarmType = alarmId % 2 JSON_TEMPLATE[23+(probeIdx*11)+(alarmType*2)] = v -- Wait until we at least have some config before broadcasting if (ringing and not curr.ringing) and (hmConfig and hmConfig.ucid) then curr.ringing = os.time() broadcastAlarm(probeIdx, (alarmType == 0) and "L" or "H", v) elseif not ringing and curr.ringing then curr.ringing = nil broadcastAlarm(probeIdx, nil, v) end curr.t = v hmAlarms[i] = curr end end local function segAdcRange(line) local vals = segSplit(line) for i = 1, #vals do vals[i] = tonumber(vals[i]) end publishStatusVal("adc", vals) end local function segmentValidate(line) -- First character always has to be $ if line:sub(1, 1) ~= "$" then return false end -- The line optionally ends with *XX hex checksum local _, _, csum = line:find("*(%x%x)$", -3) if csum then csum = tonumber(csum, 16) for i = 2, #line-3 do local b = line:byte(i) -- If there is a null, force checksum invalid if b == 0 then b = 170 end csum = bxor(csum, b) end csum = csum == 0 if not csum then nixio.syslog("warning", "Checksum failed: "..line) if hmConfig then hmConfig.cerr = (hmConfig.cerr or 0) + 1 end end end -- Returns nil if no checksum or true/false if checksum checks return csum end local function hmRequestConfig(now) hmWrite("\n/config\n") hmConfigLastReceive = now or os.time() end local function checkHmConfigRemaining() if hmConfigRemaining == nil then return end if hmConfigLastReceive == nil then return end -- If it has been more than N seconds since last config receive -- request a retransmit local now = os.time() if now - hmConfigLastReceive > 2 then nixio.syslog("warning", "Requesting config retransmit for " .. table.concat(hmConfigRemaining, ",")) return hmRequestConfig(now) end end local function serialHandler(polle) for line in polle.lines do if serialLog then serialLog:write(line) serialLog:write("\n") end local csumOk = segmentValidate(line) if csumOk ~= false then if hmConfig == nil then hmConfig = {} hmRequestConfig() end -- Remove the checksum of it was there if csumOk == true then line = line:sub(1, -4) end segmentCall(line) end -- if validate end -- for line checkHmConfigRemaining() end local function lmclientSendTo(fd, addr, val) if #val <= LMCLIENT_BUFSIZE then fd:sendto(val, addr) else while val ~= "" do fd:sendto(val:sub(1, LMCLIENT_BUFSIZE), addr) val = val:sub(LMCLIENT_BUFSIZE) end end end local function initHmVars() hmConfig = nil rfMap = {} rfStatus = {} hmAlarms = {} extendedStatusProbeVals = {} extendedStatusVals = {} pluginStatusListeners = {} pluginSegmentListeners = {} JSON_TEMPLATE = {} for _,v in pairs(JSON_TEMPLATE_SRC) do JSON_TEMPLATE[#JSON_TEMPLATE+1] = v end unthrottleUpdates() hmConfigLastReceive = nil hmConfigRemaining = { "UCID", "HMPD", "HMFN", "HMPN", "HMPC,0", "HMPC,1", "HMPC,2", "HMPC,3", "HMPO", "HMLD", "HMLB", "HMAL" -- $HMRM not required } end local function initPlugins() lmunkprobe.init() lmpeaks.init() lmdph.init() lmramp.init() lmipwatch.init() end local function lmdStart() if serialPolle then return true end local cfg = uci.cursor() local SERIAL_DEVICE = cfg:get("linkmeter", "daemon", "serial_device") or "auto" local SERIAL_BAUD = cfg:get("linkmeter", "daemon", "serial_baud") or "38400" autobackActivePeriod = tonumber(cfg:get("linkmeter", "daemon", "autoback_active") or 0) autobackInactivePeriod = tonumber(cfg:get("linkmeter", "daemon", "autoback_inactive") or 0) if (SERIAL_DEVICE:lower() == "auto") then if nixio.fs.access("/dev/ttyS0") then SERIAL_DEVICE = "/dev/ttyS0" else SERIAL_DEVICE = "/dev/ttyAMA0" end end initHmVars() if os.execute("/bin/stty -F " .. SERIAL_DEVICE .. " raw -echo " .. SERIAL_BAUD) ~= 0 then return nil, -2, "Can't set serial baud" end local logfile = cfg:get("linkmeter", "daemon", "serial_log") if logfile then serialLog = nixio.open(logfile, nixio.open_flags("creat", "wronly", "trunc")) end local serialfd = nixio.open(SERIAL_DEVICE, nixio.open_flags("rdwr")) if not serialfd then return nil, -2, "Can't open serial device" end serialfd:setblocking(false) lastHmUpdate = os.time() lastAutoBackup = lastHmUpdate nixio.umask("0022") -- Create database if not nixio.fs.access(RRD_FILE) then rrdCreate() end initPlugins() -- Attempt to flush the serial buffer -- otherwise when /config is sent it could overrun local discard repeat discard = serialfd:read(1024) if discard ~= false and serialLog then serialLog:write("DISCARD ") serialLog:write(discard) end until (not discard or #discard == 0) serialPolle = { fd = serialfd, lines = serialfd:linesource(), events = nixio.poll_flags("in"), handler = serialHandler, bytens = math.floor(1000 * 1000 * 1000 / SERIAL_BAUD * 10) -- time to transmit 1 byte in nanoseconds } Server.register_pollfd(serialPolle) return true end local function lmdStop() if not serialPolle then return true end Server.unregister_pollfd(serialPolle) serialPolle.fd:setblocking(true) serialPolle.fd:close() serialPolle = nil if serialLog then serialLog:close() serialLog = nil end initHmVars() -- Save the database in case the user is rebooting it will be up to date if nixio.fs.access(RRD_FILE) then nixio.fs.copy(RRD_FILE, RRD_AUTOBACK) end return true end local function segLmSet(line) if not serialPolle then return "ERR" end -- Replace the $LMST,k,v with /set?k=v hmWrite(line:gsub("^%$LMST,(%w+),(.*)", "\n/set?%1=%2\n")) -- Let the next updates come immediately to make it seem more responsive unthrottleUpdates() return "OK" end local function segLmReboot(line) if not serialPolle then return "ERR" end hmWrite("\n/reboot\n") -- Clear our cached config to request it again when reboot is complete initHmVars() initPlugins() return "OK" end local function segLmGet(line) local vals = segSplit(line) local cm = buildConfigMap() local retVal = {} for i = 1, #vals, 2 do retVal[#retVal+1] = cm[vals[i]] or vals[i+1] or "" end return table.concat(retVal, '\n') end local function segLmRfStatus(line) local retVal = "" for id, item in pairs(rfStatus) do if retVal ~= "" then retVal = retVal .. "," end retVal = retVal .. ('{"id":%s,"lobatt":%d,"rssi":%d,"reset":%d,"native":%d}'):format( id, item.lobatt, item.rssi, item.reset, item.native) end retVal = "[" .. retVal .. "]" return retVal end local function segLmDaemonControl(line) local vals = segSplit(line) -- Start the daemon if there is any non-zero parameter else stop it if #vals > 0 and vals[1] ~= "0" then lmdStart() else lmdStop() end return "OK" end local function segLmStateUpdate() -- If the "time" field is still 0, we haven't gotten an update if JSON_TEMPLATE[2] == 0 then return "{}" else return table.concat(JSON_TEMPLATE) end end local function segLmAlarmTest(line) local vals = segSplit(line) if #vals > 0 then local probeIdx = tonumber(vals[1]) local alarmType = vals[2] or "" local thresh = vals[3] or "" -- If alarmType is blank, use nil to simulate turn off alarmType = alarmType ~= "" and alarmType or nil -- If thresh is blank, use current thresh = thresh and tonumber(thresh) or math.floor(tonumber(JSON_TEMPLATE[20+(probeIdx*11)]) or 0) local pid = broadcastAlarm(probeIdx, alarmType, thresh) return "OK " .. pid else return "ERR" end end local function registerStreamingStatus(fd, addr, line) -- $LMSS,[statusonly] local vals = segSplit(line) statusListeners[#statusListeners + 1] = {fd=fd, addr=addr, statusonly=(vals[1] == "1")} unthrottleUpdates() -- make sure the new client gets the next available update end local lmdStartTime local function lmdTick(now) if lmdStartTime and serialPolle and now - lmdStartTime > 10 then unregisterTickListener(lmdTick) -- always stop checking after timeout if not hmConfig then nixio.syslog("warning", "No response from HeaterMeter, running avrupdate") lmdStop() if os.execute("/usr/bin/avrupdate -d") ~= 0 then nixio.syslog("err", "avrupdate failed") else nixio.syslog("info", "avrupdate OK") end lmdStart() end end end local segmentMap = { ["$HMAL"] = segAlarmLimits, ["$HMAR"] = segAdcRange, ["$HMFN"] = segFanParams, ["$HMHI"] = segHostInteractive, ["$HMLB"] = segLcdBacklight, ["$HMLD"] = segLidParams, ["$HMLG"] = segLogMessage, ["$HMND"] = segNoiseDump, ["$HMPC"] = segProbeCoeffs, ["$HMPD"] = segPidParams, ["$HMPN"] = segProbeNames, ["$HMPO"] = segProbeOffsets, ["$HMPS"] = segPidInternals, ["$HMRC"] = segResetConfig, ["$HMRF"] = segRfUpdate, ["$HMRM"] = segRfMap, ["$HMSU"] = segStateUpdate, ["$UCID"] = segUcIdentifier, ["$LMAT"] = segLmAlarmTest, ["$LMGT"] = segLmGet, ["$LMST"] = segLmSet, ["$LMSU"] = segLmStateUpdate, ["$LMRB"] = segLmReboot, ["$LMRF"] = segLmRfStatus, ["$LMDC"] = segLmDaemonControl, ["$LMCF"] = segLmConfig, ["$LMTT"] = segLmToast, -- "$LMUP" -- unkprobe plugin -- "$LMDS" -- stats plugin -- $LMSS -- streaming status (lmclient request) } function segmentCall(line) local seg = line:sub(1,5) local segmentFunc = segmentMap[seg] or pluginSegmentListeners[seg] if segmentFunc then local ok, returnval = pcall(segmentFunc, line) if ok then return returnval else nixio.syslog("err", "Error handling " .. seg .. " in " .. returnval) return "ERR" end else return "ERR" end end local function prepare_daemon() nixio.openlog('linkmeterd') local ipcfd = nixio.socket("unix", "dgram") if not ipcfd then return nil, -2, "Can't create IPC socket" end nixio.fs.unlink("/var/run/linkmeter.sock") ipcfd:bind("/var/run/linkmeter.sock") ipcfd:setblocking(false) Server.register_pollfd({ fd = ipcfd, events = nixio.poll_flags("in"), handler = function (polle) while true do local msg, addr = polle.fd:recvfrom(128) if not (msg and addr) then return end if msg:sub(1, 5) == "$LMSS" then registerStreamingStatus(polle.fd, addr, msg) else lmclientSendTo(polle.fd, addr, segmentCall(msg)) end end -- while true end -- handler }) lmdStartTime = os.time() registerTickListener(lmdTick) return lmdStart() end -- -- linkmeterd service control functions --- function start() prepare_daemon() if uci.cursor():get("linkmeter", "daemon", "daemonize") == "1" then Server.daemonize() end Server.run() end
----------------------------------- -- Area: Upper Jeuno -- NPC: Afdeen -- Standard Merchant NPC -- !pos 1.462 0.000 21.627 244 ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:startEvent(179); end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 179 and option == 1) then player:setPos(0,0,0,0,44); end end;
--- -- codelite/tests/test_codelite_config.lua -- Automated test suite for CodeLite project generation. -- Copyright (c) 2015 Manu Evans and the Premake project --- local suite = test.declare("codelite_cproj_config") local p = premake local codelite = p.modules.codelite --------------------------------------------------------------------------- -- Setup/Teardown --------------------------------------------------------------------------- local wks, prj, cfg function suite.setup() p.action.set("codelite") p.escaper(codelite.esc) p.indent(" ") wks = test.createWorkspace() end local function prepare() prj = test.getproject(wks,1) cfg = test.getconfig(prj, "Debug") end function suite.OnProjectCfg_Compiler() prepare() codelite.project.compiler(cfg) test.capture [[ <Compiler Options="" C_Options="" Assembler="" Required="yes" PreCompiledHeader="" PCHInCommandLine="no" UseDifferentPCHFlags="no" PCHFlags=""> </Compiler> ]] end function suite.OnProjectCfg_Flags() optimize "Debug" exceptionhandling "Off" rtti "Off" pic "On" symbols "On" language "C++" cppdialect "C++11" flags { "NoBufferSecurityCheck" } forceincludes { "forced_include1.h", "forced_include2.h" } buildoptions { "-opt1", "-opt2" } prepare() codelite.project.compiler(cfg) test.capture [[ <Compiler Options="-O0;-fPIC;-g;-std=c++11;-fno-exceptions;-fno-stack-protector;-fno-rtti;-include forced_include1.h;-include forced_include2.h;-opt1;-opt2" C_Options="-O0;-fPIC;-g;-include forced_include1.h;-include forced_include2.h;-opt1;-opt2" Assembler="" Required="yes" PreCompiledHeader="" PCHInCommandLine="no" UseDifferentPCHFlags="no" PCHFlags=""> </Compiler> ]] end function suite.OnProjectCfg_Includes() includedirs { "dir/", "dir2" } prepare() codelite.project.compiler(cfg) test.capture [[ <Compiler Options="" C_Options="" Assembler="" Required="yes" PreCompiledHeader="" PCHInCommandLine="no" UseDifferentPCHFlags="no" PCHFlags=""> <IncludePath Value="dir"/> <IncludePath Value="dir2"/> </Compiler> ]] end function suite.OnProjectCfg_Defines() defines { "TEST", "DEF" } prepare() codelite.project.compiler(cfg) test.capture [[ <Compiler Options="" C_Options="" Assembler="" Required="yes" PreCompiledHeader="" PCHInCommandLine="no" UseDifferentPCHFlags="no" PCHFlags=""> <Preprocessor Value="TEST"/> <Preprocessor Value="DEF"/> </Compiler> ]] end function suite.OnProjectCfg_Linker() prepare() codelite.project.linker(cfg) test.capture [[ <Linker Required="yes" Options=""> </Linker> ]] end function suite.OnProjectCfg_LibPath() libdirs { "test/", "test2" } prepare() codelite.project.linker(cfg) test.capture [[ <Linker Required="yes" Options=""> <LibraryPath Value="test"/> <LibraryPath Value="test2"/> </Linker> ]] end function suite.OnProjectCfg_Libs() links { "a", "b" } prepare() codelite.project.linker(cfg) test.capture [[ <Linker Required="yes" Options="-la;-lb"> </Linker> ]] end -- TODO: test sibling lib project links function suite.OnProjectCfg_ResCompiler() prepare() codelite.project.resourceCompiler(cfg) test.capture [[ <ResourceCompiler Options="" Required="no"/> ]] end function suite.OnProjectCfg_ResInclude() files { "x.rc" } resincludedirs { "dir/" } prepare() codelite.project.resourceCompiler(cfg) test.capture [[ <ResourceCompiler Options="" Required="yes"> <IncludePath Value="dir"/> </ResourceCompiler> ]] end function suite.OnProjectCfg_General() system "Windows" prepare() codelite.project.general(cfg) test.capture [[ <General OutputFile="bin/Debug/MyProject.exe" IntermediateDirectory="obj/Debug" Command="bin/Debug/MyProject.exe" CommandArguments="" UseSeparateDebugArgs="no" DebugArguments="" WorkingDirectory="" PauseExecWhenProcTerminates="yes" IsGUIProgram="no" IsEnabled="yes"/> ]] end function suite.OnProjectCfg_Environment() debugenvs { "ENV_ONE=1", "ENV_TWO=2" } prepare() codelite.project.environment(cfg) test.capture( ' <Environment EnvVarSetName="&lt;Use Defaults&gt;" DbgSetName="&lt;Use Defaults&gt;">\n' .. ' <![CDATA[ENV_ONE=1\n' .. 'ENV_TWO=2]]>\n' .. ' </Environment>' ) end function suite.OnProjectCfg_Debugger() prepare() codelite.project.debugger(cfg) test.capture [[ <Debugger IsRemote="no" RemoteHostName="" RemoteHostPort="" DebuggerPath="" IsExtended="no"> <DebuggerSearchPaths/> <PostConnectCommands/> <StartupCommands/> </Debugger> ]] end function suite.OnProjectCfg_DebuggerOpts() debugremotehost "localhost" debugport(2345) debugextendedprotocol(true) debugsearchpaths { "search/", "path" } debugconnectcommands { "connectcmd1", "cmd2" } debugstartupcommands { "startcmd1", "cmd2" } prepare() codelite.project.debugger(cfg) test.capture [[ <Debugger IsRemote="yes" RemoteHostName="localhost" RemoteHostPort="2345" DebuggerPath="" IsExtended="yes"> <DebuggerSearchPaths>search path</DebuggerSearchPaths> <PostConnectCommands>connectcmd1 cmd2</PostConnectCommands> <StartupCommands>startcmd1 cmd2</StartupCommands> </Debugger> ]] end function suite.OnProject_PreBuild() prebuildcommands { "cmd0", "cmd1" } prepare() codelite.project.preBuild(prj) test.capture [[ <PreBuild> <Command Enabled="yes">cmd0</Command> <Command Enabled="yes">cmd1</Command> </PreBuild> ]] end function suite.OnProject_PreBuild_Escaped() prebuildcommands { "touch \"./build/copyright\" && echo OK", "cat \"./lib/copyright\" >> \"./build/copyright\"" } prepare() codelite.project.preBuild(prj) test.capture [[ <PreBuild> <Command Enabled="yes">touch "./build/copyright" &amp;&amp; echo OK</Command> <Command Enabled="yes">cat "./lib/copyright" &gt;&gt; "./build/copyright"</Command> </PreBuild> ]] end function suite.OnProject_PostBuild() postbuildcommands { "cmd0", "cmd1" } prepare() codelite.project.postBuild(prj) test.capture [[ <PostBuild> <Command Enabled="yes">cmd0</Command> <Command Enabled="yes">cmd1</Command> </PostBuild> ]] end function suite.OnProject_PostBuild_Escaped() postbuildcommands { "touch \"./build/copyright\" && echo OK", "cat \"./lib/copyright\" >> \"./build/copyright\"" } prepare() codelite.project.postBuild(prj) test.capture [[ <PostBuild> <Command Enabled="yes">touch "./build/copyright" &amp;&amp; echo OK</Command> <Command Enabled="yes">cat "./lib/copyright" &gt;&gt; "./build/copyright"</Command> </PostBuild> ]] end -- TODO: test custom build function suite.OnProject_AdditionalRules() prepare() codelite.project.additionalRules(prj) test.capture [[ <AdditionalRules> <CustomPostBuild/> <CustomPreBuild/> </AdditionalRules> ]] end function suite.OnProject_Completion() language "C++" cppdialect "C++11" prepare() codelite.project.completion(prj) test.capture [[ <Completion EnableCpp11="yes" EnableCpp14="no"> <ClangCmpFlagsC/> <ClangCmpFlags/> <ClangPP/> <SearchPaths/> </Completion> ]] end --------------------------------------------------------------------------- -- Setup/Teardown --------------------------------------------------------------------------- function suite.OnProjectCfg_UnsignedCharOn() unsignedchar "On" prepare() codelite.project.compiler(cfg) test.capture [[ <Compiler Options="-funsigned-char" C_Options="-funsigned-char" Assembler="" Required="yes" PreCompiledHeader="" PCHInCommandLine="no" UseDifferentPCHFlags="no" PCHFlags=""> </Compiler> ]] end function suite.OnProjectCfg_UnsignedCharOff() unsignedchar "Off" prepare() codelite.project.compiler(cfg) test.capture [[ <Compiler Options="-fno-unsigned-char" C_Options="-fno-unsigned-char" Assembler="" Required="yes" PreCompiledHeader="" PCHInCommandLine="no" UseDifferentPCHFlags="no" PCHFlags=""> </Compiler> ]] end
------------------------------------------------------------------------------- -- -- tek.class -- Written by Timm S. Mueller <tmueller at schulze-mueller.de> -- See copyright notice in COPYRIGHT -- -- OVERVIEW:: -- [[#ClassOverview]] : Class ${subclasses(Class)} -- -- This module implements inheritance and the creation of objects -- from classes. -- -- IMPLEMENTS:: -- - object:getClass() - Returns the class of an object, or the super -- class of a class -- - object:getClassName() - Returns the class name of an object or class -- - object:getSuper() - Returns the super class of an object or class -- - object:instanceOf() - Checks if an object descends from a class -- - Class.module() - Creates a new class from a superclass -- - Class.new() - Creates and returns a new object -- - Class.newClass() - Creates a child class from a super class -- - object:setClass() - Changes the class of an object, or the super -- class of a class -- ------------------------------------------------------------------------------- local assert = assert local error = error local require = require local tostring = tostring local getmetatable = getmetatable local setmetatable = setmetatable -- use proxied object model: local PROXY = false -- in proxied mode, trace uninitialized variable accesses: local DEBUG = false --[[ header token for documentation generator: module "tek.class" local Class = _M ]] local Class = { } Class._NAME = "tek.class" Class._VERSION = "Class 9.1" Class.__index = Class if PROXY then function Class.new(class, self) self = self or { } local mt = { __class = class } if DEBUG then function mt.__index(tab, key) local val = mt[key] if val == nil then error(("Uninitialized read: %s.%s"):format( tab:getClassName(), key), 2) end return val end function mt.__newindex(tab, key, val) error(("Uninitialized write: %s.%s=%s"):format( tab:getClassName(), key, tostring(val)), 2) mt[key] = val end else mt.__index = mt mt.__newindex = mt end setmetatable(mt, class) return setmetatable(self, mt) end function Class:getClass() local mt = getmetatable(self) return mt.__class or mt end function Class:setClass(class) local mt = getmetatable(self) mt.__class = class setmetatable(mt, class) end function Class:getSuper() return getmetatable(self.__class or self) end else ------------------------------------------------------------------------------- -- object = Class.new(class[, object]): -- Creates and returns a new object of the given {{class}}. Optionally, -- it just prepares the specified {{object}} (a table) for inheritance and -- attaches the {{class}}' methods and data. ------------------------------------------------------------------------------- function Class.new(class, self) return setmetatable(self or { }, class) end ------------------------------------------------------------------------------- -- class = object:getClass(): -- This function returns the class of an {{object}}. If applied to a -- class instead of an object, it returns its super class, e.g.: -- superclass = Class.getClass(class) ------------------------------------------------------------------------------- function Class:getClass() return getmetatable(self) end ------------------------------------------------------------------------------- -- object:setClass(class): Changes the class of an object -- or the super class of a class. ------------------------------------------------------------------------------- function Class:setClass(class) setmetatable(self, class) end ------------------------------------------------------------------------------- -- object:getSuper(): Gets the super class of an object or class. -- For example, to forward a call to a {{method}} to its super class, -- without knowing its class: -- self:getSuper().method(self, ...) ------------------------------------------------------------------------------- function Class:getSuper() return getmetatable(self.__index or getmetatable(self)) end end ------------------------------------------------------------------------------- -- class = Class.newClass(superclass[, class]): -- Derives a new class from the specified {{superclass}}. Optionally, -- an existing {{class}} (a table) can be specified. If a {{_NAME}} field -- exists in this class, it will be used. Otherwise, or if a new class is -- created, {{class._NAME}} will be composed from {{superclass._NAME}} and -- an unique identifier. The same functionality can be achieved by calling -- a class like a function, so the following invocations are equivalent: -- class = Class.newClass(superclass) -- class = superclass() -- The second notation allows a super class to be passed as the second -- argument to Lua's {{module}} function, which will set up a child class -- inheriting from {{superclass}} in the module table. ------------------------------------------------------------------------------- function Class.newClass(superclass, class) local class = class or { } class.__index = class class.__call = newClass class._NAME = class._NAME or superclass._NAME .. tostring(class):gsub("^table: 0x(.*)$", ".%1") return setmetatable(class, superclass) end ------------------------------------------------------------------------------- -- name = object:getClassName(): This function returns the {{_NAME}} -- attribute of the {{object}}'s class. It is also possible to apply this -- function to a class instead of an object. ------------------------------------------------------------------------------- function Class:getClassName() return self._NAME end ------------------------------------------------------------------------------- -- is_descendant = object:instanceOf(class): -- Returns '''true''' if {{object}} is an instance of or descends from the -- specified {{class}}. It is also possible to apply this function to a class -- instead of an object, e.g.: -- Class.instanceOf(Button, Area) ------------------------------------------------------------------------------- function Class:instanceOf(ancestor) assert(ancestor) while self ~= ancestor do self = getmetatable(self) if not self then return false end end return true end ------------------------------------------------------------------------------- -- class, superclass = Class.module(classname, superclassname): Creates a new -- class from the specified superclass. {{superclassname}} is being loaded -- and its method Class:newClass() invoked with the {{_NAME}} field set to -- {{classname}}. Both class and superclass will be returned. ------------------------------------------------------------------------------- function Class.module(classname, superclassname) local superclass = require(superclassname) return superclass:newClass { _NAME = classname }, superclass end return Class
-- -- Copyright (c) 2015 Jonathan Howard. -- function bullet_library(_kind) newoption { trigger = "without-cl", description = "Disable OpenCL for Bullet." } project "bullet" language "C++" kind(_kind) includedirs { BULLET_DIR .. "src/" } files { BULLET_DIR .. "src/**.h", BULLET_DIR .. "src/**.cpp" } if _OPTIONS["without-cl"] then excludes { BULLET_DIR .. "src/Bullet3OpenCL/**.cpp", BULLET_DIR .. "src/Bullet3OpenCL/**.h" } end end
--************************ --name : SINGLE_DEL_NX_01.lua --ver : 0.1 --author : Kintama --date : 2004/09/09 --lang : en --desc : terminal mission --npc : --************************ --changelog: --2004/09/09(0.1): Added description --************************ function DIALOG() NODE(0) SAY("NEXT, how can I help you?") SAY("NEXT, where do you want to go today?") SAY("Hello there. Come about the delivery job?") SAY("Welcome to Neocron Exploration Technology Inc. How can I help you?") SAY("Hey. Are you here about the delivery job?") SAY("G'day to you. We here at NEXT could use your help, if you are interested.") ANSWER("Yes, I am here regarding the delivery job.",1) ANSWER("Yeah, I heard you needed a drop done. Just give me the information and the package.",1) ANSWER("I'm here about the delivery job. Just give me the where and when and I will drop it off.",1) ANSWER("Sorry, I all ready have a job.",4) ANSWER("Find someone else, I am not interested in helping you.",4) ANSWER("Look buddy, do I look like some kind of Runner? I don't do deliveries.",4) NODE(1) GIVEQUESTITEM(91) SAY("OK. I have a package here for a certain %NPC_NAME(1) at %NPC_WORLD(1). Make sure you deliver it fast, we do work with transportation after all. Good luck.") SAY("All right, Runner. %NPC_NAME(1) is waiting for this delivery. Try looking at %NPC_WORLD(1). Please make a swift drop, we are in the transportation business after all.") SAY("Hmmm, this isn't right... Oh, yeah, listen up. %NPC_NAME(1) of the Bergen-Dahl Motor company needs this package. Deliver it at %NPC_WORLD(1). Make it quick and then get back here.") ACTIVATEDIALOGTRIGGER(0) SETNEXTDIALOGSTATE(2) ENDDIALOG() NODE(2) ISMISSIONTARGETACCOMPLISHED(1) if (result==0) then SAY("Wherever you want to go - go NEXT. Yes, that applies to packages too. Make the drop like I told you.") SAY("%NPC_NAME(1) from Bergen-Dahl Motors called, again, and asked for his package. Hurry up and drop it off.") SAY("Are you into anarchy? Well, NEXT isn't. Here you do as you have been told. Deliver the friggin package!") SAY("Listen, I don't have time to talk. %NPC_NAME(1) is still waiting for the drop.") ENDDIALOG() else SAY("Well done. The guys from Bergen-Dahl called and said they got the package. The fee of %REWARD_MONEY() credits has been deposited into your account.") SAY("Thanks. %NPC_NAME(1) confirmed the drop and %REWARD_MONEY() credits has been deposited in your account. Thank you for your assistance.") SAY("Hello again. The drop has been confirmed and %REWARD_MONEY() credits has been moved to your account. G'day and we look forward to working with you again.") SAY("Bergen-Dahl Motors called and confirmed the drop. I have moved %REWARD_MONEY() credits to your personal account. We are thankful for your assistance.") SAY("That wasn't very fast... But, the guys at Bergen-Dahl motors got the package. %REWARD_MONEY() credits have been moved to your account. That is all, you may leave.") ACTIVATEDIALOGTRIGGER(2) ENDDIALOG() end NODE(3) TAKEQUESTITEM(91) if (result==0) then SAY("Listen, buddy. We at Bergen-Dahl are not suckers. You have a package for me, right? Hand it over!") SAY("I was promised that package long ago. I hope you are not withholding it from me, pal...") SAY("Yeah, sure, screw the Bergen-Dahl grease-monkey why don't you. I know you are supposed to deliver a package for me. Where is it?") ENDDIALOG() else SAY("Ah, good. The package from NEXT, right? %NPC_NAME(0) will pay you for the delivery.") SAY("You have the package from NEXT! Good. %NPC_NAME(0) probably has some creds for you.") SAY("This is the stuff %NPC_NAME(0) at NEXT sent us? OK. They will pay for the delivery. Thanks, pal.") SAY("All right! The NEXT package. Kind of funny Bergen-Dahl motors have to rely on NEXT for this. %NPC_NAME(0) will pay you.") SAY("Took you long enough to get that thing here. %NPC_NAME(0) will have to pay you, because I won't.") ACTIVATEDIALOGTRIGGER(1) SETNEXTDIALOGSTATE(5) ENDDIALOG() end NODE(4) SAY("Ok, please go away if you don't have any business here at NEXT.") SAY("This is me talking to you. This is me ignoring you...") SAY("NEXT thanks you for your visit and wishes you a good day. Bye.") ENDDIALOG() NODE(5) SAY("What the hell do you want here? I got the packet, now go back to %NPC_NAME(0) to recieve your reward") SAY("Thanks for delivering this package. Now go back to %NPC_NAME(0) to recieve your reward.") ENDDIALOG() end
local Object = require("object") local Action = Object:new(); function Action:new (obj) obj = Object.new( self, obj ) obj.f = nil obj.tags = {}; return obj end function Action:addTag (tag) self.tags[tag] = true end function Action:removeTag (tag) self.tags[tag] = nil end function Action:isTagged (tag) return self.tags[tag] end return Action
-- 裸vim映射(不包括插件) -- colemark user local is_colemark_user = true local map_opt = {silent = true, noremap = true} -- 方向移动 vim.api.nvim_set_keymap('n', 'n', 'j', map_opt) vim.api.nvim_set_keymap('n', 'e', 'k', map_opt) vim.api.nvim_set_keymap('n', 'i', 'l', map_opt) vim.api.nvim_set_keymap('v', 'n', 'j', map_opt) vim.api.nvim_set_keymap('v', 'e', 'k', map_opt) vim.api.nvim_set_keymap('v', 'i', 'l', map_opt) -- 单词移动 vim.api.nvim_set_keymap('n', 'k', 'e', map_opt) vim.api.nvim_set_keymap('v', 'k', 'e', map_opt) -- 插入模式 vim.api.nvim_set_keymap('n', 'u', 'i', map_opt) -- 撤销 vim.api.nvim_set_keymap('n', 'l', 'u', map_opt) -- 窗口移动 vim.api.nvim_set_keymap('n', '<space>', '<C-w>', map_opt); -- TODO nvim-tree vim.api.nvim_set_keymap('n', '<leader>f', ':NvimTreeToggle<CR>', map_opt)
#! /usr/bin/lua -- ---------------------------------------------------- -- text_create.lua -- -- Jun/22/2011 -- -- ---------------------------------------------------- require ('text_manipulate') -- ---------------------------------------------------- function data_prepare_proc () dict_aa = {} dict_aa = dict_append_proc (dict_aa,"t2381","名古屋",83175,"1981-5-17") dict_aa = dict_append_proc (dict_aa,"t2382","豊橋",47154,"1981-8-9") dict_aa = dict_append_proc (dict_aa,"t2383","岡崎",53643,"1981-9-15") dict_aa = dict_append_proc (dict_aa,"t2384","一宮",41329,"1981-3-22") dict_aa = dict_append_proc (dict_aa,"t2385","蒲郡",86178,"1981-7-11") dict_aa = dict_append_proc (dict_aa,"t2386","常滑",38527,"1981-9-21") dict_aa = dict_append_proc (dict_aa,"t2387","大府",49536,"1981-1-4") dict_aa = dict_append_proc (dict_aa,"t2388","瀬戸",57545,"1981-10-21") dict_aa = dict_append_proc (dict_aa,"t2389","犬山",45326,"1981-3-18") return dict_aa end -- ---------------------------------------------------- print ("*** 開始 ***") file_out=arg[1] dict_aa = data_prepare_proc () text_write_proc (file_out,dict_aa) print ("*** 終了 ***") -- ----------------------------------------------------
---@class mx.io:mx.io.io local M = {} table.merge(M, require('mx.io.io')) table.merge(M, require('mx.io.utils')) return M
function Is_self_describing( n ) local s = tostring( n ) local t = {} for i = 0, 9 do t[i] = 0 end for i = 1, s:len() do local idx = tonumber( s:sub(i,i) ) t[idx] = t[idx] + 1 end for i = 1, s:len() do if t[i-1] ~= tonumber( s:sub(i,i) ) then return false end end return true end for i = 1, 999999999 do print( Is_self_describing( i ) ) end
local ecs = require('ecs') local mgr = ecs.NewManager() local e1 = mgr.NewEntity() mgr.AddComponent(e1, { Name='A1', X = 1, HP = 2, }, 1) local e2 = mgr.NewEntity() mgr.AddComponent(e2, { Name='A2', X = 10, HP = 5, }, 1) local sys = {} function sys.Update(mgr) print('Frame:', mgr.GetFrameCount()) local ents, comps = mgr.GetAllComponent(1) for index, value in ipairs(comps) do local entity = ents[index] value.X = value.X + 1 value.HP = value.HP - 1 if value.HP <= 0 then mgr.RemoveEntity(entity) end print(string.format('%d name:%s position:%s hp:%d', entity, value.Name, value.X, value.HP)) end end mgr.AddSystem(sys) mgr.Update() mgr.Update() mgr.Update() local bin = mgr.Encode() mgr.Decode(bin) mgr.Update() mgr.Update()
return {'kaffer','kaffers','kaf','kaffa','kaffer','kafferbuffel','kafferen','kafferpokken','kafir','kafkaiaans','kafkaesk','kafmolen','kaft','kaftan','kaften','kafzak','kafkafan','kaffiya','kaffa','kafferde','kafferden','kaffers','kafje','kafjes','kafmolens','kaftans','kaftte','kafferbuffels','kafirs','kafkaiaanse','kafzakken','kafkaeske','kafkafans','kaffiyas'}
local t = Def.Model { Meshes=NOTESKIN:GetPath('_Down','Tap Note'); Materials=NOTESKIN:GetPath('_Down','Tap Note'); Bones=NOTESKIN:GetPath('_Down','Tap Note'); }; return t;
require "TimedActions/ISBaseTimedAction" ISInventoryTransferAction = ISBaseTimedAction:derive("ISInventoryTransferAction"); function ISInventoryTransferAction:isValid() if (not self.destContainer:isExistYet()) or (not self.srcContainer:isExistYet()) then return false end -- Limit items per container in MP if isClient() then local limit = getServerOptions():getInteger("ItemNumbersLimitPerContainer") if limit > 0 and (not instanceof(self.destContainer:getParent(), "IsoGameCharacter")) and self.destContainer:getItems():size()+1 > limit then return false end end if ISTradingUI.instance and ISTradingUI.instance:isVisible() then return false; end if not self.srcContainer:contains(self.item) then return false; end if self.srcContainer == self.destContainer then return false; end if self.destContainer:getType()=="floor" then if instanceof(self.item, "Moveable") and self.item:getSpriteGrid()==nil then if not self.item:CanBeDroppedOnFloor() then return false; end end end if not self.destContainer:hasRoomFor(self.character, self.item) then if (self.destContainer:getType() == "floor") then if (self.item:getActualWeight() < self.destContainer:getCapacity() or self.destContainer:getContentsWeight() > self.destContainer:getCapacity()) then return false; end else return false; end end if self.destContainer:getOnlyAcceptCategory() and self.item:getCategory() ~= self.destContainer:getOnlyAcceptCategory() then return false; end if self.item:getContainer() == self.srcContainer and not self.destContainer:isInside(self.item) then return true; end if isClient() and self.srcContainer:getSourceGrid() and SafeHouse.isSafeHouse(self.srcContainer:getSourceGrid(), self.character:getUsername(), true) then return false; end return false; end function ISInventoryTransferAction:update() -- if self.updateDestCont then -- self.destContainer:setSourceGrid(self.character:getCurrentSquare()); -- end -- -- if self.updateSrcCont then -- self.srcContainer:setSourceGrid(self.character:getCurrentSquare()); -- end self.item:setJobDelta(self.action:getJobDelta()); end function ISInventoryTransferAction:removeItemOnCharacter() if self.character:getPrimaryHandItem() == self.item then self.character:setPrimaryHandItem(nil); end if self.character:getSecondaryHandItem() == self.item then self.character:setSecondaryHandItem(nil); end if self.character:getClothingItem_Torso() == self.item then self.character:setClothingItem_Torso(nil); end if self.character:getClothingItem_Torso() == self.item then self.character:setClothingItem_Torso(nil); end if self.character:getClothingItem_Legs() == self.item then self.character:setClothingItem_Legs(nil); end if self.character:getClothingItem_Feet() == self.item then self.character:setClothingItem_Feet(nil); end if self.character:getClothingItem_Back() == self.item then self.character:setClothingItem_Back(nil); end if self.item and self.item:getCategory() == "Clothing" then triggerEvent("OnClothingUpdated", self.character) end end ISInventoryTransferAction.putSound = nil; function ISInventoryTransferAction:start() -- stop microwave working when putting new stuff in it if self.destContainer and self.destContainer:getType() == "microwave" and self.destContainer:getParent() and self.destContainer:getParent():Activated() then self.destContainer:getParent():setActivated(false); end if self.srcContainer and self.srcContainer:getType() == "microwave" and self.srcContainer:getParent() and self.srcContainer:getParent():Activated() then self.srcContainer:getParent():setActivated(false); end -- if self.destContainer:getPutSound() then if not ISInventoryTransferAction.putSound or not self.character:getEmitter():isPlaying(ISInventoryTransferAction.putSound) then ISInventoryTransferAction.putSound = self.character:getEmitter():playSound("PZ_PutInBag"); elseif not self.character:getEmitter():isPlaying(ISInventoryTransferAction.putSound) then ISInventoryTransferAction.putSound = self.character:getEmitter():playSound("PZ_PutInBag"); end -- end if self.srcContainer == self.character:getInventory() then if self.destContainer:isInCharacterInventory(self.character) then self.item:setJobType(getText("IGUI_Packing")); else self.item:setJobType(getText("IGUI_PuttingInContainer")); end return; elseif self.srcContainer:isInCharacterInventory(self.character) then if self.destContainer == self.character:getInventory() then self.item:setJobType(getText("IGUI_Unpacking")); else self.item:setJobType(getText("IGUI_TakingFromContainer")); end return; elseif not self.srcContainer:isInCharacterInventory(self.character) then if self.destContainer:isInCharacterInventory(self.character) then self.item:setJobType(getText("IGUI_TakingFromContainer")); -- self.maxTime = 30; return; end end self.item:setJobType(getText("IGUI_MovingToContainer")); end function ISInventoryTransferAction:stop() ISBaseTimedAction.stop(self); self.item:setJobDelta(0.0); end function ISInventoryTransferAction:perform() self.item:setJobDelta(0.0); if self.item:isFavorite() and not self.destContainer:isInCharacterInventory(self.character) then ISBaseTimedAction.perform(self); return; end if(self.item ~= nil) then local ssquare = getSourceSquareOfItem(self.item,self.character) --print(tostring(ssquare)) if(ssquare ~= nil) then local OwnerGroupId = SSGM:GetGroupIdFromSquare(ssquare) local TakerGroupId = self.character:getModData().Group if(OwnerGroupId ~= -1) and (TakerGroupId ~= OwnerGroupId) then print("ga stealing detected!") SSGM:Get(OwnerGroupId):stealingDetected(self.character) end end end if self.destContainer:isInCharacterInventory(self.character) then end if self.srcContainer:isInCharacterInventory(self.character) then end if self.srcContainer:getType() ~= "TradeUI" and isClient() and not self.destContainer:isInCharacterInventory(self.character) and self.destContainer:getType()~="floor" then self.destContainer:addItemOnServer(self.item); end if self.srcContainer:getType() ~= "TradeUI" and isClient() and not self.srcContainer:isInCharacterInventory(self.character) and self.srcContainer:getType()~="floor" then self.srcContainer:removeItemOnServer(self.item); end if self.destContainer:getType() ~= "TradeUI" then self.srcContainer:DoRemoveItem(self.item); end -- clear it from the queue. self.srcContainer:setDrawDirty(true); self.srcContainer:setHasBeenLooted(true); self.destContainer:setDrawDirty(true); -- deal with containers that are floor if self.destContainer:getType()=="floor" then self.destContainer:DoAddItemBlind(self.item); self.character:getCurrentSquare():AddWorldInventoryItem(self.item, self.character:getX() - math.floor(self.character:getX()), self.character:getY() - math.floor(self.character:getY()), self.character:getZ() - math.floor(self.character:getZ())); self:removeItemOnCharacter(); elseif self.srcContainer:getType()=="floor" and self.item:getWorldItem() ~= nil then self.item:getWorldItem():getSquare():transmitRemoveItemFromSquare(self.item:getWorldItem()); self.item:getWorldItem():getSquare():removeWorldObject(self.item:getWorldItem()); -- self.item:getWorldItem():getSquare():getObjects():remove(self.item:getWorldItem()); self.item:setWorldItem(nil); self.destContainer:AddItem(self.item); else if self.srcContainer:getType() ~= "TradeUI" then self.destContainer:AddItem(self.item); end if self.character:getInventory() ~= self.destContainer then self:removeItemOnCharacter(); end end if self.destContainer:getParent() and instanceof(self.destContainer:getParent(), "BaseVehicle") and self.destContainer:getParent():getPartById(self.destContainer:getType()) then local part = self.destContainer:getParent():getPartById(self.destContainer:getType()); part:setContainerContentAmount(part:getItemContainer():getCapacityWeight()); end if self.srcContainer:getParent() and instanceof(self.srcContainer:getParent(), "BaseVehicle") and self.srcContainer:getParent():getPartById(self.srcContainer:getType()) then local part = self.srcContainer:getParent():getPartById(self.srcContainer:getType()); part:setContainerContentAmount(part:getItemContainer():getCapacityWeight()); end -- Hack for giving cooking XP. if instanceof(self.item, "Food") then self.item:setChef(self.character:getFullName()) end if self.destContainer:getType() == "stonefurnace" then self.item:setWorker(self.character:getFullName()); end local pdata = getPlayerData(self.character:getPlayerNum()); pdata.playerInventory:refreshBackpacks(); pdata.lootInventory:refreshBackpacks(); -- do the overlay sprite if not isClient() then if self.srcContainer:getParent() and self.srcContainer:getParent():getOverlaySprite() then ItemPicker.updateOverlaySprite(self.srcContainer:getParent()) end if self.destContainer:getParent() then ItemPicker.updateOverlaySprite(self.destContainer:getParent()) end end -- needed to remove from queue / start next. ISBaseTimedAction.perform(self); if self.onCompleteFunc then local args = self.onCompleteArgs self.onCompleteFunc(args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]) end end function ISInventoryTransferAction:setOnComplete(func, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) self.onCompleteFunc = func self.onCompleteArgs = { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 } end function ISInventoryTransferAction:getTimeDelta() return 0; end function ISInventoryTransferAction:new (character, item, srcContainer, destContainer, time) local o = {} setmetatable(o, self) self.__index = self o.character = character; o.item = item; o.srcContainer = srcContainer; o.destContainer = destContainer; o.stopOnWalk = ((not o.destContainer:isInCharacterInventory(o.character)) or (not o.srcContainer:isInCharacterInventory(o.character))) and (o.destContainer:getType() ~= "floor"); o.stopOnRun = o.destContainer:getType() ~= "floor"; if destContainer:getType() ~= "TradeUI" and srcContainer:getType() ~= "TradeUI" then o.maxTime = 120; -- increase time for bigger objects or when backpack is more full. local destCapacityDelta = 1.0; if o.srcContainer == o.character:getInventory() then if o.destContainer:isInCharacterInventory(o.character) then -- self.item:setJobType("Packing"); destCapacityDelta = o.destContainer:getCapacityWeight() / o.destContainer:getMaxWeight(); else -- self.item:setJobType("Putting in container"); o.maxTime = 50; end elseif not o.srcContainer:isInCharacterInventory(o.character) then if o.destContainer:isInCharacterInventory(o.character) then -- self.item:setJobType("Taking from container"); o.maxTime = 50; end end if destCapacityDelta < 0.4 then destCapacityDelta = 0.4; end local w = item:getActualWeight(); if w > 3 then w = 3; end; o.maxTime = o.maxTime * (w) * destCapacityDelta; if getCore():getGameMode()=="LastStand" then o.maxTime = o.maxTime * 0.3; end if o.destContainer:getType()=="floor" then o.maxTime = o.maxTime * 0.1; end if character:HasTrait("Dextrous") then o.maxTime = o.maxTime * 0.5 end if character:HasTrait("AllThumbs") then o.maxTime = o.maxTime * 4.0 end else o.maxTime = 0; end if time then o.maxTime = time; end if character:getAccessLevel() ~= "None" or (instanceof(character, "IsoPlayer") and character:isGhostMode()) then o.maxTime = 1; end o.jobType = getText("IGUI_JobType_Grabbing", item:getName()); if item:isFavorite() and not o.destContainer:isInCharacterInventory(o.character) then o.maxTime = 0; end return o end
local bot = GetBot(); if bot:IsInvulnerable() or bot:IsHero() == false or bot:IsIllusion() then return; end local ability_item_usage_generic = dofile( GetScriptDirectory().."/ability_item_usage_generic" ) local utils = require(GetScriptDirectory() .. "/util") local mutils = require(GetScriptDirectory() .. "/MyUtility") function AbilityLevelUpThink() ability_item_usage_generic.AbilityLevelUpThink(); end function BuybackUsageThink() ability_item_usage_generic.BuybackUsageThink(); end function CourierUsageThink() ability_item_usage_generic.CourierUsageThink(); end function ItemUsageThink() ability_item_usage_generic.ItemUsageThink() end --[[ Abilities "Ability1" "warlock_fatal_bonds" "Ability2" "warlock_shadow_word" "Ability3" "warlock_upheaval" "Ability4" "generic_hidden" "Ability5" "generic_hidden" "Ability6" "warlock_rain_of_chaos" "Ability10" "special_bonus_unique_warlock_5" "Ability11" "special_bonus_cast_range_125" "Ability12" "special_bonus_exp_boost_40" "Ability13" "special_bonus_unique_warlock_3" "Ability14" "special_bonus_unique_warlock_4" "Ability15" "special_bonus_unique_warlock_6" "Ability16" "special_bonus_unique_warlock_2" "Ability17" "special_bonus_unique_warlock_1" ]] --[[ modifier_warlock_fatal_bonds modifier_warlock_shadow_word modifier_warlock_upheaval modifier_warlock_rain_of_chaos_death_trigger modifier_warlock_rain_of_chaos_thinker modifier_special_bonus_unique_warlock_1 modifier_special_bonus_unique_warlock_2 modifier_warlock_golem_flaming_fists modifier_warlock_golem_permanent_immolation modifier_warlock_golem_permanent_immolation_debuff ]]-- local abilities = mutils.InitiateAbilities(bot, {0,1,2,5,11}); local castQDesire = 0; local castWDesire = 0; local castEDesire = 0; local castRDesire = 0; local castRefresher = 0; local function ConsiderQ() if mutils.CanBeCast(abilities[1]) == false then return BOT_ACTION_DESIRE_NONE, nil; end local nCastRange = mutils.GetProperCastRange(false, bot, abilities[1]:GetCastRange()); local nCastPoint = abilities[1]:GetCastPoint(); local manaCost = abilities[1]:GetManaCost(); local nRadius = abilities[1]:GetSpecialValueInt( "search_aoe" ); local nCount = abilities[1]:GetSpecialValueInt( "count" ); if mutils.IsRetreating(bot) then local target = mutils.GetVulnerableWeakestUnit(true, true, nCastRange, bot); if target ~= nil and mutils.GetUnitCountAroundEnemyTarget(target, nRadius) >= nCount/2 then return BOT_ACTION_DESIRE_HIGH, target; end end if mutils.IsGoingOnSomeone(bot) then local target = bot:GetTarget(); if mutils.IsValidTarget(target) and mutils.CanCastOnNonMagicImmune(target) and mutils.IsInRange(target, bot, nCastRange) then if mutils.GetUnitCountAroundEnemyTarget(target, nRadius) >= nCount/2 then return BOT_ACTION_DESIRE_HIGH, target; end end end return BOT_ACTION_DESIRE_NONE, nil; end local lastCheck = -90; local function ConsiderW() if mutils.CanBeCast(abilities[2]) == false then return BOT_ACTION_DESIRE_NONE, "", nil; end local nCastRange = mutils.GetProperCastRange(false, bot, abilities[2]:GetCastRange()); local nCastPoint = abilities[2]:GetCastPoint(); local manaCost = abilities[2]:GetManaCost(); local nRadius = 0; if abilities[5]:IsTrained() then nRadius = 250 end if DotaTime() >= lastCheck + 2.0 then local weakest = nil; local minHP = 100000; local allies = bot:GetNearbyHeroes(nCastRange, false, BOT_MODE_NONE); if #allies > 0 then for i=1,#allies do if allies[i]:HasModifier("modifier_warlock_shadow_word") == false and mutils.CanCastOnNonMagicImmune(allies[i]) and allies[i]:GetHealth() <= minHP and allies[i]:GetHealth() <= 0.55*allies[i]:GetMaxHealth() then weakest = allies[i]; minHP = allies[i]:GetHealth(); end end end if weakest ~= nil then if abilities[5]:IsTrained() then return BOT_ACTION_DESIRE_HIGH, "loc", weakest:GetLocation(); else return BOT_ACTION_DESIRE_HIGH, "unit", weakest; end end lastCheck = DotaTime(); end if mutils.IsInTeamFight(bot, 1200) and abilities[5]:IsTrained() then local locationAoE = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRange, nRadius, 0, 0 ); if ( locationAoE.count >= 2 ) then return BOT_ACTION_DESIRE_LOW, "loc", locationAoE.targetloc; end end if mutils.IsGoingOnSomeone(bot) then local target = bot:GetTarget(); if mutils.IsValidTarget(target) and mutils.CanCastOnNonMagicImmune(target) and mutils.IsInRange(target, bot, nCastRange) and target:HasModifier("modifier_warlock_shadow_word") == false then if abilities[5]:IsTrained() then return BOT_ACTION_DESIRE_HIGH, "loc", target:GetLocation(); else return BOT_ACTION_DESIRE_HIGH, "unit", target; end end end return BOT_ACTION_DESIRE_NONE, "", nil; end local function GetTotalMana(slot) local total = 0; for i=1,#slot do total = total + abilities[slot[i]]:GetManaCost(); end return total; end local function ConsiderE() if not mutils.CanBeCast(abilities[3]) then return BOT_ACTION_DESIRE_NONE, nil; end if abilities[4]:IsFullyCastable() and bot:GetMana() >= GetTotalMana({3,4}) then return BOT_ACTION_DESIRE_NONE, nil; elseif abilities[4]:IsFullyCastable() == false and abilities[1]:IsFullyCastable() and abilities[2]:IsFullyCastable() then return BOT_ACTION_DESIRE_NONE, nil; end local nCastRange = mutils.GetProperCastRange(false, bot, abilities[3]:GetCastRange()); local nCastPoint = abilities[3]:GetCastPoint(); local manaCost = abilities[3]:GetManaCost(); local nRadius = abilities[3]:GetSpecialValueInt( "aoe" ); if mutils.IsInTeamFight(bot, 1200) then local locationAoE = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRange, nRadius/2, 0, 0 ); if ( locationAoE.count >= 2 ) then return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc; end end -- If we're going after someone if mutils.IsGoingOnSomeone(bot) then local npcTarget = bot:GetTarget(); if mutils.IsValidTarget(npcTarget) and mutils.CanCastOnNonMagicImmune(npcTarget) and mutils.IsInRange(npcTarget, bot, nCastRange + 200) then local enemies = npcTarget:GetNearbyHeroes(nRadius, false, BOT_MODE_NONE); if #enemies >= 2 then return BOT_ACTION_DESIRE_HIGH, npcTarget:GetExtrapolatedLocation(nCastPoint); end end end return BOT_ACTION_DESIRE_NONE, nil; end local function ConsiderR() if not mutils.CanBeCast(abilities[4]) then return BOT_ACTION_DESIRE_NONE, nil; end if abilities[1]:IsFullyCastable() and bot:GetMana() >= GetTotalMana({1,3,4}) then return BOT_ACTION_DESIRE_NONE, nil; end local nCastRange = mutils.GetProperCastRange(false, bot, abilities[4]:GetCastRange()); local nCastPoint = abilities[4]:GetCastPoint(); local manaCost = abilities[4]:GetManaCost(); local nRadius = abilities[4]:GetSpecialValueInt( "aoe" ); if mutils.IsInTeamFight(bot, 1200) then local locationAoE = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRange, nRadius/2, 0, 0 ); if ( locationAoE.count >= 2 ) then return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc; end end return BOT_ACTION_DESIRE_NONE, nil; end function AbilityUsageThink() if mutils.CantUseAbility(bot) then return end castQDesire, qTarget = ConsiderQ(); castWDesire, wType, wTarget = ConsiderW(); castEDesire, eTarget = ConsiderE(); castRDesire, rTarget = ConsiderR(); if castRDesire > 0 then bot:Action_UseAbilityOnLocation(abilities[4], rTarget); return end if castQDesire > 0 then bot:Action_UseAbilityOnEntity(abilities[1], qTarget); return end if castWDesire > 0 then if wType == "loc" then bot:Action_UseAbilityOnLocation(abilities[2], wTarget); else bot:Action_UseAbilityOnEntity(abilities[2], wTarget); end return end if castEDesire > 0 then bot:Action_UseAbilityOnLocation(abilities[3], eTarget); return end end
local att = {} att.name = "md_mchoke" att.displayName = "Modified Choke" att.displayNameShort = "MChoke" att.statModifiers = {OverallMouseSensMult = -0.15, VelocitySensitivityMult = 0.15, DrawSpeedMult = -0.05, HipSpreadMult = 0.1 } if CLIENT then att.displayIcon = surface.GetTextureID("atts/saker") att.description = {[1] = {t = "Decreases clump spread by 10%.", c = CustomizableWeaponry.textColors.POSITIVE}} end function att:attachFunc() self.ClumpSpread = nil end function att:detachFunc() self.ClumpSpread = self.ClumpSpread_Orig end CustomizableWeaponry:registerAttachment(att)
local S = homedecor.gettext local toilet_sbox = { type = "fixed", fixed = { -6/16, -8/16, -8/16, 6/16, 9/16, 8/16 }, } local toilet_cbox = { type = "fixed", fixed = { {-6/16, -8/16, -8/16, 6/16, 1/16, 8/16 }, {-6/16, -8/16, 4/16, 6/16, 9/16, 8/16 } } } homedecor.register("toilet", { description = S("Toilet"), mesh = "homedecor_toilet_closed.obj", tiles = { "homedecor_marble.png^[colorize:#ffffff:175", "homedecor_marble.png^[colorize:#ffffff:175", "homedecor_marble.png^[colorize:#ffffff:175", "homedecor_generic_metal_black.png^[brighten" }, selection_box = toilet_sbox, node_box = toilet_cbox, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), on_punch = function (pos, node, puncher) node.name = "homedecor:toilet_open" minetest.set_node(pos, node) end }) homedecor.register("toilet_open", { mesh = "homedecor_toilet_open.obj", tiles = { "homedecor_marble.png^[colorize:#ffffff:175", "homedecor_marble.png^[colorize:#ffffff:175", "homedecor_marble.png^[colorize:#ffffff:175", "default_water.png", "homedecor_generic_metal_black.png^[brighten" }, selection_box = toilet_sbox, collision_box = toilet_cbox, drop = "homedecor:toilet", groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), on_punch = function (pos, node, puncher) node.name = "homedecor:toilet" minetest.set_node(pos, node) minetest.sound_play("homedecor_toilet_flush", { pos=pos, max_hear_distance = 5, gain = 1, }) end }) -- toilet paper :-) local tp_cbox = { type = "fixed", fixed = { -0.25, 0.125, 0.0625, 0.1875, 0.4375, 0.5 } } homedecor.register("toilet_paper", { description = S("Toilet paper"), mesh = "homedecor_toilet_paper.obj", tiles = { "homedecor_generic_quilted_paper.png", "default_wood.png" }, inventory_image = "homedecor_toilet_paper_inv.png", selection_box = tp_cbox, walkable = false, groups = {snappy=3,oddly_breakable_by_hand=3}, sounds = default.node_sound_defaults(), }) --Sink local sink_cbox = { type = "fixed", fixed = { -5/16, -8/16, 1/16, 5/16, 8/16, 8/16 } } homedecor.register("sink", { description = S("Bathroom Sink"), mesh = "homedecor_bathroom_sink.obj", tiles = { "homedecor_marble.png^[colorize:#ffffff:175", "homedecor_marble.png", "default_water.png" }, inventory_image="homedecor_bathroom_sink_inv.png", selection_box = sink_cbox, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), node_box = { type = "fixed", fixed = { { -5/16, 5/16, 1/16, -4/16, 8/16, 8/16 }, { 5/16, 5/16, 1/16, 4/16, 8/16, 8/16 }, { -5/16, 5/16, 1/16, 5/16, 8/16, 2/16 }, { -5/16, 5/16, 6/16, 5/16, 8/16, 8/16 }, { -4/16, -8/16, 1/16, 4/16, 5/16, 6/16 } } }, on_destruct = function(pos) homedecor.stop_particle_spawner({x=pos.x, y=pos.y+1, z=pos.z}) end }) --Taps local function taps_on_rightclick(pos, node, clicker) local below = minetest.get_node_or_nil({x=pos.x, y=pos.y-1, z=pos.z}) if below and below.name == "homedecor:shower_tray" or below.name == "homedecor:sink" or below.name == "homedecor:kitchen_cabinet_with_sink" then local particledef = { outlet = { x = 0, y = -0.44, z = 0.28 }, velocity_x = { min = -0.1, max = 0.1 }, velocity_y = -0.3, velocity_z = { min = -0.1, max = 0 }, spread = 0 } homedecor.start_particle_spawner(pos, node, particledef, "homedecor_faucet") end end homedecor.register("taps", { description = S("Bathroom taps/faucet"), mesh = "homedecor_bathroom_faucet.obj", tiles = { "homedecor_generic_metal_black.png^[brighten", "homedecor_generic_metal_bright.png", "homedecor_generic_metal_black.png^[colorize:#ffffff:200", "homedecor_generic_metal_bright.png" }, inventory_image = "3dforniture_taps_inv.png", wield_image = "3dforniture_taps_inv.png", selection_box = { type = "fixed", fixed = { -4/16, -7/16, 4/16, 4/16, -4/16, 8/16 }, }, walkable = false, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), on_rightclick = taps_on_rightclick, on_destruct = homedecor.stop_particle_spawner, on_rotate = screwdriver.disallow }) homedecor.register("taps_brass", { description = S("Bathroom taps/faucet (brass)"), mesh = "homedecor_bathroom_faucet.obj", tiles = { "homedecor_generic_metal_brass.png", "homedecor_generic_metal_brass.png", "homedecor_generic_metal_black.png^[colorize:#ffffff:200", "homedecor_generic_metal_brass.png" }, inventory_image = "3dforniture_taps_brass_inv.png", wield_image = "3dforniture_taps_brass_inv.png", selection_box = { type = "fixed", fixed = { -4/16, -7/16, 4/16, 4/16, -4/16, 8/16 }, }, walkable = false, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), on_rightclick = taps_on_rightclick, on_destruct = homedecor.stop_particle_spawner, on_rotate = screwdriver.disallow }) --Shower Tray homedecor.register("shower_tray", { description = S("Shower Tray"), tiles = { "forniture_marble_base_ducha_top.png", "homedecor_marble.png" }, node_box = { type = "fixed", fixed = { { -0.5, -0.5, -0.5, 0.5, -0.45, 0.5 }, { -0.5, -0.45, -0.5, 0.5, -0.4, -0.45 }, { -0.5, -0.45, 0.45, 0.5, -0.4, 0.5 }, { -0.5, -0.45, -0.45, -0.45, -0.4, 0.45 }, { 0.45, -0.45, -0.45, 0.5, -0.4, 0.45 } }, }, selection_box = homedecor.nodebox.slab_y(0.1), groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), on_destruct = function(pos) homedecor.stop_particle_spawner({x=pos.x, y=pos.y+2, z=pos.z}) -- the showerhead homedecor.stop_particle_spawner({x=pos.x, y=pos.y+1, z=pos.z}) -- the taps, if any end }) --Shower Head local sh_cbox = { type = "fixed", fixed = { -0.2, -0.4, -0.05, 0.2, 0.1, 0.5 } } homedecor.register("shower_head", { drawtype = "mesh", mesh = "homedecor_shower_head.obj", tiles = { "homedecor_generic_metal_black.png^[brighten", "homedecor_shower_head.png" }, inventory_image = "homedecor_shower_head_inv.png", description = "Shower Head", groups = {snappy=3}, selection_box = sh_cbox, walkable = false, on_rotate = screwdriver.disallow, on_rightclick = function (pos, node, clicker) local below = minetest.get_node_or_nil({x=pos.x, y=pos.y-2.0, z=pos.z}) if below and below.name == "homedecor:shower_tray" then local particledef = { outlet = { x = 0, y = -0.42, z = 0.1 }, velocity_x = { min = -0.15, max = 0.15 }, velocity_y = -2, velocity_z = { min = -0.3, max = 0.1 }, spread = 0.12 } homedecor.start_particle_spawner(pos, node, particledef, "homedecor_shower") end end, on_destruct = function(pos) homedecor.stop_particle_spawner(pos) end }) local bs_cbox = { type = "fixed", fixed = { -8/16, -8/16, 1/16, 8/16, 8/16, 8/16 } } homedecor.register("bathroom_set", { drawtype = "mesh", mesh = "homedecor_bathroom_set.obj", tiles = { "homedecor_bathroom_set_mirror.png", "homedecor_bathroom_set_tray.png", "homedecor_bathroom_set_toothbrush.png", "homedecor_bathroom_set_cup.png", "homedecor_bathroom_set_toothpaste.png", }, inventory_image = "homedecor_bathroom_set_inv.png", description = "Bathroom sundries set", groups = {snappy=3}, selection_box = bs_cbox, walkable = false, sounds = default.node_sound_glass_defaults(), }) minetest.register_alias("3dforniture:toilet", "homedecor:toilet") minetest.register_alias("3dforniture:toilet_open", "homedecor:toilet_open") minetest.register_alias("3dforniture:sink", "homedecor:sink") minetest.register_alias("3dforniture:taps", "homedecor:taps") minetest.register_alias("3dforniture:shower_tray", "homedecor:shower_tray") minetest.register_alias("3dforniture:shower_head", "homedecor:shower_head") minetest.register_alias("3dforniture:table_lamp", "homedecor:table_lamp_off") minetest.register_alias("toilet", "homedecor:toilet") minetest.register_alias("sink", "homedecor:sink") minetest.register_alias("taps", "homedecor:taps") minetest.register_alias("shower_tray", "homedecor:shower_tray") minetest.register_alias("shower_head", "homedecor:shower_head") minetest.register_alias("table_lamp", "homedecor:table_lamp_off")
return { LrSdkVersion = 4.1, LrToolkitIdentifier = 'com.adobe.lightroom.export.metropublisher', LrPluginName = 'MetroPublisher', LrExportServiceProvider = { title = 'MetroPublisher', file = 'MetroPublisherExportServiceProvider.lua', }, VERSION = { major=1, minor=5, revision=0, build=0, }, }
return { lazy_load = function(load) load "nvim-metals" end, plugins = function(use) use { "scalameta/nvim-metals", opt = true } end, setup = function() local has_lsp, _ = pcall(require, "lspconfig") if not has_lsp then print "Scala dependends on lsp. The functionality is disable" return end local has_telescope, _ = pcall(require, "telescope") if not has_telescope then print "Scala dependends on telescope. The functionality is disable" return end vim.g.metals_use_global_executable = true vim.api.nvim_exec( [[ augroup metals_lsp autocmd! autocmd FileType scala,sbt lua require('metals').initialize_or_attach(require('modules.lang.scala').setup()) autocmd FileType scala,sbt nnoremap <buffer> <localleader>a <cmd>lua require("telescope").extensions.metals.commands()<CR> augroup END ]], false ) return { on_attach = require("modules.lsp").on_attach, capabilities = require("cmp_nvim_lsp").update_capabilities(vim.lsp.protocol.make_client_capabilities()), init_options = { statusBarProvider = "on", compilerOptions = { isCompletionItemResolve = false, }, }, -- tvp = {}, settings = { showImplicitArguments = true, showInferredType = true, superMethodLensesEnabled = true, excludedPackages = { "akka.actor.typed.javadsl", "com.github.swagger.akka.javadsl", "akka.stream.javadsl" }, }, } end, }
local notify = require("blaz.helper.notify") local has_telescope_actions, actions = pcall(require, "telescope.actions") if not has_telescope_actions then notify.warn( "Fuzzy Finder", "nvim-telescope actions not found!", "Skipping configuration for this plugin...", "Some features will not work properly..." ) return end local has_telescope_themes, themes = pcall(require, "telescope.themes") if not has_telescope_themes then notify.warn( "Fuzzy Finder", "nvim-telescope themes not found!", "Skipping configuration for this plugin...", "Some features will not work properly..." ) return end local opts = { defaults = { mappings = { i = { ["<C-n>"] = false, ["<C-p>"] = false, ["<C-j>"] = actions.move_selection_next, ["<C-k>"] = actions.move_selection_previous, }, }, layout_config = { prompt_position = "top", }, prompt_prefix = "🔍 ", selection_caret = "👉 ", entry_prefix = " ", selection_strategy = "reset", sorting_strategy = "descending", scroll_strategy = "cycle", color_devicons = true, }, pickers = { colorscheme = { theme = "cursor", previewer = false, prompt_prefix = "🎨 " }, find_files = { theme = "dropdown", previewer = false, }, git_files = { theme = "dropdown", previewer = false, }, git_branches = { theme = "dropdown", prompt_prefix = " ", }, git_commits = { prompt_prefix = " ", }, buffer = { theme = "dropdown", prompt_prefix = "﬘ ", }, codeaction = { theme = "cursor", }, help_tags = { theme = "ivy", prompt_prefix = "⁉ ", }, planets = { prompt_prefix = "🌎 ", }, }, extensions = { fzy_native = { override_generic_sorter = false, override_file_sorter = true, }, ["ui-select"] = { themes.get_cursor({ -- even more opts }), -- pseudo code / specification for writing custom displays, like the one -- for "codeactions" -- specific_opts = { -- [kind] = { -- make_indexed = function(items) -> indexed_items, width, -- make_displayer = function(widths) -> displayer -- make_display = function(displayer) -> function(e) -- make_ordinal = function(e) -> string -- }, -- -- for example to disable the custom builtin "codeactions" display -- do the following -- codeactions = false, -- } }, }, } return opts
--[[ Copyright (C) 2018 Kubos Corporation 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. ]] -- This codec implements the SLIP or KISS protocol. It's called SLIP when -- used on a serial link and KISS when used on radio but it's the same protocol. -- The purpose is to provide basic message framing as well as stream syncing. local concat = table.concat local gsub = string.gsub local sub = string.sub local find = string.find local function kiss_escape(c) if c == '\xc0' then return '\xdb\xdc' end if c == '\xdb' then return '\xdb\xdd' end return c end local function decode(chunk, index) local frame repeat -- Look for first full kiss frame local a, b = find(chunk, '\xc0\x00', index) if not a then return end local c = find(chunk, '\xc0', b) if not c then return end -- Extract the frame payload frame = sub(chunk, b + 1, c - 1) index = c -- Unescape KISS control characters local valid = true frame = gsub(frame, '\xdb(.)', function (m) if m == '\xdc' then return '\xc0' end if m == '\xdd' then return '\xdb' end -- If an invalid escape is found, abort this frame valid = false return m end) until valid return frame, index end local function encode(frame) return concat { '\xc0\x00', gsub(frame, '.', kiss_escape), '\xc0' } end return { encode = encode, decode = decode, }
return { fadeOut = 1.5, mode = 2, id = "WORLD401A", once = true, fadeType = 2, fadein = 1.5, scripts = { { expression = 2, side = 2, bgName = "bg_port_talantuo", actor = 605020, dir = 1, nameColor = "#a9f548", say = "前方就是塔兰托港了,嗯?这些在港口里飘荡的旗帜......皇家的舰队居然已经先到了么。", bgm = "story-italy", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 8, side = 2, bgName = "bg_port_talantuo", actor = 605020, dir = 1, nameColor = "#a9f548", say = "这还真是...没想到女王陛下已经先到了,接待不周还请恕罪。", flashout = { black = true, dur = 0.5, alpha = { 0, 1 } }, flashin = { delay = 0.5, dur = 0.5, black = true, alpha = { 1, 0 } }, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 205010, side = 2, bgName = "bg_port_talantuo", nameColor = "#ffff4d", dir = 1, say = "没事,没事~陆间海我可是很熟的,就算闭着眼睛都能带着舰队开到塔兰托,不需要有什么多余的担心。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 5, side = 2, bgName = "bg_port_talantuo", actor = 605020, dir = 1, nameColor = "#a9f548", say = "陛下您的心情好像不是很好啊,路上发生什么不愉快的事了么?", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 205010, side = 2, bgName = "bg_port_talantuo", nameColor = "#ffff4d", dir = 1, say = "发生了什么不愉快的事么...........?!你还真问得出来啊!我可是从皇家本岛出发之后,一路先到了圣彼得伯格,然后到了霍尔斯坦,然后到了土伦港,最后才来到你们塔兰托港的!", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 }, action = { { type = "shake", y = 45, delay = 0, dur = 0.15, x = 0, number = 2 } } }, { actor = 605020, side = 2, bgName = "bg_port_talantuo", nameColor = "#a9f548", dir = 1, say = "啊哈哈哈......这还真是趟辛苦的旅程啊~不过重樱舰队也是经历了漫长的旅途才到这里的哟。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 205010, side = 2, bgName = "bg_port_talantuo", nameColor = "#ffff4d", dir = 1, say = "重樱舰队也已经到了么....领头的是......嗯?", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 205010, side = 2, bgName = "bg_port_talantuo", nameColor = "#ffff4d", dir = 1, say = "原来是{namecode:161}的妹妹{namecode:91}啊。本以为机会难得,能见一见你们那艘神秘的总旗舰{namecode:83}呢,或者至少也是{namecode:74}、{namecode:82}之类的。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 205010, side = 2, bgName = "bg_port_talantuo", nameColor = "#ffff4d", dir = 1, say = "签订停火协议这么重要的事,你能做这个决定么?", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307010, side = 2, bgName = "bg_port_talantuo", nameColor = "#a9f548", dir = 1, say = "好像听到一阵吵得要命的噪音,究竟是从哪里发出来的......", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307010, side = 2, bgName = "bg_port_talantuo", nameColor = "#a9f548", dir = 1, say = "啊,原来如此,是皇家的小不点女王啊,没能在第一时间注意到您的存在是我的疏忽,实在抱歉。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307010, side = 2, bgName = "bg_port_talantuo", nameColor = "#a9f548", dir = 1, say = "至于您刚才问出来的问题,也难怪皇家之前被铁血整的那么惨,你们的情报能力真是下降了不少啊。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 205010, side = 2, bgName = "bg_port_talantuo", nameColor = "#ffff4d", dir = 1, say = "你......!", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 }, action = { { type = "shake", y = 45, delay = 0, dur = 0.15, x = 0, number = 2 } } }, { expression = 1, side = 2, bgName = "bg_port_talantuo", actor = 205050, dir = 1, nameColor = "#ffff4d", say = "感谢{namecode:91}阁下指出我们的不足之处,我们一定会着手进行改进,争取让类似白鹰获悉AF详情那样精彩的情报战再发生几次。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307010, side = 2, bgName = "bg_port_talantuo", nameColor = "#a9f548", dir = 1, say = "呵呵............", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 5, side = 2, bgName = "bg_port_talantuo", actor = 605020, dir = 1, nameColor = "#a9f548", say = "唉...你们都冷静一点~这次大家不是都抱有和平的意愿才会齐聚塔兰托的嘛,就不要像这样针锋相对了。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 8, side = 2, bgName = "bg_port_talantuo", actor = 605020, dir = 1, blackBg = true, nameColor = "#a9f548", say = "腓特烈大帝的也在赶来这里的路上,在那之前请各位放宽身心,尽情享受一下撒丁风情吧~", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } } } }
--[[ Copyright 2014 Sergej Nisin 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 LevelManager = {} local this = LevelManager function LevelManager.load() local contents if love.filesystem.isFile("levels.lua") then contents = love.filesystem.read("levels.lua") else contents = love.filesystem.read("levelsd.lua") end this.worlds = Tserial.unpack(contents) end function LevelManager.getWorldProgress(world, custom) if custom == "custom" then world = "cus_"..world end if custom == "myworld" or custom == "playmyworld" then return 0 end local worldprog = 0 if SaveManager.save.worlds and SaveManager.save.worlds[world] then for i, v in pairs(SaveManager.save.worlds[world]) do if v then worldprog = worldprog + 1 end end else worldprog = 0 end return worldprog end function LevelManager.canPlayLevel(world, level, custom) if custom == "custom" then world = "cus_"..world end if custom == "myworld" or custom == "playmyworld" then return true end if SaveManager.save.worlds and SaveManager.save.worlds[world] and SaveManager.save.worlds[world][level] then return true end local notmade = 3 for i = 1,level-1 do if (not SaveManager.save.worlds) or (not SaveManager.save.worlds[world]) or (not SaveManager.save.worlds[world][i]) then notmade = notmade-1 end end if notmade > 0 then return true end return false end function LevelManager.setLevelSuccessed(world, level, custom) print(world, level, custom) if custom == "custom" then world = "cus_"..world end if custom == "myworld" or custom == "playmyworld" then return end if not SaveManager.save.worlds then SaveManager.save.worlds = {} end if not SaveManager.save.worlds[world] then SaveManager.save.worlds[world] = {} end SaveManager.save.worlds[world][level] = true SaveManager.saveGame() end function LevelManager.isLevelFinished(world, level, custom) if custom == "custom" then world = "cus_"..world end if custom == "myworld" or custom == "playmyworld" then return false end if SaveManager.save.worlds and SaveManager.save.worlds[world] and SaveManager.save.worlds[world][level] then return true else return false end end function LevelManager.isWorldFinished(world) local worldprog = LevelManager.getWorldProgress(world) local numlevels = LevelManager.getNumLevels(world) if worldprog >= numlevels then return true else return false end end function LevelManager.getWorld(world) return this.worlds[world] end function LevelManager.getNumLevels(world) return #this.worlds[world].levels end return LevelManager
-- program to travel in a line for a specified # of blocks in the direction it's facing print("\nHow far shall I travel?") dist = tonumber(read()) print("Should I make a walkable tunnel? [y/N]") local temp = read() walkable = false if string.lower(temp) == "y" or string.lower(temp) == "yes" then walkable = true end turtle.select(1) distGone = 0 while distGone < dist do turtle.refuel() if turtle.detect() then turtle.dig() end turtle.forward() if walkable and turtle.detectUp() then turtle.digUp() end if distGone % 10 then print("Traveled " .. distGone .. " blocks.") distGone = distGone + 1 end print("Finished traveling " .. dist .. " blocks.")
----------------------------------- -- Ability: Bestial Loyalty -- Calls a beast to fight by your side without consuming bait -- Obtained: Beastmaster Level 23 -- Recast Time: 20:00 -- Duration: Dependent on jug pet used. ----------------------------------- require("scripts/globals/common") require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------- function onAbilityCheck(player, target, ability) if player:getPet() ~= nil then return tpz.msg.basic.ALREADY_HAS_A_PET,0 elseif not player:hasValidJugPetItem() then return tpz.msg.basic.NO_JUG_PET_ITEM,0 elseif not player:canUseMisc(tpz.zoneMisc.PET) then return tpz.msg.basic.CANT_BE_USED_IN_AREA,0 else return 0,0 end end function onUseAbility(player, target, ability) tpz.pet.spawnPet(player, player:getWeaponSubSkillType(tpz.slot.AMMO)) end
--[[ /////// ////////////////// /////// PROJECT: MTA iLife - German Fun Reallife Gamemode /////// VERSION: 1.7.2 /////// DEVELOPERS: See DEVELOPERS.md in the top folder /////// LICENSE: See LICENSE.md in the top folder /////// ///////////////// ]] -- ####################################### -- ## Project: iLife ## -- ## For MTA: San Andreas ## -- ## Name: cArtifactManager.lua ## -- ## Author: Noneatme(Gunvarrel) ## -- ## Version: 1.0 ## -- ## License: See top Folder ## -- ## Date: March 2015 ## -- ####################################### cArtifactManager = inherit(cSingleton); --[[ ]] -- /////////////////////////////// -- //getRandomArtifactPosition//// -- ///// Returns: void ////// -- /////////////////////////////// function cArtifactManager:getRandomArtifactPosition() local randX, randY = math.random(self.m_iMinDistanceX, self.m_iMaxDistanceX), math.random(self.m_iMinDistanceY, self.m_iMaxDistanceY) for index, art in pairs(self.m_tblArtifacts) do local x, y = art:getPosition() local dist = getDistanceBetweenPoints2D(x, y, randX, randY) if(dist < self.m_iMinArtifactDistance) then return self:getRandomArtifactPosition(); end end return randX, randY end -- /////////////////////////////// -- ///// generateArtifact ////// -- ///// Returns: void ////// -- /////////////////////////////// function cArtifactManager:generateArtifact() local x, y = self:getRandomArtifactPosition(); self.m_tblArtifacts[self.m_iCurrentArtifact] = cArtifact:new(self.m_iCurrentArtifact, x, y) self.m_iCurrentArtifact = self.m_iCurrentArtifact+1; end -- /////////////////////////////// -- ///// getArtifactsNearPlayer////// -- ///// Returns: void ////// -- /////////////////////////////// function cArtifactManager:getArtifactsNearPlayer(uPlayer, iDistance) local x, y, z = uPlayer:getPosition() local arts = {} for _, artifact in pairs(self.m_tblArtifacts) do if(artifact) and not(artifact.m_bDone) then local x2, y2 = artifact:getPosition() if(getDistanceBetweenPoints2D(x, y, x2, y2) <= iDistance) then arts[artifact] = getDistanceBetweenPoints2D(x, y, x2, y2) end end end return arts; end -- /////////////////////////////// -- ///// doEntdeckeArtifact //// -- ///// Returns: void ////// -- /////////////////////////////// function cArtifactManager:doEntdeckeArtifact(uPlayer, iID) local artifact = self.m_tblArtifacts[iID]; if not(artifact.m_bDone) then artifact:generateArtifactCrate(); self:generateArtifact(); end end -- /////////////////////////////// -- ///// scanForPlayerArtifact//// -- ///// Returns: void ////// -- /////////////////////////////// function cArtifactManager:scanForPlayerArtifacts(uPlayer, iID) local distance = 10; if(iID == 302) then distance = 25; elseif(iID == 303) then distance = 50; end distance = distance*10 local arts = self:getArtifactsNearPlayer(uPlayer, distance) triggerClientEvent(uPlayer, "onClientPlayerArtifactScannerResultsGet", uPlayer, arts) for artifact, distance in pairs(arts) do if(artifact.m_iZ) then if(distance < self.m_iMinDistanceToDiscover) then self:doEntdeckeArtifact(uPlayer, artifact.m_iID) end end end uPlayer.m_bArtifactScanned = true; end -- /////////////////////////////// -- ///// updateZPosition ////// -- ///// Returns: void ////// -- /////////////////////////////// function cArtifactManager:updateZPosition(uPlayer, iArtifact, iZ) if(self.m_tblArtifacts[iArtifact]) and (uPlayer.m_bArtifactScanned) then self.m_tblArtifacts[iArtifact].m_iZ = iZ or false; if(self.m_tblArtifacts[iArtifact].m_iZ) then local x, y = self.m_tblArtifacts[iArtifact]:getPosition() local x2, y2 = uPlayer:getPosition() if(getDistanceBetweenPoints2D(x, y, x2, y2) <= self.m_iMinDistanceToDiscover) then self:doEntdeckeArtifact(uPlayer, iArtifact) end end end end -- /////////////////////////////// -- ///// generateNewArtifacts///// -- ///// Returns: void ////// -- /////////////////////////////// function cArtifactManager:generateNewArtifacts(iAtOnce) if(tonumber(iAtOnce)) then self.m_iMaxArtifactsAtOnce = iAtOnce:tonumber(); end for id, art in pairs(self.m_tblArtifacts) do if(art) then delete(art) end art = nil end self.m_tblArtifacts = {} local sTick = getTickCount() for i = 1, self.m_iMaxArtifactsAtOnce, 1 do self:generateArtifact() end outputDebugString("Generated "..self.m_iMaxArtifactsAtOnce.." Artifacts in "..((getTickCount()-sTick)/1000).."s") end -- /////////////////////////////// -- ///// Constructor ////// -- ///// Returns: void ////// -- /////////////////////////////// function cArtifactManager:constructor(...) -- Klassenvariablen -- addEvent("onArtifactZPositionUpdate", true) self.m_iMaxArtifactsAtOnce = 500; self.m_iMinArtifactDistance = 50; self.m_iCurrentArtifact = 1 self.m_iMinDistanceToDiscover = 15; self.m_iMinDistanceX, self.m_iMinDistanceY = -3000, -3000 self.m_iMaxDistanceX, self.m_iMaxDistanceY = 3000, 3000 self.m_tblArtifacts = {} -- Funktionen -- self:generateNewArtifacts(); self.m_funcOnZPositionReceive = function(...) self:updateZPosition(client, ...) end -- Events -- addEventHandler("onArtifactZPositionUpdate", getRootElement(), self.m_funcOnZPositionReceive) end -- EVENT HANDLER --
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include('shared.lua') local MODEL = Model( "models/dav0r/balloon/balloon.mdl" ) /*--------------------------------------------------------- Name: Initialize ---------------------------------------------------------*/ function ENT:Initialize() // Use the helibomb model just for the shadow (because it's about the same size) self.Entity:SetModel( MODEL ) self.Entity:PhysicsInit( SOLID_VPHYSICS ) // Set up our physics object here local phys = self.Entity:GetPhysicsObject() if (phys:IsValid()) then phys:SetMass( 100 ) phys:Wake() phys:EnableGravity( false ) end self:SetForce( 1 ) self.Entity:StartMotionController() self.DieTime = CurTime() + 60 * 5; end /*--------------------------------------------------------- Name: SetForce ---------------------------------------------------------*/ function ENT:SetForce( force ) self.Force = force * 5000 end /*--------------------------------------------------------- Name: OnTakeDamage ---------------------------------------------------------*/ function ENT:OnTakeDamage( dmginfo ) if (self.Entity:GetTable().Indestructible) then return end local r, g, b = self.Entity:GetColor() local effectdata = EffectData() effectdata:SetOrigin( self.Entity:GetPos() ) effectdata:SetStart( Vector( r, g, b ) ) util.Effect( "perp_balloon_pop", effectdata ) self.Entity:Remove() end /*--------------------------------------------------------- Name: Simulate ---------------------------------------------------------*/ function ENT:PhysicsSimulate( phys, deltatime ) local Force = self.Force; if self.DieTime - 60 < CurTime() then Perc = 1 - (CurTime() / self.DieTime); Force = (Force * Perc) - 100; end local vLinear = Vector( 0, 0, Force ) * deltatime local vAngular = Vector( 0, 0, 0 ) return vAngular, vLinear, SIM_GLOBAL_FORCE end /*--------------------------------------------------------- Name: OnRestore ---------------------------------------------------------*/ function ENT:OnRestore( ) self.Force = self.Entity:GetNetworkedFloat( 0 ) end function ENT:Think ( ) if self.DieTime < CurTime() then self:TakeDamage(100); end end
-- Cuppa -- ----------- local HOME = os.getenv("HOME") local cuppaMenu = hs.menubar.new() cuppaMenu:setTitle("🍵") cuppaMenu:setTooltip("Cuppa tea timer. ⌘+click to cancel the timer") local cuppaTimer = nil local cuppaTimerTimer = nil -- stolen from Cuppa.app local pourSound = hs.sound.getByFile(HOME .. "/.hammerspoon/pour.aiff") local spoonSound = hs.sound.getByFile(HOME .. "/.hammerspoon/spoon.aiff") -- for notification center local cuppaImage = hs.image.imageFromPath(HOME .. "/.hammerspoon/cuppa.jpg") -- set the title of the menubar local function cuppaSetTitle(timeLeft) if timeLeft ~= nil then cuppaMenu:setTitle("🍵 " .. timeLeft) else cuppaMenu:setTitle("🍵") end end -- callback called when the cuppa timer reaches the end local function cuppaTimerEnd() hs.alert.show("🍵 is ready!") hs.notify.new({title="Cuppa", informativeText="Your tea cup 🍵 is ready!"}):setIdImage(cuppaImage):send() cuppaSetTitle() spoonSound:play() end -- callback called to update the countdown timer on the menubar local function cuppaTimerUpdate() if cuppaTimer ~= nil then local secondsLeft = cuppaTimer:nextTrigger() if secondsLeft < 0 then secondsLeft = 0 end local timeLeft = os.date("!%X", math.floor(secondsLeft)) if secondsLeft < (60 * 60) then timeLeft = string.sub(timeLeft, 4) end cuppaSetTitle(timeLeft) end end -- callback called by the supervisor timer to check on the cuppa timer local function cuppaTimerPing() if cuppaTimer == nil or not cuppaTimer:running() then return true end return false end -- cancel the current cuppa timer local function cuppaTimerCancel() if cuppaTimer ~= nil then cuppaTimer:stop() end if cuppaTimerTimer ~= nil then cuppaTimerTimer:stop() end hs.alert.show("Cuppa timer canceled") cuppaSetTitle() end -- prompt the user for a cuppa timer local function cuppaAskForTimer(mod) local script = [[ display dialog "How many minutes?" default answer "3" set answer to text returned of result return answer ]] if mod["cmd"] then cuppaTimerCancel(); return; end local success, out, _ = hs.osascript.applescript(script) if success then local minutes = tonumber(out) if minutes ~= nil and minutes > 0 then cuppaTimer = hs.timer.doAfter(minutes * 60, cuppaTimerEnd) cuppaTimerTimer = hs.timer.doUntil(cuppaTimerPing, cuppaTimerUpdate, 1) cuppaTimerUpdate() pourSound:play() end end end cuppaMenu:setClickCallback(cuppaAskForTimer)
local OOP = require("oop"); local bzUtils = require("bz_core"); local bzRoutine = require("bz_routine"); local misc = require("misc"); local KeyListener = misc.KeyListener; local Decorate = OOP.Decorate; local Implements = OOP.Implements; local KeyListener = misc.KeyListener; local Class = OOP.Class; local Routine = bzRoutine.Routine; local spectateRoutine = Decorate( --We need to listne to players Implements(KeyListener), Routine({ name = "spectateRoutine", delay = 0.0 }), Class("spectateRoutine",{ constructor = function() self.sp_targets = nil; self.alive = true; self.cam = false; end, methods = { onInit = function(...) local ts, key = ...; self.sp_targets = ts; self.key_list = {}; self.key_i = 1; for i, v in pairs(self.sp_targets) do table.insert(self.key_list,i); if(i == key) then self.key_i = #self.key_list; end end if(#self.key_list > 0) then print("Spectating started"); else self:stop(); end end, watchNext = function() if(#self.key_list <= 0) then return false; end self.key_i = (self.key_i%#self.key_list) + 1; return true; end, update = function(dtime) if(self.cam) then if(CameraCancelled()) then self:stop(); return; end local h = self.sp_targets[self.key_list[self.key_i]]; if(IsValid(h)) then --TODO: add smoothing CameraObject(h,0,1000,-3000,h); else self.sp_targets[self.key_list[self.key_i]] = nil; table.remove(self.key_list,key_i); if not self:watchNext() then self:stop(); end end elseif(IsValid(GetPlayerHandle())) then self.cam = CameraReady(); end end, isAlive = function() return self.alive; end, save = function() end, load = function() end, stop = function() print("STOP!"); self.alive = false; end, removeKey = function(key) if(self.sp_targets[key] ~= nil) then local c_key = self.key_list[self.key_i]; for i, v in ipairs(self.key_list) do if(key == v) then table.remove(i); break; end end self.sp_targets[key] = nil; if(key == c_key) then self:watchNext(); else self.key_i = math.min(1,self.key_i-1); end if(#self.key_list <= 0) then self:stop(); end end end, onDestroy = function() print("Spectating stoped"); CameraFinish(); end, onGameKey = function(key) if(key == "Tab") then self:watchNext(); end end } }) ); bzRoutine.routineManager:registerClass(spectateRoutine);
local _, Addon = ...; local EmptyListMixin = {}; --[[=========================================================================== | Shows or hides the empty text ========================================================================--]] function EmptyListMixin:ShowEmptyText(show) local empty = self.EmptyText; if (empty) then if (show) then empty:Show() else empty:Hide() end end end --[[=========================================================================== | Modifies the empty text ========================================================================--]] function EmptyListMixin:SetEmptyText(text) if (self.EmptyText) then self.EmptyText:SetText(text or "") end end --[[=========================================================================== | Retrives the empty text ========================================================================--]] function EmptyListMixin:GetEmptyText() if (self.EmptyText) then return self.EmptyText:GetText() or "" end return nil end Addon.Controls = Addon.Controls or {} Addon.Controls.EmptyListMixin = EmptyListMixin;
--[[ Minecart ======== Copyright (C) 2019-2020 Joachim Stolberg MIT See license.txt for more information ]]-- -- for lazy programmers local M = minetest.get_meta local RegisteredInventories = {} -- Take the given number of items from the inv. -- Returns nil if ItemList is empty. function minecart.inv_take_items(inv, listname, num) if inv:is_empty(listname) then return nil end local size = inv:get_size(listname) for idx = 1, size do local items = inv:get_stack(listname, idx) if items:get_count() > 0 then local taken = items:take_item(num) inv:set_stack(listname, idx, items) return taken end end return nil end function minecart.take_items(pos, param2, num) local npos, node if param2 then npos, node = minecart.get_next_node(pos, (param2 + 2) % 4) else npos, node = pos, minetest.get_node(pos) end local def = RegisteredInventories[node.name] local owner = M(pos):get_string("owner") local inv = minetest.get_inventory({type="node", pos=npos}) if def and inv and def.take_listname and (not def.allow_take or def.allow_take(npos, nil, owner)) then return minecart.inv_take_items(inv, def.take_listname, num) elseif def and def.take_item then return def.take_item(npos, num, owner) else local ndef = minetest.registered_nodes[node.name] if ndef and ndef.minecart_hopper_takeitem then return ndef.minecart_hopper_takeitem(npos, num) end end end function minecart.put_items(pos, param2, stack) local npos, node = minecart.get_next_node(pos, param2) local def = RegisteredInventories[node.name] local owner = M(pos):get_string("owner") local inv = minetest.get_inventory({type="node", pos=npos}) if def and inv and def.put_listname and (not def.allow_put or def.allow_put(npos, stack, owner)) then local leftover = inv:add_item(def.put_listname, stack) if leftover:get_count() > 0 then return leftover end elseif def and def.put_item then return def.put_item(npos, stack, owner) elseif minecart.is_air_like(node.name) or minecart.is_nodecart_available(npos) then minetest.add_item(npos, stack) else local ndef = minetest.registered_nodes[node.name] if ndef and ndef.minecart_hopper_additem then local leftover = ndef.minecart_hopper_additem(npos, stack) if leftover:get_count() > 0 then return leftover end else return stack end end end function minecart.untake_items(pos, param2, stack) local npos, node if param2 then npos, node = minecart.get_next_node(pos, (param2 + 2) % 4) else npos, node = pos, minetest.get_node(pos) end local def = RegisteredInventories[node.name] local inv = minetest.get_inventory({type="node", pos=npos}) if def and inv and def.put_listname then return inv:add_item(def.put_listname, stack) elseif def and def.untake_item then return def.untake_item(npos, stack) else local ndef = minetest.registered_nodes[node.name] if ndef and ndef.minecart_hopper_untakeitem then return ndef.minecart_hopper_untakeitem(npos, stack) end end end -- Register inventory node for hopper access -- (for example, see below) function minecart.register_inventory(node_names, def) for _, name in ipairs(node_names) do RegisteredInventories[name] = { allow_put = def.put and def.put.allow_inventory_put, put_listname = def.put and def.put.listname, allow_take = def.take and def.take.allow_inventory_take, take_listname = def.take and def.take.listname, put_item = def.put and def.put.put_item, take_item = def.take and def.take.take_item, untake_item = def.take and def.take.untake_item, } end end -- Allow the hopper the access to itself minecart.register_inventory({"minecart:hopper"}, { put = { allow_inventory_put = function(pos, stack, player_name) local owner = M(pos):get_string("owner") return owner == player_name end, listname = "main", }, take = { allow_inventory_take = function(pos, stack, player_name) local owner = M(pos):get_string("owner") return owner == player_name end, listname = "main", }, })
--[[ /////// ////////////////// /////// PROJECT: MTA iLife - German Fun Reallife Gamemode /////// VERSION: 1.7.2 /////// DEVELOPERS: See DEVELOPERS.md in the top folder /////// LICENSE: See LICENSE.md in the top folder /////// ///////////////// ]] local QuestID = 11 local Quest = Quests[QuestID] Quest.Texts = { ["Accepted"] = "Finde drei Gramm Kokain und gebe es dem Obdachlosen!", ["Finished"] = "Kehre zum Obdachlosen zur\\ueck!" } for k,v in ipairs(Quest:getPeds(2)) do addEventHandler("onElementClicked", v, function(button, state, thePlayer) if (button == "left") and (state == "down") then if (getDistanceBetweenElements3D(v,thePlayer) < 5) then local QuestState = thePlayer:isQuestActive(Quest) if (QuestState and not(QuestState == "Finished")) then if (thePlayer:getInventory():removeItem(Items[14], 3)) then thePlayer:refreshInventory() Quest:playerFinish(thePlayer) else thePlayer:showInfoBox("error", "Du besitzt zu wenig Kokain!") end end end end end ) end Quest.playerReachedRequirements = function(thePlayer, bOutput) if ( thePlayer:isQuestFinished(Quests[8]) ) then return true end return false end Quest.getTaskPosition = function() --Should return int, dim, x, y, z return 0, 0, 1487.4013671875, -1699.23046875, 14.046875 end Quest.onAccept = function(thePlayer) outputChatBox("Obdachloser: Mach schnell! Ich zitter schon!", thePlayer, 255,255,255) return true end Quest.onResume = function(thePlayer) return true end Quest.onProgress = function(thePlayer) return true end Quest.onFinish = function(thePlayer) outputChatBox("Obdachloser: Das zieh ich mir jetzt erstmal rein!", thePlayer, 255,255,255) return true end Quest.onAbort = function(thePlayer) local QuestState = thePlayer:isQuestActive(Quest) if (QuestState and (QuestState == "Finished")) then thePlayer:getInventory():addItem(Items[14], 3) thePlayer:refreshInventory() end return true end --outputDebugString("Loaded Questscript: server/Classes/Quest/Scripts/"..tostring(QuestID)..".lua")
object_tangible_loot_loot_schematic_armor_appearance_neutral_clone_bicep_r = object_tangible_loot_loot_schematic_shared_armor_appearance_neutral_clone_bicep_r:new { } ObjectTemplates:addTemplate(object_tangible_loot_loot_schematic_armor_appearance_neutral_clone_bicep_r, "object/tangible/loot/loot_schematic/armor_appearance_neutral_clone_bicep_r.iff")