content stringlengths 5 1.05M |
|---|
name = "Leveling: Route 22 (near the Pewter city)"
author = "Liquid"
description = [[This script will train the first pokémon of your team.
It will also try to capture shinies by throwing pokéballs.
Start anywhere between Route 1 or Pewter city.]]
local team = require "teamlib"
local maxLv = 14
function onStart()
return team.onStart(maxLv)
end
function onPathAction()
while not isTeamSortedByLevelAscending() and getOption(4) do
return sortTeamByLevelAscending()
end
if team.isTrainingOver(maxLv) and not team.isSearching() then
return logout("Complete training! Stop the bot.")
end
if team.useLeftovers() then
return
end
if getUsablePokemonCount() > 1
and (getPokemonLevel(team.getLowestIndexOfUsablePokemon()) < maxLv
or team.isSearching())
then
if getMapName() == "Pokecenter Viridian" then
moveToCell(9,22)
elseif getMapName() == "Viridian City" then
moveToCell(0,48)
elseif getMapName() == "Route 22" then
moveToGrass()
elseif getMapName() == "Prof. Antibans Classroom" then
return team.antibanclassroom()
end
else
if getMapName() == "Route 22" then
moveToCell(60,11)
elseif getMapName() == "Viridian City" then
moveToCell(44,43)
elseif getMapName() == "Pokecenter Viridian" then
usePokecenter()
elseif getMapName() == "Prof. Antibans Classroom" then
return team.antibanclassroom()
end
end
end
function onBattleAction()
return team.onBattleFighting()
end
function onStop()
return team.onStop()
end
function onBattleMessage(message)
return team.onBattleMessage(message)
end
function onDialogMessage(message)
return team.onAntibanDialogMessage(message)
end
function onSystemMessage(message)
return team.onSystemMessage(message)
end |
local helpers = require('tests.helpers')
local child = helpers.new_child_neovim()
local eq = assert.are.same
-- Helpers with child processes
--stylua: ignore start
local load_module = function(config) child.mini_load('comment', config) end
local unload_module = function() child.mini_unload('comment') end
local reload_module = function(config) unload_module(); load_module(config) end
local set_cursor = function(...) return child.set_cursor(...) end
local get_cursor = function(...) return child.get_cursor(...) end
local set_lines = function(...) return child.set_lines(...) end
local get_lines = function(...) return child.get_lines(...) end
local type_keys = function(...) return child.type_keys(...) end
--stylua: ignore end
-- Data =======================================================================
-- Reference text
-- aa
-- aa
-- aa
--
-- aa
-- aa
-- aa
local example_lines = { 'aa', ' aa', ' aa', '', ' aa', ' aa', 'aa' }
-- Unit tests =================================================================
describe('MiniComment.setup()', function()
before_each(function()
child.setup()
load_module()
end)
it('creates side effects', function()
-- Global variable
assert.True(child.lua_get('_G.MiniComment ~= nil'))
end)
it('creates `config` field', function()
assert.True(child.lua_get([[type(_G.MiniComment.config) == 'table']]))
-- Check default values
local assert_config = function(field, value)
eq(child.lua_get('MiniComment.config.' .. field), value)
end
assert_config('mappings.comment', 'gc')
assert_config('mappings.comment_line', 'gcc')
assert_config('mappings.textobject', 'gc')
end)
it('respects `config` argument', function()
unload_module()
load_module({ mappings = { comment = 'gC' } })
assert.True(child.lua_get([[MiniComment.config.mappings.comment == 'gC']]))
end)
it('validates `config` argument', function()
unload_module()
local assert_config_error = function(config, name, target_type)
assert.error_matches(function()
load_module(config)
end, vim.pesc(name) .. '.*' .. vim.pesc(target_type))
end
assert_config_error('a', 'config', 'table')
assert_config_error({ mappings = 'a' }, 'mappings', 'table')
assert_config_error({ mappings = { comment = 1 } }, 'mappings.comment', 'string')
assert_config_error({ mappings = { comment_line = 1 } }, 'mappings.comment_line', 'string')
assert_config_error({ mappings = { textobject = 1 } }, 'mappings.textobject', 'string')
end)
it('properly handles `config.mappings`', function()
local has_map = function(lhs)
return child.cmd_capture('omap ' .. lhs):find('MiniComment') ~= nil
end
assert.True(has_map('gc'))
unload_module()
child.api.nvim_del_keymap('o', 'gc')
-- Supplying empty string should mean "don't create keymap"
load_module({ mappings = { textobject = '' } })
assert.False(has_map('gc'))
end)
end)
describe('MiniComment.toggle_lines()', function()
child.setup()
load_module()
before_each(function()
set_lines(example_lines)
child.api.nvim_buf_set_option(0, 'commentstring', '# %s')
end)
it('works', function()
child.lua('MiniComment.toggle_lines(3, 5)')
eq(get_lines(2, 5), { ' # aa', ' #', ' # aa' })
child.lua('MiniComment.toggle_lines(3, 5)')
eq(get_lines(2, 5), { ' aa', '', ' aa' })
end)
it('validates arguments', function()
set_lines({ 'aa', 'aa', 'aa' })
assert.error_matches(function()
child.lua('MiniComment.toggle_lines(-1, 1)')
end, 'line_start.*1')
assert.error_matches(function()
child.lua('MiniComment.toggle_lines(100, 101)')
end, 'line_start.*3')
assert.error_matches(function()
child.lua('MiniComment.toggle_lines(1, -1)')
end, 'line_end.*1')
assert.error_matches(function()
child.lua('MiniComment.toggle_lines(1, 100)')
end, 'line_end.*3')
assert.error_matches(function()
child.lua('MiniComment.toggle_lines(2, 1)')
end, 'line_start.*less than or equal.*line_end')
end)
it("works with different 'commentstring' options", function()
-- Two-sided
set_lines(example_lines)
child.api.nvim_buf_set_option(0, 'commentstring', '/* %s */')
child.lua('MiniComment.toggle_lines(3, 5)')
eq(get_lines(2, 5), { ' /* aa */', ' /**/', ' /* aa */' })
child.lua('MiniComment.toggle_lines(3, 5)')
eq(get_lines(2, 5), { ' aa', '', ' aa' })
-- Right-sided
set_lines(example_lines)
child.api.nvim_buf_set_option(0, 'commentstring', '%s #')
child.lua('MiniComment.toggle_lines(3, 5)')
eq(get_lines(2, 5), { ' aa #', ' #', ' aa #' })
child.lua('MiniComment.toggle_lines(3, 5)')
eq(get_lines(2, 5), { ' aa', '', ' aa' })
-- Latex (#25)
set_lines(example_lines)
child.api.nvim_buf_set_option(0, 'commentstring', '%%s')
child.lua('MiniComment.toggle_lines(3, 5)')
eq(get_lines(2, 5), { ' % aa', ' %', ' % aa' })
child.lua('MiniComment.toggle_lines(3, 5)')
eq(get_lines(2, 5), { ' aa', '', ' aa' })
end)
it('correctly computes indent', function()
child.lua('MiniComment.toggle_lines(2, 4)')
eq(get_lines(1, 4), { ' # aa', ' # aa', ' #' })
set_lines(example_lines)
child.lua('MiniComment.toggle_lines(4, 4)')
eq(get_lines(3, 4), { '#' })
end)
it('correctly detects comment/uncomment', function()
local lines = { '', 'aa', '# aa', '# aa', 'aa', '' }
-- It should uncomment only if all lines are comments
set_lines(lines)
child.lua('MiniComment.toggle_lines(3, 4)')
eq(get_lines(), { '', 'aa', 'aa', 'aa', 'aa', '' })
set_lines(lines)
child.lua('MiniComment.toggle_lines(2, 4)')
eq(get_lines(), { '', '# aa', '# # aa', '# # aa', 'aa', '' })
set_lines(lines)
child.lua('MiniComment.toggle_lines(3, 5)')
eq(get_lines(), { '', 'aa', '# # aa', '# # aa', '# aa', '' })
set_lines(lines)
child.lua('MiniComment.toggle_lines(1, 6)')
eq(get_lines(), { '#', '# aa', '# # aa', '# # aa', '# aa', '#' })
end)
it('uncomments on inconsistent indent levels', function()
set_lines({ '# aa', ' # aa', ' # aa' })
child.lua('MiniComment.toggle_lines(1, 3)')
eq(get_lines(), { 'aa', ' aa', ' aa' })
end)
it('respects tabs (#20)', function()
child.api.nvim_buf_set_option(0, 'expandtab', false)
set_lines({ '\t\taa', '\t\taa' })
child.lua('MiniComment.toggle_lines(1, 2)')
eq(get_lines(), { '\t\t# aa', '\t\t# aa' })
child.lua('MiniComment.toggle_lines(1, 2)')
eq(get_lines(), { '\t\taa', '\t\taa' })
end)
it('adds spaces inside non-empty lines', function()
-- Two-sided
set_lines(example_lines)
child.api.nvim_buf_set_option(0, 'commentstring', '/*%s*/')
child.lua('MiniComment.toggle_lines(3, 5)')
eq(get_lines(2, 5), { ' /* aa */', ' /**/', ' /* aa */' })
-- Right-sided
set_lines(example_lines)
child.api.nvim_buf_set_option(0, 'commentstring', '%s#')
child.lua('MiniComment.toggle_lines(3, 5)')
eq(get_lines(2, 5), { ' aa #', ' #', ' aa #' })
end)
it('removes trailing whitespace', function()
set_lines({ 'aa', 'aa ', ' ' })
child.lua('MiniComment.toggle_lines(1, 3)')
child.lua('MiniComment.toggle_lines(1, 3)')
eq(get_lines(), { 'aa', 'aa', '' })
end)
end)
-- Functional tests ===========================================================
describe('Commenting', function()
child.setup()
load_module()
before_each(function()
set_lines(example_lines)
child.api.nvim_buf_set_option(0, 'commentstring', '# %s')
end)
it('works in Normal mode', function()
set_cursor(2, 2)
type_keys({ 'g', 'c', 'a', 'p' })
eq(get_lines(), { '# aa', '# aa', '# aa', '#', ' aa', ' aa', 'aa' })
-- Cursor moves to start line
eq(get_cursor(), { 1, 0 })
-- Supports `v:count`
set_lines(example_lines)
set_cursor(2, 0)
type_keys({ '2', 'g', 'c', 'a', 'p' })
eq(get_lines(), { '# aa', '# aa', '# aa', '#', '# aa', '# aa', '# aa' })
end)
it('works in Visual mode', function()
set_cursor(2, 2)
type_keys({ 'v', 'a', 'p', 'g', 'c' })
eq(get_lines(), { '# aa', '# aa', '# aa', '#', ' aa', ' aa', 'aa' })
-- Cursor moves to start line
eq(get_cursor(), { 1, 0 })
end)
it('works with different mapping', function()
reload_module({ mappings = { comment = 'gC' } })
set_cursor(2, 2)
type_keys({ 'g', 'C', 'a', 'p' })
eq(get_lines(), { '# aa', '# aa', '# aa', '#', ' aa', ' aa', 'aa' })
end)
it("respects 'commentstring'", function()
child.api.nvim_buf_set_option(0, 'commentstring', '/*%s*/')
set_cursor(2, 2)
type_keys({ 'g', 'c', 'a', 'p' })
eq(get_lines(), { '/* aa */', '/* aa */', '/* aa */', '/**/', ' aa', ' aa', 'aa' })
end)
it('allows dot-repeat', function()
local doubly_commented = { '# # aa', '# # aa', '# # aa', '# #', '# aa', '# aa', '# aa' }
set_lines(example_lines)
set_cursor(2, 2)
type_keys({ 'g', 'c', 'a', 'p' })
type_keys('.')
eq(get_lines(), doubly_commented)
-- Not immediate dot-repeat
set_lines(example_lines)
set_cursor(2, 2)
type_keys({ 'g', 'c', 'a', 'p' })
set_cursor(7, 0)
type_keys('.')
eq(get_lines(), doubly_commented)
end)
it('preserves marks', function()
set_cursor(2, 0)
-- Set '`<' and '`>' marks
type_keys('VV')
type_keys({ 'g', 'c', 'i', 'p' })
child.assert_visual_marks(2, 2)
end)
end)
describe('Commenting current line', function()
child.setup()
load_module()
before_each(function()
set_lines(example_lines)
child.api.nvim_buf_set_option(0, 'commentstring', '# %s')
end)
it('works', function()
set_lines(example_lines)
set_cursor(1, 1)
type_keys({ 'g', 'c', 'c' })
eq(get_lines(0, 2), { '# aa', ' aa' })
-- Works on empty line
set_lines(example_lines)
set_cursor(4, 0)
type_keys({ 'g', 'c', 'c' })
eq(get_lines(2, 5), { ' aa', '#', ' aa' })
-- Supports `v:count`
set_lines(example_lines)
set_cursor(2, 0)
type_keys({ '2', 'g', 'c', 'c' })
eq(get_lines(0, 3), { 'aa', ' # aa', ' # aa' })
end)
it('works with different mapping', function()
reload_module({ mappings = { comment_line = 'gCC' } })
set_cursor(1, 0)
type_keys({ 'g', 'C', 'C' })
eq(get_lines(0, 1), { '# aa' })
end)
it('allows dot-repeat', function()
set_lines(example_lines)
set_cursor(1, 1)
type_keys({ 'g', 'c', 'c' })
type_keys('.')
eq(get_lines(), example_lines)
-- Not immediate dot-repeat
set_lines(example_lines)
set_cursor(1, 1)
type_keys({ 'g', 'c', 'c' })
set_cursor(7, 0)
type_keys('.')
eq(get_lines(6, 7), { '# aa' })
end)
end)
describe('Comment textobject', function()
child.setup()
load_module()
before_each(function()
set_lines(example_lines)
child.api.nvim_buf_set_option(0, 'commentstring', '# %s')
end)
it('works', function()
set_lines({ 'aa', '# aa', '# aa', 'aa' })
set_cursor(2, 0)
type_keys({ 'd', 'g', 'c' })
eq(get_lines(), { 'aa', 'aa' })
end)
it('does nothing when not inside textobject', function()
-- Builtin operators
type_keys({ 'd', 'g', 'c' })
eq(get_lines(), example_lines)
-- Comment operator
-- Main problem here at time of writing happened while calling `gc` on
-- comment textobject when not on comment line. This sets `]` mark right to
-- the left of `[` (but not when cursor in (1, 0)).
local validate_no_action = function(line, col)
set_lines(example_lines)
set_cursor(line, col)
type_keys({ 'g', 'c', 'g', 'c' })
eq(get_lines(), example_lines)
end
validate_no_action(1, 1)
validate_no_action(2, 2)
-- Doesn't work (but should) because both `[` and `]` are set to (1, 0)
-- (instead of more reasonable (1, -1) or (0, 2147483647)).
-- validate_no_action(1, 0)
end)
it('works with different mapping', function()
reload_module({ mappings = { textobject = 'gC' } })
set_lines({ 'aa', '# aa', '# aa', 'aa' })
set_cursor(2, 0)
type_keys({ 'd', 'g', 'C' })
eq(get_lines(), { 'aa', 'aa' })
end)
it('allows dot-repeat', function()
set_lines({ 'aa', '# aa', '# aa', 'aa', '# aa' })
set_cursor(2, 0)
type_keys({ 'd', 'g', 'C' })
set_cursor(3, 0)
type_keys('.')
eq(get_lines(), { 'aa', 'aa' })
end)
end)
child.stop()
|
#!/usr/bin/env luajit
require("test.test-parser")
require("test.test-xpath-converter")
luaunit = require("luaunit")
os.exit(luaunit.LuaUnit.run())
|
module 'mock'
local insert, remove = table.insert, table.remove
local function _onAnimUpdate( anim )
local t = anim:getTime()
local state = anim.source
return state:onUpdate( t )
end
local function _onAnimKeyFrame( timer, keyId, timesExecuted, time, value )
local state = timer.source
local keys= state.keyEventMap[ keyId ]
local time = timer:getTime()
for i, key in ipairs( keys ) do
key:executeEvent( state, time )
end
end
local animPool = {}
local newAnim = function()
local anim = remove( animPool, 1 )
if not anim then
return MOAIAnim.new()
end
return anim
end
--------------------------------------------------------------------
CLASS: AnimatorState ()
:MODEL{}
function AnimatorState:__init()
self.animator = false
-- self.anim = newAnim()
self.anim = MOAIAnim.new()
self.anim.source = self
self.updateListenerTracks = {}
self.attrLinks = {}
self.attrLinkCount = 0
self.parentThrottle = 1
self.throttle = 1
self.clipSpeed = 1
self.actualThrottle = 1
self.trackTargets = {}
self.stopping = false
self.previewing = false
self.length = 0
self.clip = false
self.clipMode = 'clip'
self.defaultMode = false
self.startPos = 0
self.endPos = 0
self.duration = 0
self.vars = {}
self.fixedMode = false
self.elapsedTimer = MOAITimer.new()
self.elapsedTimer:setMode( MOAITimer.CONTINUE )
self.elapsedTimer:attach( self.anim )
self.elapsedTimer:setListener(
MOAIAnim.EVENT_TIMER_END_SPAN,
function()
self:stop()
end
)
self.onVarChanged = false
self.roughness = false
end
function AnimatorState:setRoughness( r )
self.roughness = r
end
function AnimatorState:getClipName()
if not self.clip then return nil end
return self.clip:getName()
end
function AnimatorState:getMoaiAction()
return self.anim
end
---
function AnimatorState:isActive()
return self.anim:isActive()
end
function AnimatorState:setParentThrottle( t )
self.parentThrottle = t or 1
self:updateThrottle()
end
function AnimatorState:setThrottle( t )
self.throttle = t or 1
self:updateThrottle()
end
function AnimatorState:getThrottle()
return self.throttle
end
function AnimatorState:setClipSpeed( speed )
self.clipSpeed = speed
self:updateThrottle()
end
function AnimatorState:updateThrottle()
local t = self.throttle * self.clipSpeed * self.parentThrottle
self.actualThrottle = t
self.anim:throttle( t )
self.elapsedTimer:throttle( 1 / t )
end
function AnimatorState:resetRange()
self:setRange( 0, self.length )
end
function AnimatorState:setRange( startPos, endPos )
local p0, p1
if not startPos then --current time
p0 = self:getTime()
else
p0 = self:affirmPos( startPos )
end
if not endPos then --end time
p1 = self.clipLength
else
p1 = self:affirmPos( endPos )
end
self.startPos = p0
self.endPos = p1
self.anim:setSpan( p0, p1 )
end
function AnimatorState:getRange()
return self.startPos, self.endPos
end
function AnimatorState:setDuration( duration )
self.duration = duration or 0
self:updateDuration()
end
function AnimatorState:getDuration()
return self.duration
end
function AnimatorState:setFixedMode( mode )
self.fixedMode = true
self.anim:setMode( mode or self.defaultMode or MOAITimer.NORMAL )
end
function AnimatorState:setMode( mode )
if self.fixedMode then return end
self.anim:setMode( mode or self.defaultMode or MOAITimer.NORMAL )
end
function AnimatorState:getMode()
return self.anim:getMode()
end
function AnimatorState:play( mode )
if mode then
self:setMode( mode )
end
return self:start()
end
function AnimatorState:playRange( startPos, endPos, mode )
self:setRange( startPos, endPos )
return self:resetAndPlay( mode )
end
function AnimatorState:playUntil( endPos )
self:setRange( nil, endPos )
return self:start()
end
function AnimatorState:seek( pos )
local t = self:affirmPos( pos )
self:apply( t )
end
function AnimatorState:start()
self.anim:start()
local p0, p1 = self:getRange()
self:apply( p0 )
self.anim:pause( false )
if self.animator then
self.animator:onStateStart( self )
end
return self.anim
end
function AnimatorState:stop()
if not self.anim then return end --cleared
if self.stopping then return end
self.stopping = true
self.anim:stop()
self.elapsedTimer:stop()
if self.animator then
self.animator:onStateStop( self )
end
end
function AnimatorState:reset()
self:resetContext()
self.elapsedTimer:setTime( 0 )
self.elapsedTimer:attach( self.anim )
self:seek( 0 )
end
function AnimatorState:clear()
local anim = self.anim
anim:clear()
anim.source = false
anim:setListener( MOAIAnim.EVENT_TIMER_KEYFRAME, nil )
anim:setListener( MOAIAnim.EVENT_NODE_POST_UPDATE, nil )
self:clearContext()
self.anim = false
-- insert( animPool, anim )
end
function AnimatorState:resetAndPlay( mode )
self:reset()
return self:play( mode )
end
function AnimatorState:isPaused()
return self.anim:isPaused()
end
function AnimatorState:isBusy()
return self.anim:isBusy()
end
function AnimatorState:isDone()
return self.anim:isDone()
end
function AnimatorState:pause( paused )
self.anim:pause( paused )
end
function AnimatorState:resume()
local anim = self.anim
if not anim:isBusy() then
anim:start()
end
anim:pause( false )
end
function AnimatorState:getTime()
return self.anim:getTime()
end
function AnimatorState:getElapsed()
return self.elapsedTimer:getTime()
end
function AnimatorState:apply( t, flush )
local anim = self.anim
local t0 = anim:getTime()
anim:apply( t0, t )
anim:setTime( t )
if flush ~= false then
anim:flushUpdate()
end
end
function AnimatorState:findMarker( id )
return self.clip:findMarker( id )
end
function AnimatorState:affirmPos( pos )
local tt = type( pos )
if tt == 'string' then
local marker = self:findMarker( pos )
pos = marker and marker:getPos()
elseif tt == 'nil' then
return 0
end
return clamp( pos, 0, self.clipLength )
end
--
function AnimatorState:onUpdate( t, t0 )
local roughness = self.roughness
if roughness then
t = t + noise( roughness )
end
for i, entry in ipairs( self.updateListenerTracks ) do
if self.stopping then return end --edge case: new clip started in apply
local track = entry[1]
local context = entry[2]
track:apply( self, context, t, t0 )
end
end
function AnimatorState:resetContext()
for i, entry in ipairs( self.updateListenerTracks ) do
local track = entry[1]
local context = entry[2]
track:reset( self, context )
end
end
function AnimatorState:clearContext()
for i, entry in ipairs( self.updateListenerTracks ) do
local track = entry[1]
local context = entry[2]
track:clear( self, context )
end
end
function AnimatorState:getAnimator()
return self.animator
end
function AnimatorState:loadClip( animator, clip )
self.animator = animator
self.targetRoot = animator._entity
self.targetScene = self.targetRoot.scene
local context = clip:getBuiltContext()
self.clip = clip
self.clipLength = context.length
self.defaultMode = clip.defaultMode
local anim = self.anim
local previewing = self.previewing
for track in pairs( context.playableTracks ) do
if track:isLoadable( self ) then
if ( not previewing ) or track:isPreviewable() then
track:onStateLoad( self )
end
end
end
anim:reserveLinks( self.attrLinkCount )
for i, linkInfo in ipairs( self.attrLinks ) do
local track, curve, target, attrId, asDelta = unpack( linkInfo )
if target then
if ( not previewing ) or track:isPreviewable() then
anim:setLink( i, curve, target, attrId, asDelta )
end
end
end
--event key
anim:setCurve( context.eventCurve )
self.keyEventMap = context.keyEventMap
--range init
anim:setSpan( self.clipLength )
self.elapsedTimer:setTime( 0 )
self:updateDuration()
anim:flushUpdate()
anim:setListener( MOAIAnim.EVENT_TIMER_KEYFRAME, _onAnimKeyFrame )
anim:setListener( MOAIAnim.EVENT_NODE_POST_UPDATE, _onAnimUpdate )
--sort update listeners
table.sort(
self.updateListenerTracks,
function(lhs, rhs)
local t1 = lhs[1]
local t2 = rhs[1]
return t1:getPriority() < t2:getPriority()
end
)
-- print( '\n\nupdate track order' )
-- for i, entry in ipairs( self.updateListenerTracks ) do
-- print( entry[1]:getClassName() )
-- end
end
function AnimatorState:updateDuration()
local duration = self.duration
if duration > 0 then
self.elapsedTimer:setSpan( duration )
self.elapsedTimer:pause( false )
else
self.elapsedTimer:setSpan( 0 )
self.elapsedTimer:pause( true )
end
end
function AnimatorState:addUpdateListenerTrack( track, context )
table.insert( self.updateListenerTracks, { track, context } )
end
function AnimatorState:addAttrLink( track, curve, target, id, asDelta )
self.attrLinkCount = self.attrLinkCount + 1
self.attrLinks[ self.attrLinkCount ] = { track, curve, target, id, asDelta or false }
end
function AnimatorState:findTarget( targetPath )
local obj = targetPath:get( self.targetRoot, self.targetScene )
return obj
end
function AnimatorState:getTargetRoot()
return self.targetRoot, self.targetScene
end
function AnimatorState:setTrackTarget( track, target )
self.trackTargets[ track ] = target
end
function AnimatorState:getTrackTarget( track )
return self.trackTargets[ track ]
end
function AnimatorState:setListener( evId, func )
self.anim:setListener( evId, func )
end
|
local listMgr = require 'vm.list'
---@class EmmyGeneric
local mt = {}
mt.__index = mt
mt.type = 'emmy.generic'
function mt:getName()
return self.name:getName()
end
function mt:setValue(value)
self._value = value
end
function mt:getValue()
return self._value
end
return function (manager, defs)
for _, def in ipairs(defs) do
setmetatable(def, mt)
def._manager = manager
def._binds = {}
end
return defs
end
|
local themeManager = {}
themeManager.onThemeChange = {}
function themeManager.onThemeChange:Connect()
-- mock event
-- in tbd
end
return themeManager |
if GetBot():IsInvulnerable() or not GetBot():IsHero() or not string.find(GetBot():GetUnitName(), "hero") or GetBot():IsIllusion() then
return;
end
local ability_item_usage_generic = dofile( GetScriptDirectory().."/ability_item_usage_shutnik" )
local utils = require(GetScriptDirectory() .. "/util")
local mutil = require(GetScriptDirectory() .. "/Mylogic")
function AbilityLevelUpThink()
ability_item_usage_generic.AbilityLevelUpThink();
end
function BuybackUsageThink()
ability_item_usage_generic.BuybackUsageThink();
end
function CourierUsageThink()
ability_item_usage_generic.CourierUsageThink();
end
local castDCDesire = 0;
local castIGDesire = 0;
local castFBDesire = 0;
local castOODesire = 0;
local abilityIG = nil;
local abilityFB = nil;
local abilityDC = nil;
local abilityOO = nil;
local threshold = 0.25;
local npcBot = nil;
function AbilityUsageThink()
if npcBot == nil then npcBot = GetBot(); end
if mutil.CanNotUseAbility(npcBot) then return end
if abilityIG == nil then abilityIG = npcBot:GetAbilityByName( "techies_land_mines" ) end
if abilityFB == nil then abilityFB = npcBot:GetAbilityByName( "techies_stasis_trap" ) end
if abilityDC == nil then abilityDC = npcBot:GetAbilityByName( "techies_suicide" ) end
if abilityOO == nil then abilityOO = npcBot:GetAbilityByName( "techies_remote_mines" ) end
castDCDesire, castDCLocation = ConsiderDecay();
castOODesire, castOOLocation = ConsiderOverwhelmingOdds();
castIGDesire, castIGTarget = ConsiderIgnite();
castFBDesire, castFBTarget = ConsiderFireblast();
castSoulRing();
if ( castIGDesire > 0 )
then
npcBot:Action_UseAbilityOnLocation( abilityIG, castIGTarget );
return;
end
if ( castOODesire > 0 )
then
npcBot:Action_UseAbilityOnLocation( abilityOO, castOOLocation );
return;
end
if ( castDCDesire > 0 )
then
npcBot:Action_UseAbilityOnLocation( abilityDC, castDCLocation );
return;
end
if ( castFBDesire > 0 )
then
npcBot:Action_UseAbilityOnLocation( abilityFB, castFBTarget );
return;
end
end
function SoulRingAvailable()
for i = 0, 5
do
local item = npcBot:GetItemInSlot(i);
if (item~=nil) then
if(item:GetName() == "item_soul_ring") then
return item;
end
end
end
return nil;
end
function castSoulRing()
local sr=SoulRingAvailable()
if sr~=nil and sr:IsFullyCastable() and npcBot:GetHealth() > 2 * 150
then
local currManaRatio = npcBot:GetMana() / npcBot:GetMaxMana();
if ( abilityIG:IsCooldownReady() or abilityFB:IsCooldownReady() or abilityDC:IsCooldownReady() or abilityOO:IsCooldownReady() ) and
currManaRatio < 0.8
then
npcBot:Action_UseAbility(sr);
return
end
end
end
function InRadius(uType, nRadius, vLocation)
local unit = GetUnitList(UNIT_LIST_ALLIED_OTHER);
if uType == "mines" then
for _,u in pairs (unit)
do
if u:GetUnitName() == "npc_dota_techies_land_mine"
then
if GetUnitToLocationDistance(u, vLocation) <= nRadius then
return true;
end
end
end
elseif uType == "traps" then
for _,u in pairs (unit)
do
if u:GetUnitName() == "npc_dota_techies_stasis_trap"
then
if GetUnitToLocationDistance(u, vLocation) <= nRadius then
return true;
end
end
end
end
return false;
end
function ConsiderIgnite()
if ( not abilityIG:IsFullyCastable() ) then
return BOT_ACTION_DESIRE_NONE, 0;
end
local nRadius = abilityIG:GetSpecialValueInt('radius')+20;
local nCastRange = abilityIG:GetCastRange();
local vLocation = npcBot:GetXUnitsInFront(nCastRange)+RandomVector(200);
local currManaRatio = npcBot:GetMana() / npcBot:GetMaxMana();
if mutil.IsRetreating(npcBot)
then
local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( nCastRange, true, BOT_MODE_NONE );
for _,npcEnemy in pairs( tableNearbyEnemyHeroes )
do
if ( npcBot:WasRecentlyDamagedByHero( npcEnemy, 2.0 ) and not InRadius("mines", nRadius, vLocation) )
then
return BOT_ACTION_DESIRE_MODERATE, npcBot:GetXUnitsInFront(nCastRange);
end
end
end
if ( npcBot:GetActiveMode() == BOT_MODE_ROSHAN )
then
local npcTarget = npcBot:GetAttackTarget();
if ( mutil.IsRoshan(npcTarget) and mutil.CanCastOnMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, npcBot, nCastRange) )
then
return BOT_ACTION_DESIRE_LOW, npcTarget:GetLocation();
end
end
if mutil.IsPushing(npcBot)
then
local tableNearbyEnemyTowers = npcBot:GetNearbyTowers( 800, true );
if tableNearbyEnemyTowers ~= nil and #tableNearbyEnemyTowers > 0 and not tableNearbyEnemyTowers[1]:IsInvulnerable()
then
local loc = tableNearbyEnemyTowers[1]:GetLocation()+RandomVector(300);
if not InRadius("mines", nRadius, loc) then
return BOT_ACTION_DESIRE_MODERATE, loc;
end
end
end
if mutil.IsDefending(npcBot)
then
local tableNearbyAllyTowers = npcBot:GetNearbyTowers( 800, false );
if tableNearbyAllyTowers ~= nil and #tableNearbyAllyTowers > 0 and not tableNearbyAllyTowers[1]:IsInvulnerable()
then
local loc = tableNearbyAllyTowers[1]:GetLocation()+RandomVector(300);
if not InRadius("mines", nRadius, loc) then
return BOT_ACTION_DESIRE_MODERATE, loc;
end
end
end
if mutil.IsGoingOnSomeone(npcBot)
then
local npcTarget = npcBot:GetTarget();
if ( mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) )
then
local loc = npcTarget:GetLocation();
if not InRadius("mines", nRadius, loc) then
return BOT_ACTION_DESIRE_MODERATE, loc;
end
end
end
if not InRadius("mines", nRadius, vLocation) and currManaRatio > threshold and npcBot:DistanceFromFountain() > 1500 and DotaTime() > 0 then
return BOT_ACTION_DESIRE_LOW, vLocation;
end
return BOT_ACTION_DESIRE_NONE, 0;
end
function ConsiderFireblast()
if ( not abilityFB:IsFullyCastable() ) then
return BOT_ACTION_DESIRE_NONE, 0;
end
local nRadius = 620;
local nCastRange = abilityFB:GetCastRange();
local vLocation = npcBot:GetXUnitsInFront(nCastRange)+RandomVector(200);
local currManaRatio = npcBot:GetMana() / npcBot:GetMaxMana();
if mutil.IsRetreating(npcBot)
then
local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( nCastRange, true, BOT_MODE_NONE );
for _,npcEnemy in pairs( tableNearbyEnemyHeroes )
do
if ( npcBot:WasRecentlyDamagedByHero( npcEnemy, 2.0 ) )
then
return BOT_ACTION_DESIRE_LOW, npcBot:GetXUnitsInFront(nCastRange);
end
end
end
if mutil.IsDefending(npcBot)
then
local tableNearbyAllyTowers = npcBot:GetNearbyTowers( 800, false );
if tableNearbyAllyTowers ~= nil and #tableNearbyAllyTowers > 0 and not tableNearbyAllyTowers[1]:IsInvulnerable() then
local loc = tableNearbyAllyTowers[1]:GetLocation()+RandomVector(300);
if not InRadius("traps", nRadius, loc) then
return BOT_ACTION_DESIRE_MODERATE, loc;
end
end
end
if mutil.IsGoingOnSomeone(npcBot)
then
local npcTarget = npcBot:GetTarget();
if ( mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) )
then
local loc = npcTarget:GetLocation();
if not InRadius("traps", nRadius, loc) then
return BOT_ACTION_DESIRE_MODERATE, loc;
end
end
end
if not InRadius("traps", nRadius, vLocation) and currManaRatio > threshold and npcBot:DistanceFromFountain() > 1500 and DotaTime() > 0 then
return BOT_ACTION_DESIRE_LOW, vLocation;
end
return BOT_ACTION_DESIRE_NONE, 0;
end
function ConsiderDecay()
if ( not abilityDC:IsFullyCastable() )
then
return BOT_ACTION_DESIRE_NONE, 0;
end
local nRadius = abilityDC:GetSpecialValueInt( "radius" );
local nCastRange = abilityDC:GetCastRange();
local nCastPoint = abilityDC:GetCastPoint( );
local nDamage = abilityDC:GetSpecialValueInt("damage");
local nHPP = npcBot:GetHealth() / npcBot:GetMaxHealth();
if mutil.IsRetreating(npcBot)
then
local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( nCastRange, true, BOT_MODE_NONE );
for _,npcEnemy in pairs( tableNearbyEnemyHeroes )
do
if ( npcBot:WasRecentlyDamagedByHero( npcEnemy, 2.0 ) )
then
if nHPP >= 0.65 then
return BOT_ACTION_DESIRE_LOW, npcBot:GetXUnitsInFront(nCastRange);
else
return BOT_ACTION_DESIRE_LOW, npcEnemy:GetLocation();
end
end
end
end
if mutil.IsInTeamFight(npcBot, 1200)
then
local locationAoE = npcBot:FindAoELocation( true, true, npcBot:GetLocation(), nCastRange, nRadius/2, 0, 0 );
if ( locationAoE.count >= 2 ) then
return BOT_ACTION_DESIRE_LOW, locationAoE.targetloc;
end
end
if mutil.IsGoingOnSomeone(npcBot)
then
local npcTarget = npcBot:GetTarget();
if mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, npcBot, nCastRange+200)
then
local EnemyHeroes = npcTarget:GetNearbyHeroes( nRadius, false, BOT_MODE_NONE );
if ( #EnemyHeroes >= 1 )
then
return BOT_ACTION_DESIRE_MODERATE, npcTarget:GetExtrapolatedLocation( nCastPoint );
end
end
end
return BOT_ACTION_DESIRE_NONE, 0;
end
function ConsiderOverwhelmingOdds()
if ( not abilityOO:IsFullyCastable() )
then
return BOT_ACTION_DESIRE_NONE, 0;
end
local npcBot = GetBot();
local nCastRange = abilityOO:GetCastRange();
local vLocation = npcBot:GetXUnitsInFront(nCastRange);
local currManaRatio = npcBot:GetMana() / npcBot:GetMaxMana();
if mutil.IsRetreating(npcBot)
then
local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( nCastRange, true, BOT_MODE_NONE );
for _,npcEnemy in pairs( tableNearbyEnemyHeroes )
do
if ( npcBot:WasRecentlyDamagedByHero( npcEnemy, 2.0 ) )
then
return BOT_ACTION_DESIRE_MODERATE, npcBot:GetXUnitsInFront(nCastRange);
end
end
end
if mutil.IsPushing(npcBot)
then
local tableNearbyEnemyTowers = npcBot:GetNearbyTowers( 800, true );
if tableNearbyEnemyTowers ~= nil and #tableNearbyEnemyTowers > 0 and not tableNearbyEnemyTowers[1]:IsInvulnerable() then
return BOT_ACTION_DESIRE_MODERATE, tableNearbyEnemyTowers[1]:GetLocation() + RandomVector(300);
end
end
if mutil.IsDefending(npcBot)
then
local tableNearbyAllyTowers = npcBot:GetNearbyTowers( 800, false );
if tableNearbyAllyTowers ~= nil and #tableNearbyAllyTowers > 0 and not tableNearbyAllyTowers[1]:IsInvulnerable() then
return BOT_ACTION_DESIRE_LOW, tableNearbyAllyTowers[1]:GetLocation() + RandomVector(300);
end
end
if mutil.IsGoingOnSomeone(npcBot)
then
local npcTarget = npcBot:GetTarget();
if ( mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) )
then
return BOT_ACTION_DESIRE_LOW, npcTarget:GetLocation();
end
end
if currManaRatio > threshold and npcBot:DistanceFromFountain() > 1000 then
return BOT_ACTION_DESIRE_LOW, vLocation;
end
return BOT_ACTION_DESIRE_NONE, 0;
end
|
--====================================================================--
-- dmc_widget/theme_manager/background_style.lua
--
-- Documentation: http://docs.davidmccuskey.com/
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2015 David McCuskey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
--== DMC Corona Widgets : Widget Background Style
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--====================================================================--
--== DMC Widgets Setup
--====================================================================--
local dmc_widget_data = _G.__dmc_widget
local dmc_widget_func = dmc_widget_data.func
local widget_find = dmc_widget_func.find
--====================================================================--
--== DMC Widgets : newTextStyle
--====================================================================--
--====================================================================--
--== Imports
local Objects = require 'dmc_objects'
local BaseStyle = require( widget_find( 'theme_manager.base_style' ) )
--====================================================================--
--== Setup, Constants
local newClass = Objects.newClass
local ObjectBase = Objects.ObjectBase
local Widgets = nil -- set later
--====================================================================--
--== Text Style Class
--====================================================================--
local TextStyle = newClass( BaseStyle, {name="Text Style"} )
--== Class Constants
TextStyle.__base_style__ = nil
TextStyle.EXCLUDE_PROPERTY_CHECK = {
width=true,
height=true
}
TextStyle.DEFAULT = {
name='text-default-style',
width=nil,
height=nil,
align='center',
anchorX=0.5,
anchorY=0.5,
debugOn=false,
fillColor={1,1,1,0},
font=native.systemFont,
fontSize=24,
marginX=0,
marginY=0,
strokeColor={0,0,0,1},
strokeWidth=0,
textColor={0,0,0,1}
}
--== Event Constants
TextStyle.EVENT = 'text-style-event'
-- from super
-- Class.STYLE_UPDATED
--======================================================--
--== Start: Setup DMC Objects
function TextStyle:__init__( params )
-- print( "TextStyle:__init__", params )
params = params or {}
self:superCall( '__init__', params )
--==--
--== Style Properties ==--
-- self._data
-- self._inherit
-- self._widget
-- self._parent
-- self._onProperty
-- self._name
-- self._debugOn
self._width = nil
self._height = nil
self._align = nil
self._anchorX = nil
self._anchorY = nil
self._fillColor = nil
self._font = nil
self._fontSize = nil
self._marginX = nil
self._marginY = nil
self._strokeColor = nil
self._strokeWidth = nil
self._textColor = nil
end
--== END: Setup DMC Objects
--======================================================--
--====================================================================--
--== Static Methods
function TextStyle.initialize( manager )
-- print( "TextStyle.initialize", manager )
Widgets = manager
TextStyle._setDefaults()
end
--====================================================================--
--== Public Methods
--== updateStyle
-- force is used when making exact copy of data, incl 'nil's
--
function TextStyle:updateStyle( info, params )
-- print( "TextStyle:updateStyle" )
params = params or {}
if params.force==nil then params.force=true end
--==--
local force=params.force
if info.debugOn~=nil or force then self.debugOn=info.debugOn end
if info.width~=nil or force then self.width=info.width end
if info.height~=nil or force then self.height=info.height end
if info.align~=nil or force then self.align=info.align end
if info.anchorX~=nil or force then self.anchorX=info.anchorX end
if info.anchorY~=nil or force then self.anchorY=info.anchorY end
if info.fillColor~=nil or force then self.fillColor=info.fillColor end
if info.font~=nil or force then self.font=info.font end
if info.fontSize~=nil or force then self.fontSize=info.fontSize end
if info.marginX~=nil or force then self.marginX=info.marginX end
if info.marginY~=nil or force then self.marginY=info.marginY end
if info.strokeColor~=nil or force then self.strokeColor=info.strokeColor end
if info.strokeWidth~=nil or force then self.strokeWidth=info.strokeWidth end
if info.textColor~=nil or force then self.textColor=info.textColor end
end
--====================================================================--
--== Private Methods
function TextStyle._setDefaults()
-- print( "TextStyle._setDefaults" )
local style = TextStyle:new{
data=TextStyle.DEFAULT
}
TextStyle.__base_style__ = style
end
function TextStyle:_checkProperties()
BaseStyle._checkProperties( self )
--[[
we don't check for width/height because nil is valid value
sometimes we just use width/height of the text object
-- assert( self.width, "Style: requires 'width'" )
-- assert( self.height, "Style: requires 'height'" )
--]]
assert( self.align, "Style: requires 'align'" )
assert( self.anchorY, "Style: requires 'anchory'" )
assert( self.anchorX, "Style: requires 'anchorX'" )
assert( self.fillColor, "Style: requires 'fillColor'" )
assert( self.font, "Style: requires 'font'" )
assert( self.fontSize, "Style: requires 'fontSize'" )
assert( self.marginX, "Style: requires 'marginX'" )
assert( self.marginY, "Style: requires 'marginY'" )
assert( self.strokeColor, "Style: requires 'strokeColor'" )
assert( self.strokeWidth, "Style: requires 'strokeWidth'" )
assert( self.textColor, "Style: requires 'textColor'" )
end
--====================================================================--
--== Event Handlers
-- none
return TextStyle
|
require("github-theme").setup({theme_style = "dimmed"})
|
local gameplay = {}
gameplay.challengeRowId = "challenge"
function gameplay.answerRowId(index)
return {type="answer", index=index}
end
function gameplay.newGameplay(game)
local gp = {
game=game
}
function gp:renderGameplayView()
if self.challengeRowInsertFunction then self.challengeRowInsertFunction(gameplay.challengeRowId) end
for i, v in ipairs(game.answers) do
if self.answerRowInsertFunction then
self.answerRowInsertFunction(gameplay.answerRowId(i))
end
end
end
function gp:renderRow(row, id)
if id == gameplay.challengeRowId then
self.challengeRowRenderFunction(row)
end
if type(id) == "table" and id.type == "answer" then
self.answerRowRenderFunction(row)
end
end
return gp
end
return gameplay |
package.path = package.path .. ";../../?.lua"
sock = require "sock"
bitser = require "spec.bitser"
-- Utility functions
function isColliding(this, other)
return this.x < other.x + other.w and
this.y < other.y + other.h and
this.x + this.w > other.x and
this.y + this.h > other.y
end
function love.load()
-- how often an update is sent out
tickRate = 1/60
tick = 0
server = sock.newServer("*", 22122, 2)
server:setSerialization(bitser.dumps, bitser.loads)
-- Players are being indexed by peer index here, definitely not a good idea
-- for a larger game, but it's good enough for this application.
server:on("connect", function(data, client)
-- tell the peer what their index is
client:send("playerNum", client:getIndex())
end)
-- receive info on where a player is located
server:on("mouseY", function(y, client)
local index = client:getIndex()
players[index].y = y
end)
function newPlayer(x, y)
return {
x = x,
y = y,
w = 20,
h = 100,
}
end
function newBall(x, y)
return {
x = x,
y = y,
vx = 150,
vy = 150,
w = 15,
h = 15,
}
end
local marginX = 50
players = {
newPlayer(marginX, love.graphics.getHeight()/2),
newPlayer(love.graphics.getWidth() - marginX, love.graphics.getHeight()/2)
}
scores = {0, 0}
ball = newBall(love.graphics.getWidth()/2, love.graphics.getHeight()/2)
end
function love.update(dt)
server:update()
-- wait until 2 players connect to start playing
local enoughPlayers = #server.clients >= 2
if not enoughPlayers then return end
for i, player in pairs(players) do
-- This is a naive solution, if the ball is inside the paddle it might bug out
-- But hey, it's low stakes pong
if isColliding(ball, player) then
ball.vx = ball.vx * -1
ball.vy = ball.vy * -1
end
end
-- Left/Right bounds
if ball.x < 0 or ball.x > love.graphics.getWidth() then
if ball.x < 0 then
scores[2] = scores[2] + 1
else
scores[1] = scores[1] + 1
end
server:sendToAll("scores", scores)
ball.x = love.graphics.getWidth()/2
ball.y = love.graphics.getHeight()/2
ball.vx = ball.vx * -1
ball.vy = ball.vy * -1
end
-- Top/Bottom bounds
if ball.y < 0 or ball.y > love.graphics.getHeight() - ball.h then
ball.vy = ball.vy * -1
if ball.y < 0 then
ball.y = 0
end
if ball.y > love.graphics.getHeight() - ball.h then
ball.y = love.graphics.getHeight() - ball.h
end
end
ball.x = ball.x + ball.vx * dt
ball.y = ball.y + ball.vy * dt
tick = tick + dt
if tick >= tickRate then
tick = 0
for i, player in pairs(players) do
server:sendToAll("playerState", {i, player})
end
server:sendToAll("ballState", ball)
end
end
function love.draw()
for i, player in pairs(players) do
love.graphics.rectangle('fill', player.x, player.y, player.w, player.h)
end
love.graphics.rectangle('fill', ball.x, ball.y, ball.w, ball.h)
local score = ("%d - %d"):format(scores[1], scores[2])
love.graphics.print(score, 5, 5)
end
|
local XboxCatalogData = require(script.Parent.XboxCatalogData)
local NativeProducts = require(script.Parent.NativeProducts)
local Promise = require(script.Parent.Parent.Promise)
local function sortAscending(a, b)
return a.robuxValue < b.robuxValue
end
local function selectProduct(neededRobux, availableProducts)
table.sort(availableProducts, sortAscending)
for _, product in ipairs(availableProducts) do
if product.robuxValue >= neededRobux then
return Promise.resolve(product)
end
end
return Promise.reject()
end
local function selectRobuxProduct(platform, neededRobux, userIsSubscribed)
-- Premium is not yet enabled for XBox, so we always use the existing approach
if platform == Enum.Platform.XBoxOne then
return XboxCatalogData.GetCatalogInfoAsync()
:andThen(function(availableProducts)
return selectProduct(neededRobux, availableProducts)
end)
end
local productOptions
if platform == Enum.Platform.IOS then
productOptions = userIsSubscribed
and NativeProducts.IOS.PremiumSubscribed
or NativeProducts.IOS.PremiumNotSubscribed
else -- This product format is standard for other supported platforms (Android, Amazon, and UWP)
if platform == Enum.Platform.Android then
-- Contains upsell for 4500 and 10000 packages only available on android
productOptions = userIsSubscribed
and NativeProducts.Standard.PremiumSubscribedLarger
or NativeProducts.Standard.PremiumNotSubscribedLarger
else
productOptions = userIsSubscribed
and NativeProducts.Standard.PremiumSubscribed
or NativeProducts.Standard.PremiumNotSubscribed
end
end
return selectProduct(neededRobux, productOptions)
end
return selectRobuxProduct |
--
-- Chartboost Corona SDK
-- Created by: Chris
--
-- This file contains methods used to animate content
--
local CBAnimationType = require "chartboost.model.CBAnimationType"
local CBAnimations = require "chartboost.view.CBAnimations"
--- params: CBAnimationType, CBImpression, CBAnimationProtocol, boolean
local function doTransitionWithAnimationType(animType, impression, block, isInTransition)
assert(CBAnimationType.assert(animType), "First parameter 'animType' must be a CBAnimationType.")
assert(type(impression) == "table", "Second parameter 'impression' must be a CBImpression.")
if block then assert(type(block) == "function", "Third parameter 'block' must be a function or nil.") end
assert(type(isInTransition) == "boolean", "Fourth parameter 'isInTransition' must be a boolean.")
local animDuration = 600
-- do checks to see if impression has been canceled prior to self animation getting a chance to occur
if not impression or not impression.parentView then
return
end
local layer = impression.parentView.content
if not layer then
return
end
layer = layer.group
local width = display.contentWidth
local height = display.contentHeight
local degrees = 60
local scale = 0.4
local offset = (1.0 - scale) / 2.0
local rotateAnimation
local scaleAnimation
local translateAnimation
local listener = function()
if block then
block(impression)
end
end
if animType == CBAnimationType.CBAnimationTypeNone then
listener()
return
end
local addParams = function(params, anim)
if anim then
for k,v in pairs(anim) do
if type(v) == "table" and v.from and v.to then
params[k] = v.to
layer[k] = v.from
end
end
end
end
if animType == CBAnimationType.CBAnimationTypePerspectiveZoom then
if (isInTransition) then
rotateAnimation = CBAnimations.AlphaAnimation(0, 1.0)
scaleAnimation = CBAnimations.ScaleAnimation(scale, 1.0, scale, 1.0)
translateAnimation = CBAnimations.TranslateAnimation(width * offset, 0, -height * scale, 0)
else
rotateAnimation = CBAnimations.AlphaAnimation(1.0, 0)
scaleAnimation = CBAnimations.ScaleAnimation(1.0, scale, 1.0, scale)
translateAnimation = CBAnimations.TranslateAnimation(0, width * offset, 0, height)
end
local animParams = {time = animDuration, onComplete = listener}
addParams(animParams, rotateAnimation)
addParams(animParams, scaleAnimation)
addParams(animParams, translateAnimation)
transition.to(layer, animParams)
elseif animType == CBAnimationType.CBAnimationTypePerspectiveRotate then
if (isInTransition) then
rotateAnimation = CBAnimations.AlphaAnimation(0, 1.0)
scaleAnimation = CBAnimations.ScaleAnimation(scale, 1.0, scale, 1.0)
translateAnimation = CBAnimations.TranslateAnimation(-width * scale, 0, height * offset, 0)
else
rotateAnimation = CBAnimations.AlphaAnimation(1.0, 0)
scaleAnimation = CBAnimations.ScaleAnimation(1.0, scale, 1.0, scale)
translateAnimation = CBAnimations.TranslateAnimation(0, width, 0, height * offset)
end
local animParams = {time = animDuration, onComplete = listener}
addParams(animParams, rotateAnimation)
addParams(animParams, scaleAnimation)
addParams(animParams, translateAnimation)
--print((require "json").encode(animParams))
transition.to(layer, animParams)
elseif animType == CBAnimationType.CBAnimationTypeSlideFromBottom then
local fromx, tox = 0, 0
local fromy, toy = 0, 0
if (isInTransition) then
fromy = height
else
toy = height
end
translateAnimation = CBAnimations.TranslateAnimation(fromx, tox, fromy, toy)
local animParams = {time = animDuration, onComplete = listener}
addParams(animParams, translateAnimation)
transition.to(layer, animParams)
elseif animType == CBAnimationType.CBAnimationTypeSlideFromTop then
local fromx, tox = 0, 0
local fromy, toy = 0, 0
if (isInTransition) then
fromy = -height
else
toy = -height
end
translateAnimation = CBAnimations.TranslateAnimation(fromx, tox, fromy, toy)
local animParams = {time = animDuration, onComplete = listener}
addParams(animParams, translateAnimation)
transition.to(layer, animParams)
elseif animType == CBAnimationType.CBAnimationTypeBounce then
layer:setReferencePoint(display.CenterReferencePoint)
if (isInTransition) then
scaleAnimation = CBAnimations.ScaleAnimation(0.6, 1.1, 0.6, 1.1)
local animParams = {time = animDuration * 0.6, onComplete = function()
local scaleAnimation2 = CBAnimations.ScaleAnimation(1.1, 0.9, 1.1, 0.9)
local animParams2 = {time = animDuration * (0.8 - 0.6), onComplete = function()
local scaleAnimation3 = CBAnimations.ScaleAnimation(0.9, 1, 0.9, 1)
local animParams3 = {time = animDuration * (0.9 - 0.8), onComplete = function()
layer:setReferencePoint(display.TopLeftReferencePoint)
listener()
end}
addParams(animParams3, scaleAnimation3)
transition.to(layer, animParams3)
end}
addParams(animParams2, scaleAnimation2)
transition.to(layer, animParams2)
end}
addParams(animParams, scaleAnimation)
transition.to(layer, animParams)
else
scaleAnimation = CBAnimations.ScaleAnimation(1.0, 0, 1.0, 0)
local animParams = {time = animDuration, onComplete = listener}
addParams(animParams, scaleAnimation)
transition.to(layer, animParams)
end
end
end
--- params: CBAnimationType, CBImpression, CBAnimationProtocol, boolean
--- Make sure chartboost view gets measured before we start animation
local function transitionWithAnimationType(animType, impression, block, isInTransition)
assert(CBAnimationType.assert(animType), "First parameter 'animType' must be a CBAnimationType.")
assert(type(impression) == "table", "Second parameter 'impression' must be a CBImpression.")
if block then assert(type(block) == "function", "Third parameter 'block' must be a function or nil.") end
assert(type(isInTransition) == "boolean", "Fourth parameter 'isInTransition' must be a boolean.")
-- do checks to see if impression has been canceled prior to this animation getting a chance to occur
if not impression or not impression.parentView then
return
end
local layer = impression.parentView.content
if not layer then
return
end
doTransitionWithAnimationType(animType, impression, block, isInTransition)
end
--- params: CBAnimationType, CBImpression, CBAnimationProtocol
local function transitionInWithAnimationType(animType, impression, block)
assert(CBAnimationType.assert(animType), "First parameter 'animType' must be a CBAnimationType.")
assert(type(impression) == "table", "Second parameter 'impression' must be a CBImpression.")
if block then assert(type(block) == "function", "Third parameter 'block' must be a function or nil.") end
transitionWithAnimationType(animType, impression, block, true)
end
--- params: CBAnimationType, CBImpression, CBAnimationProtocol
local function transitionOutWithAnimationType(animType, impression, block)
assert(CBAnimationType.assert(animType), "First parameter 'animType' must be a CBAnimationType.")
assert(type(impression) == "table", "Second parameter 'impression' must be a CBImpression.")
if block then assert(type(block) == "function", "Third parameter 'block' must be a function or nil.") end
doTransitionWithAnimationType(animType, impression, block, false)
end
return {
transitionOutWithAnimationType = transitionOutWithAnimationType,
transitionInWithAnimationType = transitionInWithAnimationType
} |
#!/usr/bin/env luajit
-- Copyright 2020, Michael Adler <therisen06@gmail.com>
local log = require("log")
log.level = "error"
local SeatingSystem = require("seatingsystem")
local fname = "input.txt"
--local fname = "small.txt"
local function read_input()
local grid = {}
local f = io.open(fname, "r")
local max_x = nil
local y = 1
for line in f:lines() do
local x = 1
for c in line:gmatch(".") do
local t = grid[x] or {}
t[y] = c
grid[x] = t
x = x + 1
end
if not max_x then
max_x = #line
end
y = y + 1
end
f:close()
return SeatingSystem.new(grid, max_x, y)
end
local function solve(seatingsystem, cb)
repeat
local has_changes = cb()
until has_changes == false
local count = 0
for x = 1, seatingsystem.max_x do
for y = 1, seatingsystem.max_y do
if seatingsystem:is_occupied(x, y) then
count = count + 1
end
end
end
return count
end
local function part1()
local seatingsystem = read_input()
return solve(seatingsystem, function()
return seatingsystem:advance()
end)
end
local function part2()
local seatingsystem = read_input()
return solve(seatingsystem, function()
return seatingsystem:advance2()
end)
end
local answer1 = part1()
print("Part 1:", answer1)
local answer2 = part2()
print("Part 2:", answer2)
assert(answer1 == 2441)
assert(answer2 == 2190)
|
local root = script.parent
local destination = root:GetCustomProperty("Destination"):WaitForObject()
local trigger = root:FindChildByType("Trigger")
function OnBeginOverlap(theTrigger, player)
player:SetWorldPosition(destination:GetWorldPosition() + Vector3.New(0, 0, 100))
end
trigger.beginOverlapEvent:Connect(OnBeginOverlap) |
-----------------------------------
-- Area: Northern San d'Oria
-- NPC: Baraka
-- Involved in Missions 2-3
-- !pos 36 -2 -2 231
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/missions")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
if (player:getCurrentMission(BASTOK) ~= tpz.mission.id.bastok.NONE) then
local missionStatus = player:getCharVar("MissionStatus")
if (player:getCurrentMission(BASTOK) == tpz.mission.id.bastok.THE_EMISSARY) then
if (missionStatus == 1) then
player:startEvent(581)
elseif (missionStatus == 2) then
player:showText(npc, 11141)
else
player:startEvent(539)
end
end
else
local pNation = player:getNation()
if (pNation == tpz.nation.SANDORIA) then
player:startEvent(580)
elseif (pNation == tpz.nation.WINDURST) then
player:startEvent(579)
else
player:startEvent(539)
end
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if (csid == 581) then
-- This cs should only play if you visit San d'Oria first
-- If you visit Windurst first you will encounter Lion in Heaven's Tower instead
if (player:getCurrentMission(BASTOK) == tpz.mission.id.bastok.THE_EMISSARY
and player:getCharVar("MissionStatus") < 2) then
player:setCharVar("MissionStatus", 2)
player:delKeyItem(tpz.ki.LETTER_TO_THE_CONSULS_BASTOK)
end
end
end
|
--[[
Author: Noya
Date: April 5, 2015
Creates the Life Drain Particle rope.
It is indexed on the caster handle to have access to it later, because the Color CP changes if the drain is restoring mana.
]]
function LifeDrainParticle( event)
local caster = event.caster
local target = event.target
local ability = event.ability
local particleName = "particles/units/heroes/hero_pugna/pugna_life_drain.vpcf"
caster.LifeDrainParticle = ParticleManager:CreateParticle(particleName, PATTACH_ABSORIGIN_FOLLOW, caster)
ParticleManager:SetParticleControlEnt(caster.LifeDrainParticle, 1, target, PATTACH_POINT_FOLLOW, "attach_hitloc", target:GetAbsOrigin(), true)
end
--[[
Author: Noya
Date: April 5, 2015
When cast on an enemy, drains health from the target enemy unit to heal himself.
If the hero has full HP, and the enemy target is a Hero, Life Drain will restore mana instead.
When cast on an ally, it will drain his own health into his ally.
]]
function LifeDrainHealthTransfer( event )
local caster = event.caster
local target = event.target
local ability = event.ability
local health_drain = ability:GetLevelSpecialValueFor( "health_drain" , ability:GetLevel() - 1 )
local tick_rate = ability:GetLevelSpecialValueFor( "tick_rate" , ability:GetLevel() - 1 )
local HP_drain = health_drain * tick_rate
-- HP drained depends on the actual damage dealt. This is for MAGICAL damage type
local HP_gain = HP_drain * ( 1 - target:GetMagicalArmorValue())
print(HP_drain,target:GetMagicalArmorValue(),HP_gain)
-- Act according to the targets team
local targetTeam = target:GetTeamNumber()
local casterTeam = caster:GetTeamNumber()
-- If its an illusion then kill it
if target:IsIllusion() then
target:ForceKill(true)
ability:OnChannelFinish(false)
caster:Stop()
return
else
-- Location variables
local caster_location = caster:GetAbsOrigin()
local target_location = target:GetAbsOrigin()
-- Distance variables
local distance = (target_location - caster_location):Length2D()
local break_distance = ability:GetCastRange()
local direction = (target_location - caster_location):Normalized()
-- If the leash is broken then stop the channel
if distance >= break_distance then
ability:OnChannelFinish(false)
caster:Stop()
return
end
-- Make sure that the caster always faces the target
caster:SetForwardVector(direction)
end
if targetTeam == casterTeam then
-- Health Transfer Caster->Ally
ApplyDamage({ victim = caster, attacker = caster, damage = HP_drain, damage_type = DAMAGE_TYPE_MAGICAL })
target:Heal( HP_gain, caster)
--TODO: Check if this damage transfer should be lethal
-- Set the particle control color as green
ParticleManager:SetParticleControl(caster.LifeDrainParticle, 10, Vector(0,0,0))
ParticleManager:SetParticleControl(caster.LifeDrainParticle, 11, Vector(0,0,0))
else
if caster:GetHealthDeficit() > 0 then
-- Health Transfer Enemy->Caster
ApplyDamage({ victim = target, attacker = caster, damage = HP_drain, damage_type = DAMAGE_TYPE_MAGICAL })
caster:Heal( HP_gain, caster)
-- Set the particle control color as green
ParticleManager:SetParticleControl(caster.LifeDrainParticle, 10, Vector(0,0,0))
ParticleManager:SetParticleControl(caster.LifeDrainParticle, 11, Vector(0,0,0))
elseif target:IsHero() then
-- Health to Mana Transfer Enemy->Caster
ApplyDamage({ victim = target, attacker = caster, damage = HP_drain, damage_type = DAMAGE_TYPE_MAGICAL })
caster:GiveMana(HP_gain)
-- Set the particle control color as BLUE
ParticleManager:SetParticleControl(caster.LifeDrainParticle, 10, Vector(1,0,0))
ParticleManager:SetParticleControl(caster.LifeDrainParticle, 11, Vector(1,0,0))
end
end
end
function LifeDrainParticleEnd( event )
local caster = event.caster
ParticleManager:DestroyParticle(caster.LifeDrainParticle,false)
end |
_G.vector = {}
dofile("builtin/common/vector.lua")
describe("vector", function()
describe("new()", function()
it("constructs", function()
assert.same({ x = 0, y = 0, z = 0 }, vector.new())
assert.same({ x = 1, y = 2, z = 3 }, vector.new(1, 2, 3))
assert.same({ x = 3, y = 2, z = 1 }, vector.new({ x = 3, y = 2, z = 1 }))
local input = vector.new({ x = 3, y = 2, z = 1 })
local output = vector.new(input)
assert.same(input, output)
assert.are_not.equal(input, output)
end)
it("throws on invalid input", function()
assert.has.errors(function()
vector.new({ x = 3 })
end)
assert.has.errors(function()
vector.new({ d = 3 })
end)
end)
end)
it("equal()", function()
local function assertE(a, b)
assert.is_true(vector.equals(a, b))
end
local function assertNE(a, b)
assert.is_false(vector.equals(a, b))
end
assertE({x = 0, y = 0, z = 0}, {x = 0, y = 0, z = 0})
assertE({x = -1, y = 0, z = 1}, {x = -1, y = 0, z = 1})
local a = { x = 2, y = 4, z = -10 }
assertE(a, a)
assertNE({x = -1, y = 0, z = 1}, a)
end)
it("add()", function()
assert.same({ x = 2, y = 4, z = 6 }, vector.add(vector.new(1, 2, 3), { x = 1, y = 2, z = 3 }))
end)
-- This function is needed because of floating point imprecision.
local function almost_equal(a, b)
if type(a) == "number" then
return math.abs(a - b) < 0.00000000001
end
return vector.distance(a, b) < 0.000000000001
end
describe("rotate_around_axis()", function()
it("rotates", function()
assert.True(almost_equal({x = -1, y = 0, z = 0},
vector.rotate_around_axis({x = 1, y = 0, z = 0}, {x = 0, y = 1, z = 0}, math.pi)))
assert.True(almost_equal({x = 0, y = 1, z = 0},
vector.rotate_around_axis({x = 0, y = 0, z = 1}, {x = 1, y = 0, z = 0}, math.pi / 2)))
assert.True(almost_equal({x = 4, y = 1, z = 1},
vector.rotate_around_axis({x = 4, y = 1, z = 1}, {x = 4, y = 1, z = 1}, math.pi / 6)))
end)
it("keeps distance to axis", function()
local rotate1 = {x = 1, y = 3, z = 1}
local axis1 = {x = 1, y = 3, z = 2}
local rotated1 = vector.rotate_around_axis(rotate1, axis1, math.pi / 13)
assert.True(almost_equal(vector.distance(axis1, rotate1), vector.distance(axis1, rotated1)))
local rotate2 = {x = 1, y = 1, z = 3}
local axis2 = {x = 2, y = 6, z = 100}
local rotated2 = vector.rotate_around_axis(rotate2, axis2, math.pi / 23)
assert.True(almost_equal(vector.distance(axis2, rotate2), vector.distance(axis2, rotated2)))
local rotate3 = {x = 1, y = -1, z = 3}
local axis3 = {x = 2, y = 6, z = 100}
local rotated3 = vector.rotate_around_axis(rotate3, axis3, math.pi / 2)
assert.True(almost_equal(vector.distance(axis3, rotate3), vector.distance(axis3, rotated3)))
end)
it("rotates back", function()
local rotate1 = {x = 1, y = 3, z = 1}
local axis1 = {x = 1, y = 3, z = 2}
local rotated1 = vector.rotate_around_axis(rotate1, axis1, math.pi / 13)
rotated1 = vector.rotate_around_axis(rotated1, axis1, -math.pi / 13)
assert.True(almost_equal(rotate1, rotated1))
local rotate2 = {x = 1, y = 1, z = 3}
local axis2 = {x = 2, y = 6, z = 100}
local rotated2 = vector.rotate_around_axis(rotate2, axis2, math.pi / 23)
rotated2 = vector.rotate_around_axis(rotated2, axis2, -math.pi / 23)
assert.True(almost_equal(rotate2, rotated2))
local rotate3 = {x = 1, y = -1, z = 3}
local axis3 = {x = 2, y = 6, z = 100}
local rotated3 = vector.rotate_around_axis(rotate3, axis3, math.pi / 2)
rotated3 = vector.rotate_around_axis(rotated3, axis3, -math.pi / 2)
assert.True(almost_equal(rotate3, rotated3))
end)
it("is right handed", function()
local v_before1 = {x = 0, y = 1, z = -1}
local v_after1 = vector.rotate_around_axis(v_before1, {x = 1, y = 0, z = 0}, math.pi / 4)
assert.True(almost_equal(vector.normalize(vector.cross(v_after1, v_before1)), {x = 1, y = 0, z = 0}))
local v_before2 = {x = 0, y = 3, z = 4}
local v_after2 = vector.rotate_around_axis(v_before2, {x = 1, y = 0, z = 0}, 2 * math.pi / 5)
assert.True(almost_equal(vector.normalize(vector.cross(v_after2, v_before2)), {x = 1, y = 0, z = 0}))
local v_before3 = {x = 1, y = 0, z = -1}
local v_after3 = vector.rotate_around_axis(v_before3, {x = 0, y = 1, z = 0}, math.pi / 4)
assert.True(almost_equal(vector.normalize(vector.cross(v_after3, v_before3)), {x = 0, y = 1, z = 0}))
local v_before4 = {x = 3, y = 0, z = 4}
local v_after4 = vector.rotate_around_axis(v_before4, {x = 0, y = 1, z = 0}, 2 * math.pi / 5)
assert.True(almost_equal(vector.normalize(vector.cross(v_after4, v_before4)), {x = 0, y = 1, z = 0}))
local v_before5 = {x = 1, y = -1, z = 0}
local v_after5 = vector.rotate_around_axis(v_before5, {x = 0, y = 0, z = 1}, math.pi / 4)
assert.True(almost_equal(vector.normalize(vector.cross(v_after5, v_before5)), {x = 0, y = 0, z = 1}))
local v_before6 = {x = 3, y = 4, z = 0}
local v_after6 = vector.rotate_around_axis(v_before6, {x = 0, y = 0, z = 1}, 2 * math.pi / 5)
assert.True(almost_equal(vector.normalize(vector.cross(v_after6, v_before6)), {x = 0, y = 0, z = 1}))
end)
end)
describe("rotate()", function()
it("rotates", function()
assert.True(almost_equal({x = -1, y = 0, z = 0},
vector.rotate({x = 1, y = 0, z = 0}, {x = 0, y = math.pi, z = 0})))
assert.True(almost_equal({x = 0, y = -1, z = 0},
vector.rotate({x = 1, y = 0, z = 0}, {x = 0, y = 0, z = math.pi / 2})))
assert.True(almost_equal({x = 1, y = 0, z = 0},
vector.rotate({x = 1, y = 0, z = 0}, {x = math.pi / 123, y = 0, z = 0})))
end)
it("is counterclockwise", function()
local v_before1 = {x = 0, y = 1, z = -1}
local v_after1 = vector.rotate(v_before1, {x = math.pi / 4, y = 0, z = 0})
assert.True(almost_equal(vector.normalize(vector.cross(v_after1, v_before1)), {x = 1, y = 0, z = 0}))
local v_before2 = {x = 0, y = 3, z = 4}
local v_after2 = vector.rotate(v_before2, {x = 2 * math.pi / 5, y = 0, z = 0})
assert.True(almost_equal(vector.normalize(vector.cross(v_after2, v_before2)), {x = 1, y = 0, z = 0}))
local v_before3 = {x = 1, y = 0, z = -1}
local v_after3 = vector.rotate(v_before3, {x = 0, y = math.pi / 4, z = 0})
assert.True(almost_equal(vector.normalize(vector.cross(v_after3, v_before3)), {x = 0, y = 1, z = 0}))
local v_before4 = {x = 3, y = 0, z = 4}
local v_after4 = vector.rotate(v_before4, {x = 0, y = 2 * math.pi / 5, z = 0})
assert.True(almost_equal(vector.normalize(vector.cross(v_after4, v_before4)), {x = 0, y = 1, z = 0}))
local v_before5 = {x = 1, y = -1, z = 0}
local v_after5 = vector.rotate(v_before5, {x = 0, y = 0, z = math.pi / 4})
assert.True(almost_equal(vector.normalize(vector.cross(v_after5, v_before5)), {x = 0, y = 0, z = 1}))
local v_before6 = {x = 3, y = 4, z = 0}
local v_after6 = vector.rotate(v_before6, {x = 0, y = 0, z = 2 * math.pi / 5})
assert.True(almost_equal(vector.normalize(vector.cross(v_after6, v_before6)), {x = 0, y = 0, z = 1}))
end)
end)
it("dir_to_rotation()", function()
-- Comparing rotations (pitch, yaw, roll) is hard because of certain ambiguities,
-- e.g. (pi, 0, pi) looks exactly the same as (0, pi, 0)
-- So instead we convert the rotation back to vectors and compare these.
local function forward_at_rot(rot)
return vector.rotate(vector.new(0, 0, 1), rot)
end
local function up_at_rot(rot)
return vector.rotate(vector.new(0, 1, 0), rot)
end
local rot1 = vector.dir_to_rotation({x = 1, y = 0, z = 0}, {x = 0, y = 1, z = 0})
assert.True(almost_equal({x = 1, y = 0, z = 0}, forward_at_rot(rot1)))
assert.True(almost_equal({x = 0, y = 1, z = 0}, up_at_rot(rot1)))
local rot2 = vector.dir_to_rotation({x = 1, y = 1, z = 0}, {x = 0, y = 0, z = 1})
assert.True(almost_equal({x = 1/math.sqrt(2), y = 1/math.sqrt(2), z = 0}, forward_at_rot(rot2)))
assert.True(almost_equal({x = 0, y = 0, z = 1}, up_at_rot(rot2)))
for i = 1, 1000 do
local rand_vec = vector.new(math.random(), math.random(), math.random())
if vector.length(rand_vec) ~= 0 then
local rot_1 = vector.dir_to_rotation(rand_vec)
local rot_2 = {
x = math.atan2(rand_vec.y, math.sqrt(rand_vec.z * rand_vec.z + rand_vec.x * rand_vec.x)),
y = -math.atan2(rand_vec.x, rand_vec.z),
z = 0
}
assert.True(almost_equal(rot_1, rot_2))
end
end
end)
end)
|
CLASS.name = "Medic"
CLASS.faction = FACTION_CITIZEN
CLASS.business = {
-- Heal stuff
["aidkit"] = 10,
["healvial"] = 5,
["healthkit"] = 1
}
function CLASS:OnSet(client)
end
CLASS_COOK = CLASS.index
|
-- видеоскрипт для воспроизведения коллекций из TMDb (23/11/21)
-- открывает подобные ссылки:
-- collection_tmdb=645
-- автор west_side
if m_simpleTV.Control.ChangeAdress ~= 'No' then return end
local inAdr = m_simpleTV.Control.CurrentAdress
if not inAdr then return end
if not inAdr:match('^collection_tmdb=%d+') then return end
m_simpleTV.Control.ChangeAdress = 'Yes'
m_simpleTV.Control.CurrentAdress = ''
local session = m_simpleTV.Http.New('Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.2785.143 Safari/537.36')
if not session then return end
m_simpleTV.Http.SetTimeout(session, 16000)
local function imdb_id(tmdbid)
local urltm = decode64('aHR0cHM6Ly9hcGkudGhlbW92aWVkYi5vcmcvMy9tb3ZpZS8=') .. tmdbid .. decode64('P2FwaV9rZXk9ZDU2ZTUxZmI3N2IwODFhOWNiNTE5MmVhYWE3ODIzYWQmYXBwZW5kX3RvX3Jlc3BvbnNlPXZpZGVvcyZsYW5ndWFnZT1ydQ==')
local rc3,answertm = m_simpleTV.Http.Request(session,{url=urltm})
if rc3~=200 then
m_simpleTV.Http.Close(session)
return ''
end
require('json')
answertm = answertm:gsub('(%[%])', '"nil"')
local tab = json.decode(answertm)
local id = tab.imdb_id or ''
return id
end
local function getadr1(url)
local rc, answer = m_simpleTV.Http.Request(session, {url = url})
if rc ~= 200 then return '' end
require 'playerjs'
local playerjs_url = answer:match('src="([^"]+/playerjsdev[^"]+)')
answer = answer:match("file\'(:.-)return pub")
answer = answer:gsub(": ",''):gsub("'#",'#'):gsub("'\n.-$",'')
answer = playerjs.decode(answer, playerjs_url)
local adr = answer:match('%[1080p%](https://stream%.voidboost%..-%.m3u8)') or answer:match('%[720p%](https://stream%.voidboost%..-%.m3u8)') or answer:match('%[480p%](https://stream%.voidboost%..-%.m3u8)') or answer:match('%[360p%](https://stream%.voidboost%..-%.m3u8)') or answer:match('%[240p%](https://stream%.voidboost%..-%.m3u8)') or ''
return adr
end
local tmdbcolid = inAdr:match('^collection_tmdb=(%d+)')
----------------------
local urlt1 = decode64('aHR0cHM6Ly9hcGkudGhlbW92aWVkYi5vcmcvMy9jb2xsZWN0aW9uLw==') .. tmdbcolid .. decode64('P2FwaV9rZXk9ZDU2ZTUxZmI3N2IwODFhOWNiNTE5MmVhYWE3ODIzYWQmbGFuZ3VhZ2U9cnU=')
local rc, answert1 = m_simpleTV.Http.Request(session, {url = urlt1})
if rc~=200 then
return ''
end
require('json')
answert1 = answert1:gsub('(%[%])', '"nil"')
local tab = json.decode(answert1)
if not tab or not tab.parts or not tab.parts[1] or not tab.parts[1].id or not tab.parts[1].title
then
return '' end
local title = tab.name
local poster = 'http://image.tmdb.org/t/p/w500_and_h282_face' .. tab.poster_path
local t, i, j = {}, 1, 1
while true do
if not tab.parts[j] or not tab.parts[j].id
then
break
end
t[i]={}
local id_media = tab.parts[j].id
if imdb_id(id_media) and imdb_id(id_media) ~= '' and getadr1('https://voidboost.net/embed/' .. imdb_id(id_media)) and getadr1('https://voidboost.net/embed/' .. imdb_id(id_media)) ~= '' then
local rus = tab.parts[j].title or ''
local orig = tab.parts[j].original_title or ''
local year = tab.parts[j].release_date or ''
if year and year~= '' then
year = year:match('%d%d%d%d')
else year = '0' end
local poster
if tab.parts[j].backdrop_path and tab.parts[j].backdrop_path ~= 'null' then
poster = tab.parts[j].backdrop_path
poster = 'http://image.tmdb.org/t/p/w500_and_h282_face' .. poster
elseif tab.parts[j].poster_path and tab.parts[j].poster_path ~= 'null' then
poster = tab.parts[j].poster_path
poster = 'http://image.tmdb.org/t/p/w220_and_h330_face' .. poster
else poster = 'simpleTVImage:./luaScr/user/westSide/icons/no-img.png'
end
local overview = tab.parts[j].overview or ''
t[i].Id = i
t[i].Name = rus .. ' (' .. year .. ')'
t[i].year = year
t[i].InfoPanelLogo = poster
t[i].Address = getadr1('https://voidboost.net/embed/' .. imdb_id(id_media))
t[i].InfoPanelName = rus .. ' / ' .. orig .. ' ' .. year
t[i].InfoPanelTitle = overview
t[i].InfoPanelShowTime = 10000
i=i+1
end
m_simpleTV.OSD.ShowMessageT({text = 'Загрузка коллекции ' .. j
, color = ARGB(255, 155, 255, 155)
, showTime = 1000 * 5
, id = 'channelName'})
j=j+1
end
----------------------
if tonumber(tmdbcolid) == 10 then
table.sort(t, function(a, b) return a.Name < b.Name end)
for i = 1, #t do
t[i].Id = i
end
else
table.sort(t, function(a, b) return tostring(a.year) < tostring(b.year) end)
for i = 1, #t do
t[i].Id = i
end
end
if t[1] and t[1].Address then m_simpleTV.Control.CurrentAddress = t[1].Address end
m_simpleTV.OSD.ShowSelect_UTF8(title, 0, t, 8000, 2 + 64)
m_simpleTV.Control.SetTitle(title)
if m_simpleTV.Control.MainMode == 0 then
m_simpleTV.Control.ChangeChannelLogo(poster, m_simpleTV.Control.ChannelID, 'CHANGE_IF_NOT_EQUAL')
m_simpleTV.Control.ChangeChannelName(title, m_simpleTV.Control.ChannelID, true)
end
m_simpleTV.Control.CurrentTitle_UTF8 = title
m_simpleTV.OSD.ShowMessageT({text = title, color = 0xff9999ff, showTime = 1000 * 5, id = 'channelName'})
----------------------
-- debug_in_file(retAdr .. '\n') |
if not ConVarExists("sv_weapon_holsters") then
CreateConVar("sv_weapon_holsters",1, { FCVAR_REPLICATED, FCVAR_ARCHIVE,FCVAR_SERVER_CAN_EXECUTE }, "Enable Weapon Holsters (server side)" )
end
WepHolster = WepHolster or {}
WepHolster.HL2Weps = {
["weapon_pistol"] = "Pistol",
["weapon_357"] = "357",
["weapon_frag"] = "Frag Grenade",
["weapon_slam"] = "SLAM",
["weapon_crowbar"] = "Crowbar",
["weapon_stunstick"] = "Stunstick",
["weapon_shotgun"] = "Shotgun",
["weapon_rpg"] = "RPG Launcher",
["weapon_smg1"] = "SMG",
["weapon_ar2"] = "AR2",
["weapon_crossbow"] = "Crossbow",
["weapon_physcannon"] = "Gravity Gun",
["weapon_physgun"] = "Physics Gun"
}
|
print('core.utils.http')
_http = {
--
};
--
-- Encodes a character as a percent encoded string
local function char_to_pchar(c)
return string.format("%%%02X", c:byte(1,1))
end
-- encodeURI replaces all characters except the following with the appropriate UTF-8 escape sequences:
-- ; , / ? : @ & = + $
-- alphabetic, decimal digits, - _ . ! ~ * ' ( )
-- #
function _http.encodeURI(str)
return (str:gsub("[^%;%,%/%?%:%@%&%=%+%$%w%-%_%.%!%~%*%'%(%)%#]", char_to_pchar))
end
-- encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
function _http.encodeURIComponent(str)
return (str:gsub("[^%w%-_%.%!%~%*%'%(%)]", char_to_pchar))
end |
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local common = ReplicatedStorage.common
local lib = ReplicatedStorage.lib
local event = ReplicatedStorage.event
local PizzaAlpaca = require(lib.PizzaAlpaca)
local CharacterLightApplier = PizzaAlpaca.GameModule:extend("CharacterLightApplier")
local function addLight(character)
local newLight = Instance.new("PointLight")
newLight.Parent = character:WaitForChild("HumanoidRootPart")
end
local function playerAdded(player)
player.CharacterAdded:connect(addLight)
if player.Character then
addLight(player)
end
end
function CharacterLightApplier:init()
Players.PlayerAdded:Connect(function(player)
playerAdded(player)
end)
for _, player in pairs(Players:GetPlayers()) do
playerAdded(player)
end
end
function CharacterLightApplier:postInit()
end
return CharacterLightApplier |
local ioe = require 'ioe'
local base = require 'app.base'
local serial = require 'serialdriver'
local app = base:subclass("FREEIOE.APP.OTHER.SIM_MP1")
app.static.API_VER = 9
function app:on_init()
self._serial_sent = 0
self._serial_recv = 0
end
function app:on_start()
--- 生成设备唯一序列号
local sys_id = self._sys:id()
local sn = sys_id.."."..self._name
--- 增加设备实例
local inputs = {
{name="serial_sent", desc="Serial sent bytes", vt="int", unit="bytes"},
{name="serial_recv", desc="Serial received bytes", vt="int", unit="bytes"},
}
local meta = self._api:default_meta()
meta.name = "CEMS MP1"
meta.inst = self._name
meta.description = "CEMS MP1 Simulation"
self._dev = self._api:add_device(sn, meta, inputs)
local opt = {
port = '/dev/ttyS2',
baudrate = 9600,
data_bits = 8,
parity = 'NONE',
stop_bits = 1,
flow_control = 'OFF'
}
if ioe.developer_mode() then
opt.port = '/tmp/ttyS2'
end
local port = serial:new(opt.port, opt.baudrate or 9600, opt.data_bits or 8, opt.parity or 'NONE', opt.stop_bits or 1, opt.flow_control or "OFF")
local r, err = port:open()
if not r then
self._log:warning("Failed open port, error: "..err)
return nil, err
end
port:start(function(data, err)
-- Recevied Data here
if data then
self._dev:dump_comm('SERIAL-IN', data)
self._serial_recv = self._serial_recv + string.len(data)
else
self._log:error(err)
end
end)
self._port = port
return true
end
function app:on_run(tms)
if self._port then
data = '##0236ST=31;CN=2011;PW=123456;MN=MP1;CP=&&DataTime=20210129152246;01-Rtd=8.764,01-ZsRtd=14.387;02-Rtd=9.933,02-ZsRtd=16.307;03-Rtd=86.131,03-ZsRtd=141.392;B02-Rtd=6015.213;S01-Rtd=13.893;S02-Rtd=2.491;S03-Rtd=44.586;S05-Rtd=0;S08-Rtd=53.796&&524F\r\n'
self._serial_sent = self._serial_sent + string.len(data)
self._dev:dump_comm('SERIAL-OUT', data)
self._port:write(data)
end
self._dev:set_input_prop('serial_sent', 'value', self._serial_sent)
self._dev:set_input_prop('serial_recv', 'value', self._serial_recv)
return 5000
end
return app
|
return {
id1 = 10,
id2 = 19,
id3 = "ab10",
num = 10,
desc = "desc10",
} |
---
-- update_move_area_canvas_command.lua
local class = require "middleclass"
local BaseCommand = require "frames.gameplay_frame.commands.base_command"
local UpdateMoveAreaCanvasCommand = class("UpdateMoveAreaCanvasCommand", BaseCommand)
function UpdateMoveAreaCanvasCommand:initialize(data)
BaseCommand.initialize(self)
self:check_abstract_methods(UpdateMoveAreaCanvasCommand)
self.move_area_canvas = nil
if not data.logic then
error("UpdateMoveAreaCanvasCommand:initialize(): no data.logic argument!")
end
if not data.view_context then
error("UpdateMoveAreaCanvasCommand:initialize(): no data.view_context argument!")
end
if not data.drawer then
error("UpdateMoveAreaCanvasCommand:initialize(): no data.drawer argument!")
end
self.move_area_canvas = nil
self.logic = data.logic
self.view_context = data.view_context
self.drawer = data.drawer
end
function UpdateMoveAreaCanvasCommand:execute()
if not self.move_area_canvas then
local sixe_x, size_y = self.logic:get_full_map_size()
self.move_area_canvas = love.graphics.newCanvas(sixe_x, size_y)
end
self.move_area_canvas:renderTo(
function ()
love.graphics.clear()
local cells = self.view_context:get_all_moving_area_tiles()
for _, cell in ipairs(cells) do
local tiles = cell:get_tiles()
local pos_x, pos_y = cell:get_position():get()
for _, tile in ipairs(tiles) do
self.drawer:draw_at(tile, pos_x, pos_y)
end
end
end
)
return self.move_area_canvas
end
return UpdateMoveAreaCanvasCommand
|
require "divs"
require "cols"
require "fun"
function _divs(n,s,d)
n = {}
for i = 1,1000 do add(n,r()^2) end
s = Split:new{get=same,maxBins=4}
for i,range in pairs(s:div(n)) do
print(i,range.lo,range.up) end
f= Fun:new()
f:import('data/maxwell.csv')
print(#f.nums)
for _,num in ipairs(f.nums) do
get=function (row) return row.x[num.pos] end
s=Split:new{get=get}:div(f.rows)
print(num.pos,num.name,r3(num.mu)) end
end
_divs()
|
cc.exports.OrderMap = function(...)
local t = {}
function t:push(key, val)
t[#t+1] = {key=key,val=val}
return t
end
function t:pop()
table.remove(t, #t)
return t
end
function t:get(i)
return t[i]
end
local args = {...}
if args and #args >=2 then
for i=1, #args, 2 do
local k,v = args[i], args[i+1]
if k and v then
t:push(k,v)
end
end
end
return t
end
|
local tonumber = tonumber
local gsub = gsub
BuildModule('NetEasePinyin-1.0')
function unchinesefilter(data)
return gsub(data, 'u(%x+)', function(x)
local b = tonumber(x, 16)
return b >= 0x80 and (b < 0x4e00 or b > 0x9fa5) and ''
end)
end
function uncharfilter(data)
return gsub(data, 'u(%x+)', function(x)
local b = tonumber(x, 16)
return b < 0x80 and not (
(b >= 0x30 and b <= 0x39) or
(b >= 0x41 and b <= 0x5a) or
(b >= 0x61 and b <= 0x7a)
) and ''
end)
end
function numberfilter(data)
return gsub(data, 'u(%x+)', function(x)
local b = tonumber(x, 16)
return b >= 0x30 and b <= 0x39 and ''
end)
end
function assicfilter(data)
return gsub(data, 'u(%x+)', function(x)
return tonumber(x, 16) < 0x80 and ''
end)
end |
-- Localize globals
local error, coroutine, modlib, unpack
= error, coroutine, modlib, unpack
-- Set environment
local _ENV = {}
setfenv(1, _ENV)
no_op = function() end
function curry(func, ...)
local args = { ... }
return function(...) return func(unpack(args), ...) end
end
function curry_tail(func, ...)
local args = { ... }
return function(...) return func(unpack(modlib.table.concat({...}, args))) end
end
function curry_full(func, ...)
local args = { ... }
return function() return func(unpack(args)) end
end
function args(...)
local args = { ... }
return function(func) return func(unpack(args)) end
end
function value(val) return function() return val end end
function values(...)
local args = { ... }
return function() return unpack(args) end
end
-- Equivalent to `for x, y, z in iterator, state, ... do callback(x, y, z) end`
function iterate(callback, iterator, state, ...)
local function loop(...)
if ... == nil then return end
callback(...)
return loop(iterator(state, ...))
end
return loop(iterator(state, ...))
end
function for_generator(caller, ...)
local co = coroutine.create(function(...)
return caller(function(...)
return coroutine.yield(...)
end, ...)
end)
local args = {...}
return function()
if coroutine.status(co) == "dead" then
return
end
local function _iterate(status, ...)
if not status then
error((...))
end
return ...
end
return _iterate(coroutine.resume(co, unpack(args)))
end
end
-- Does not use select magic, stops at the first nil value
function aggregate(binary_func, total, ...)
if total == nil then return end
local function _aggregate(value, ...)
if value == nil then return end
total = binary_func(total, value)
return _aggregate(...)
end
_aggregate(...)
return total
end
function override_chain(func, override)
return function(...)
func(...)
return override(...)
end
end
function assert(value, callback)
if not value then
error(callback())
end
end
--+ Calls func using the provided arguments, deepcopies all arguments
function call_by_value(func, ...)
return func(unpack(modlib.table.deepcopy{...}))
end
-- Functional wrappers for Lua's builtin metatable operators (arithmetic, concatenation, length, comparison, indexing, call)
function add(a, b)
return a + b
end
function mul(a, b)
return a * b
end
function div(a, b)
return a / b
end
function mod(a, b)
return a % b
end
function pow(a, b)
return a ^ b
end
function unm(a)
return -a
end
function concat(a, b)
return a .. b
end
function len(a)
return #a
end
function eq(a, b)
return a == b
end
function lt(a, b)
return a < b
end
function le(a, b)
return a <= b
end
function index(object, key)
return object[key]
end
function newindex(object, key, value)
object[key] = value
end
function call(object, ...)
object(...)
end
-- Functional wrappers for logical operators, suffixed with _ to avoid a syntax error
function not_(a)
return not a
end
function and_(a, b)
return a and b
end
function or_(a, b)
return a or b
end
-- Export environment
return _ENV |
-- keymaps
local utils = require('thijssesc.utils')
local nnoremap = utils.keymap.nnoremap
local noremap = utils.keymap.noremap
local tnoremap = utils.keymap.tnoremap
vim.g.mapleader = ' '
-- reload config
nnoremap { '<leader>rr', ':so $MYVIMRC' }
-- stop the search highlighting if enabled. source: tj
nnoremap { '<CR>', [[{-> v:hlsearch ? ':nohl<CR>' : '<CR>'}()]], expr = true }
-- paste from clipboard
nnoremap { '<leader>p', '"+p' }
nnoremap { '<leader>P', '"+P' }
-- copy (file) to clipboard
nnoremap { '<leader>y', '"+y' }
nnoremap { '<leader>Y', 'gg"+yG' }
-- unmap arrow keys
noremap { '<Dowp>', '<Nop>' }
noremap { '<Left>', '<Nop>' }
noremap { '<Right>', '<Nop>' }
noremap { '<Up>', '<Nop>' }
-- auto-center
nnoremap { 'G', 'Gzz' }
nnoremap { 'n', 'nzz' }
nnoremap { 'N', 'Nzz' }
-- sorting
nnoremap { '<leader>so', [[vip:'<,'>sort ui<CR>]] }
-- spell-checking
nnoremap { '<leader>se', ':setlocal spell! spelllang=en_us<CR>' }
nnoremap { '<leader>sn', ':setlocal spell! spelllang=nl_nl<CR>' }
-- switch buffers
nnoremap { '<C-h>', '<C-w>h' }
nnoremap { '<C-j>', '<C-w>j' }
nnoremap { '<C-k>', '<C-w>k' }
nnoremap { '<C-l>', '<C-w>l' }
-- resize splits
nnoremap { '<A-C-h>', ':vertical resize -2<CR>' }
nnoremap { '<A-C-j>', ':resize +2<CR>' }
nnoremap { '<A-C-k>', ':resize -2<CR>' }
nnoremap { '<A-C-l>', ':vertical resize +2<CR>' }
-- easy switching from/into terminal buffers
tnoremap { '<Esc>', [[<C-\><C-n>]] }
tnoremap { '<C-w>', [[<C-\><C-n><C-w>]] }
tnoremap { '<C-h>', [[<C-\><C-n><C-w>h]] }
tnoremap { '<C-j>', [[<C-\><C-n><C-w>j]] }
tnoremap { '<C-k>', [[<C-\><C-n><C-w>k]] }
tnoremap { '<C-l>', [[<C-\><C-n><C-w>l]] }
tnoremap { '<C-d>', [[<C-\><C-n><C-w>:q<CR>]] }
-- I hate this
nnoremap { 'q:', '<Nop>' }
-- cycle through qflist and localtion list
nnoremap { ']q', ':cnext<CR>' }
nnoremap { '[q', ':cprev<CR>' }
nnoremap { ']l', ':lnext<CR>' }
nnoremap { '[l', ':lprev<CR>' }
-- anti-pattern: cycle through buffers
nnoremap { '[b', ':bprev<CR>' }
nnoremap { ']b', ':bnext<CR>' }
|
local lib = {}
local atan2 = require'math'.atan2 or require'math'.atan
local sin = require'math'.sin
local sqrt = require'math'.sqrt
local unpack = unpack or require'table'.unpack
-- Pure Pursuit
local function get_inverse_curvature(pose_rbt, p_lookahead)
local x_rbt, y_rbt, th_rbt = unpack(pose_rbt)
local x_ref, y_ref = unpack(p_lookahead)
-- Lookahead distance
local dx, dy = x_ref - x_rbt, y_ref - y_rbt
local lookahead = sqrt(dx*dx + dy*dy)
-- Relative angle towards the lookahead reference point
local alpha = atan2(y_ref - y_rbt, x_ref - x_rbt)
alpha = alpha - th_rbt
-- kappa is curvature (inverse of the radius of curvature)
local two_sa = 2 * sin(alpha)
local kappa = two_sa / lookahead
local radius_of_curvature = lookahead / two_sa
-- Returns the inverse curvature and radius of curvature
return {
alpha = alpha,
kappa = kappa,
radius_of_curvature = radius_of_curvature,
}
end
lib.get_inverse_curvature = get_inverse_curvature
-- https://en.wikipedia.org/wiki/PID_controller#PID_controller_theory
-- TODO: Orientation...
local function pid(params)
-- Default params have P control with gain of 1
if type(params)~='table' then params = {} end
-- r is the desired value (setpoint)
-- Default drives to zero
local r = tonumber(params.r) or 0
-- Default drives to zero
local r_dot = tonumber(params.r_dot) or 0
-- Default to P control
local Kp = tonumber(params.Kp) or 1
local Ki = tonumber(params.Ki) or 0
local Kd = tonumber(params.Kd) or 0
-- Closure for accumulation of error
local e_last = 0
local e_total = 0
-- Function takes y as the measured value
-- Optionally, take in the measured derivative
local function controller(y, y_dot)
-- Error is difference between setpoint and present value
local e_p = r - y
e_total = e_total + e_p
-- Optionally use the desired change in setpoint derivative
local e_d = y_dot and (r_dot - y_dot) or (e_last - e_p)
e_last = e_p
--
local u_p = Kp * e_p
local u_i = Ki * e_total
local u_d = Kd * e_d
-- Return the control and the error state
local u = u_p + u_i + u_d
return u, e_p, e_total
end
return controller
end
lib.pid = pid
return lib
|
local contract = require('charon.contract')
local test = {}
test.should_erase_table_errors = function()
local model = {}
model.errors = {}
model.errors.total = 'is a total error'
contract.clear(model)
assert( model.errors.total == nil )
end
return test
|
local typedefs = require "kong.db.schema.typedefs"
local plugin = {
PRIORITY = 1000, -- set the plugin priority, which determines plugin execution order
VERSION = "0.1",
}
function plugin:init_worker()
kong.log.err("!!!!!!!!!!!!! TCP init_worker")
dump(typedefs.protocols)
end
function plugin:certificate(plugin_conf)
end
function plugin:rewrite(plugin_conf)
end
function plugin:preread(plugin_conf)
kong.log.inspect(plugin_conf) -- check the logs for a pretty-printed config!
kong.log.err("!!!!!!!!!!!!! TCP preread")
dump(typedefs.protocols)
end
function plugin:access(plugin_conf)
kong.log.inspect(plugin_conf) -- check the logs for a pretty-printed config!
kong.log.err("!!!!!!!!!!!!! TCP access")
dump(typedefs.protocols)
end
function plugin:header_filter(plugin_conf)
end
function plugin:body_filter(plugin_conf)
end
function plugin:log(plugin_conf)
kong.log.err("!!!!!!!!!!!!! TCP log")
end
dump = function(...)
local info = debug.getinfo(2) or {}
local input = { n = select("#", ...), ...}
local write = require("pl.pretty").write
local serialized
if input.n == 1 and type(input[1]) == "table" then
serialized = "(" .. type(input[1]) .. "): " .. write(input[1])
elseif input.n == 1 then
serialized = "(" .. type(input[1]) .. "): " .. tostring(input[1]) .. "\n"
else
local n
n, input.n = input.n, nil
serialized = "(list, #" .. n .. "): " .. write(input)
end
print(ngx.WARN,
"\027[31m\n",
"function '", tostring(info.name), ":" , tostring(info.currentline),
"' in '", tostring(info.short_src), "' wants you to know:\n",
serialized,
"\027[0m")
end
return plugin
|
local queries = require("nvim-treesitter.query")
local M = {}
function M.init()
require("nvim-treesitter").define_modules({
tree_setter = {
-- the file with the "main-code" of the module
module_path = "tree-setter.main",
-- Look if the module supports the current language by looking up,
-- if there's an appropriate query file to it. For example if we're
-- currently editing a C file, then this function looks if there's a
-- "tree-setter/queries/c/tsetter.scm" file.
is_supported = function(lang)
return queries.get_query(lang, 'tsetter') ~= nil
end
}
})
end
return M
|
ModifyEvent(-2, -2, -1, -1, -1, -1, -1, 2468, 2468, 2468, -2, -2, -2);--by fanyu 打开箱子,改变贴图 场景28-18
AddItem(171, 50);
AddItem(186, 2);
AddEthics(-1);
do return end;
|
-- Make tapping Control send Escape, and holding it send Control.
hs.loadSpoon('ControlEscape'):start()
-- Use Control + Space to start a new global modal state with Hammerspoon.
-- The bindings below apply only after the modal state has been started.
modal = hs.hotkey.modal.new('control', 'space', '')
-- Reload Hammerspoon configuration and exit the modal state.
modal:bind('', 'r', nil, function ()
hs.reload()
modal:exit()
end)
-- Resize the focused window to 33% screen width and 100% screen height,
-- anchor it to the left of the screen, and exit the modal state.
modal:bind('', '1', nil, function ()
local window = hs.window.focusedWindow()
local screen = window:screen():frame()
local frame = window:frame()
frame.x = screen.x
frame.y = screen.y
frame.w = screen.w / 3
frame.h = screen.h
window:setFrame(frame, 0)
modal:exit()
end)
-- Resize the focused window to 50% screen width and 100% screen height,
-- anchor it to the left of the screen, and exit the modal state.
modal:bind('', '2', nil, function ()
local window = hs.window.focusedWindow()
local screen = window:screen():frame()
local frame = window:frame()
frame.x = screen.x
frame.y = screen.y
frame.w = screen.w / 2
frame.h = screen.h
window:setFrame(frame, 0)
modal:exit()
end)
-- Resize the focused window to 67% screen width and 100% screen height,
-- anchor it to the left of the screen, and exit the modal state.
modal:bind('', '3', nil, function ()
local window = hs.window.focusedWindow()
local screen = window:screen():frame()
local frame = window:frame()
frame.x = screen.x
frame.y = screen.y
frame.w = screen.w / 3 * 2
frame.h = screen.h
window:setFrame(frame, 0)
modal:exit()
end)
-- Resize the focused window to 67% screen width and 100% screen height,
-- anchor it to the right of the screen, and exit the modal state.
modal:bind('', '8', nil, function ()
local window = hs.window.focusedWindow()
local screen = window:screen():frame()
local frame = window:frame()
frame.x = screen.w / 3
frame.y = screen.y
frame.w = screen.w / 3 * 2
frame.h = screen.h
window:setFrame(frame, 0)
modal:exit()
end)
-- Resize the focused window to 50% screen width and 100% screen height,
-- anchor it to the right of the screen, and exit the modal state.
modal:bind('', '9', nil, function ()
local window = hs.window.focusedWindow()
local screen = window:screen():frame()
local frame = window:frame()
frame.x = screen.w / 2
frame.y = screen.y
frame.w = screen.w / 2
frame.h = screen.h
window:setFrame(frame, 0)
modal:exit()
end)
-- Resize the focused window to 33% screen width and 100% screen height,
-- anchor it to the right of the screen, and exit the modal state.
modal:bind('', '0', nil, function ()
local window = hs.window.focusedWindow()
local screen = window:screen():frame()
local frame = window:frame()
frame.x = screen.w / 3 * 2
frame.y = screen.y
frame.w = screen.w / 3
frame.h = screen.h
window:setFrame(frame, 0)
modal:exit()
end)
-- Resize the focused window to 100% screen width and 100% screen height
-- and exit the modal state.
modal:bind('', 'f', nil, function ()
local window = hs.window.focusedWindow()
local screen = window:screen():frame()
local frame = window:frame()
frame.x = screen.x
frame.y = screen.y
frame.w = screen.w
frame.h = screen.h
window:setFrame(frame, 0)
modal:exit()
end)
-- Resize the focused window to 67% screen width and 100% screen height,
-- center it, and exit the modal state.
modal:bind('', 'j', nil, function ()
local window = hs.window.focusedWindow()
local screen = window:screen():frame()
local frame = window:frame()
frame.x = screen.w / 6
frame.y = screen.y
frame.w = screen.w / 3 * 2
frame.h = screen.h
window:setFrame(frame, 0)
modal:exit()
end)
-- Move the focused window left one display.
modal:bind('', 'h', nil, function ()
local window = hs.window.focusedWindow()
window:moveOneScreenWest(true, true, 0)
modal:exit()
end)
-- Move the focused window right one display.
modal:bind('', 'l', nil, function ()
local window = hs.window.focusedWindow()
window:moveOneScreenEast(true, true, 0)
modal:exit()
end)
-- Exit the modal state.
modal:bind('', 'escape', nil, function ()
modal:exit()
end)
|
-- Copyright 2017-2022 Jason Tackaberry
--
-- 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 t0 = reaper.time_precise()
local rtk = require 'rtk'
local t1 = reaper.time_precise()
local App = require 'app'
function main(basedir)
rtk.call(App, basedir, t0, t1)
end
return main
|
local OrderQueue = require "battlefield2.OrderQueue"
local Entity = require "battlefield2.Entity"
local InputSystem = require "battlefield2.system.Input"
-- 打印表的格式的方法
local function _sprinttb(tb, tabspace, deep)
deep = deep or 0
if deep > 20 then return '...' end
tabspace =tabspace or ''
local str =string.format(tabspace .. '{\n' )
for k,v in pairs(tb or {}) do
if type(v)=='table' then
if type(k)=='string' then
str =str .. string.format("%s%s =\n", tabspace..' ', k)
str =str .. _sprinttb(v, tabspace..' ', deep + 1)
elseif type(k)=='number' then
str =str .. string.format("%s[%d] =\n", tabspace..' ', k)
str =str .. _sprinttb(v, tabspace..' ', deep + 1)
end
else
if type(k)=='string' then
str =str .. string.format("%s%s = %s,\n", tabspace..' ', tostring(k), tostring(v))
elseif type(k)=='number' then
str =str .. string.format("%s[%s] = %s,\n", tabspace..' ', tostring(k), tostring(v))
end
end
end
str =str .. string.format(tabspace .. '},\n' )
return str
end
function sprinttb(tb, tabspace)
local function ss()
return _sprinttb(tb, tabspace);
end
return setmetatable({}, {
__concat = ss,
__tostring = ss,
});
end
local Sync = {NOTIFY = {}}
--[[
local NOTIFY = {
ENTITY_ADD = 'ENTITY_ADD', -- 1,
ENTITY_CHANGE = 'ENTITY_CHANGE', -- 2,
ENTITY_REMOVED = 'ENTITY_REMOVED', -- 3,
UNIT_HURT = 'UNIT_HURT', -- 101,
UNIT_HEALTH = 'UNIT_HEALTH', -- 102,
}
--]]
function Sync.Init(game)
game.inputQueue = OrderQueue();
end
function Sync.Start(game)
end
function Sync.Tick(game)
while game.sync_reader do
local tick, event, data = game.sync_reader(game);
if not tick then
break;
end
-- game:LOG('+', tick, event, data);
game.inputQueue:Append(tick, event, data);
end
while true do
local tick, event, data = game.inputQueue:Pop(game.tick)
if not tick then
break;
end
-- game:LOG('-', tick, event, data);
if Sync.NOTIFY[event] then
Sync.NOTIFY[event](game, data, tick);
end
end
end
function Sync.Stop()
end
local Component = {
Property = require "battlefield2.component.Property",
Skill = require "battlefield2.component.Skill",
Health = require "battlefield2.component.Health",
Force = require "battlefield2.component.Force",
Round = require "battlefield2.component.Round",
GameRound = require "battlefield2.component.Round",
Input = require "battlefield2.component.Input",
Buff = require "battlefield2.component.Buff",
Pet = require "battlefield2.component.Pet",
Bullet = require "battlefield2.component.Bullet",
MagicField = require "battlefield2.component.MagicField",
BuffInventory = require "battlefield2.component.EntityBag",
PetInventory = require "battlefield2.component.EntityBag",
Config = require "battlefield2.component.Config",
Position = require "battlefield2.component.Position",
GlobalData = require "battlefield2.component.GlobalData",
PetHealth = require "battlefield2.component.PetHealth",
ShowNumber = require "battlefield2.component.ShowNumber",
RandomBuff = require "battlefield2.component.RandomBuff",
AutoKill = require "battlefield2.component.AutoKill",
Timeout = require "battlefield2.component.Timeout",
Player = require "battlefield2.component.Player",
SingSkill = require "battlefield2.component.SingSkill",
AutoInput = require "battlefield2.component.AutoInput",
}
function Sync.Decode(data)
local entity = Entity(data[1]);
for _, v in ipairs(data[2] or {}) do
local class = Component[ v[1] ]
if v[1] == "Health" and v[2] then
class = Component['PetHealth'];
end
local comp = nil;
if class then
comp = entity:AddComponent(v[1], class());
else
assert(false, 'unknown component ' .. v[1])
end
if comp and comp.DeSerialize then
comp:DeSerialize(v[2]);
end
end
return entity;
end
function Sync.NOTIFY.ENTITY_ADD(game, data, tick)
game:LOG('Sync.NOTIFY.ENTITY_ADD', tick, sprinttb(data));
-- game.sync_server:DispatchEvent(NOTIFY.ENTITY_ADD, entity:Serialize());
local entity = Sync.Decode(data)
--[[
if entity.Buff then
game:LOG('add buff', entity.uuid);
end
if entity.Input and entity.Property then
game:LOG('add role', entity.uuid);
end
if entity.Bullet then
game:LOG('add bullet', entity.uuid);
end
--]]
game:AddEntity(entity);
end
function Sync.NOTIFY.ENTITY_REMOVED(game, data, tick)
-- game.sync_server:DispatchEvent(NOTIFY.ENTITY_REMOVED, {uuid});
game:LOG('entity removed', data[1]);
game:RemoveEntity(data[1]);
end
function Sync.NOTIFY.ENTITY_CHANGE(game, data, tick)
game:LOG('Sync.NOTIFY.ENTITY_CHANGE', sprinttb(data));
local entity = game:GetEntity(data[1]);
if entity then
entity:ApplyChange(data);
end
game:DispatchEvent('ENTITY_CHANGE', data[1], entity);
end
function Sync.NOTIFY.UNIT_HURT(game, data, tick)
-- game:LOG('UNIT_HURT', data[1], data[2]);
game:DispatchEvent('UNIT_HURT', {uuid = data[1], value = data[2], flag = data[3], name_id = data[4], attacker = data[5], element = data[6], restrict = data[7]});
end
function Sync.NOTIFY.UNIT_HEALTH(game, data, tick)
-- game:LOG('UNIT_HEALTH', data[1], data[2]);
game:DispatchEvent('UNIT_HEALTH', {uuid = data[1], value = data[2], flag = data[3], name_id = data[4], attacker = data[5], element = data[6]});
end
function Sync.NOTIFY.UNIT_CAST_SKILL(game, data, tick)
game:LOG('UNIT_CAST_SKILL', data[1], data[2], data[3])
game:DispatchEvent('UNIT_CAST_SKILL', {uuid = data[1], skill = data[2], target = data[3], skill_type = data[4]});
end
function Sync.NOTIFY.UNIT_SKILL_FINISHED(game, data, tick)
game:LOG('UNIT_SKILL_FINISHED', data[1]);
game:DispatchEvent('UNIT_SKILL_FINISHED', {uuid = data[1]})
end
function Sync.NOTIFY.UNIT_BEFORE_ACTION(game, data)
game:DispatchEvent('UNIT_BEFORE_ACTION', data[1]);
end
function Sync.NOTIFY.UNIT_AFTER_ACTION(game, data)
game:DispatchEvent('UNIT_AFTER_ACTION', data[1]);
end
function Sync.NOTIFY.UNIT_PREPARE_ACTION(game, data)
game:DispatchEvent('UNIT_PREPARE_ACTION', data[1]);
end
function Sync.NOTIFY.WAVE_ALL_ENTER(game)
game:DispatchEvent('WAVE_ALL_ENTER');
end
function Sync.NOTIFY.ROUND_START(game)
game:DispatchEvent('ROUND_START');
end
function Sync.NOTIFY.WAVE_START(game)
game:DispatchEvent('WAVE_START');
end
function Sync.NOTIFY.WAVE_FINISHED(game)
game:DispatchEvent('WAVE_FINISHED');
end
function Sync.NOTIFY.UNIT_PLAY_ACTION(game, data)
game:DispatchEvent("UNIT_PLAY_ACTION", data[1], data[2]);
end
function Sync.NOTIFY.FIGHT_FINISHED(game, data)
game.round_info.final_winner = data[1];
game:DispatchEvent("FIGHT_FINISHED", data[1]);
end
function Sync.NOTIFY.UNIT_SHOW_NUMBER(game, data)
game:DispatchEvent("UNIT_SHOW_NUMBER", {uuid = data[1], value = data[2], type = data[3], name = data[4]});
end
function Sync.NOTIFY.ADD_BATTLE_DIALOG(game, data)
game:DispatchEvent("ADD_BATTLE_DIALOG", {dialog_id = data[1]});
end
function Sync.NOTIFY.PALY_BATTLE_GUIDE(game, data)
game:DispatchEvent("PALY_BATTLE_GUIDE", {id = data[1]});
end
function Sync.NOTIFY.SHOW_ERROR_INFO(game, data)
game:DispatchEvent("SHOW_ERROR_INFO", {id = data[1]});
end
function Sync.NOTIFY.SKILL_CHANGE_ID(game, data)
game:DispatchEvent("SKILL_CHANGE_ID", data[1], data[2], data[3]);
end
function Sync.NOTIFY.SHOW_BUFF_EFFECT(game, data)
game:DispatchEvent("SHOW_BUFF_EFFECT", data[1], data[2], data[3], data[4]);
end
function Sync.NOTIFY.SYNC(game, data)
game.tick = data[1]
for _, v in ipairs(data[2]) do
Sync.NOTIFY.ENTITY_ADD(game, data)
end
end
function Sync.SetReader(game, reader)
game.sync_reader = reader
end
return Sync;
|
local constants = {}
constants.default_colors = {
tape_background_color = "#000000cc",
tape_border_color = "#cc",
tape_label_color = "#cc",
tape_line_color_1 = "#66",
tape_line_color_2 = "#66cc66",
tape_line_color_3 = "#cc6666",
tape_line_color_4 = "#cccc66"
}
constants.divisor_labels = {
subgrid = "Grid size:",
split = "# of splits:"
}
constants.divisor_minimums = {
subgrid = 2,
split = 2
}
constants.modes = {
subgrid = "subgrid",
split = "split"
}
-- TEMPORARY - item labels don't support localised strings
constants.mode_labels = {
subgrid = "Subgrid",
split = "Split"
}
constants.setting_names = {
["tl-log-selection-area"] = "log_selection_area",
["tl-draw-tape-on-ground"] = "draw_tape_on_ground",
["tl-tape-line-width"] = "tape_line_width",
["tl-tape-clear-delay"] = "tape_clear_delay",
["tl-tape-background-color"] = "tape_background_color",
["tl-tape-border-color"] = "tape_border_color",
["tl-tape-label-color"] = "tape_label_color",
["tl-tape-line-color-1"] = "tape_line_color_1",
["tl-tape-line-color-2"] = "tape_line_color_2",
["tl-tape-line-color-3"] = "tape_line_color_3",
["tl-tape-line-color-4"] = "tape_line_color_4"
}
return constants
|
return LoadActor(THEME:GetPathB("_option child","underlay"),"SystemDirection"); |
function Achmed_OnCombat(Unit, Event)
Unit:SendChatMessage(14, 0, "You no take kebab!")
Unit:RegisterEvent("Achmed_Enrage", 1000, 0)
Unit:RegisterEvent("Achmed_Chill", 28000, 0)
Unit:RegisterEvent("Achmed_Waterspite", 32000, 0)
Unit:RegisterEvent("Achmed_Blastwave", 25000, 0)
Unit:PlaySoundToSet(12491)
end
function Achmed_Chill(Unit, Event)
Unit:FullCastSpellOnTarget(29290, Unit:GetRandomPlayer(0))
Unit:SendChatMessage(14, 0, "Here, taste some of my Cat kebab!")
end
function Achmed_Blastwave(Unit, Event)
Unit:CastSpell(36278)
Unit:SendChatMessage(14, 0, "Feel the power of the kebab!")
end
function Achmed_Waterspite(Unit, Event)
Unit:FullCastSpellOnTarget(35008, Unit:GetRandomPlayer(0))
Unit:SendChatMessage(14, 0, "Here try some of my special made garlic dressing")
end
function Achmed_Enrage(Unit, Event)
if Unit:GetHealthPct() < 50 then
Unit:RemoveEvents();
Unit:SendChatMessage(14, 0, "You really did it now. feel the anger of the kebab!")
Unit:CastSpell(44779)
Unit:FullCastSpellOnTarget(15283, Unit:GetRandomPlayer(0))
end
end
function Achmed_OnDied(Unit, Event)
Unit:RemoveEvents()
Unit:SendChatMessage(12, 0, "NOO! The kebab must be..delivered..")
end
function Achmed_OnKilledTarget(Unit, Event)
Unit:SendChatMessage(14, 0, "A kebab here, a kebab there..")
end
RegisterUnitEvent(8999233, 1, "Achmed_OnCombat")
RegisterUnitEvent(8999233, 3, "Achmed_OnKilledTarget")
RegisterUnitEvent(8999233, 4, "Achmed_OnDied") |
print("X-Vest Made by Xerxes468893#0001 / Peter Greek") -- dont remove please
RegisterCommand("vest", function(source, args, raw)
local player = source
if (player > 0) then
local version = args[1]
TriggerClientEvent("ARPF:vest", source, version)
CancelEvent()
end
end, false)
RegisterCommand("removevest", function(source, args, raw)
local player = source
if (player > 0) then
TriggerClientEvent("ARPF:vestoff", source)
CancelEvent()
end
end, false)
|
CodexDB["zones"]["enUS"]={
[1]="Dun Morogh",
[2]="Longshore",
[3]="Badlands",
[4]="Blasted Lands",
[7]="Blackwater Cove",
[8]="Swamp of Sorrows",
[9]="Northshire Valley",
[10]="Duskwood",
[11]="Wetlands",
[12]="Elwynn Forest",
[13]="The World Tree",
[14]="Durotar",
[15]="Dustwallow Marsh",
[16]="Azshara",
[17]="The Barrens",
[18]="Crystal Lake",
[19]="Zul\'Gurub",
[20]="Moonbrook",
[21]="Kul Tiras",
[22]="Programmer Isle",
[23]="Northshire River",
[24]="Northshire Abbey",
[25]="Blackrock Mountain",
[26]="Lighthouse",
[28]="Western Plaguelands",
[30]="Nine",
[32]="The Cemetary",
[33]="Stranglethorn Vale",
[34]="Echo Ridge Mine",
[35]="Booty Bay",
[36]="Alterac Mountains",
[37]="Lake Nazferiti",
[38]="Loch Modan",
[40]="Westfall",
[41]="Deadwind Pass",
[42]="Darkshire",
[43]="Wild Shore",
[44]="Redridge Mountains",
[45]="Arathi Highlands",
[46]="Burning Steppes",
[47]="The Hinterlands",
[49]="Dead Man\'s Hole",
[51]="Searing Gorge",
[53]="Thieves Camp",
[54]="Jasperlode Mine",
[55]="Valley of Heroes UNUSED",
[56]="Heroes\' Vigil",
[57]="Fargodeep Mine",
[59]="Northshire Vineyards",
[60]="Forest\'s Edge",
[61]="Thunder Falls",
[62]="Brackwell Pumpkin Patch",
[63]="The Stonefield Farm",
[64]="The Maclure Vineyards",
[65]="***On Map Dungeon***",
[66]="***On Map Dungeon***",
[67]="***On Map Dungeon***",
[68]="Lake Everstill",
[69]="Lakeshire",
[70]="Stonewatch",
[71]="Stonewatch Falls",
[72]="The Dark Portal",
[73]="The Tainted Scar",
[74]="Pool of Tears",
[75]="Stonard",
[76]="Fallow Sanctuary",
[77]="Anvilmar",
[80]="Stormwind Mountains",
[81]="Jeff NE Quadrant Changed",
[82]="Jeff NW Quadrant",
[83]="Jeff SE Quadrant",
[84]="Jeff SW Quadrant",
[85]="Tirisfal Glades",
[86]="Stone Cairn Lake",
[87]="Goldshire",
[88]="Eastvale Logging Camp",
[89]="Mirror Lake Orchard",
[91]="Tower of Azora",
[92]="Mirror Lake",
[93]="Vul\'Gol Ogre Mound",
[94]="Raven Hill",
[95]="Redridge Canyons",
[96]="Tower of Ilgalar",
[97]="Alther\'s Mill",
[98]="Rethban Caverns",
[99]="Rebel Camp",
[100]="Nesingwary\'s Expedition",
[101]="Kurzen\'s Compound",
[102]="Ruins of Zul\'Kunda",
[103]="Ruins of Zul\'Mamwe",
[104]="The Vile Reef",
[105]="Mosh\'Ogg Ogre Mound",
[106]="The Stockpile",
[107]="Saldean\'s Farm",
[108]="Sentinel Hill",
[109]="Furlbrow\'s Pumpkin Farm",
[111]="Jangolode Mine",
[113]="Gold Coast Quarry",
[115]="Westfall Lighthouse",
[116]="Misty Valley",
[117]="Grom\'gol Base Camp",
[118]="Whelgar\'s Excavation Site",
[120]="Westbrook Garrison",
[121]="Tranquil Gardens Cemetery",
[122]="Zuuldaia Ruins",
[123]="Bal\'lal Ruins",
[125]="Kal\'ai Ruins",
[126]="Tkashi Ruins",
[127]="Balia\'mah Ruins",
[128]="Ziata\'jai Ruins",
[129]="Mizjah Ruins",
[130]="Silverpine Forest",
[131]="Kharanos",
[132]="Coldridge Valley",
[133]="Gnomeregan",
[134]="Gol\'Bolar Quarry",
[135]="Frostmane Hold",
[136]="The Grizzled Den",
[137]="Brewnall Village",
[138]="Misty Pine Refuge",
[139]="Eastern Plaguelands",
[141]="Teldrassil",
[142]="Ironband\'s Excavation Site",
[143]="Mo\'grosh Stronghold",
[144]="Thelsamar",
[145]="Algaz Gate",
[146]="Stonewrought Dam",
[147]="The Farstrider Lodge",
[148]="Darkshore",
[149]="Silver Stream Mine",
[150]="Menethil Harbor",
[151]="Designer Island",
[152]="The Bulwark",
[153]="Ruins of Lordaeron",
[154]="Deathknell",
[155]="Night Web\'s Hollow",
[156]="Solliden Farmstead",
[157]="Agamand Mills",
[158]="Agamand Family Crypt",
[159]="Brill",
[160]="Whispering Gardens",
[161]="Terrace of Repose",
[162]="Brightwater Lake",
[163]="Gunther\'s Retreat",
[164]="Garren\'s Haunt",
[165]="Balnir Farmstead",
[166]="Cold Hearth Manor",
[167]="Crusader Outpost",
[168]="The North Coast",
[169]="Whispering Shore",
[170]="Lordamere Lake",
[172]="Fenris Isle",
[173]="Faol\'s Rest",
[186]="Dolanaar",
[187]="Darnassus UNUSED",
[188]="Shadowglen",
[189]="Steelgrill\'s Depot",
[190]="Hearthglen",
[192]="Northridge Lumber Camp",
[193]="Ruins of Andorhal",
[195]="School of Necromancy",
[196]="Uther\'s Tomb",
[197]="Sorrow Hill",
[198]="The Weeping Cave",
[199]="Felstone Field",
[200]="Dalson\'s Tears",
[201]="Gahrron\'s Withering",
[202]="The Writhing Haunt",
[203]="Mardenholde Keep",
[204]="Pyrewood Village",
[205]="Dun Modr",
[206]="Westfall",
[207]="The Great Sea",
[208]="Unused Ironcladcove",
[209]="Shadowfang Keep",
[210]="***On Map Dungeon***",
[211]="Iceflow Lake",
[212]="Helm\'s Bed Lake",
[213]="Deep Elem Mine",
[214]="The Great Sea",
[215]="Mulgore",
[219]="Alexston Farmstead",
[220]="Red Cloud Mesa",
[221]="Camp Narache",
[222]="Bloodhoof Village",
[223]="Stonebull Lake",
[224]="Ravaged Caravan",
[225]="Red Rocks",
[226]="The Skittering Dark",
[227]="Valgan\'s Field",
[228]="The Sepulcher",
[229]="Olsen\'s Farthing",
[230]="The Greymane Wall",
[231]="Beren\'s Peril",
[232]="The Dawning Isles",
[233]="Ambermill",
[235]="Fenris Keep",
[236]="Shadowfang Keep",
[237]="The Decrepit Ferry",
[238]="Malden\'s Orchard",
[239]="The Ivar Patch",
[240]="The Dead Field",
[241]="The Rotting Orchard",
[242]="Brightwood Grove",
[243]="Forlorn Rowe",
[244]="The Whipple Estate",
[245]="The Yorgen Farmstead",
[246]="The Cauldron",
[247]="Grimesilt Dig Site",
[249]="Dreadmaul Rock",
[250]="Ruins of Thaurissan",
[251]="Flame Crest",
[252]="Blackrock Stronghold",
[253]="The Pillar of Ash",
[254]="Blackrock Mountain",
[255]="Altar of Storms",
[256]="Aldrassil",
[257]="Shadowthread Cave",
[258]="Fel Rock",
[259]="Lake Al\'Ameth",
[260]="Starbreeze Village",
[261]="Gnarlpine Hold",
[262]="Ban\'ethil Barrow Den",
[263]="The Cleft",
[264]="The Oracle Glade",
[265]="Wellspring River",
[266]="Wellspring Lake",
[267]="Hillsbrad Foothills",
[268]="Azshara Crater",
[269]="Dun Algaz",
[271]="Southshore",
[272]="Tarren Mill",
[275]="Durnholde Keep",
[276]="UNUSED Stonewrought Pass",
[277]="The Foothill Caverns",
[278]="Lordamere Internment Camp",
[279]="Dalaran",
[280]="Strahnbrad",
[281]="Ruins of Alterac",
[282]="Crushridge Hold",
[283]="Slaughter Hollow",
[284]="The Uplands",
[285]="Southpoint Tower",
[286]="Hillsbrad Fields",
[287]="Hillsbrad",
[288]="Azurelode Mine",
[289]="Nethander Stead",
[290]="Dun Garok",
[293]="Thoradin\'s Wall",
[294]="Eastern Strand",
[295]="Western Strand",
[296]="South Seas UNUSED",
[297]="Jaguero Isle",
[298]="Baradin Bay",
[299]="Menethil Bay",
[300]="Misty Reed Strand",
[301]="The Savage Coast",
[302]="The Crystal Shore",
[303]="Shell Beach",
[305]="North Tide\'s Run",
[306]="South Tide\'s Run",
[307]="The Overlook Cliffs",
[308]="The Forbidding Sea",
[309]="Ironbeard\'s Tomb",
[310]="Crystalvein Mine",
[311]="Ruins of Aboraz",
[312]="Janeiro\'s Point",
[313]="Northfold Manor",
[314]="Go\'Shek Farm",
[315]="Dabyrie\'s Farmstead",
[316]="Boulderfist Hall",
[317]="Witherbark Village",
[318]="Drywhisker Gorge",
[320]="Refuge Pointe",
[321]="Hammerfall",
[322]="Blackwater Shipwrecks",
[323]="O\'Breen\'s Camp",
[324]="Stromgarde Keep",
[325]="The Tower of Arathor",
[326]="The Sanctum",
[327]="Faldir\'s Cove",
[328]="The Drowned Reef",
[330]="Thandol Span",
[331]="Ashenvale",
[332]="The Great Sea",
[333]="Circle of East Binding",
[334]="Circle of West Binding",
[335]="Circle of Inner Binding",
[336]="Circle of Outer Binding",
[337]="Apocryphan\'s Rest",
[338]="Angor Fortress",
[339]="Lethlor Ravine",
[340]="Kargath",
[341]="Camp Kosh",
[342]="Camp Boff",
[343]="Camp Wurg",
[344]="Camp Cagg",
[345]="Agmond\'s End",
[346]="Hammertoe\'s Digsite",
[347]="Dustbelch Grotto",
[348]="Aerie Peak",
[349]="Wildhammer Keep",
[350]="Quel\'Danil Lodge",
[351]="Skulk Rock",
[352]="Zun\'watha",
[353]="Shadra\'Alor",
[354]="Jintha\'Alor",
[355]="The Altar of Zul",
[356]="Seradane",
[357]="Feralas",
[358]="Brambleblade Ravine",
[359]="Bael Modan",
[360]="The Venture Co. Mine",
[361]="Felwood",
[362]="Razor Hill",
[363]="Valley of Trials",
[364]="The Den",
[365]="Burning Blade Coven",
[366]="Kolkar Crag",
[367]="Sen\'jin Village",
[368]="Echo Isles",
[369]="Thunder Ridge",
[370]="Drygulch Ravine",
[371]="Dustwind Cave",
[372]="Tiragarde Keep",
[373]="Scuttle Coast",
[374]="Bladefist Bay",
[375]="Deadeye Shore",
[377]="Southfury River",
[378]="Camp Taurajo",
[379]="Far Watch Post",
[380]="The Crossroads",
[381]="Boulder Lode Mine",
[382]="The Sludge Fen",
[383]="The Dry Hills",
[384]="Dreadmist Peak",
[385]="Northwatch Hold",
[386]="The Forgotten Pools",
[387]="Lushwater Oasis",
[388]="The Stagnant Oasis",
[390]="Field of Giants",
[391]="The Merchant Coast",
[392]="Ratchet",
[393]="Darkspear Strand",
[394]="Darrowmere Lake UNUSED",
[395]="Caer Darrow UNUSED",
[396]="Winterhoof Water Well",
[397]="Thunderhorn Water Well",
[398]="Wildmane Water Well",
[399]="Skyline Ridge",
[400]="Thousand Needles",
[401]="The Tidus Stair",
[403]="Shady Rest Inn",
[404]="Bael\'dun Digsite",
[405]="Desolace",
[406]="Stonetalon Mountains",
[407]="Orgrimmar UNUSED",
[408]="Gillijim\'s Isle",
[409]="Island of Doctor Lapidis",
[410]="Razorwind Canyon",
[411]="Bathran\'s Haunt",
[412]="The Ruins of Ordil\'Aran",
[413]="Maestra\'s Post",
[414]="The Zoram Strand",
[415]="Astranaar",
[416]="The Shrine of Aessina",
[417]="Fire Scar Shrine",
[418]="The Ruins of Stardust",
[419]="The Howling Vale",
[420]="Silverwind Refuge",
[421]="Mystral Lake",
[422]="Fallen Sky Lake",
[424]="Iris Lake",
[425]="Moonwell",
[426]="Raynewood Retreat",
[427]="The Shady Nook",
[428]="Night Run",
[429]="Xavian",
[430]="Satyrnaar",
[431]="Splintertree Post",
[432]="The Dor\'Danil Barrow Den",
[433]="Falfarren River",
[434]="Felfire Hill",
[435]="Demon Fall Canyon",
[436]="Demon Fall Ridge",
[437]="Warsong Lumber Camp",
[438]="Bough Shadow",
[439]="The Shimmering Flats",
[440]="Tanaris",
[441]="Lake Falathim",
[442]="Auberdine",
[443]="Ruins of Mathystra",
[444]="Tower of Althalaxx",
[445]="Cliffspring Falls",
[446]="Bashal\'Aran",
[447]="Ameth\'Aran",
[448]="Grove of the Ancients",
[449]="The Master\'s Glaive",
[450]="Remtravel\'s Excavation",
[452]="Mist\'s Edge",
[453]="The Long Wash",
[454]="Wildbend River",
[455]="Blackwood Den",
[456]="Cliffspring River",
[457]="The Veiled Sea",
[458]="Gold Road",
[459]="Scarlet Watch Post",
[460]="Sun Rock Retreat",
[461]="Windshear Crag",
[463]="Cragpool Lake",
[464]="Mirkfallon Lake",
[465]="The Charred Vale",
[466]="Valley of the Bloodfuries",
[467]="Stonetalon Peak",
[468]="The Talon Den",
[469]="Greatwood Vale",
[470]="Thunder Bluff UNUSED",
[471]="Brave Wind Mesa",
[472]="Fire Stone Mesa",
[473]="Mantle Rock",
[474]="Hunter Rise UNUSED",
[475]="Spirit RiseUNUSED",
[476]="Elder RiseUNUSED",
[477]="Ruins of Jubuwal",
[478]="Pools of Arlithrien",
[479]="The Rustmaul Dig Site",
[480]="Camp E\'thok",
[481]="Splithoof Crag",
[482]="Highperch",
[483]="The Screeching Canyon",
[484]="Freewind Post",
[485]="The Great Lift",
[486]="Galak Hold",
[487]="Roguefeather Den",
[488]="The Weathered Nook",
[489]="Thalanaar",
[490]="Un\'Goro Crater",
[491]="Razorfen Kraul",
[492]="Raven Hill Cemetery",
[493]="Moonglade",
[495]="DELETE ME",
[496]="Brackenwall Village",
[497]="Swamplight Manor",
[498]="Bloodfen Burrow",
[499]="Darkmist Cavern",
[500]="Moggle Point",
[501]="Beezil\'s Wreck",
[502]="Witch Hill",
[503]="Sentry Point",
[504]="North Point Tower",
[505]="West Point Tower",
[506]="Lost Point",
[507]="Bluefen",
[508]="Stonemaul Ruins",
[509]="The Den of Flame",
[510]="The Dragonmurk",
[511]="Wyrmbog",
[512]="Onyxia\'s Lair UNUSED",
[513]="Theramore Isle",
[514]="Foothold Citadel",
[515]="Ironclad Prison",
[516]="Dustwallow Bay",
[517]="Tidefury Cove",
[518]="Dreadmurk Shore",
[536]="Addle\'s Stead",
[537]="Fire Plume Ridge",
[538]="Lakkari Tar Pits",
[539]="Terror Run",
[540]="The Slithering Scar",
[541]="Marshal\'s Refuge",
[542]="Fungal Rock",
[543]="Golakka Hot Springs",
[556]="The Loch",
[576]="Beggar\'s Haunt",
[596]="Kodo Graveyard",
[597]="Ghost Walker Post",
[598]="Sar\'theris Strand",
[599]="Thunder Axe Fortress",
[600]="Bolgan\'s Hole",
[602]="Mannoroc Coven",
[603]="Sargeron",
[604]="Magram Village",
[606]="Gelkis Village",
[607]="Valley of Spears",
[608]="Nijel\'s Point",
[609]="Kolkar Village",
[616]="Hyjal",
[618]="Winterspring",
[636]="Blackwolf River",
[637]="Kodo Rock",
[638]="Hidden Path",
[639]="Spirit Rock",
[640]="Shrine of the Dormant Flame",
[656]="Lake Elune\'ara",
[657]="The Harborage",
[676]="Outland",
[696]="Craftsmen\'s Terrace UNUSED",
[697]="Tradesmen\'s Terrace UNUSED",
[698]="The Temple Gardens UNUSED",
[699]="Temple of Elune UNUSED",
[700]="Cenarion Enclave UNUSED",
[701]="Warrior\'s Terrace UNUSED",
[702]="Rut\'theran Village",
[716]="Ironband\'s Compound",
[717]="The Stockade",
[718]="Wailing Caverns",
[719]="Blackfathom Deeps",
[720]="Fray Island",
[721]="Gnomeregan",
[722]="Razorfen Downs",
[736]="Ban\'ethil Hollow",
[796]="Scarlet Monastery",
[797]="Jerod\'s Landing",
[798]="Ridgepoint Tower",
[799]="The Darkened Bank",
[800]="Coldridge Pass",
[801]="Chill Breeze Valley",
[802]="Shimmer Ridge",
[803]="Amberstill Ranch",
[804]="The Tundrid Hills",
[805]="South Gate Pass",
[806]="South Gate Outpost",
[807]="North Gate Pass",
[808]="North Gate Outpost",
[809]="Gates of Ironforge",
[810]="Stillwater Pond",
[811]="Nightmare Vale",
[812]="Venomweb Vale",
[813]="The Bulwark",
[814]="Southfury River",
[815]="Southfury River",
[816]="Razormane Grounds",
[817]="Skull Rock",
[818]="Palemane Rock",
[819]="Windfury Ridge",
[820]="The Golden Plains",
[821]="The Rolling Plains",
[836]="Dun Algaz",
[837]="Dun Algaz",
[838]="North Gate Pass",
[839]="South Gate Pass",
[856]="Twilight Grove",
[876]="GM Island",
[877]="Delete ME",
[878]="Southfury River",
[879]="Southfury River",
[880]="Thandol Span",
[881]="Thandol Span",
[896]="Purgation Isle",
[916]="The Jansen Stead",
[917]="The Dead Acre",
[918]="The Molsen Farm",
[919]="Stendel\'s Pond",
[920]="The Dagger Hills",
[921]="Demont\'s Place",
[922]="The Dust Plains",
[923]="Stonesplinter Valley",
[924]="Valley of Kings",
[925]="Algaz Station",
[926]="Bucklebree Farm",
[927]="The Shining Strand",
[928]="North Tide\'s Hollow",
[936]="Grizzlepaw Ridge",
[956]="The Verdant Fields",
[976]="Gadgetzan",
[977]="Steamwheedle Port",
[978]="Zul\'Farrak",
[979]="Sandsorrow Watch",
[980]="Thistleshrub Valley",
[981]="The Gaping Chasm",
[982]="The Noxious Lair",
[983]="Dunemaul Compound",
[984]="Eastmoon Ruins",
[985]="Waterspring Field",
[986]="Zalashji\'s Den",
[987]="Land\'s End Beach",
[988]="Wavestrider Beach",
[989]="Uldum",
[990]="Valley of the Watchers",
[991]="Gunstan\'s Post",
[992]="Southmoon Ruins",
[996]="Render\'s Camp",
[997]="Render\'s Valley",
[998]="Render\'s Rock",
[999]="Stonewatch Tower",
[1000]="Galardell Valley",
[1001]="Lakeridge Highway",
[1002]="Three Corners",
[1016]="Direforge Hill",
[1017]="Raptor Ridge",
[1018]="Black Channel Marsh",
[1019]="The Green Belt",
[1020]="Mosshide Fen",
[1021]="Thelgen Rock",
[1022]="Bluegill Marsh",
[1023]="Saltspray Glen",
[1024]="Sundown Marsh",
[1025]="The Green Belt",
[1036]="Angerfang Encampment",
[1037]="Grim Batol",
[1038]="Dragonmaw Gates",
[1039]="The Lost Fleet",
[1056]="Darrow Hill",
[1057]="Thoradin\'s Wall",
[1076]="Webwinder Path",
[1097]="The Hushed Bank",
[1098]="Manor Mistmantle",
[1099]="Camp Mojache",
[1100]="Grimtotem Compound",
[1101]="The Writhing Deep",
[1102]="Wildwind Lake",
[1103]="Gordunni Outpost",
[1104]="Mok\'Gordun",
[1105]="Feral Scar Vale",
[1106]="Frayfeather Highlands",
[1107]="Idlewind Lake",
[1108]="The Forgotten Coast",
[1109]="East Pillar",
[1110]="West Pillar",
[1111]="Dream Bough",
[1112]="Jademir Lake",
[1113]="Oneiros",
[1114]="Ruins of Ravenwind",
[1115]="Rage Scar Hold",
[1116]="Feathermoon Stronghold",
[1117]="Ruins of Solarsal",
[1118]="Lower Wilds UNUSED",
[1119]="The Twin Colossals",
[1120]="Sardor Isle",
[1121]="Isle of Dread",
[1136]="High Wilderness",
[1137]="Lower Wilds",
[1156]="Southern Barrens",
[1157]="Southern Gold Road",
[1176]="Zul\'Farrak",
[1196]="UNUSEDAlcaz Island",
[1216]="Timbermaw Hold",
[1217]="Vanndir Encampment",
[1218]="TESTAzshara",
[1219]="Legash Encampment",
[1220]="Thalassian Base Camp",
[1221]="Ruins of Eldarath ",
[1222]="Hetaera\'s Clutch",
[1223]="Temple of Zin-Malor",
[1224]="Bear\'s Head",
[1225]="Ursolan",
[1226]="Temple of Arkkoran",
[1227]="Bay of Storms",
[1228]="The Shattered Strand",
[1229]="Tower of Eldara",
[1230]="Jagged Reef",
[1231]="Southridge Beach",
[1232]="Ravencrest Monument",
[1233]="Forlorn Ridge",
[1234]="Lake Mennar",
[1235]="Shadowsong Shrine",
[1236]="Haldarr Encampment",
[1237]="Valormok",
[1256]="The Ruined Reaches",
[1276]="The Talondeep Path",
[1277]="The Talondeep Path",
[1296]="Rocktusk Farm",
[1297]="Jaggedswine Farm",
[1316]="Razorfen Downs",
[1336]="Lost Rigger Cove",
[1337]="Uldaman",
[1338]="Lordamere Lake",
[1339]="Lordamere Lake",
[1357]="Gallows\' Corner",
[1377]="Silithus",
[1397]="Emerald Forest",
[1417]="Sunken Temple",
[1437]="Dreadmaul Hold",
[1438]="Nethergarde Keep",
[1439]="Dreadmaul Post",
[1440]="Serpent\'s Coil",
[1441]="Altar of Storms",
[1442]="Firewatch Ridge",
[1443]="The Slag Pit",
[1444]="The Sea of Cinders",
[1445]="Blackrock Mountain",
[1446]="Thorium Point",
[1457]="Garrison Armory",
[1477]="The Temple of Atal\'Hakkar",
[1497]="Undercity",
[1517]="Uldaman",
[1518]="Not Used Deadmines",
[1519]="Stormwind City",
[1537]="Ironforge",
[1557]="Splithoof Hold",
[1577]="The Cape of Stranglethorn",
[1578]="Southern Savage Coast",
[1579]="Unused The Deadmines 002",
[1580]="Unused Ironclad Cove 003",
[1581]="The Deadmines",
[1582]="Ironclad Cove",
[1583]="Blackrock Spire",
[1584]="Blackrock Depths",
[1597]="Raptor Grounds UNUSED",
[1598]="Grol\'dom Farm UNUSED",
[1599]="Mor\'shan Base Camp",
[1600]="Honor\'s Stand UNUSED",
[1601]="Blackthorn Ridge UNUSED",
[1602]="Bramblescar UNUSED",
[1603]="Agama\'gor UNUSED",
[1617]="Valley of Heroes",
[1637]="Orgrimmar",
[1638]="Thunder Bluff",
[1639]="Elder Rise",
[1640]="Spirit Rise",
[1641]="Hunter Rise",
[1657]="Darnassus",
[1658]="Cenarion Enclave",
[1659]="Craftsmen\'s Terrace",
[1660]="Warrior\'s Terrace",
[1661]="The Temple Gardens",
[1662]="Tradesmen\'s Terrace",
[1677]="Gavin\'s Naze",
[1678]="Sofera\'s Naze",
[1679]="Corrahn\'s Dagger",
[1680]="The Headland",
[1681]="Misty Shore",
[1682]="Dandred\'s Fold",
[1683]="Growless Cave",
[1684]="Chillwind Point",
[1697]="Raptor Grounds",
[1698]="Bramblescar",
[1699]="Thorn Hill",
[1700]="Agama\'gor",
[1701]="Blackthorn Ridge",
[1702]="Honor\'s Stand",
[1703]="The Mor\'shan Rampart",
[1704]="Grol\'dom Farm",
[1717]="Razorfen Kraul",
[1718]="The Great Lift",
[1737]="Mistvale Valley",
[1738]="Nek\'mani Wellspring",
[1739]="Bloodsail Compound",
[1740]="Venture Co. Base Camp",
[1741]="Gurubashi Arena",
[1742]="Spirit Den",
[1757]="The Crimson Veil",
[1758]="The Riptide",
[1759]="The Damsel\'s Luck",
[1760]="Venture Co. Operations Center",
[1761]="Deadwood Village",
[1762]="Felpaw Village",
[1763]="Jaedenar",
[1764]="Bloodvenom River",
[1765]="Bloodvenom Falls",
[1766]="Shatter Scar Vale",
[1767]="Irontree Woods",
[1768]="Irontree Cavern",
[1769]="Timbermaw Hold",
[1770]="Shadow Hold",
[1771]="Shrine of the Deceiver",
[1777]="Itharius\'s Cave",
[1778]="Sorrowmurk",
[1779]="Draenil\'dur Village",
[1780]="Splinterspear Junction",
[1797]="Stagalbog",
[1798]="The Shifting Mire",
[1817]="Stagalbog Cave",
[1837]="Witherbark Caverns",
[1857]="Thoradin\'s Wall",
[1858]="Boulder\'gor",
[1877]="Valley of Fangs",
[1878]="The Dustbowl",
[1879]="Mirage Flats",
[1880]="Featherbeard\'s Hovel",
[1881]="Shindigger\'s Camp",
[1882]="Plaguemist Ravine",
[1883]="Valorwind Lake",
[1884]="Agol\'watha",
[1885]="Hiri\'watha",
[1886]="The Creeping Ruin",
[1887]="Bogen\'s Ledge",
[1897]="The Maker\'s Terrace",
[1898]="Dustwind Gulch",
[1917]="Shaol\'watha",
[1937]="Noonshade Ruins",
[1938]="Broken Pillar",
[1939]="Abyssal Sands",
[1940]="Southbreak Shore",
[1941]="Caverns of Time",
[1942]="The Marshlands",
[1943]="Ironstone Plateau",
[1957]="Blackchar Cave",
[1958]="Tanner Camp",
[1959]="Dustfire Valley",
[1977]="Zul\'Gurub",
[1978]="Misty Reed Post",
[1997]="Bloodvenom Post ",
[1998]="Talonbranch Glade ",
[2017]="Stratholme",
[2037]="UNUSEDShadowfang Keep 003",
[2057]="Scholomance",
[2077]="Twilight Vale",
[2078]="Twilight Shore",
[2079]="Alcaz Island",
[2097]="Darkcloud Pinnacle",
[2098]="Dawning Wood Catacombs",
[2099]="Stonewatch Keep",
[2100]="Maraudon",
[2101]="Stoutlager Inn",
[2102]="Thunderbrew Distillery",
[2103]="Menethil Keep",
[2104]="Deepwater Tavern",
[2117]="Shadow Grave",
[2118]="Brill Town Hall",
[2119]="Gallows\' End Tavern",
[2137]="The Pools of VisionUNUSED",
[2138]="Dreadmist Den",
[2157]="Bael\'dun Keep",
[2158]="Emberstrife\'s Den",
[2159]="Onyxia\'s Lair",
[2160]="Windshear Mine",
[2161]="Roland\'s Doom",
[2177]="Battle Ring",
[2197]="The Pools of Vision",
[2198]="Shadowbreak Ravine",
[2217]="Broken Spear Village",
[2237]="Whitereach Post",
[2238]="Gornia",
[2239]="Zane\'s Eye Crater",
[2240]="Mirage Raceway",
[2241]="Frostsaber Rock",
[2242]="The Hidden Grove",
[2243]="Timbermaw Post",
[2244]="Winterfall Village",
[2245]="Mazthoril",
[2246]="Frostfire Hot Springs",
[2247]="Ice Thistle Hills",
[2248]="Dun Mandarr",
[2249]="Frostwhisper Gorge",
[2250]="Owl Wing Thicket",
[2251]="Lake Kel\'Theril",
[2252]="The Ruins of Kel\'Theril",
[2253]="Starfall Village",
[2254]="Ban\'Thallow Barrow Den",
[2255]="Everlook",
[2256]="Darkwhisper Gorge",
[2257]="Deeprun Tram",
[2258]="The Fungal Vale",
[2259]="UNUSEDThe Marris Stead",
[2260]="The Marris Stead",
[2261]="The Undercroft",
[2262]="Darrowshire",
[2263]="Crown Guard Tower",
[2264]="Corin\'s Crossing",
[2265]="Scarlet Base Camp",
[2266]="Tyr\'s Hand",
[2267]="The Scarlet Basilica",
[2268]="Light\'s Hope Chapel",
[2269]="Browman Mill",
[2270]="The Noxious Glade",
[2271]="Eastwall Tower",
[2272]="Northdale",
[2273]="Zul\'Mashar",
[2274]="Mazra\'Alor",
[2275]="Northpass Tower",
[2276]="Quel\'Lithien Lodge",
[2277]="Plaguewood",
[2278]="Scourgehold",
[2279]="Stratholme",
[2280]="UNUSED Stratholme",
[2297]="Darrowmere Lake",
[2298]="Caer Darrow",
[2299]="Darrowmere Lake",
[2300]="Caverns of Time",
[2301]="Thistlefur Village",
[2302]="The Quagmire",
[2303]="Windbreak Canyon",
[2317]="South Seas",
[2318]="The Great Sea",
[2319]="The Great Sea",
[2320]="The Great Sea",
[2321]="The Great Sea",
[2322]="The Veiled Sea",
[2323]="The Veiled Sea",
[2324]="The Veiled Sea",
[2325]="The Veiled Sea",
[2326]="The Veiled Sea",
[2337]="Razor Hill Barracks",
[2338]="South Seas",
[2339]="The Great Sea",
[2357]="Bloodtooth Camp",
[2358]="Forest Song",
[2359]="Greenpaw Village",
[2360]="Silverwing Outpost",
[2361]="Nighthaven",
[2362]="Shrine of Remulos",
[2363]="Stormrage Barrow Dens",
[2364]="The Great Sea",
[2365]="The Great Sea",
[2366]="The Black Morass",
[2367]="Old Hillsbrad Foothills",
[2368]="Tarren Mill",
[2369]="Southshore",
[2370]="Durnholde Keep",
[2371]="Dun Garok",
[2372]="Hillsbrad Fields",
[2373]="Eastern Strand",
[2374]="Nethander Stead",
[2375]="Darrow Hill",
[2376]="Southpoint Tower",
[2377]="Thoradin\'s Wall",
[2378]="Western Strand",
[2379]="Azurelode Mine",
[2397]="The Great Sea",
[2398]="The Great Sea",
[2399]="The Great Sea",
[2400]="The Forbidding Sea",
[2401]="The Forbidding Sea",
[2402]="The Forbidding Sea",
[2403]="The Forbidding Sea",
[2404]="Tethris Aran",
[2405]="Ethel Rethor",
[2406]="Ranazjar Isle",
[2407]="Kormek\'s Hut",
[2408]="Shadowprey Village",
[2417]="Blackrock Pass",
[2418]="Morgan\'s Vigil",
[2419]="Slither Rock",
[2420]="Terror Wing Path",
[2421]="Draco\'dar",
[2437]="Ragefire Chasm",
[2457]="Nightsong Woods",
[2477]="The Veiled Sea",
[2478]="Morlos\'Aran",
[2479]="Emerald Sanctuary",
[2480]="Jadefire Glen",
[2481]="Ruins of Constellas",
[2497]="Bitter Reaches",
[2517]="Rise of the Defiler",
[2518]="Lariss Pavilion",
[2519]="Woodpaw Hills",
[2520]="Woodpaw Den",
[2521]="Verdantis River",
[2522]="Ruins of Isildien",
[2537]="Grimtotem Post",
[2538]="Camp Aparaje",
[2539]="Malaka\'jin",
[2540]="Boulderslide Ravine",
[2541]="Sishir Canyon",
[2557]="Dire Maul",
[2558]="Deadwind Ravine",
[2559]="Diamondhead River",
[2560]="Ariden\'s Camp",
[2561]="The Vice",
[2562]="Karazhan",
[2563]="Morgan\'s Plot",
[2577]="Dire Maul",
[2597]="Alterac Valley",
[2617]="Scrabblescrew\'s Camp",
[2618]="Jadefire Run",
[2619]="Thondroril River",
[2620]="Thondroril River",
[2621]="Lake Mereldar",
[2622]="Pestilent Scar",
[2623]="The Infectis Scar",
[2624]="Blackwood Lake",
[2625]="Eastwall Gate",
[2626]="Terrorweb Tunnel",
[2627]="Terrordale",
[2637]="Kargathia Keep",
[2657]="Valley of Bones",
[2677]="Blackwing Lair",
[2697]="Deadman\'s Crossing",
[2717]="Molten Core",
[2737]="The Scarab Wall",
[2738]="Southwind Village",
[2739]="Twilight Base Camp",
[2740]="The Crystal Vale",
[2741]="The Scarab Dais",
[2742]="Hive\'Ashi",
[2743]="Hive\'Zora",
[2744]="Hive\'Regal",
[2757]="Shrine of the Fallen Warrior",
[2777]="UNUSED Alterac Valley",
[2797]="Blackfathom Deeps",
[2817]="***On Map Dungeon***",
[2837]="The Master\'s Cellar",
[2838]="Stonewrought Pass",
[2839]="Alterac Valley",
[2857]="The Rumble Cage",
[2877]="Chunk Test",
[2897]="Zoram\'gar Outpost",
[2917]="Hall of Legends",
[2918]="Champions\' Hall",
[2937]="Grosh\'gok Compound",
[2938]="Sleeping Gorge",
[2957]="Irondeep Mine",
[2958]="Stonehearth Outpost",
[2959]="Dun Baldar",
[2960]="Icewing Pass",
[2961]="Frostwolf Village",
[2962]="Tower Point",
[2963]="Coldtooth Mine",
[2964]="Winterax Hold",
[2977]="Iceblood Garrison",
[2978]="Frostwolf Keep",
[2979]="Tor\'kren Farm",
[3017]="Frost Dagger Pass",
[3037]="Ironstone Camp",
[3038]="Weazel\'s Crater",
[3039]="Tahonda Ruins",
[3057]="Field of Strife",
[3058]="Icewing Cavern",
[3077]="Valor\'s Rest",
[3097]="The Swarming Pillar",
[3098]="Twilight Post",
[3099]="Twilight Outpost",
[3100]="Ravaged Twilight Camp",
[3117]="Shalzaru\'s Lair",
[3137]="Talrendis Point",
[3138]="Rethress Sanctum",
[3139]="Moon Horror Den",
[3140]="Scalebeard\'s Cave",
[3157]="Boulderslide Cavern",
[3177]="Warsong Labor Camp",
[3197]="Chillwind Camp",
[3217]="The Maul",
[3237]="The Maul UNUSED",
[3257]="Bones of Grakkarond",
[3277]="Warsong Gulch",
[3297]="Frostwolf Graveyard",
[3298]="Frostwolf Pass",
[3299]="Dun Baldar Pass",
[3300]="Iceblood Graveyard",
[3301]="Snowfall Graveyard",
[3302]="Stonehearth Graveyard",
[3303]="Stormpike Graveyard",
[3304]="Icewing Bunker",
[3305]="Stonehearth Bunker",
[3306]="Wildpaw Ridge",
[3317]="Revantusk Village",
[3318]="Rock of Durotan",
[3319]="Silverwing Grove",
[3320]="Warsong Lumber Mill",
[3321]="Silverwing Hold",
[3337]="Wildpaw Cavern",
[3338]="The Veiled Cleft",
[3357]="Yojamba Isle",
[3358]="Arathi Basin",
[3377]="The Coil",
[3378]="Altar of Hir\'eek",
[3379]="Shadra\'zaar",
[3380]="Hakkari Grounds",
[3381]="Naze of Shirvallah",
[3382]="Temple of Bethekk",
[3383]="The Bloodfire Pit",
[3384]="Altar of the Blood God",
[3397]="Zanza\'s Rise",
[3398]="Edge of Madness",
[3417]="Trollbane Hall",
[3418]="Defiler\'s Den",
[3419]="Pagle\'s Pointe",
[3420]="Farm",
[3421]="Blacksmith",
[3422]="Lumber Mill",
[3423]="Gold Mine",
[3424]="Stables",
[3425]="Cenarion Hold",
[3426]="Staghelm Point",
[3427]="Bronzebeard Encampment",
[3428]="Ahn\'Qiraj",
[3429]="Ruins of Ahn\'Qiraj",
[3446]="Twilight\'s Run",
[3447]="Ortell\'s Hideout",
[3448]="Scarab Terrace",
[3449]="General\'s Terrace",
[3450]="The Reservoir",
[3451]="The Hatchery",
[3452]="The Comb",
[3453]="Watchers\' Terrace",
[3454]="Ruins of Ahn\'Qiraj",
[3456]="Naxxramas",
[3459]="City",
[3478]="Gates of Ahn\'Qiraj",
[3486]="Ravenholdt Manor",
}
|
C_PlayerInfo = {}
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerInfo.GUIDIsPlayer)
---@param guid string
---@return boolean isPlayer
function C_PlayerInfo.GUIDIsPlayer(guid) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerInfo.GetClass)
---@param playerLocation PlayerLocationMixin
---@return string? className
---@return string? classFilename
---@return number? classID
function C_PlayerInfo.GetClass(playerLocation) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerInfo.GetName)
---@param playerLocation PlayerLocationMixin
---@return string? name
function C_PlayerInfo.GetName(playerLocation) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerInfo.GetRace)
---@param playerLocation PlayerLocationMixin
---@return number? raceID
function C_PlayerInfo.GetRace(playerLocation) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerInfo.GetSex)
---@param playerLocation PlayerLocationMixin
---@return number? sex
function C_PlayerInfo.GetSex(playerLocation) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerInfo.IsConnected)
---@param playerLocation? PlayerLocationMixin
---@return boolean? isConnected
function C_PlayerInfo.IsConnected(playerLocation) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_PlayerInfo.UnitIsSameServer)
---@param playerLocation PlayerLocationMixin
---@return boolean unitIsSameServer
function C_PlayerInfo.UnitIsSameServer(playerLocation) end
|
application = {
content = {
width = 320,
height = 480,
scale = "letterbox"
},
notification ={
iphone = {
types = {
"badge",
"sound",
"alert"
}
}
},
showRuntimeErrors = true
}
|
local E = Game_Event:extend("Home::Fridge_Event")
function E.prototype:trigger()
Game_Map.interpreter:message(
"All the food has spoiled since the\nblackout... what a waste.",
{ showFrame = true, position = "bottom" }
)
end
return E |
-- 对xml2lua的简单封装, 简化xml2lua调用流程
local xml2lua = require "xml2lua.xml2lua"
local xml2lua_handler = require "xml2lua.xmlhandler.tree"
local type = type
local pcall = pcall
local xml = {}
-- xml字符串解析
function xml.parser(xml_data)
local cls = xml2lua.parser(xml2lua_handler:new())
-- cls:parse(xml_data)
local ok, err = pcall(cls.parse, cls, xml_data)
if not ok then
return err
end
return cls.handler.root
end
-- xml文件读取
function xml.load(xml_path)
if type(xml_path) ~= 'string' or xml_path == '' then
return nil, '无效的xml文件路径.'
end
local xfile, error = xml2lua.loadFile(xml_path)
if xfile then
return xml.parser(xfile)
end
return xfile, error
end
-- 将table序列化为xml
function xml.toxml( ... )
return xml2lua.toXml(...)
end
return xml
|
-----------------------------------
-- Area: Ordelle's Caves
-- NPC: ??? - 17568147
-- Spawns Aroma Leech - RSE Satchets
-----------------------------------
local ID = require("scripts/zones/Ordelles_Caves/IDs")
require("scripts/globals/npc_util")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local playerRace = player:getRace()
local raceOffset = 0
if playerRace >= 6 then -- will subtract 1 from playerRace calculations for loot starting at taru female, because taru satchet encompasses both sexes
raceOffset = 1
end
if VanadielRSELocation() == 0 and VanadielRSERace() == playerRace and not player:hasItem(18246 + playerRace - raceOffset) then
npcUtil.popFromQM(player, npc, ID.mob.AROMA_LEECH, {claim=true, hide=math.random(600,1800), look=true, radius=1}) -- ??? despawns and respawns 10-30 minutes after NM dies
for i = 1, 7 do
SetDropRate(172, 18246 + i, 0) -- zeros all drop rates
end
SetDropRate(172, 18246 + playerRace - raceOffset, 130) -- adds 13% drop rate to specific week's race
local newSpawn = math.random(1,3) -- determine new spawn point for ???
if newSpawn == 1 then
npcUtil.queueMove(npc, {-135.826, 0.547, 176.380})
elseif newSpawn == 2 then
npcUtil.queueMove(npc, {-193.776, -0.190, 533.996}) -- TODO: get 100% accurate spawn point from retail
else
npcUtil.queueMove(npc, {15.359, 32.000, -21.885}) -- TODO: get 100% accurate spawn point from retail
end
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
ITEM.name = "Nightstar"
ITEM.model ="models/nasca/etherealsrp_artifacts/nightstar.mdl"
ITEM.description = "Spikey yellow artifact. Glowing."
ITEM.longdesc = "Emits a small amount of radiation. Emits a small gravity field that increases the carry weight of anyone using it. Causes the user to no longer experience nightmares. [ +4kg WEIGHT | +1 RAD ]"
ITEM.width = 1
ITEM.height = 1
ITEM.price = 9150
ITEM.flag = "A"
ITEM.buff = "weight"
ITEM.buffval = 4
ITEM.debuff = "rads"
ITEM.debuffval = 1
ITEM.isArtefact = true
ITEM.weight = 2 |
local class = require "xgame.class"
local heartbeat = class("heartbeat")
local REQUEST = {}
function REQUEST:heartbeat()
print("on heartbeat")
end
heartbeat.REQUEST = REQUEST
return heartbeat |
-- This is a part of uJIT's testing suite.
-- Copyright (C) 2020-2022 LuaVela Authors. See Copyright Notice in COPYRIGHT
-- Copyright (C) 2015-2020 IPONWEB Ltd. See Copyright Notice in COPYRIGHT
local args = {...}
local func_name = args[1]
assert(ujit.table[func_name],
string.format("No such function '%s' in 'ujit.table' extension library.", func_name))
local f = ujit.table[func_name]
local HOTLOOP = 1
jit.opt.start(3, "hotloop=" .. HOTLOOP)
local t = {
{},
{},
{}
}
-- Trace is recorded at 'HOTLOOP + 1' and executed at 'HOTLOOP + 2'.
local RECORDING_ITERATION = HOTLOOP + 1
assert(#t >= RECORDING_ITERATION)
for i = 1, #t do
c = f(t[i])
end
|
--[[
This file contains the help function and functions to get infos about installed maps
]]
function help()
print("Snek user manual")
print("")
print("* Start the game")
print(" To start the game just type `snek` and the game will start in a map adapted to the size of your terminal.")
print("")
print(" You can also play a custom map. To do so type `snek ` followed by the name of the map. For example `snek Factory` will start the map factory. You can list all available maps by typing `snek map`")
print("")
print("* Play the game")
print(" The aim of the game is to have the biggest snake possible. The head of the snake is represented by a `@` and it's body by `+`. To make the smake grow it must eat fruit represented by red `o`. Be careful, the snake can't hit a wall or bit it's own tail, otherwize you loose.")
print("")
print(" To control the snake, use the arrow keys.")
print("")
print("* Creating custom maps")
print(" You can create your own maps. To do so check the instructions in the readme at https://github.com/Arkaeriit/snek")
return 0
end
function invalidArgs()
io.stderr:write("Error : invalid arguments.\n","To print help type `snek help`\n")
return 1
end
--This function return a list of all the filenames of installed maps
function listMaps()
local ret1 = gFS.ls("/usr/local/share/snek/maps")
local ret2 = gFS.ls("/usr/share/snek/maps")
for i=1,#ret1 do --We remove doubles, /usr/local got priority
for k,v in pairs(ret2) do
if ret1[i] == v then
ret2[k] = nil
end
end
end
for i=1,#ret1 do --we complete names in ret1
ret1[i] = "/usr/local/share/snek/maps/"..ret1[i]
end
for k,v in pairs(ret2) do
ret2[k] = "/usr/share/snek/maps/"..v --we complete names in ret2
ret1[#ret1+1] = ret2[k] --we append ret2 to ret1
end
if #ret1 > 0 then
return ret1
else
return ret2
end
end
--change a full filename into a limited one. ex : /path/to/file -> file
function justFileName(filename)
local slash = 0 --position of the /
for i=1,#filename do
if filename:sub(i,i) == "/" then
slash = i
end
end
return filename:sub(slash+1,#filename)
end
--present the map named filename in a pretty way
function presentMap(filename)
io.stdout:write("* ")
io.stdout:write(justFileName(filename))
io.stdout:write(" : ")
local f = io.open(filename,"r")
io.stdout:write(f:read())
io.stdout:write('\n')
end
--present all the avalaible maps
function displayAvailableMaps()
local list = listMaps()
for i=1,#list do
presentMap(list[i])
end
return 0
end
|
local invokeGuardedCallback = require "invokeGuardedCallback"
local pi = require "pi"
pi(invokeGuardedCallback) |
--[[ COMMANDS ]]--
RegisterCommand('clear', function(source, args, rawCommand)
TriggerClientEvent('chat:client:ClearChat', source)
end, false)
RegisterCommand('clearall', function()
TriggerClientEvent('chat:clear', -1)
end) |
-- ===========================================================================
function GetFormattedOperationDetailText(operation, spy, city)
local outputString = ""
local eOperation = GameInfo.UnitOperations[operation.Hash].Index
local sOperationDetails = UnitManager.GetOperationDetailText(eOperation, spy, Map.GetPlot(city:GetX(), city:GetY()))
if operation.OperationType == "UNITOPERATION_SPY_GREAT_WORK_HEIST" then
outputString = Locale.Lookup("LOC_SPYMISSIONDETAILS_UNITOPERATION_SPY_GREAT_WORK_HEIST", sOperationDetails)
elseif operation.OperationType == "UNITOPERATION_SPY_SIPHON_FUNDS" then
outputString = Locale.Lookup("LOC_CUI_EP_SIPHON_FUNDS", sOperationDetails) -- CUI
elseif operation.OperationType == "UNITOPERATION_SPY_FOMENT_UNREST" then
outputString = Locale.Lookup("LOC_SPYMISSIONDETAILS_UNITOPERATION_SPY_FOMENT_UNREST", sOperationDetails)
elseif operation.OperationType == "UNITOPERATION_SPY_FABRICATE_SCANDAL" then
outputString = Locale.Lookup("LOC_SPYMISSIONDETAILS_UNITOPERATION_SPY_FABRICATE_SCANDAL", sOperationDetails)
elseif operation.OperationType == "UNITOPERATION_SPY_NEUTRALIZE_GOVERNOR" then
outputString = Locale.Lookup("LOC_SPYMISSIONDETAILS_UNITOPERATION_SPY_NEUTRALIZE_GOVERNOR", sOperationDetails)
elseif sOperationDetails ~= "" then
outputString = sOperationDetails
else
-- Find the loc string by OperationType if this operation doesn't use GetOperationDetailText
outputString = Locale.Lookup("LOC_SPYMISSIONDETAILS_" .. operation.OperationType)
end
return outputString
end
-- ===========================================================================
function RefreshMissionStats(parentControl, operation, result, spy, city, targetPlot)
-- Update turns to completed
local eOperation = operation.Index
local turnsToComplete = UnitManager.GetTimeToComplete(eOperation, spy)
parentControl.TurnsToCompleteLabel:SetText(turnsToComplete)
-- Update mission success chance
if operation.Hash ~= UnitOperationTypes.SPY_COUNTERSPY then
local resultProbability = UnitManager.GetResultProbability(eOperation, spy, targetPlot)
if resultProbability["ESPIONAGE_SUCCESS_UNDETECTED"] then
local probability = resultProbability["ESPIONAGE_SUCCESS_UNDETECTED"]
-- Add ESPIONAGE_SUCCESS_MUST_ESCAPE
if resultProbability["ESPIONAGE_SUCCESS_MUST_ESCAPE"] then
probability = probability + resultProbability["ESPIONAGE_SUCCESS_MUST_ESCAPE"]
end
probability = math.floor((probability * 100) + 0.5)
parentControl.ProbabilityLabel:SetText(probability .. "%")
-- Set Color
if probability > 85 then
parentControl.ProbabilityLabel:SetColorByName("OperationChance_Green")
elseif probability > 65 then
parentControl.ProbabilityLabel:SetColorByName("OperationChance_YellowGreen")
elseif probability > 45 then
parentControl.ProbabilityLabel:SetColorByName("OperationChance_Yellow")
elseif probability > 25 then
parentControl.ProbabilityLabel:SetColorByName("OperationChance_Orange")
else
parentControl.ProbabilityLabel:SetColorByName("OperationChance_Red")
end
end
parentControl.ProbabilityGrid:SetHide(false)
else
parentControl.ProbabilityGrid:SetHide(true)
end
-- result is the data bundle retruned by CanStartOperation container useful information about the operation query
-- If the results contain a plot ID then show that as the target district
if operation.Hash == UnitOperationTypes.SPY_COUNTERSPY then
local kDistrictInfo = GameInfo.Districts[targetPlot:GetDistrictType()]
parentControl.MissionDistrictName:SetText(Locale.Lookup(kDistrictInfo.Name))
local iconString = "ICON_" .. kDistrictInfo.DistrictType
if parentControl.MissionDistrictIcon then
parentControl.MissionDistrictIcon:SetIcon(iconString)
end
elseif result and result[UnitOperationResults.PLOTS] then
for i, districtPlotID in ipairs(result[UnitOperationResults.PLOTS]) do
local districts = city:GetDistricts()
for i, district in districts:Members() do
local districtPlot = Map.GetPlot(district:GetX(), district:GetY())
if districtPlot:GetIndex() == districtPlotID then
local districtInfo = GameInfo.Districts[district:GetType()]
parentControl.MissionDistrictName:SetText(Locale.Lookup(districtInfo.Name))
local iconString = "ICON_" .. districtInfo.DistrictType
if parentControl.MissionDistrictIcon then
parentControl.MissionDistrictIcon:SetIcon(iconString)
end
end
end
end
else -- Default to show city center
parentControl.MissionDistrictName:SetText(Locale.Lookup("LOC_DISTRICT_CITY_CENTER_NAME"))
parentControl.MissionDistrictIcon:SetIcon("ICON_DISTRICT_CITY_CENTER")
end
end
-- ===========================================================================
function GetSpyRankNameByLevel(level)
local spyRankName = ""
if (level == 4) then
spyRankName = "LOC_ESPIONAGE_LEVEL_4_NAME"
elseif (level == 3) then
spyRankName = "LOC_ESPIONAGE_LEVEL_3_NAME"
elseif (level == 2) then
spyRankName = "LOC_ESPIONAGE_LEVEL_2_NAME"
else
spyRankName = "LOC_ESPIONAGE_LEVEL_1_NAME"
end
return spyRankName
end
-- ===========================================================================
function GetMissionDescriptionString(mission, noloot, withloot)
if mission.LootInfo >= 0 then
return Locale.Lookup(withloot, GetMissionLootString(mission), mission.CityName)
end
return Locale.Lookup(noloot, mission.CityName)
end
-- ===========================================================================
function GetMissionOutcomeDetails(mission)
local outcomeDetails = {}
local kOpDef = GameInfo.UnitOperations[mission.Operation]
if kOpDef ~= nil and kOpDef.Hash == UnitOperationTypes.SPY_COUNTERSPY then
-- Counterspy specific
outcomeDetails.Success = true
outcomeDetails.Description = Locale.Lookup("LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_SUCCESS_COUNTERSPY",
mission.CityName)
outcomeDetails.SpyStatus = ""
elseif mission.InitialResult == EspionageResultTypes.SUCCESS_UNDETECTED then
-- Success and undetected
outcomeDetails.Success = true
outcomeDetails.Description = GetMissionDescriptionString(mission,
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_SUCCESS_UNDETECTED",
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_SUCCESS_UNDETECTED_STOLELOOT")
outcomeDetails.SpyStatus = ""
elseif mission.InitialResult == EspionageResultTypes.SUCCESS_MUST_ESCAPE then
-- Success but detected
if mission.EscapeResult == EspionageResultTypes.FAIL_MUST_ESCAPE then
-- Success and escaped
outcomeDetails.Success = true
outcomeDetails.Description = GetMissionDescriptionString(mission,
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_SUCCESS_DETECTED_ESCAPED",
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_SUCCESS_DETECTED_STOLELOOT")
outcomeDetails.SpyStatus = ""
elseif mission.EscapeResult == EspionageResultTypes.KILLED then
-- Success and killed
outcomeDetails.Success = false
outcomeDetails.Description = GetMissionDescriptionString(mission,
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_SUCCESS_DETECTED_KILLED",
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_SUCCESS_DETECTED_KILLED_STOLELOOT")
outcomeDetails.SpyStatus = Locale.ToUpper("LOC_ESPIONAGEOVERVIEW_SPYKILLED")
elseif mission.EscapeResult == EspionageResultTypes.CAPTURED then
-- Success and captured
outcomeDetails.Success = false
outcomeDetails.Description = GetMissionDescriptionString(mission,
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_SUCCESS_DETECTED_CAPTURED",
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_SUCCESS_DETECTED_CAPTURED_STOLELOOT")
outcomeDetails.SpyStatus = Locale.ToUpper("LOC_ESPIONAGEOVERVIEW_SPYCAUGHT")
end
elseif mission.InitialResult == EspionageResultTypes.FAIL_UNDETECTED then
-- Failure but undetected
outcomeDetails.Success = false
outcomeDetails.Description = GetMissionDescriptionString(mission,
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_FAILURE_UNDETECTED",
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_FAILURE_UNDETECTED_STOLELOOT")
outcomeDetails.SpyStatus = ""
elseif mission.InitialResult == EspionageResultTypes.FAIL_MUST_ESCAPE then
-- Failure and detected
if mission.EscapeResult == EspionageResultTypes.FAIL_MUST_ESCAPE then
-- Failure and escaped
outcomeDetails.Success = false
outcomeDetails.Description = GetMissionDescriptionString(mission,
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_FAILURE_DETECTED_ESCAPED",
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_FAILURE_DETECTED_ESCAPED_STOLELOOT")
outcomeDetails.SpyStatus = ""
elseif mission.EscapeResult == EspionageResultTypes.KILLED then
-- Failure and killed
outcomeDetails.Success = false
outcomeDetails.Description = GetMissionDescriptionString(mission,
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_FAILURE_DETECTED_KILLED",
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_FAILURE_DETECTED_KILLED_STOLELOOT")
outcomeDetails.SpyStatus = Locale.ToUpper("LOC_ESPIONAGEOVERVIEW_SPYKILLED")
elseif mission.EscapeResult == EspionageResultTypes.CAPTURED then
-- Failure and captured
outcomeDetails.Success = false
outcomeDetails.Description = GetMissionDescriptionString(mission,
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_FAILURE_DETECTED_CAPTURED",
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_FAILURE_DETECTED_CAPTURED_STOLELOOT")
outcomeDetails.SpyStatus = Locale.ToUpper("LOC_ESPIONAGEOVERVIEW_SPYCAUGHT")
end
elseif mission.InitialResult == EspionageResultTypes.KILLED then
-- Killed
outcomeDetails.Success = false
outcomeDetails.Description = GetMissionDescriptionString(mission, "LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_KILLED",
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_KILLED_STOLELOOT")
outcomeDetails.SpyStatus = Locale.ToUpper("LOC_ESPIONAGEOVERVIEW_SPYKILLED")
elseif mission.InitialResult == EspionageResultTypes.CAPTURED then
-- Captured
outcomeDetails.Success = false
outcomeDetails.Description = GetMissionDescriptionString(mission, "LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_CAPTURED",
"LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_CAPTURED_STOLELOOT")
outcomeDetails.SpyStatus = Locale.ToUpper("LOC_ESPIONAGEOVERVIEW_SPYCAUGHT")
end
return outcomeDetails
end
-- ===========================================================================
function GetMissionLootString(mission)
local lootString = ""
local operationInfo = GameInfo.UnitOperations[mission.Operation]
if operationInfo.Hash == UnitOperationTypes.SPY_STEAL_TECH_BOOST then
local techInfo = GameInfo.Technologies[mission.LootInfo]
lootString = techInfo.Name
elseif operationInfo.Hash == UnitOperationTypes.SPY_GREAT_WORK_HEIST then
local greatWorkType = Game.GetGreatWorkTypeFromIndex(mission.LootInfo)
local greatWorkInfo = GameInfo.GreatWorks[greatWorkType]
lootString = greatWorkInfo.Name
elseif operationInfo.Hash == UnitOperationTypes.SPY_SIPHON_FUNDS then
if mission.LootInfo <= 0 then
lootString = Locale.Lookup("LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_NO_GOLD")
else
lootString = Locale.Lookup("LOC_ESPIONAGEOVERVIEW_MISSIONOUTCOME_GOLD", mission.LootInfo)
end
end
return lootString
end
-- ===========================================================================
function CanMissionBeRenewed(mission)
local kOperationInfo = GameInfo.UnitOperations[mission.Operation]
if kOperationInfo.Hash == UnitOperationTypes.SPY_LISTENING_POST or kOperationInfo.Hash ==
UnitOperationTypes.SPY_COUNTERSPY then
return true
end
return false
end
|
local Name = class('Name')
--Name.static.surnames = Game.wordbase.surnames:column_by_name(Game.wordbase.surnames:column_names()[1])
function Name:initialize(sex, age)
self.sex = chance.helpers.pick({"M", "F"})
if type(sex) == 'string' and #sex >= 1 then
self.sex = sex:sub(1,1):upper()
end
local year = Config.GameYear - 30
if type(age) == number and age < Config.GameYear - 1880 and age > 4 then
local year = Config.GameYear - age
end
if self.sex == "F" then
self.firstname = chance.helpers.pick(Sources.girl_names)
-- print("Select: "..self.sex .." ".. year.. " cnt: "..#(Game.wordbase.girl_names))
else
self.firstname = chance.helpers.pick(Sources.boy_names)
-- print("Select: "..self.sex .." ".. year.. " cnt: "..#(Game.wordbase.boy_names))
end
self.lastname = chance.helpers.pick(Sources.surnames)
end
function Name:emit(flags)
if flags == "i" then --informal
return self.firstname
end
if flags == "f" then
if self.sex == "M" then
return "Mr. " .. self.lastname
else
return "Ms. " .. self.lastname
end
end
if flags == "g" then
return self.firstname
end
if flags == 'l' then
return self.lastname
end
return self.firstname .. " " .. self.lastname
end
return Name
|
local bind = require('keymap.bind')
local map_cr = bind.map_cr
local map_cu = bind.map_cu
local map_cmd = bind.map_cmd
-- default map
local def_map = {
-- Vim map
["n|<C-x>k"] = map_cr('bdelete'):with_noremap():with_silent(),
["n|Y"] = map_cmd('y$'),
["n|]w"] = map_cu('WhitespaceNext'):with_noremap(),
["n|[w"] = map_cu('WhitespacePrev'):with_noremap(),
["n|]b"] = map_cu('bp'):with_noremap(),
["n|[b"] = map_cu('bn'):with_noremap(),
["n|<C-h>"] = map_cmd('<C-w>h'):with_noremap(),
["n|<C-l>"] = map_cmd('<C-w>l'):with_noremap(),
["n|<C-j>"] = map_cmd('<C-w>j'):with_noremap(),
["n|<C-k>"] = map_cmd('<C-w>k'):with_noremap(),
["n|<A-[>"] = map_cr('vertical resize -5'):with_silent(),
["n|<A-]>"] = map_cr('vertical resize +5'):with_silent(),
["n|<Leader>e"] = map_cmd(":e <c-r>=expand('%:p:h')<cr>/"):with_noremap(),
-- Insert
["i|<C-h>"] = map_cmd('<BS>'):with_noremap(),
["i|<C-d>"] = map_cmd('<Del>'):with_noremap(),
["i|<C-u>"] = map_cmd('<C-G>u<C-U>'):with_noremap(),
["i|<C-b>"] = map_cmd('<Left>'):with_noremap(),
["i|<C-f>"] = map_cmd('<Right>'):with_noremap(),
["i|<C-a>"] = map_cmd('<ESC>^i'):with_noremap(),
["i|<C-j>"] = map_cmd('<Esc>o'):with_noremap(),
["i|<C-k>"] = map_cmd('<Esc>O'):with_noremap(),
["i|<C-e>"] = map_cmd([[pumvisible() ? "\<C-e>" : "\<End>"]]):with_noremap():with_expr(),
["i|jk"] = map_cmd('<Esc>'):with_noremap(),
-- command line
["c|<C-b>"] = map_cmd('<Left>'):with_noremap(),
["c|<C-f>"] = map_cmd('<Right>'):with_noremap(),
["c|<C-a>"] = map_cmd('<Home>'):with_noremap(),
["c|<C-e>"] = map_cmd('<End>'):with_noremap(),
["c|<C-d>"] = map_cmd('<Del>'):with_noremap(),
["c|<C-h>"] = map_cmd('<BS>'):with_noremap(),
["c|<C-t>"] = map_cmd([[<C-R>=expand("%:p:h") . "/" <CR>]]):with_noremap(),
}
bind.nvim_load_mapping(def_map)
|
local awful = require('awful')
require('awful.autofocus')
local modkey = require('configuration.keys.mod').modKey
local altkey = require('configuration.keys.mod').altKey
local clientKeys =
awful.util.table.join(
awful.key(
{modkey},
'f',
function(c)
local offset = 0
if c.screen == screen.primary then
offsetx = 48
end
c.floating = not c.floating
c.width = (mouse.screen.geometry["width"] - offset) * 0.8
c.height = (mouse.screen.geometry["height"] - offset) * 0.8
c.x = (mouse.screen.geometry["x"] + offset) + ((mouse.screen.geometry["width"] - offset) / 2) - (c.width / 2) + 24
c.y = (mouse.screen.geometry["y"] + offset) + ((mouse.screen.geometry["height"] - offset) / 2) - (c.height / 2) + 24
c:raise()
end,
{description = 'toggle floating', group = 'client'}
),
awful.key(
{modkey},
'q',
function(c)
c:kill()
end,
{description = 'close', group = 'client'}
)
)
return clientKeys
|
function OnEvent(event, arg)
if event == "G_PRESSED" then
modifiers = {"ctrl", "shift", "alt"};
pressed = "";
for i = 1, 3 do
if IsModifierPressed(modifiers[i]) then
if pressed == "" then
pressed = pressed .. modifiers[i];
else
pressed = pressed .. "+" .. modifiers[i];
end
end
end
if pressed ~= "" then
macroKey = pressed .. "+f" .. arg;
OutputLogMessage("Macro Key Pressed " .. macroKey .. "\n");
PlayMacro(macroKey);
end
end
end |
---
-- @module RxValueBaseUtils
-- @author Quenty
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local RxInstanceUtils = require("RxInstanceUtils")
local RxBrioUtils = require("RxBrioUtils")
local RxValueBaseUtils = {}
-- TODO: Handle default value/nothing there, instead of memory leaking!
function RxValueBaseUtils.observe(parent, className, name, ...)
return RxInstanceUtils.observeLastNamedChildBrio(parent, className, name)
:Pipe({
RxBrioUtils.switchMap(function(valueObject)
return RxValueBaseUtils.observeValue(valueObject)
end)
})
end
function RxValueBaseUtils.observeValue(valueObject)
return RxInstanceUtils.observeProperty(valueObject, "Value")
end
return RxValueBaseUtils |
mrequire "src/class"
mrequire "src/engine/task"
newclass("Topic",
function(id)
return {
id = id,
options = { }
}
end
)
function Topic:addOptions(...)
for _, opt in ipairs({ ... }) do
if opt.enabled == nil then
opt.enabled = true
end
opt.flags = opt.flags or ""
table.insert(self.options, opt)
end
end
function Topic:getOptions()
local ret = { }
for id, opt in ipairs(self.options) do
if opt.enabled and (not opt.condition or opt.condition()) then
table.insert(ret, { id = id, caption = opt.caption })
end
end
return ret
end
function Topic:option(id)
local option = self.options[id]
if option.flags:match("o") then
option.enabled = false
end
Task.start(function()
game.enableInput(false)
if not option.flags:match("s") then
Adventure.player:say(option.caption)
end
option.callback()
game.enableInput(true)
if not option.flags:match("x") then
self:show()
end
end)
end
function Topic:show()
game.showTopic(self)
end
--------------------------------------------------
newclass("Dialogue",
function()
return {
topics = { }
}
end
)
function Dialogue.time(msg)
local words = 0
for _ in msg:gfind("[^%s]+") do words = words + 1 end
words = math.max(5, words)
return words * 0.5
end
function Dialogue:addTopic(id)
local topic = Topic.new(id)
self.topics[i] = topic
return topic
end
|
local TechiesHUD = {}
TechiesHUD.Identity = "TechiesHUD"
TechiesHUD.Locale = {
["name"] = {
["english"] = "TechiesHUD"
},
["desc"] = {
["english"] = "TechiesHUD v1.3.2",
["russian"] = "TechiesHUD v1.3.2"
},
["optionDetonate"] = {
["english"] = "Auto detonate remote mines",
["russian"] = "Авто взрыв бочек"
},
["optionActiveAeon"] = {
["english"] = "If hero has aeon, activate it",
["russian"] = "Если герой имеет aeon активировать его"
},
["drawRadiusLR"] = {
["english"] = "Draw radius Land Mines",
["russian"] = "Рисовать радиус Land Mines"
},
["detonateWK"] = {
["english"] = "Detonate if WK have ult",
["russian"] = "Взрывать если WK имеет ульт"
},
["detonateAegis"] = {
["english"] = "Detonate if hero have aegis",
["russian"] = "Взрывать если герой имеет аегис"
},
["detonateFast"] = {
["english"] = "Detonate if hero can't escape",
["russian"] = "Взрывать если герой не сможет убежать"
},
["drawRadiusSR"] = {
["english"] = "Draw radius Stasis Trap",
["russian"] = "Рисовать радиус Stasis Trap"
},
["drawRadiusRR"] = {
["english"] = "Draw radius Remote Mines",
["russian"] = "Рисовать радиус Remote Mines"
},
["autoPlant"] = {
["english"] = "Auto plant mines",
["russian"] = "Авто плент"
},
["stackMines"] = {
["english"] = "Stack mines",
["russian"] = "Стакать мины"
},
["stackRange"] = {
["english"] = "Range stack mines",
["russian"] = "Радиус стака мин"
},
["blastInfo"] = {
["english"] = "Blast off info",
["russian"] = "Сколько урона до смерти Blast Off"
},
["delayDetonate"] = {
["english"] = "Detonate delay",
["russian"] = "Задержка автоматического подрыва"
},
["forceStaff"] = {
["english"] = "Auto force stuff",
["russian"] = "Автоматическое приминение force stuff"
},
["forceStaffLine"] = {
["english"] = "Draw force stuff line",
["russian"] = "Рисовать линию force stuff"
},
["panelInfo"] = {
["english"] = "Info panel",
["russian"] = "Информационная панель"
},
["drawCircleMethod"] = {
["english"] = "The method of drawing a circle",
["russian"] = "Метод рисования круга"
},
["autoPlantNumMines"] = {
["english"] = "Number of mines for planting",
["russian"] = "Количество мин для плента"
},
["autoPlantStackRange"] = {
["english"] = "Radius to the nearest mine",
["russian"] = "Радиус поиска ближайшей мины"
},
["autoPlantKey"] = {
["english"] = "Set position for auto plant",
["russian"] = "Указать позицию для авто плента"
},
["detonateCam"] = {
["english"] = "Show auto detonate position",
["russian"] = "Показывать место автоматической детонации"
},
["FDFailSwitch"] = {
["english"] = "Focused Detonate FailSwitch",
["russian"] = "Focused Detonate FailSwitch"
},
["FDFailSwitchTogleMode"] = {
["english"] = "FD FailSwitch mode",
["russian"] = "Режим FD FailSwitch"
},
["detonateTogleMode"] = {
["english"] = "Auto detonate mode",
["russian"] = "Режим авто детонации"
},
["updateSettings"] = {
["english"] = "Update settings",
["russian"] = "Обновить настройки"
},
["panelInfoXL"] = {
["english"] = "panel x offset for radiant",
["russian"] = "Смещение панели по х для radiant"
},
["panelInfoXR"] = {
["english"] = "panel x offset for dire",
["russian"] = "Смещение панели по х для dire"
},
["panelInfoY"] = {
["english"] = "panel y offset",
["russian"] = "Смещение панели по y"
},
["panelInfoSize"] = {
["english"] = "Panel height offset",
["russian"] = "Высота панели"
},
["panelInfoDist"] = {
["english"] = "Panel width offset",
["russian"] = "Ширина панели"
},
["panelInfoGemAndSentry"] = {
["english"] = "Show Gem and Sentry",
["russian"] = "Показывать у героя Gem и Sentry"
},
["detonateSection"] = {
["english"] = "Auto detonate remote mines if they can kill the enemy",
["russian"] = "Авто взрывание remote mines если они могут убить врага"
},
["autoStackSection1"] = {
["english"] = "Automatically plant mines in the places indicated by you",
["russian"] = "Автоматически ставит remote mines в отмеченые места"
},
["autoStackSection2"] = {
["english"] = "Use the key \"Set position\" and a shift to create several positions",
["russian"] = "Используйте клавишу \"Указать позицию\" и Shift что бы указать позиции"
},
["autoStackSection3"] = {
["english"] = "Use the simple key \"Set position\" that would clear all positions",
["russian"] = "Просто нажмите клавишу \"Указать позицию\" что бы очистить все позиции"
},
["stackMinesSection"] = {
["english"] = "Puts mines as close as possible to each other",
["russian"] = "Помещает мины как можно ближе друг к другу"
},
["FDFailSwitchSection1"] = {
["english"] = "Focused Detonate Fail Switch Will not detonate remote mines if they do not cause damage",
["russian"] = "Focused Detonate Fail Switch не даст взорвать remote mines если они не нанесут урона героям"
},
["FDFailSwitchSection2"] = {
["english"] = "For forced detonate, use Alt + Focused Detonate",
["russian"] = "Для обычного использования используйте клавиши Alt + Focused Detonate"
},
["minePlacer"] = {
["english"] = "Optimization for the mines plant",
["russian"] = "Оптимизация для установки мин"
},
["minePlacerLM"] = {
["english"] = "Find the closest place when installing the Land Mine",
["russian"] = "Найти ближайшее место при установке Land Mine"
},
["minePlacerST"] = {
["english"] = "Find the closest place when installing the Stasis Trap",
["russian"] = "Найти ближайшее место при установке Stasis Trap"
},
["drawingOptionSection"] = {
["english"] = "Everything related to drawing",
["russian"] = "Все что связано с рисованием"
},
["panelOptionsSection"] = {
["english"] = "Panel calibration",
["russian"] = "Калибровка панели"
},
["resCircle"] = {
["english"] = "Circle resolution",
["russian"] = "Качество круга"
},
["altInfo"] = {
["english"] = "Show additional info if alt key pressed",
["russian"] = "Показывать дополнительную информацию, если нажата клавиша alt"
},
["altInfoDrawing"] = {
["english"] = "Alt info",
["russian"] = "Alt информация"
},
["altInfoRemoteNumberInManaPool"] = {
["english"] = "Show under the cursor a stock of remote mines in the manapool",
["russian"] = "Показывать под курсором запас remote mines в манапуле"
},
["altInfoEnemyNumRemote"] = {
["english"] = "Show under the enemy hero the number of remote mines needed to kill",
["russian"] = "Показывать под вражеским героем количество remote mines необходимых для убийства"
},
["altInfoTimeMines"] = {
["english"] = "Show under remote mines, list mines with time left, level and detonate button",
["russian"] = "Показывать под remote mines, лист мин с оставшимся временем и кнопкой взрыва"
},
["altInfoTimeMinesPanelSize"] = {
["english"] = "Panel size",
["russian"] = "Размер панели"
},
["altInfoNumLevelRemote"] = {
["english"] = "Show under remote mines, how many there are mines of a certain level",
["russian"] = "Показывать под remote mines, сколько там мин определенного уровня"
},
["font1"] = {
["english"] = "Size font for timings and blast off damage info",
["russian"] = "Размер шрифта для таймингов и информации о уроне blast off"
},
["font2"] = {
["english"] = "Size font for top panel",
["russian"] = "Размер шрифта для верхней панели"
},
["empty"] = {
["english"] = "",
["russian"] = ""
},
["detonateMode"] = {
["english"] = {
[0] = "Detonate how much need",
[1] = "Detonate all"
},
["russian"] = {
[0] = "Взорвать сколько нужно",
[1] = "Взорвать все"
}
},
["drawCircleMode"] = {
["english"] = {
[0] = "Lines",
[1] = "Particles"
},
["russian"] = {
[0] = "Линии",
[1] = "Частицы"
}
}
}
TechiesHUD.BlastPosition = nil
TechiesHUD.BlastPositionCircle = nil
TechiesHUD.LandMinesList = {}
TechiesHUD.StasisMinesList = {}
TechiesHUD.RemoteMinesList = {}
TechiesHUD.UndefEntity = {}
TechiesHUD.ParticleList = {}
TechiesHUD.LandMinesTimings = {}
TechiesHUD.RemoteMinesDamage = {}
TechiesHUD.RemoteMinesCreateTimings = {}
TechiesHUD.ScreenScale1 = Renderer.GetScreenSize() / 1600
if TechiesHUD.ScreenScale1 < 0.7 then
TechiesHUD.ScreenScale1 = 0.7
end
TechiesHUD.ScreenScale = TechiesHUD.ScreenScale1
local optionTotal
local optionUpdate
local optionActiveAeon
local optionDetonate
local optionDrawCircleMethod
local optionLR
local optionSR
local optionRR
local optionAutoPlant
local optionResCircle
local optionBlastInfo
local optionDelay
local optionForceDrawLine
local optionPanelInfo
local optionDetonateFast
local optionForce
local optionAutoPlantNumMines
local optionDetonateWk
local optionDetonateAegis
local optionLegitDetonate
local optionDetonateCam
local optionFDFailSwitch
local optionFDFailSwitchMode
local optionPanelInfoXL
local optionPanelInfoXR
local optionPanelInfoY
local optionPanelInfoSize
local optionPanelInfoDist
local optionPanelInfoGemAndSentry
local optionFont1
local optionFont2
local optionFont3
local optionAltInfoDrawing
local optionAltInfoRemoteNumberInManaPool
local optionAltInfoNumLevelRemote
local optionAltInfoEnemyNumRemote
local optionAltInfoTimeMines
local optionAltInfoTimeMinesPanelSize
local optionMinePlacerLM
local optionMinePlacerST
local size_x, size_y = Renderer.GetScreenSize()
local hero_time = {}
local hero_rotate_time = {}
local forc_time = 0
local forced_time = 0
local force_direction = {}
local remote_pos_draw = {}
local mines_num = {}
local check_detonate = 0
local spot_for_plant = {}
local plant_time = 0
local hero_cam_time = nil
local wisp_overcharge = 1
local kunkka_ghostship = 1
local flame_guard = 0
local state_mines = {}
local need_enemy = {}
function TechiesHUD.OnGameStart()
hero_time = {}
hero_rotate_time = {}
forc_time = 0
forced_time = 0
force_direction = {}
remote_pos_draw = {}
mines_num = {}
check_detonate = 0
spot_for_plant = {}
plant_time = 0
hero_cam_time = nil
state_mines = {}
need_enemy = {}
wisp_overcharge = 1
kunkka_ghostship = 1
flame_guard = 0
TechiesHUD.LandMinesList = {}
TechiesHUD.StasisMinesList = {}
TechiesHUD.RemoteMinesList = {}
TechiesHUD.UndefEntity = {}
TechiesHUD.LandMinesTimings = {}
TechiesHUD.RemoteMinesDamage = {}
TechiesHUD.RemoteMinesCreateTimings = {}
end
function TechiesHUD.OnEntityCreate(ent)
table.insert(TechiesHUD.UndefEntity, ent)
end
function TechiesHUD.OnEntityDestroy(ent)
if not optionTotal then return end
if TechiesHUD.ParticleList[ent] then
Particle.Destroy(TechiesHUD.ParticleList[ent].particle)
if TechiesHUD.ParticleList[ent].particle2 then
Particle.Destroy(TechiesHUD.ParticleList[ent].particle2)
end
TechiesHUD.ParticleList[ent] = nil
end
TechiesHUD.LandMinesList[ent] = nil
TechiesHUD.StasisMinesList[ent] = nil
TechiesHUD.RemoteMinesList[ent] = nil
TechiesHUD.LandMinesTimings[ent] = nil
TechiesHUD.RemoteMinesDamage[ent] = nil
TechiesHUD.RemoteMinesCreateTimings[ent] = nil
end
local Monitor = {
["10"] = { ["first"] = 25.903, ["next"] = 55.903, ["step"] = 3.7 },
["9"] = { ["first"] = 28.326, ["next"] = 55.32, ["step"] = 3.314 },
["3"] = { ["first"] = 21.09, ["next"] = 57.34, ["step"] = 4.4 },
["1"] = { ["first"] = 31.875, ["next"] = 54.375, ["step"] = 2.8 }}
function TechiesHUD.GetSize()
local w, h = Renderer.GetScreenSize()
local r = w / h
local m = "3"
if math.floor(r * 10) / 10 == 1.6 then
m = "10"
elseif math.floor(r * 10) / 10 == 1.7 then
m = "9"
elseif math.floor(r * 10) / 10 == 2.1 then
m = "1"
end
local p = ( w / 100 )
return math.floor((Monitor[m]["step"] + optionPanelInfoDist / 10) * p)
end
function TechiesHUD.GetHeroPos(indexHero)
local w, h = Renderer.GetScreenSize()
local r = w / h
local m = "3"
if math.floor(r * 10) / 10 == 1.6 then
m = "10"
elseif math.floor(r * 10) / 10 == 1.7 then
m = "9"
elseif math.floor(r * 10) / 10 == 2.1 then
m = "1"
end
local p = ( w / 100 )
local dw = Monitor[m]["first"] + indexHero * (Monitor[m]["step"] + optionPanelInfoDist / 10) + optionPanelInfoXL
if indexHero > 4 then
dw = Monitor[m]["next"] + (indexHero - 5) * (Monitor[m]["step"] + optionPanelInfoDist / 10) + optionPanelInfoXR
end
local pos = math.floor(p * dw)
return pos, math.floor(h * 0.06 + optionPanelInfoY)
end
function TechiesHUD.GetHeroPosCenterX(indexHero)
local x, y = TechiesHUD.GetHeroPos(indexHero)
x = x + math.floor(TechiesHUD.GetSize() / 2)
return x, y
end
function TechiesHUD.GetDamageAndShieldAfterDetonate(Unit, remote_damage, Hp, Mp, Shield, visage_stack, templar_stack)
local additional_res = 1
local base_resist = NPC.GetMagicalArmorDamageMultiplier(Unit)
if not Shield then
Shield = 0
if NPC.HasModifier(Unit, "modifier_item_hood_of_defiance_barrier") then
Shield = Shield + 325
end
if NPC.HasModifier(Unit, "modifier_item_pipe_barrier") then
Shield = Shield + 400
end
if NPC.HasItem(Unit, "item_infused_raindrop", 1) and Ability.GetCooldownTimeLeft(NPC.GetItem(Unit, "item_infused_raindrop", 1)) == 0 then
Shield = Shield + 120
end
if NPC.HasModifier(Unit, "modifier_ember_spirit_flame_guard") then
Shield = Shield + flame_guard
end
end
if NPC.HasAbility(Unit, "spectre_dispersion") then -- damage_reflection_pct
additional_res = additional_res * (1 - Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "spectre_dispersion"), "damage_reflection_pct") / 100)
end
if NPC.HasAbility(Unit, "antimage_spell_shield") and Entity.IsDormant(Unit) then -- spell_shield_resistance
additional_res = additional_res * (1 - Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "antimage_spell_shield"), "spell_shield_resistance") / 100)
end
if NPC.HasItem(Unit, "item_cloak", 1) and Entity.IsDormant(Unit) then -- spell_shield_resistance
additional_res = additional_res * 0.85
end
if NPC.HasItem(Unit, "item_hood_of_defiance", 1) and Entity.IsDormant(Unit) then -- spell_shield_resistance
additional_res = additional_res * 0.75
end
if NPC.HasItem(Unit, "item_pipe", 1) and Entity.IsDormant(Unit) then -- spell_shield_resistance
additional_res = additional_res * 0.70 * 0.9 -- aura
end
if NPC.HasModifier(Unit, "modifier_wisp_overcharge") then
additional_res = additional_res * wisp_overcharge
end
if NPC.HasModifier(Unit, "modifier_kunkka_ghost_ship_damage_absorb") then
additional_res = additional_res * kunkka_ghostship
end
if NPC.HasModifier(Unit, "modifier_ursa_enrage") then
additional_res = additional_res * 0.2
end
if NPC.HasModifier(Unit, "modifier_pangolier_shield_crash_buff") then
additional_res = additional_res * (1 - Modifier.GetStackCount(NPC.GetModifier(Unit, "modifier_pangolier_shield_crash_buff")) / 100)
end
if NPC.HasModifier(Unit, "modifier_visage_gravekeepers_cloak") then -- damage_reduction
if not visage_stack then
visage_stack = Modifier.GetStackCount(NPC.GetModifier(Unit, "modifier_visage_gravekeepers_cloak"))
end
if visage_stack > 0 then
local resist = (1 - Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "visage_gravekeepers_cloak"), "damage_reduction") / 100 * visage_stack)
visage_stack = visage_stack - 1
additional_res = additional_res * resist
end
end
if NPC.HasModifier(Unit, "modifier_templar_assassin_refraction_absorb") then
if not templar_stack then
templar_stack = Modifier.GetStackCount(NPC.GetModifier(Unit, "modifier_templar_assassin_refraction_absorb"))
end
if templar_stack > 0 then
templar_stack = templar_stack - 1
additional_res = 0
end
end
if NPC.HasModifier(Unit, "modifier_medusa_mana_shield") then -- absorption_tooltip
local resist = 1 - Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "medusa_mana_shield"), "absorption_tooltip") / 100
local damage_per_mana = Ability.GetLevelSpecialValueForFloat(NPC.GetAbility(Unit, "medusa_mana_shield"), "damage_per_mana")
local mana_damage = remote_damage * (1 - resist) / damage_per_mana
if Mp >= mana_damage then
Mp = Mp - mana_damage
else
resist = (remote_damage * resist + (mana_damage - Mp) * damage_per_mana) / remote_damage
Mp = 0
end
additional_res = additional_res * resist
end
if NPC.HasAbility(Unit, "huskar_berserkers_blood") then -- maximum_resistance
local resist = (1 - (Hp - Entity.GetMaxHealth(Unit) * 0.1) / (Entity.GetMaxHealth(Unit) * 0.9)) * (Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "huskar_berserkers_blood"), "maximum_resistance") / 100)
if resist > Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "huskar_berserkers_blood"), "maximum_resistance") / 100 then
resist = Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "huskar_berserkers_blood"), "maximum_resistance") / 100
end
base_resist = base_resist / (1 - (1 - (Entity.GetHealth(Unit) - Entity.GetMaxHealth(Unit) * 0.1) / (Entity.GetMaxHealth(Unit) * 0.9)) * (Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "huskar_berserkers_blood"), "maximum_resistance") / 100))
additional_res = additional_res * (1 - resist)
end
local calc_remote_damage = (remote_damage - Shield) * base_resist * additional_res
if calc_remote_damage < 0 then
calc_remote_damage = 0
end
if NPC.HasItem(Unit, "item_aeon_disk", 1) and Ability.GetCooldownTimeLeft(NPC.GetItem(Unit, "item_aeon_disk", 1)) == 0 and (Hp - calc_remote_damage) / Entity.GetMaxHealth(Unit) < 0.8 then -- spell_shield_resistance
if optionActiveAeon then
Hp = 0
calc_remote_damage = 999999
else
additional_res = 0
end
end
Hp = Hp - (remote_damage - Shield) * base_resist * additional_res
if Shield - remote_damage > 0 then
Shield = Shield - remote_damage
if Shield < 120 and NPC.HasItem(Unit, "item_infused_raindrop", 1) and Ability.GetCooldownTimeLeft(NPC.GetItem(Unit, "item_infused_raindrop", 1)) == 0 then
Shield = 0
end
else
Shield = 0
end
return calc_remote_damage, Hp, Mp, Shield, visage_stack, templar_stack
end
function TechiesHUD.GetNumRemoteForKill(Unit, remote_damage, Hp, Mp)
if NPC.GetMagicalArmorDamageMultiplier(Unit) == 0 then
return 1/0
end
if not Hp == Entity.GetMaxHealth(Unit) then
Hp = Hp + NPC.GetHealthRegen(Unit) * 0.3
end
if not Mp == NPC.GetMaxMana(Unit) then
Mp = Mp + NPC.GetManaRegen(Unit) * 0.3
end
local magic_shield = 0
if NPC.HasModifier(Unit, "modifier_item_hood_of_defiance_barrier") then
magic_shield = magic_shield + 325
end
if NPC.HasModifier(Unit, "modifier_item_pipe_barrier") then
magic_shield = magic_shield + 400
end
if NPC.HasItem(Unit, "item_infused_raindrop", 1) and Ability.GetCooldownTimeLeft(NPC.GetItem(Unit, "item_infused_raindrop", 1)) == 0 then
magic_shield = magic_shield + 120
end
if NPC.HasModifier(Unit, "modifier_ember_spirit_flame_guard") then
magic_shield = magic_shield + flame_guard
end
local additional_res
local base_resist
local num_calc = 0
local visage_stack
if Hp == Entity.GetMaxHealth(Unit) then
visage_stack = 4
end
while Hp > 0 do
num_calc = num_calc + 1
additional_res = 1
base_resist = NPC.GetMagicalArmorDamageMultiplier(Unit)
if NPC.HasAbility(Unit, "spectre_dispersion") then -- damage_reflection_pct
additional_res = additional_res * (1 - Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "spectre_dispersion"), "damage_reflection_pct") / 100)
end
if NPC.HasAbility(Unit, "antimage_spell_shield") and Entity.IsDormant(Unit) then -- spell_shield_resistance
additional_res = additional_res * (1 - Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "antimage_spell_shield"), "spell_shield_resistance") / 100)
end
if NPC.HasItem(Unit, "item_cloak", 1) and Entity.IsDormant(Unit) then -- spell_shield_resistance
additional_res = additional_res * 0.85
end
if NPC.HasItem(Unit, "item_hood_of_defiance", 1) and Entity.IsDormant(Unit) then -- spell_shield_resistance
additional_res = additional_res * 0.75
end
if NPC.HasItem(Unit, "item_pipe", 1) and Entity.IsDormant(Unit) then -- spell_shield_resistance
additional_res = additional_res * 0.70 * 0.9 -- aura
end
if NPC.HasModifier(Unit, "modifier_wisp_overcharge") then
additional_res = additional_res * wisp_overcharge
end
if NPC.HasModifier(Unit, "modifier_kunkka_ghost_ship_damage_absorb") then
additional_res = additional_res * kunkka_ghostship
end
if NPC.HasModifier(Unit, "modifier_ursa_enrage") then
additional_res = additional_res * 0.2
end
if NPC.HasModifier(Unit, "modifier_pangolier_shield_crash_buff") then
additional_res = additional_res * (1 - Modifier.GetStackCount(NPC.GetModifier(Unit, "modifier_pangolier_shield_crash_buff")) / 100)
end
if NPC.HasModifier(Unit, "modifier_visage_gravekeepers_cloak") then -- damage_reduction
if not visage_stack then
visage_stack = Modifier.GetStackCount(NPC.GetModifier(Unit, "modifier_visage_gravekeepers_cloak"))
end
if visage_stack > 0 then
local resist = (1 - Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "visage_gravekeepers_cloak"), "damage_reduction") / 100 * visage_stack)
visage_stack = visage_stack - 1
additional_res = additional_res * resist
end
end
if NPC.HasModifier(Unit, "modifier_medusa_mana_shield") then -- absorption_tooltip
local resist = 1 - Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "medusa_mana_shield"), "absorption_tooltip") / 100
local damage_per_mana = Ability.GetLevelSpecialValueForFloat(NPC.GetAbility(Unit, "medusa_mana_shield"), "damage_per_mana")
local mana_damage = remote_damage * (1 - resist) / damage_per_mana
if Mp >= mana_damage then
Mp = Mp - mana_damage
else
resist = (remote_damage * resist + (mana_damage - Mp) * damage_per_mana) / remote_damage
Mp = 0
end
additional_res = additional_res * resist
end
if NPC.HasAbility(Unit, "huskar_berserkers_blood") then -- maximum_resistance
local resist = (1 - (Hp - Entity.GetMaxHealth(Unit) * 0.1) / (Entity.GetMaxHealth(Unit) * 0.9)) * (Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "huskar_berserkers_blood"), "maximum_resistance") / 100)
if resist > Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "huskar_berserkers_blood"), "maximum_resistance") / 100 then
resist = Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "huskar_berserkers_blood"), "maximum_resistance") / 100
end
base_resist = base_resist / (1 - (1 - (Entity.GetHealth(Unit) - Entity.GetMaxHealth(Unit) * 0.1) / (Entity.GetMaxHealth(Unit) * 0.9)) * (Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "huskar_berserkers_blood"), "maximum_resistance") / 100))
additional_res = additional_res * (1 - resist)
end
local calc_remote_damage = (remote_damage - magic_shield) * base_resist * additional_res
if calc_remote_damage < 0 then
calc_remote_damage = 0
end
Hp = Hp - calc_remote_damage
if magic_shield - remote_damage > 0 then
magic_shield = magic_shield - remote_damage
if magic_shield < 120 and NPC.HasItem(Unit, "item_infused_raindrop", 1) and Ability.GetCooldownTimeLeft(NPC.GetItem(Unit, "item_infused_raindrop", 1)) == 0 then
magic_shield = 0
end
else
magic_shield = 0
end
end
if NPC.HasModifier(Unit, "modifier_templar_assassin_refraction_absorb") then
num_calc = num_calc + Modifier.GetStackCount(NPC.GetModifier(Unit, "modifier_templar_assassin_refraction_absorb"))
end
local last = 0
if additional_res and base_resist then
last = Hp / (remote_damage * additional_res * base_resist)
end
return num_calc + last
end
function TechiesHUD.Code(x, y)
local xmin, ymin = 0, 0
local xmax, ymax = Renderer.GetScreenSize()
local result = ((x < xmin) and 1 or 0) << 3 |
((x > xmax) and 1 or 0) << 2 |
((y < ymin) and 1 or 0) << 1 |
((y > ymax) and 1 or 0)
return result
end
function TechiesHUD.ClipLine(x1, y1, x2, y2)
local c1, c2 = TechiesHUD.Code(x1, y1), TechiesHUD.Code(x2, y2)
local dx, dy
local xmin, ymin = 0, 0
local xmax, ymax = Renderer.GetScreenSize()
while (c1 | c2) ~= 0 do
if (c1 & c2) ~= 0 then
return x1, y1, x2, y2
end
dx = x2 - x1
dy = y2 - y1
if c1 ~= 0 then
if x1 < xmin then
y1 = y1 + dy * (xmin - x1) / dx
x1 = xmin
elseif x1 > xmax then
y1 = y1 + dy * (xmax - x1) / dx
x1 = xmax
elseif y1 < ymin then
x1 = x1 + dx * (ymin - y1) / dy
y1 = ymin
elseif y1 > ymax then
x1 = x1 + dx * (ymax - y1) / dy
y1 = ymax
end
c1 = TechiesHUD.Code(x1, y1)
else
if x2 < xmin then
y2 = y2 + dy * (xmin - x2) / dx
x2 = xmin
elseif x2 > xmax then
y2 = y2 + dy * (xmax - x2) / dx
x2 = xmax
elseif y2 < ymin then
x2 = x2 + dx * (ymin - y2) / dy
y2 = ymin
elseif y2 > ymax then
x2 = x2 + dx * (ymax - y2) / dy
y2 = ymax
end
c2 = TechiesHUD.Code(x2, y2)
end
end
return x1, y1, x2, y2
end
function TechiesHUD.DrawCircle(UnitPos, radius, degree)
local x, y, visible = Renderer.WorldToScreen(UnitPos + Vector(0, radius, 0))
if visible == 1 then
for angle = 0, 360 / degree do
local x1, y1 = Renderer.WorldToScreen(UnitPos + Vector(0, radius, 0):Rotated(Angle(0, angle * degree, 0)))
Renderer.DrawLine(x, y, x1, y1)
x, y = x1, y1
end
end
end
function TechiesHUD.CheckMove(Unit, Unit2, pred_time)
local UnitPos = Entity.GetAbsOrigin(Unit)
local UnitPos2 = Entity.GetAbsOrigin(Unit2)
local MoveSpeed = NPC.GetMoveSpeed(Unit)
local TurnRate = 0.0942 / NPC.GetTurnRate(Unit)
local firstRotate = Entity.GetAbsRotation(Unit):GetYaw() - 90
local x4, y4
local dergee = 30
local check = 1
for angle = 0, 360 / dergee / 2 do
local radius = (MoveSpeed * pred_time) - (TurnRate * ((angle * dergee) / 180) * MoveSpeed)
x4 = 0 * math.cos((firstRotate + (angle * dergee)) / 57.3) - radius * math.sin((firstRotate + (angle * dergee)) / 57.3)
y4 = radius * math.cos((firstRotate + (angle * dergee)) / 57.3) + 0 * math.sin((firstRotate + (angle * dergee)) / 57.3)
if (UnitPos - UnitPos2 + Vector(x4, y4, 0)):Length() > 425 then
check = 0
end
end
firstRotate = 0 - firstRotate
for angle = 0, 360 / dergee / 2 do
local radius = (MoveSpeed * pred_time) - (TurnRate * ((angle * dergee) / 180) * MoveSpeed)
x4 = 0 * math.cos((firstRotate + (angle * dergee)) / -57.3) - radius * math.sin((firstRotate + (angle * dergee)) / -57.3)
y4 = radius * math.cos((firstRotate + (angle * dergee)) / -57.3) + 0 * math.sin((firstRotate + (angle * dergee)) / -57.3)
if (UnitPos - UnitPos2 + Vector(x4, y4, 0)):Length() > 425 then
check = 0
end
end
return check
end
function TechiesHUD.UpdateGUISettings()
optionTotal = GUI.IsEnabled(TechiesHUD.Identity)
if not optionTotal then return end
optionDetonate = GUI.IsEnabled(TechiesHUD.Identity .. "optionDetonate")
optionActiveAeon = GUI.IsEnabled(TechiesHUD.Identity .. "optionActiveAeon")
optionUpdate = GUI.IsEnabled(TechiesHUD.Identity .. "optionUpdate")
optionLR = GUI.IsEnabled(TechiesHUD.Identity .. "optionLR")
optionSR = GUI.IsEnabled(TechiesHUD.Identity .. "optionSR")
optionRR = GUI.IsEnabled(TechiesHUD.Identity .. "optionRR")
optionAutoPlant = GUI.IsEnabled(TechiesHUD.Identity .. "optionAutoPlant")
optionBlastInfo = GUI.IsEnabled(TechiesHUD.Identity .. "optionBlastInfo")
optionDelay = GUI.Get(TechiesHUD.Identity .. "optionDelay")
optionForceDrawLine = GUI.IsEnabled(TechiesHUD.Identity .. "optionForceDrawLine")
optionPanelInfo = GUI.IsEnabled(TechiesHUD.Identity .. "optionPanelInfo")
optionDetonateFast = GUI.IsEnabled(TechiesHUD.Identity .. "optionDetonateFast")
optionForce = GUI.IsEnabled(TechiesHUD.Identity .. "optionForce")
optionAutoPlantNumMines = GUI.Get(TechiesHUD.Identity .. "optionAutoPlantNumMines")
optionDetonateWk = GUI.IsEnabled(TechiesHUD.Identity .. "optionDetonateWk")
optionDetonateAegis = GUI.IsEnabled(TechiesHUD.Identity .. "optionDetonateAegis")
if GUI.Get(TechiesHUD.Identity .. "optionLegitDetonate", 1) and 1 or 0 == 1 then
for k, v in pairs(GUI.Get(TechiesHUD.Identity .. "optionLegitDetonate", 1)) do
optionLegitDetonate = v == 1
end
else
optionLegitDetonate = false
end
optionDetonateCam = GUI.IsEnabled(TechiesHUD.Identity .. "optionDetonateCam")
optionFDFailSwitch = GUI.IsEnabled(TechiesHUD.Identity .. "optionFDFailSwitch")
if GUI.Get(TechiesHUD.Identity .. "optionFDFailSwitchMod", 1) and 1 or 0 == 1 then
for k, v in pairs(GUI.Get(TechiesHUD.Identity .. "optionFDFailSwitchMod", 1)) do
optionFDFailSwitchMode = v == 1
end
else
optionFDFailSwitchMode = false
end
if GUI.Get(TechiesHUD.Identity .. "optionDrawCircleMethod", 1) and 1 or 0 == 1 then
for k, v in pairs(GUI.Get(TechiesHUD.Identity .. "optionDrawCircleMethod", 1)) do
if v ~= 1 then
for i, particle in pairs(TechiesHUD.ParticleList) do
Particle.Destroy(TechiesHUD.ParticleList[particle.Unit].particle)
if TechiesHUD.ParticleList[particle.Unit].particle2 then
Particle.Destroy(TechiesHUD.ParticleList[particle.Unit].particle2)
end
TechiesHUD.ParticleList[particle.Unit] = nil
end
end
optionDrawCircleMethod = v == 1
end
else
optionDrawCircleMethod = false
end
optionPanelInfoXL = GUI.Get(TechiesHUD.Identity .. "optionPanelInfoXL")
optionPanelInfoXR = GUI.Get(TechiesHUD.Identity .. "optionPanelInfoXR")
optionPanelInfoY = GUI.Get(TechiesHUD.Identity .. "optionPanelInfoY")
optionPanelInfoDist = GUI.Get(TechiesHUD.Identity .. "optionPanelInfoDist")
optionPanelInfoGemAndSentry = GUI.IsEnabled(TechiesHUD.Identity .. "optionPanelInfoGemAndSentry")
optionResCircle = GUI.Get(TechiesHUD.Identity .. "optionResCircle")
if GUI.Get(TechiesHUD.Identity .. "optionFont1") ~= optionFont1 then
optionFont1 = GUI.Get(TechiesHUD.Identity .. "optionFont1")
TechiesHUD.font = Renderer.LoadFont("Tahoma", tonumber(optionFont1), Enum.FontWeight.EXTRABOLD)
end
if GUI.Get(TechiesHUD.Identity .. "optionFont2") ~= optionFont2 or optionPanelInfoSize ~= GUI.Get(TechiesHUD.Identity .. "optionPanelInfoSize") / 100 then
optionPanelInfoSize = GUI.Get(TechiesHUD.Identity .. "optionPanelInfoSize") / 100
TechiesHUD.ScreenScale = TechiesHUD.ScreenScale1 + optionPanelInfoSize
optionFont2 = GUI.Get(TechiesHUD.Identity .. "optionFont2")
TechiesHUD.HUDfont = Renderer.LoadFont("Tahoma", math.floor(tonumber(optionFont2) * (TechiesHUD.ScreenScale)), Enum.FontWeight.EXTRABOLD)
end
if GUI.Get(TechiesHUD.Identity .. "optionAltInfoTimeMinesPanelSize") ~= optionFont3 then
optionFont3 = GUI.Get(TechiesHUD.Identity .. "optionAltInfoTimeMinesPanelSize")
TechiesHUD.Panelfont = Renderer.LoadFont("Tahoma", math.floor(18 * tonumber(optionFont3) / 100), Enum.FontWeight.EXTRABOLD)
TechiesHUD.Panelfont1 = Renderer.LoadFont("Tahoma", math.floor(18 * tonumber(optionFont3) / 100), Enum.FontWeight.NORMAL)
end
optionAltInfoDrawing = GUI.IsEnabled(TechiesHUD.Identity .. "optionAltInfoDrawing")
optionAltInfoRemoteNumberInManaPool = GUI.IsEnabled(TechiesHUD.Identity .. "optionAltInfoRemoteNumberInManaPool")
optionAltInfoNumLevelRemote = GUI.IsEnabled(TechiesHUD.Identity .. "optionAltInfoNumLevelRemote")
optionAltInfoTimeMines = GUI.IsEnabled(TechiesHUD.Identity .. "optionAltInfoTimeMines")
optionAltInfoTimeMinesPanelSize = GUI.Get(TechiesHUD.Identity .. "optionAltInfoTimeMinesPanelSize") / 100
optionAltInfoEnemyNumRemote = GUI.IsEnabled(TechiesHUD.Identity .. "optionAltInfoEnemyNumRemote")
optionMinePlacerLM = GUI.IsEnabled(TechiesHUD.Identity .. "optionMinePlacerLM")
optionMinePlacerST = GUI.IsEnabled(TechiesHUD.Identity .. "optionMinePlacerST")
end
local ClickSave = true
local CursorOnButton = false
function TechiesHUD.OnDraw()
if GUI == nil then return end
if not GUI.Exist(TechiesHUD.Identity) then
GUI.Initialize(TechiesHUD.Identity, GUI.Category.Heroes, TechiesHUD.Locale["name"], TechiesHUD.Locale["desc"], "Zerling14", "npc_dota_hero_techies")
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "detonateSection", TechiesHUD.Locale["detonateSection"], GUI.MenuType.Label) -- Detonate
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionDetonate", TechiesHUD.Locale["optionDetonate"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionActiveAeon", TechiesHUD.Locale["optionActiveAeon"], GUI.MenuType.CheckBox, 1)
--GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionUpdate", TechiesHUD.Locale["empty"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionForce", TechiesHUD.Locale["forceStaff"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionDetonateWk", TechiesHUD.Locale["detonateWK"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionDetonateAegis", TechiesHUD.Locale["detonateAegis"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionDetonateFast", TechiesHUD.Locale["detonateFast"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionLegitDetonate", TechiesHUD.Locale["detonateTogleMode"], GUI.MenuType.SelectBox, TechiesHUD.Locale["detonateMode"], { 0 }, 1, nil)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionDetonateCam", TechiesHUD.Locale["detonateCam"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionDelay", TechiesHUD.Locale["delayDetonate"], GUI.MenuType.Slider, 0, 2000, 700)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "autoStackSection1", TechiesHUD.Locale["autoStackSection1"], GUI.MenuType.Label) -- Auto stack
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "autoStackSection2", TechiesHUD.Locale["autoStackSection2"], GUI.MenuType.Label) -- Auto stack
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "autoStackSection3", TechiesHUD.Locale["autoStackSection3"], GUI.MenuType.Label) -- Auto stack
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionAutoPlant", TechiesHUD.Locale["autoPlant"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionAutoPlantNumMines", TechiesHUD.Locale["autoPlantNumMines"], GUI.MenuType.Slider, 1, 20, 6)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionAutoPlantStackRange", TechiesHUD.Locale["autoPlantStackRange"], GUI.MenuType.Slider, 0,200, 200)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionAutoPlantKey", TechiesHUD.Locale["autoPlantKey"], GUI.MenuType.Key, "T", TechiesHUD.SetSpot, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "stackMinesSection", TechiesHUD.Locale["stackMinesSection"], GUI.MenuType.Label) -- Stack mines
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionStack", TechiesHUD.Locale["stackMines"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionStackRange", TechiesHUD.Locale["stackRange"], GUI.MenuType.Slider, 0, 200, 100)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "FDFailSwitchSection1", TechiesHUD.Locale["FDFailSwitchSection1"], GUI.MenuType.Label) -- FD FailSwitch
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "FDFailSwitchSection2", TechiesHUD.Locale["FDFailSwitchSection2"], GUI.MenuType.Label) -- FD FailSwitch
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionFDFailSwitch", TechiesHUD.Locale["FDFailSwitch"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionEmpty", TechiesHUD.Locale["empty"], GUI.MenuType.Label) -- Alt info
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionFDFailSwitchMod", TechiesHUD.Locale["FDFailSwitchTogleMode"], GUI.MenuType.SelectBox, TechiesHUD.Locale["detonateMode"], { 0 }, 1, nil)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionAltInfo", TechiesHUD.Locale["altInfo"], GUI.MenuType.Label) -- Alt info
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionAltInfoDrawing", TechiesHUD.Locale["altInfoDrawing"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionAltInfoRemoteNumberInManaPool", TechiesHUD.Locale["altInfoRemoteNumberInManaPool"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionAltInfoNumLevelRemote", TechiesHUD.Locale["altInfoNumLevelRemote"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionAltInfoEnemyNumRemote", TechiesHUD.Locale["altInfoEnemyNumRemote"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionAltInfoTimeMines", TechiesHUD.Locale["altInfoTimeMines"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionAltInfoTimeMinesPanelSize", TechiesHUD.Locale["altInfoTimeMinesPanelSize"], GUI.MenuType.Slider, 50, 200, 100)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionEmpty", TechiesHUD.Locale["empty"], GUI.MenuType.Label) -- Alt info
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "drawingOptionSection", TechiesHUD.Locale["drawingOptionSection"], GUI.MenuType.Label) -- Drawing
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionPanelInfo", TechiesHUD.Locale["panelInfo"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionDrawCircleMethod", TechiesHUD.Locale["drawCircleMethod"], GUI.MenuType.SelectBox, TechiesHUD.Locale["drawCircleMode"], { 0 }, 1, nil)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionLR", TechiesHUD.Locale["drawRadiusLR"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionSR", TechiesHUD.Locale["drawRadiusSR"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionRR", TechiesHUD.Locale["drawRadiusRR"], GUI.MenuType.CheckBox, 1) -- GUI.IsEnabled(TechiesHUD.Identity .. "optionLR")
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionResCircle", TechiesHUD.Locale["resCircle"], GUI.MenuType.Slider, 1, 90, 20)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionForceDrawLine", TechiesHUD.Locale["forceStaffLine"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionBlastInfo", TechiesHUD.Locale["blastInfo"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionFont1", TechiesHUD.Locale["font1"], GUI.MenuType.Slider, 10, 80, 20)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionFont2", TechiesHUD.Locale["font2"], GUI.MenuType.Slider, 10, 80, 25)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "panelOptionsSection", TechiesHUD.Locale["panelOptionsSection"], GUI.MenuType.Label) -- Panel options
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionPanelInfoXL", TechiesHUD.Locale["panelInfoXL"], GUI.MenuType.Slider, -50, 50, 0)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionPanelInfoXR", TechiesHUD.Locale["panelInfoXR"], GUI.MenuType.Slider, -50, 50, 0)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionPanelInfoY", TechiesHUD.Locale["panelInfoY"], GUI.MenuType.Slider, -200, 200, 0)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionPanelInfoSize", TechiesHUD.Locale["panelInfoSize"], GUI.MenuType.Slider, -70, 200, 0)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionPanelInfoDist", TechiesHUD.Locale["panelInfoDist"], GUI.MenuType.Slider, -20, 20, 0)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionPanelInfoGemAndSentry", TechiesHUD.Locale["panelInfoGemAndSentry"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionMinePlacer", TechiesHUD.Locale["minePlacer"], GUI.MenuType.Label) --minePlacerLM
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionMinePlacerLM", TechiesHUD.Locale["minePlacerLM"], GUI.MenuType.CheckBox, 1)
GUI.AddMenuItem(TechiesHUD.Identity, TechiesHUD.Identity .. "optionMinePlacerST", TechiesHUD.Locale["minePlacerST"], GUI.MenuType.CheckBox, 1)
TechiesHUD.UpdateGUISettings()
for i, Unit in pairs(NPCs.GetAll()) do
table.insert(TechiesHUD.UndefEntity, Unit)
end
end
if GUI.SleepReady("updateSettings") and GUI.IsEnabled("gui:show") then
TechiesHUD.UpdateGUISettings()
GUI.Sleep("updateSettings", 0.1)
end
if not optionTotal then return end
local myHero = Heroes.GetLocal()
if not myHero then
return
end
if NPC.GetUnitName(myHero) ~= "npc_dota_hero_techies" then
return
end
local land_m = NPC.GetAbilityByIndex(myHero, 0)
local trap_m = NPC.GetAbilityByIndex(myHero, 1)
local blast = NPC.GetAbilityByIndex(myHero, 2)
local remote = NPC.GetAbilityByIndex(myHero, 5)
local force = NPC.GetItem(myHero, "item_force_staff", 1)
local land_m_damage = Ability.GetLevelSpecialValueFor(land_m, "damage")
local blast_damage = Ability.GetLevelSpecialValueFor(blast, "damage") + Ability.GetLevel(NPC.GetAbilityByIndex(myHero, 8)) * 300
local magicalDamageMul = 1 + Hero.GetIntellectTotal(myHero)/ 14 / 100 + 0.1 *(NPC.HasItem(myHero, "item_kaya", 1) and 1 or 0)
local remote_damage = Ability.GetLevelSpecialValueFor(remote, "damage")
if Ability.IsInAbilityPhase(blast) then
if optionDrawCircleMethod then
if not TechiesHUD.BlastPositionCircle then
TechiesHUD.BlastPositionCircle = Particle.Create("particles\\ui_mouseactions\\drag_selected_ring.vpcf")
Particle.SetControlPoint(TechiesHUD.BlastPositionCircle, 3, Vector(9, 0, 0))
Particle.SetControlPoint(TechiesHUD.BlastPositionCircle, 2, Vector(400, 255, 0))
Particle.SetControlPoint(TechiesHUD.BlastPositionCircle, 0, TechiesHUD.BlastPosition)
if Entity.GetHealth(myHero) / Entity.GetMaxHealth(myHero) >= 0.5 then
Particle.SetControlPoint(TechiesHUD.BlastPositionCircle, 1, Vector(255, 255, 255))
else
Particle.SetControlPoint(TechiesHUD.BlastPositionCircle, 1, Vector(255, 0, 0))
end
end
else
if Entity.GetHealth(myHero) / Entity.GetMaxHealth(myHero) >= 0.5 then
Renderer.SetDrawColor(255, 255, 255, 255)
else
Renderer.SetDrawColor(255, 0, 0, 255)
end
TechiesHUD.DrawCircle(TechiesHUD.BlastPosition, 400, optionResCircle)
end
local x, y = Renderer.WorldToScreen(TechiesHUD.BlastPosition)
Renderer.SetDrawColor(255, 255, 255, 255)
Renderer.DrawTextCentered(TechiesHUD.font, x, y, math.floor(Entity.GetHealth(myHero) - Entity.GetMaxHealth(myHero) * 0.5), 0)
elseif TechiesHUD.BlastPositionCircle then
Particle.Destroy(TechiesHUD.BlastPositionCircle)
TechiesHUD.BlastPositionCircle = nil
end
if optionAutoPlant then
for i, spot in pairs(spot_for_plant) do
local x, y, visible = Renderer.WorldToScreen(spot.position)
if visible == 1 then
Renderer.SetDrawColor(255, 255, 255, 255)
TechiesHUD.DrawCircle(spot.position, 200, optionResCircle)
end
end
end
if remote ~= nil and Ability.GetLevel(remote) ~= 0 and Input.IsKeyDown(Enum.ButtonCode.KEY_LALT) and optionAltInfoDrawing and optionAltInfoRemoteNumberInManaPool then
local x, y = Renderer.WorldToScreen(Input.GetWorldCursorPos())
Renderer.SetDrawColor(255, 255, 255, 255)
local mp = Ability.GetCooldownTimeLeft(remote) * NPC.GetManaRegen(myHero) + NPC.GetMana(myHero)
local num_remote = 0
if (Ability.GetCooldownLength(remote) + Ability.GetCastPoint(remote)) * NPC.GetManaRegen(myHero) < Ability.GetManaCost(remote) then
while mp >= Ability.GetManaCost(remote) do
num_remote = num_remote + 1
mp = mp - Ability.GetManaCost(remote) + (Ability.GetCooldownLength(remote) + Ability.GetCastPoint(remote)) * NPC.GetManaRegen(myHero)
end
Renderer.DrawText(TechiesHUD.font, x, y - 20, num_remote + math.ceil(mp / Ability.GetManaCost(remote) * 100) / 100, 0)
else
Renderer.DrawText(TechiesHUD.font, x, y - 20, "inf", 0)
end
end
CursorOnButton = false
for i, Unit in pairs(TechiesHUD.LandMinesList) do
if NPC.HasModifier(Unit, "modifier_techies_land_mine") then
local UnitPos = Entity.GetAbsOrigin(Unit)
if not optionDrawCircleMethod then
if optionLR and Entity.IsAlive(Unit) then
Renderer.SetDrawColor(255, 20, 0, 255)
TechiesHUD.DrawCircle(UnitPos, 400, optionResCircle)
end
else
if TechiesHUD.ParticleList[Unit] then
Particle.SetControlPoint(TechiesHUD.ParticleList[Unit].particle, 0, Entity.GetAbsOrigin(Unit))
end
end
if GameRules.GetGameTime() - Modifier.GetCreationTime(NPC.GetModifier(Unit, "modifier_techies_land_mine")) < 1.75 then
local x, y, visible = Renderer.WorldToScreen(UnitPos)
if visible == 1 then
Renderer.SetDrawColor(255, 255, 255, 255)
Renderer.DrawText(TechiesHUD.font, x, y, math.floor((1.75 - (GameRules.GetGameTime() - Modifier.GetCreationTime(NPC.GetModifier(Unit, "modifier_techies_land_mine")))) * 100) / 100, 0)
end
else
local IsActive = false
for j, Unit2 in pairs(Entity.GetUnitsInRadius(Unit, 400, Enum.TeamType.TEAM_ENEMY)) do
IsActive = true
if not TechiesHUD.LandMinesTimings[Unit] then
TechiesHUD.LandMinesTimings[Unit] = GameRules.GetGameTime() + 1.6
end
if TechiesHUD.LandMinesTimings[Unit] - GameRules.GetGameTime() > 0 then
local x, y, visible = Renderer.WorldToScreen(UnitPos)
if visible == 1 then
Renderer.SetDrawColor(255, 255, 255, 255)
Renderer.DrawText(TechiesHUD.font, x, y, math.floor((TechiesHUD.LandMinesTimings[Unit] - GameRules.GetGameTime()) * 100) / 100, 0)
end
end
break;
end
if not IsActive then
TechiesHUD.LandMinesTimings[Unit] = nil
end
end
elseif not Entity.IsAlive(Unit) and TechiesHUD.ParticleList[Unit] then
Particle.Destroy(TechiesHUD.ParticleList[Unit].particle)
TechiesHUD.ParticleList[Unit] = nil
end
end
for i, Unit in pairs(TechiesHUD.StasisMinesList) do
local UnitPos = Entity.GetAbsOrigin(Unit)
if not optionDrawCircleMethod then
if optionSR and Entity.IsAlive(Unit) then
Renderer.SetDrawColor(0, 255, 255, 255)
TechiesHUD.DrawCircle(UnitPos, 600, optionResCircle)
Renderer.SetDrawColor(0, 0, 255, 255)
TechiesHUD.DrawCircle(UnitPos, 405, optionResCircle)
end
else
if TechiesHUD.ParticleList[Unit] then
Particle.SetControlPoint(TechiesHUD.ParticleList[Unit].particle, 0, Entity.GetAbsOrigin(Unit))
Particle.SetControlPoint(TechiesHUD.ParticleList[Unit].particle2, 0, Entity.GetAbsOrigin(Unit))
end
end
if NPC.HasModifier(Unit, "modifier_techies_stasis_trap") and GameRules.GetGameTime() - Modifier.GetCreationTime(NPC.GetModifier(Unit, "modifier_techies_stasis_trap")) < 2 then
local x, y, visible = Renderer.WorldToScreen(UnitPos)
if visible == 1 then
Renderer.SetDrawColor(255, 255, 255, 255)
Renderer.DrawText(TechiesHUD.font, x, y, math.floor((2 - (GameRules.GetGameTime() - Modifier.GetCreationTime(NPC.GetModifier(Unit, "modifier_techies_stasis_trap")))) * 100)/100, 0)
end
end
if not Entity.IsAlive(Unit) and TechiesHUD.ParticleList[Unit] then
Particle.Destroy(TechiesHUD.ParticleList[Unit].particle)
Particle.Destroy(TechiesHUD.ParticleList[Unit].particle2)
TechiesHUD.ParticleList[Unit] = nil
end
end
remote_pos_draw = {}
mines_num = {}
for i, Unit in pairs(TechiesHUD.RemoteMinesList) do
local RemoteMinesModif = NPC.GetModifier(Unit, "modifier_techies_remote_mine")
local UnitPos = Entity.GetAbsOrigin(Unit)
if Entity.IsAlive(Unit) then
if not optionDrawCircleMethod then
if optionRR then
local scaled_x = math.floor(UnitPos:GetX())
local scaled_y = math.floor(UnitPos:GetY())
if remote_pos_draw[scaled_x] == nil then
remote_pos_draw[scaled_x] = {}
remote_pos_draw[scaled_x][scaled_y] = 0
end
if remote_pos_draw[scaled_x][scaled_y] ~= 1 then
remote_pos_draw[scaled_x][scaled_y] = 1
Renderer.SetDrawColor(0, 255, 0, 255)
TechiesHUD.DrawCircle(UnitPos, 425, optionResCircle)
end
end
else
if TechiesHUD.ParticleList[Unit] then
Particle.SetControlPoint(TechiesHUD.ParticleList[Unit].particle, 0, Entity.GetAbsOrigin(Unit))
end
end
if mines_num[Unit] == nil and RemoteMinesModif then
mines_num[Unit] = 1
end
if mines_num[Unit] == 1 then
if RemoteMinesModif then
local x, y, visible = Renderer.WorldToScreen(UnitPos)
if visible == 1 then
local num_mines = 0
local num_mines_1_lvl = 0
local num_mines_2_lvl = 0
local num_mines_3_lvl = 0
local oldest_mine = {die_time = math.huge}
local stack_mines = {}
for j, Unit2 in pairs(TechiesHUD.RemoteMinesList) do
local remote_modif = NPC.GetModifier(Unit2, "modifier_techies_remote_mine")
if NPC.IsPositionInRange(Unit2, UnitPos, 425, Enum.TeamType.TEAM_FRIEND)
and remote_modif
then
if Input.IsKeyDown(Enum.ButtonCode.KEY_LALT) and optionAltInfoDrawing then
local obj_mine = {Unit = Unit2}
if optionAltInfoNumLevelRemote then
local mines_level = (TechiesHUD.RemoteMinesDamage[Unit2] - 150) / 150
obj_mine.level = mines_level
if mines_level == 1 then
num_mines_1_lvl = num_mines_1_lvl + 1
elseif mines_level == 2 then
num_mines_2_lvl = num_mines_2_lvl + 1
elseif mines_level == 3 then
num_mines_3_lvl = num_mines_3_lvl + 1
end
end
if optionAltInfoTimeMines then
local modif_die_time = Modifier.GetDieTime(remote_modif)
obj_mine.die_time = modif_die_time
if oldest_mine.die_time > modif_die_time then
oldest_mine = {die_time = modif_die_time, mine = Unit2}
end
end
table.insert(stack_mines, obj_mine)
else
num_mines = num_mines + 1
end
mines_num[Unit2] = 0
if state_mines[Unit] == nil then
state_mines[Unit] = true
end
if need_enemy[Unit] == nil then
local need_enemy_tmp
for k, Unit3 in pairs(TechiesHUD.RemoteMinesList) do
local remote_modif = NPC.GetModifier(Unit3, "modifier_techies_remote_mine")
if NPC.IsPositionInRange(Unit3, UnitPos, 425, Enum.TeamType.TEAM_FRIEND)
and remote_modif
and Unit ~= Unit3
then
if need_enemy[Unit3] then
need_enemy_tmp = need_enemy[Unit3]
end
end
end
if need_enemy_tmp then
need_enemy[Unit] = need_enemy_tmp
else
need_enemy[Unit] = 1
end
end
need_enemy[Unit2] = need_enemy[Unit]
state_mines[Unit2] = state_mines[Unit]
if TechiesHUD.ParticleList[Unit2] then
if not state_mines[Unit] then
Particle.SetControlPoint(TechiesHUD.ParticleList[Unit2].particle, 1, Vector(20, 120, 25))
else
Particle.SetControlPoint(TechiesHUD.ParticleList[Unit2].particle, 1, Vector(80, 255, 50))
end
end
end
end
Renderer.SetDrawColor(255, 255, 255, 255)
if Input.IsKeyDown(Enum.ButtonCode.KEY_LALT) and optionAltInfoDrawing then
if optionAltInfoNumLevelRemote then
Renderer.DrawText(TechiesHUD.font, x, y - math.floor(tonumber(optionFont1) * 1), "1:" .. num_mines_1_lvl .. " 2:" .. num_mines_2_lvl .. " 3:" .. num_mines_3_lvl, 0)
end
if optionAltInfoTimeMines then
table.sort(stack_mines, function (a, b) return a.die_time < b.die_time end)
--need_enemy[Unit]
local h = 0
if #stack_mines <= 3 then
h = 1
end
Renderer.SetDrawColor(30, 30, 30, 150)
Renderer.DrawFilledRect(x, y, math.floor(80 * optionAltInfoTimeMinesPanelSize), math.floor(16 * optionAltInfoTimeMinesPanelSize) * #stack_mines + h)
Renderer.SetDrawColor(200, 200, 200, 150)
Renderer.DrawOutlineRect(x, y, math.floor(80 * optionAltInfoTimeMinesPanelSize), math.floor(16 * optionAltInfoTimeMinesPanelSize) * #stack_mines + h)
if Input.IsCursorInRect(x - math.floor(20 * optionAltInfoTimeMinesPanelSize), y, math.floor(20 * optionAltInfoTimeMinesPanelSize) + 1, math.floor(16 * optionAltInfoTimeMinesPanelSize) + 1) then
CursorOnButton = true
Renderer.SetDrawColor(100, 100, 100, 250)
if Input.IsKeyDown(Enum.ButtonCode.MOUSE_RIGHT) then
if ClickSave then
state_mines[Unit] = not state_mines[Unit]
if not state_mines[Unit] then
Particle.SetControlPoint(TechiesHUD.ParticleList[Unit].particle, 1, Vector(20, 120, 25))
else
Particle.SetControlPoint(TechiesHUD.ParticleList[Unit].particle, 1, Vector(80, 255, 50))
end
ClickSave = false
end
else
ClickSave = true
end
else
Renderer.SetDrawColor(30, 30, 30, 150)
end
Renderer.DrawFilledRect(x - math.floor(20 * optionAltInfoTimeMinesPanelSize), y, math.floor(20 * optionAltInfoTimeMinesPanelSize) + 1, math.floor(16 * optionAltInfoTimeMinesPanelSize))
Renderer.SetDrawColor(200, 200, 200, 150)
Renderer.DrawOutlineRect(x - math.floor(20 * optionAltInfoTimeMinesPanelSize), y, math.floor(20 * optionAltInfoTimeMinesPanelSize) + 1, math.floor(16 * optionAltInfoTimeMinesPanelSize) * 4)
Renderer.SetDrawColor(255, 255, 255, 255)
local text
if state_mines[Unit] then
text = "on"
else
text = "off"
end
Renderer.DrawTextCentered(TechiesHUD.Panelfont1, x - math.floor(10 * optionAltInfoTimeMinesPanelSize), y + math.floor(8 * optionAltInfoTimeMinesPanelSize), text, 0)
-- num min -
if Input.IsCursorInRect(x - math.floor(20 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) + 1, math.floor(20 * optionAltInfoTimeMinesPanelSize), math.floor(16 * optionAltInfoTimeMinesPanelSize) + 1) then
CursorOnButton = true
Renderer.SetDrawColor(100, 100, 100, 250)
if Input.IsKeyDown(Enum.ButtonCode.MOUSE_RIGHT) then
if ClickSave then
if need_enemy[Unit] > 1 then
need_enemy[Unit] = need_enemy[Unit] - 1
end
ClickSave = false
end
else
ClickSave = true
end
else
Renderer.SetDrawColor(30, 30, 30, 150)
end
Renderer.DrawFilledRect(x - math.floor(20 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize), math.floor(20 * optionAltInfoTimeMinesPanelSize), math.floor(16 * optionAltInfoTimeMinesPanelSize))
Renderer.SetDrawColor(200, 200, 200, 150)
Renderer.DrawOutlineRect(x - math.floor(20 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize), math.floor(20 * optionAltInfoTimeMinesPanelSize) + 1, math.floor(16 * optionAltInfoTimeMinesPanelSize) * 3)
Renderer.SetDrawColor(255, 255, 255, 255)
Renderer.DrawTextCentered(TechiesHUD.Panelfont1, x - math.floor(10 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) + math.floor(8 * optionAltInfoTimeMinesPanelSize), "-", 0)
-- num min text
Renderer.SetDrawColor(30, 30, 30, 150)
Renderer.DrawFilledRect(x - math.floor(20 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * 2, math.floor(20 * optionAltInfoTimeMinesPanelSize), math.floor(16 * optionAltInfoTimeMinesPanelSize))
Renderer.SetDrawColor(200, 200, 200, 150)
Renderer.DrawOutlineRect(x - math.floor(20 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * 2, math.floor(20 * optionAltInfoTimeMinesPanelSize) + 1, math.floor(16 * optionAltInfoTimeMinesPanelSize) * 2)
Renderer.SetDrawColor(255, 255, 255, 255)
Renderer.DrawTextCentered(TechiesHUD.Panelfont1, x - math.floor(10 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * 2 + math.floor(8 * optionAltInfoTimeMinesPanelSize), need_enemy[Unit], 0)
-- num min +
if Input.IsCursorInRect(x - math.floor(20 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * 3, math.floor(20 * optionAltInfoTimeMinesPanelSize), math.floor(16 * optionAltInfoTimeMinesPanelSize) + 1) then
CursorOnButton = true
Renderer.SetDrawColor(100, 100, 100, 250)
if Input.IsKeyDown(Enum.ButtonCode.MOUSE_RIGHT) then
if ClickSave then
need_enemy[Unit] = need_enemy[Unit] + 1
ClickSave = false
end
else
ClickSave = true
end
else
Renderer.SetDrawColor(30, 30, 30, 150)
end
Renderer.DrawFilledRect(x - math.floor(20 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * 3, math.floor(20 * optionAltInfoTimeMinesPanelSize), math.floor(16 * optionAltInfoTimeMinesPanelSize))
Renderer.SetDrawColor(200, 200, 200, 150)
Renderer.DrawOutlineRect(x - math.floor(20 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * 3, math.floor(20 * optionAltInfoTimeMinesPanelSize) + 1, math.floor(16 * optionAltInfoTimeMinesPanelSize))
Renderer.SetDrawColor(255, 255, 255, 255)
Renderer.DrawTextCentered(TechiesHUD.Panelfont1, x - math.floor(10 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * 3 + math.floor(8 * optionAltInfoTimeMinesPanelSize), "+", 0)
for i, oldest_mine in pairs(stack_mines) do
local h = 0
if #stack_mines <= 3 then
h = 1
end
Renderer.SetDrawColor(255, 255, 255, 255)
Renderer.DrawText(TechiesHUD.Panelfont, x + math.floor(20 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * (i - 1), math.floor((oldest_mine.die_time - GameRules.GetGameTime()) / 60) .. ":" .. string.format("%02d", math.floor((oldest_mine.die_time - GameRules.GetGameTime()) % 60)), 0)
Renderer.DrawText(TechiesHUD.Panelfont, x + math.floor(5 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * (i - 1), math.floor(oldest_mine.level))
if Input.IsCursorInRect(x + math.floor(60 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * (i - 1), x + math.floor(80 * optionAltInfoTimeMinesPanelSize) - (x + math.floor(60 * optionAltInfoTimeMinesPanelSize)), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * #stack_mines - (y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * (#stack_mines - 1)) + 1) then
CursorOnButton = true
Renderer.SetDrawColor(100, 100, 100, 250)
Renderer.DrawFilledRect(x + math.floor(60 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * (i - 1), x + math.floor(80 * optionAltInfoTimeMinesPanelSize) - (x + math.floor(60 * optionAltInfoTimeMinesPanelSize)), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * #stack_mines - (y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * (#stack_mines - 1)) + h)
if Input.IsKeyDown(Enum.ButtonCode.MOUSE_RIGHT) then
if ClickSave then
Player.PrepareUnitOrders(Players.GetLocal(), Enum.UnitOrder.DOTA_UNIT_ORDER_CAST_NO_TARGET, 0, Vector(0, 0, 0), NPC.GetAbilityByIndex(oldest_mine.Unit, 0), Enum.PlayerOrderIssuer.DOTA_ORDER_ISSUER_PASSED_UNIT_ONLY, oldest_mine.Unit, 0, 0)
ClickSave = false
end
else
ClickSave = true
end
end
Renderer.SetDrawColor(200, 200, 200, 150)
Renderer.DrawOutlineRect(x + math.floor(60 * optionAltInfoTimeMinesPanelSize), y + math.floor(16 * optionAltInfoTimeMinesPanelSize) * (i - 1), x + math.floor(80 * optionAltInfoTimeMinesPanelSize) - (x + math.floor(60 * optionAltInfoTimeMinesPanelSize)), math.floor(16 * optionAltInfoTimeMinesPanelSize) * (#stack_mines - (i - 1)) + h)
end
end
else
Renderer.DrawText(TechiesHUD.font, x, y, num_mines, 0)
end
end
end
end
end
if GameRules.GetGameTime() - TechiesHUD.RemoteMinesCreateTimings[Unit] < Ability.GetCastPoint(remote) and not RemoteMinesModif then
local x, y, visible = Renderer.WorldToScreen(UnitPos)
if visible == 1 then
Renderer.SetDrawColor(255, 255, 255, 255)
Renderer.DrawText(TechiesHUD.font, x, y - 20, math.floor((Ability.GetCastPoint(remote) - (GameRules.GetGameTime() - TechiesHUD.RemoteMinesCreateTimings[Unit])) * 100) / 100, 0)
end
end
if RemoteMinesModif and GameRules.GetGameTime() - Modifier.GetCreationTime(RemoteMinesModif) < 2 then
local x, y, visible = Renderer.WorldToScreen(UnitPos)
if visible == 1 then
Renderer.SetDrawColor(255, 255, 255, math.floor(255 * ((2 - (GameRules.GetGameTime() - Modifier.GetCreationTime(RemoteMinesModif))) / 2)))
Renderer.DrawText(TechiesHUD.font, x, y - 20, math.floor((2 - (GameRules.GetGameTime() - Modifier.GetCreationTime(RemoteMinesModif))) * 100) / 100, 0)
end
end
if not Entity.IsAlive(Unit) and TechiesHUD.ParticleList[Unit] then
Particle.Destroy(TechiesHUD.ParticleList[Unit].particle)
TechiesHUD.ParticleList[Unit] = nil
end
end
for i, Unit in pairs(Heroes.GetAll()) do
if not NPC.IsIllusion(Unit) and not Entity.IsSameTeam(myHero, Unit) then
if optionPanelInfo and remote ~= nil and Ability.GetLevel(remote) ~= 0 then
if NPC.HasAbility(Unit, "wisp_overcharge") then -- bonus_damage_pct
wisp_overcharge = 1 + Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "wisp_overcharge"), "bonus_damage_pct") / 100
end
if NPC.HasAbility(Unit, "kunkka_ghostship") then -- ghostship_absorb
kunkka_ghostship = 1 - Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "kunkka_ghostship"), "ghostship_absorb") / 100
end
if NPC.HasAbility(Unit, "ember_spirit_flame_guard") then -- absorb_amount
flame_guard = Ability.GetLevelSpecialValueFor(NPC.GetAbility(Unit, "ember_spirit_flame_guard"), "absorb_amount")
end
local Hp, Hp_all = TechiesHUD.GetNumRemoteForKill(Unit, remote_damage, Entity.GetHealth(Unit), NPC.GetMana(Unit)), TechiesHUD.GetNumRemoteForKill(Unit, remote_damage, Entity.GetMaxHealth(Unit), NPC.GetMaxMana(Unit))
local x, y = TechiesHUD.GetHeroPos(Hero.GetPlayerID(Unit))
local bary = math.ceil(28 * TechiesHUD.ScreenScale)
Renderer.SetDrawColor(0, 0, 0, 170)
Renderer.DrawFilledRect(x, y, TechiesHUD.GetSize() - 4, bary - 2)
Renderer.SetDrawColor(255, 127, 39, 255)
Renderer.DrawOutlineRect(x - 1, y - 1, TechiesHUD.GetSize() - 2, bary)
Renderer.SetDrawColor(255, 255, 255, 255)
local x, y = TechiesHUD.GetHeroPos(Hero.GetPlayerID(Unit))
Renderer.DrawTextCenteredY(TechiesHUD.HUDfont, x + 2, y + math.floor(6 * TechiesHUD.ScreenScale), math.floor(Hp * 10) / 10, 0)
Renderer.DrawTextCenteredY(TechiesHUD.HUDfont, x + 2, y + math.floor((6 + 14) * TechiesHUD.ScreenScale), math.floor(Hp_all * 10) / 10, 0)
if NPC.HasItem(Unit, "item_gem", 1) then
Renderer.DrawTextCenteredY(TechiesHUD.HUDfont, x + TechiesHUD.GetSize() - math.floor(15 * TechiesHUD.ScreenScale), y + math.floor(6 * TechiesHUD.ScreenScale), "G", 0)
end
if NPC.HasItem(Unit, "item_ward_sentry", 1) or NPC.HasItem(Unit, "item_ward_sentry", 0) or NPC.HasItem(Unit, "item_ward_dispenser", 1) or NPC.HasItem(Unit, "item_ward_dispenser", 0) then
Renderer.DrawTextCenteredY(TechiesHUD.HUDfont, x + TechiesHUD.GetSize() - math.floor(15 * TechiesHUD.ScreenScale), y + math.floor((6 + 14) * TechiesHUD.ScreenScale), "S", 0)
end
end
if not Entity.IsDormant(Unit) and Entity.IsAlive(Unit) then
local UnitPos = Entity.GetAbsOrigin(Unit)
if optionBlastInfo and blast ~= nil and Ability.GetLevel(blast) ~= 0 then
local Hp = Entity.GetHealth(Unit)
x, y = Renderer.WorldToScreen(Entity.GetAbsOrigin(Unit))
if Entity.GetMaxHealth(Unit) - Entity.GetHealth(Unit) ~= 0 then
Hp = Hp + NPC.GetHealthRegen(Unit) * 2
end
Hp = Hp - blast_damage * NPC.GetMagicalArmorDamageMultiplier(Unit) * magicalDamageMul
if Hp > 0 then
Renderer.SetDrawColor(255, 0, 0, 255)
else
Renderer.SetDrawColor(0, 255, 0, 255)
end
Renderer.DrawText(TechiesHUD.font, x, y, math.ceil(Hp), 0)
end
if optionDetonate and hero_time[Entity.GetIndex(Unit)] ~= nil and GameRules.GetGameTime() - hero_time[Entity.GetIndex(Unit)] < optionDelay / 1000 + 0.3 then -- remote delay draw
local x, y, visible = Renderer.WorldToScreen(UnitPos)
if visible == 1 then
Renderer.SetDrawColor(255, 255, 255, 255)
Renderer.DrawText(TechiesHUD.font, x, y - 15, math.floor(((optionDelay / 1000) + 0.3 - (GameRules.GetGameTime() - hero_time[Entity.GetIndex(Unit)])) * 100) / 100, 0)
end
end
if optionForceDrawLine and force ~= nil then -- force stuff line
local x, y, visible = Renderer.WorldToScreen(UnitPos)
if visible == 1 then
Renderer.SetDrawColor(255, 255, 255, 255)
local rotate = Entity.GetAbsRotation(Unit):GetYaw()
local x4 = 600 * math.cos(rotate / 57.3) - 0 * math.sin(rotate / 57.3)
local y4 = 0 * math.cos(rotate / 57.3) + 600 * math.sin(rotate / 57.3)
local x3,y3,visible3 = Renderer.WorldToScreen(UnitPos + Vector(x4,y4,0))
Renderer.DrawLine(x, y, x3, y3)
end
end
end
end
end
end
function TechiesHUD.SetSpot()
local optionAutoPlantStackRange = GUI.Get(TechiesHUD.Identity .. "optionAutoPlantStackRange")
if Input.IsKeyDown(Enum.ButtonCode.KEY_LSHIFT) then
local spot = {}
local closest_remote = nil
local cursor_pos = Input.GetWorldCursorPos()
if optionAutoPlantStackRange ~= 0 then
for i = 1, NPCs.Count() do
local Unit = NPCs.Get(i)
local UnitPos = Entity.GetAbsOrigin(Unit)
if NPC.IsPositionInRange(Unit, cursor_pos, optionAutoPlantStackRange, Enum.TeamType.TEAM_FRIEND)
and NPC.GetModifier(Unit, "modifier_techies_remote_mine") ~= nil
then
if closest_remote == nil or (UnitPos - cursor_pos):Length() < (closest_remote - cursor_pos):Length() then
closest_remote = UnitPos
end
end
end
end
if closest_remote == nil then
spot.position = cursor_pos
else
spot.position = closest_remote
end
spot.num_mines = 0
table.insert(spot_for_plant, spot)
else
spot_for_plant = {}
end
end
function TechiesHUD.OnUpdate()
if not optionTotal then return end
local myHero = Heroes.GetLocal()
if not myHero then
return
end
if NPC.GetUnitName(myHero) ~= "npc_dota_hero_techies" then
return
end
local remote = NPC.GetAbilityByIndex(myHero, 5)
local remote_damage = Ability.GetLevelSpecialValueFor(remote, "damage")
local force = NPC.GetItem(myHero, "item_force_staff", 1)
for i, Unit in pairs(TechiesHUD.UndefEntity) do
if Entity.IsNPC(Unit) then
if NPC.GetUnitName(Unit) == "npc_dota_techies_land_mine" then
if optionDrawCircleMethod then
local particle = {particle = Particle.Create("particles\\ui_mouseactions\\drag_selected_ring.vpcf"), Unit = Unit}
Particle.SetControlPoint(particle.particle, 1, Vector(255, 80, 80))
Particle.SetControlPoint(particle.particle, 3, Vector(9, 0, 0))
Particle.SetControlPoint(particle.particle, 2, Vector(425, 255, 0))
Particle.SetControlPoint(particle.particle , 0, Entity.GetAbsOrigin(Unit))
TechiesHUD.ParticleList[Unit] = particle
end
TechiesHUD.LandMinesList[Unit] = Unit
elseif NPC.GetUnitName(Unit) == "npc_dota_techies_stasis_trap" then
if optionDrawCircleMethod then
local particle = {particle = Particle.Create("particles\\ui_mouseactions\\drag_selected_ring.vpcf"), Unit = Unit, particle2 = Particle.Create("particles\\ui_mouseactions\\drag_selected_ring.vpcf")}
Particle.SetControlPoint(particle.particle, 1, Vector(80, 100, 255))
Particle.SetControlPoint(particle.particle, 3, Vector(20, 0, 0))
Particle.SetControlPoint(particle.particle, 2, Vector(430, 255, 0))
Particle.SetControlPoint(particle.particle , 0, Entity.GetAbsOrigin(Unit))
Particle.SetControlPoint(particle.particle2, 1, Vector(0, 255, 255))
Particle.SetControlPoint(particle.particle2, 3, Vector(20, 0, 0))
Particle.SetControlPoint(particle.particle2, 2, Vector(630, 255, 0))
Particle.SetControlPoint(particle.particle2 , 0, Entity.GetAbsOrigin(Unit))
TechiesHUD.ParticleList[Unit] = particle
end
TechiesHUD.StasisMinesList[Unit] = Unit
elseif NPC.GetUnitName(Unit) == "npc_dota_techies_remote_mine" then
if optionDrawCircleMethod then
local particle = {particle = Particle.Create("particles\\ui_mouseactions\\drag_selected_ring.vpcf"), Unit = Unit}
Particle.SetControlPoint(particle.particle, 1, Vector(80, 255, 50))
Particle.SetControlPoint(particle.particle, 3, Vector(20, 0, 0))
Particle.SetControlPoint(particle.particle, 2, Vector(455, 255, 0))
Particle.SetControlPoint(particle.particle , 0, Entity.GetAbsOrigin(Unit))
TechiesHUD.ParticleList[Unit] = particle
end
TechiesHUD.RemoteMinesList[Unit] = Unit
TechiesHUD.RemoteMinesDamage[Unit] = remote_damage
TechiesHUD.RemoteMinesCreateTimings[Unit] = GameRules.GetGameTime()
end
end
table.remove(TechiesHUD.UndefEntity, i)
end
if optionAutoPlant then
for i, spot in pairs(spot_for_plant) do
spot.num_mines = 0
for j, Unit2 in pairs(TechiesHUD.RemoteMinesList) do
if NPC.IsPositionInRange(Unit2, spot.position, 200, Enum.TeamType.TEAM_FRIEND)
and NPC.GetModifier(Unit2, "modifier_techies_remote_mine") ~= nil
then
spot.num_mines = spot.num_mines + 1
end
end
end
if remote ~= nil and Ability.GetLevel(remote) ~= 0 and Ability.GetCooldownTimeLeft(remote) == 0 and not Ability.IsInAbilityPhase(remote) and GameRules.GetGameTime() - plant_time > Ability.GetCastPoint(remote) + 0.1 then
local step = 0
for i, spot in pairs(spot_for_plant) do
if spot.num_mines < tonumber(optionAutoPlantNumMines) and step == 0 then
if (Entity.GetAbsOrigin(myHero) - spot.position):Length() < Ability.GetCastRange(remote) then
Ability.CastPosition(remote, spot.position, 0)
plant_time = GameRules.GetGameTime()
step = 1
else
if not Input.IsKeyDown(Enum.ButtonCode.KEY_LSHIFT) then
Player.PrepareUnitOrders(Players.GetLocal(), Enum.UnitOrder.DOTA_UNIT_ORDER_MOVE_TO_POSITION, nil, spot.position, nil, Enum.PlayerOrderIssuer.DOTA_ORDER_ISSUER_HERO_ONLY, nil, 0, 1)
plant_time = GameRules.GetGameTime() - 1.9
step = 1
end
end
end
end
end
end
if optionDetonate then -- auto detonate
--------------------------- camera
if hero_cam_time ~= nil and GameRules.GetGameTime() - hero_cam_time > 1 then
Engine.ExecuteCommand("dota_camera_set_lookatpos " .. hero_cam_first_pos:GetX() .. " " .. hero_cam_first_pos:GetY())
hero_cam_time = nil
end
--------------------------- calc damage
local visage_stack = {}
local templar_stack = {}
local visage_stack_f = {}
local templar_stack_f = {}
local hp = {}
local mp = {}
local fasthp = {}
local fastmp = {}
local magic_shield = {}
local magic_shield_f = {}
for i, Unit in pairs(TechiesHUD.RemoteMinesList) do
local UnitPos = Entity.GetAbsOrigin(Unit)
local heroes_in_radius = NPC.GetHeroesInRadius(Unit, 425 - 24, Enum.TeamType.TEAM_ENEMY)
if NPC.GetModifier(Unit, "modifier_techies_remote_mine") ~= nil
and need_enemy[Unit]
and state_mines[Unit]
and #heroes_in_radius >= need_enemy[Unit]
then
for j, v in pairs(heroes_in_radius) do
if hp[Entity.GetIndex(v)] == nil then
hp[Entity.GetIndex(v)] = (Entity.GetHealth(v) + NPC.GetHealthRegen(v) * 0.3)
mp[Entity.GetIndex(v)] = (NPC.GetMana(v) + NPC.GetManaRegen(v) * 0.3)
end
if fasthp[Entity.GetIndex(v)] == nil then
fasthp[Entity.GetIndex(v)] = (Entity.GetHealth(v) + NPC.GetHealthRegen(v) * 0.3)
fastmp[Entity.GetIndex(v)] = (NPC.GetMana(v) + NPC.GetManaRegen(v) * 0.3)
end
if hp[Entity.GetIndex(v)] > 0 or optionLegitDetonate then
local calc_damage, calc_hp, calc_mp, calc_shield, calc_visage_stack, calc_templar_stack =
TechiesHUD.GetDamageAndShieldAfterDetonate(v, TechiesHUD.RemoteMinesDamage[Unit] + 150 * (NPC.HasItem(myHero, "item_ultimate_scepter", 1) and 1 or 0),
hp[Entity.GetIndex(v)], mp[Entity.GetIndex(v)], magic_shield[Entity.GetIndex(v)], visage_stack[Entity.GetIndex(v)], templar_stack[Entity.GetIndex(v)])
hp[Entity.GetIndex(v)] = calc_hp
mp[Entity.GetIndex(v)] = calc_mp
magic_shield[Entity.GetIndex(v)] = calc_shield
visage_stack[Entity.GetIndex(v)] = calc_visage_stack
templar_stack[Entity.GetIndex(v)] = calc_templar_stack
end
if fasthp[Entity.GetIndex(v)] > 0 and TechiesHUD.CheckMove(v, Unit, 0.3 + NetChannel.GetAvgLatency(Enum.Flow.FLOW_OUTGOING) + 0.04 * (Entity.GetHealth(v) / remote_damage)) == 1 and optionDetonateFast then
local calc_damage, calc_hp, calc_mp, calc_shield, calc_visage_stack, calc_templar_stack =
TechiesHUD.GetDamageAndShieldAfterDetonate(v, TechiesHUD.RemoteMinesDamage[Unit] + 150 * (NPC.HasItem(myHero, "item_ultimate_scepter", 1) and 1 or 0),
fasthp[Entity.GetIndex(v)], fastmp[Entity.GetIndex(v)], magic_shield_f[Entity.GetIndex(v)], visage_stack_f[Entity.GetIndex(v)], templar_stack_f[Entity.GetIndex(v)])
fasthp[Entity.GetIndex(v)] = calc_hp
fastmp[Entity.GetIndex(v)] = calc_mp
magic_shield_f[Entity.GetIndex(v)] = calc_shield
visage_stack_f[Entity.GetIndex(v)] = calc_visage_stack
templar_stack_f[Entity.GetIndex(v)] = calc_templar_stack
end
end
end
end
--------------------------- detonate logic
if GameRules.GetGameTime() - check_detonate > 0.5 then
local visage_stack = {}
local templar_stack = {}
local visage_stack_f = {}
local templar_stack_f = {}
local hp1 = {}
local mp = {}
local need_damage = {}
local magic_shield = {}
local hero_pos = nil
for i, Unit in pairs(TechiesHUD.RemoteMinesList) do
local UnitPos = Entity.GetAbsOrigin(Unit)
local heroes_in_radius = NPC.GetHeroesInRadius(Unit, 425 - 24, Enum.TeamType.TEAM_ENEMY)
if NPC.GetModifier(Unit, "modifier_techies_remote_mine") ~= nil
and state_mines[Unit]
--and #heroes_in_radius >= Menu.GetValue(TechiesHUD.optionDetonateNumEnemy)
then
local num_enemy = 0
for j, v in pairs(heroes_in_radius) do
if (NPC.IsKillable(v) or (NPC.HasItem(v, "item_aegis", 1) and optionDetonateAegis) or (NPC.GetUnitName(v) == "npc_dota_hero_skeleton_king" and optionDetonateWk) or NPC.HasModifier(v, "modifier_templar_assassin_refraction_absorb")) and not NPC.HasModifier(v, "modifier_item_aeon_disk_buff") and not NPC.HasModifier(v, "modifier_dazzle_shallow_grave") and not NPC.HasModifier(v, "modifier_oracle_false_promise") then
-- for k, b in pairs(NPC.GetModifiers(v)) do
-- Log.Write(Modifier.GetName(b))
-- end
local fast_hp_check = false
if hero_time[Entity.GetIndex(v)] == nil then
hero_time[Entity.GetIndex(v)] = 0
end
if hero_time[Entity.GetIndex(v)] == 1 then
num_enemy = 999
end
if fasthp[Entity.GetIndex(v)] ~= nil and fasthp[Entity.GetIndex(v)] < 0 then
if TechiesHUD.CheckMove(v, Unit, 0.3 + NetChannel.GetAvgLatency(Enum.Flow.FLOW_OUTGOING) + 0.03 * (Entity.GetHealth(v) / remote_damage)) == 1 and optionDetonateFast then
num_enemy = num_enemy + 1
fast_hp_check = true
end
end
if (hp[Entity.GetIndex(v)] ~= nil and hp[Entity.GetIndex(v)] < 0) then
if hero_time[Entity.GetIndex(v)] == 0 then
hero_time[Entity.GetIndex(v)] = GameRules.GetGameTime()
end
if hero_time[Entity.GetIndex(v)] ~= 0 and (GameRules.GetGameTime() - hero_time[Entity.GetIndex(v)] > optionDelay / 1000) and not fast_hp_check then
num_enemy = num_enemy + 1
end
else
if hero_time[Entity.GetIndex(v)] ~= 1 then
hero_time[Entity.GetIndex(v)] = 0
end
end
end
end
local check_enemy = 0
for j, v in pairs(heroes_in_radius) do
if (need_damage[Entity.GetIndex(v)] == nil or need_damage[Entity.GetIndex(v)] < Entity.GetHealth(v) + NPC.GetHealthRegen(v) * 0.3) or optionLegitDetonate then
check_enemy = 1
end
end
if need_enemy[Unit] and num_enemy >= need_enemy[Unit] and check_enemy > 0 then
check_detonate = GameRules.GetGameTime()
Player.PrepareUnitOrders(Players.GetLocal(), Enum.UnitOrder.DOTA_UNIT_ORDER_CAST_NO_TARGET, 0, Vector(0, 0, 0), NPC.GetAbilityByIndex(Unit, 0), Enum.PlayerOrderIssuer.DOTA_ORDER_ISSUER_PASSED_UNIT_ONLY, Unit, 0, 0)
for j, v in pairs(heroes_in_radius) do
if need_damage[Entity.GetIndex(v)] == nil then
hp1[Entity.GetIndex(v)] = (Entity.GetHealth(v) + NPC.GetHealthRegen(v) * 0.3)
mp[Entity.GetIndex(v)] = (NPC.GetMana(v) + NPC.GetManaRegen(v) * 0.3)
need_damage[Entity.GetIndex(v)] = 0
end
if hero_pos == nil then
hero_pos = Entity.GetAbsOrigin(v)
end
local calc_damage, calc_hp, calc_mp, calc_shield, calc_visage_stack, calc_templar_stack =
TechiesHUD.GetDamageAndShieldAfterDetonate(v, TechiesHUD.RemoteMinesDamage[Unit] + 150 * (NPC.HasItem(myHero, "item_ultimate_scepter", 1) and 1 or 0),
hp1[Entity.GetIndex(v)], mp[Entity.GetIndex(v)], magic_shield[Entity.GetIndex(v)], visage_stack[Entity.GetIndex(v)], templar_stack[Entity.GetIndex(v)])
hp1[Entity.GetIndex(v)] = calc_hp
mp[Entity.GetIndex(v)] = calc_mp
magic_shield[Entity.GetIndex(v)] = calc_shield
visage_stack[Entity.GetIndex(v)] = calc_visage_stack
templar_stack[Entity.GetIndex(v)] = calc_templar_stack
need_damage[Entity.GetIndex(v)] = need_damage[Entity.GetIndex(v)] + calc_damage
end
end
end
end
if hero_pos ~= nil then
local x, y = Renderer.WorldToScreen(hero_pos)
if optionDetonateCam and (x < 0 or x > size_x or y < 0 or y > size_y) then
Engine.ExecuteCommand("dota_camera_set_lookatpos " .. hero_pos:GetX() .. " " .. hero_pos:GetY())
hero_cam_first_pos = Entity.GetAbsOrigin(myHero)
hero_cam_time = GameRules.GetGameTime()
end
hero_pos = nil
end
end
end -- auto detonate
for i, Unit in pairs(Heroes.GetAll()) do
local UnitPos = Entity.GetAbsOrigin(Unit)
if Ability.GetLevel(remote) ~= 0 then -- remote auto detonate
if Entity.IsHero(Unit)
and Entity.GetTeamNum(Unit) ~= Entity.GetTeamNum(myHero)
and not NPC.IsIllusion(Unit)
and not Entity.IsDormant(Unit)
and (NPC.IsKillable(Unit) or (NPC.HasItem(Unit, "item_aegis", 1) and optionDetonateAegis) or (NPC.GetUnitName(Unit) == "npc_dota_hero_skeleton_king" and optionDetonateWk)
or NPC.HasModifier(Unit, "modifier_templar_assassin_refraction_absorb"))
and not NPC.HasModifier(Unit, "modifier_dazzle_shallow_grave") and not NPC.HasModifier(Unit, "modifier_oracle_false_promise")
and not NPC.HasModifier(Unit, "modifier_item_aeon_disk_buff")
and Entity.IsAlive(Unit)
then
--Log.Write(NPC.GetMagicalArmorDamageMultiplier(Unit) .. " " .. (Entity.GetHealth(Unit) - Entity.GetMaxHealth(Unit) * 0.1) / (Entity.GetMaxHealth(Unit) * 0.9))
if hero_time[Entity.GetIndex(Unit)] == nil then
hero_time[Entity.GetIndex(Unit)] = 0
end
local remote_sum_damage = 0
local force_remote_sum_damage = 0
for j = 1, NPCs.Count() do -- calc sum damage
local Unit2 = NPCs.Get(j)
if NPC.GetModifier(Unit2, "modifier_techies_remote_mine") ~= nil and state_mines[Unit2] then
if NPC.IsPositionInRange(Unit2, UnitPos, 425, 0) then -- - NPC.GetMoveSpeed(Unit) * 0.1
remote_sum_damage = remote_sum_damage + TechiesHUD.RemoteMinesDamage[Unit2] + 150 * (NPC.HasItem(myHero, "item_ultimate_scepter", 1) and 1 or 0)
end
local rotate = Entity.GetAbsRotation(Unit):GetYaw()
local x4 = 600 * math.cos(rotate / 57.3) - 0 * math.sin(rotate / 57.3)
local y4 = 0 * math.cos(rotate / 57.3) + 600 * math.sin(rotate / 57.3)
if NPC.IsPositionInRange(Unit2, UnitPos + Vector(x4,y4,0), 425, 0) then
force_remote_sum_damage = force_remote_sum_damage + TechiesHUD.RemoteMinesDamage[Unit2] + 150 * (NPC.HasItem(myHero, "item_ultimate_scepter", 1) and 1 or 0)
end
end
end -- calc sum damage
if remote_sum_damage == 0 and hero_time[Entity.GetIndex(Unit)] ~= 1 then
hero_time[Entity.GetIndex(Unit)] = 0
end
if optionDetonate then
if optionForce then -- auto force stuff
if force ~= nil then
if hero_time[Entity.GetIndex(Unit)] == 1 and forced_time ~= 0 and GameRules.GetGameTime() - forced_time > 1 then
hero_time[Entity.GetIndex(Unit)] = 0
forced_time = 0
end
if NPC.IsPositionInRange(myHero, UnitPos, 1000, 0)
and force_remote_sum_damage * NPC.GetMagicalArmorDamageMultiplier(Unit) > Entity.GetHealth(Unit) and GameRules.GetGameTime() - forc_time > 0.5 then
if force_direction[i] == nil or force_direction[i] == 0 then
force_direction[i] = GameRules.GetGameTime()
elseif Ability.GetCooldownTimeLeft(force) == 0 and GameRules.GetGameTime() - force_direction[i] > Config.ReadInt("TechiesHUD", "Force Stuff delay", 500) / 1000 then
Player.PrepareUnitOrders(Players.GetLocal(), Enum.UnitOrder.DOTA_UNIT_ORDER_CAST_TARGET, Unit, Vector(0, 0, 0), force, Enum.PlayerOrderIssuer.DOTA_ORDER_ISSUER_PASSED_UNIT_ONLY, myHero, 0, 0)
forc_time = GameRules.GetGameTime()
hero_time[Entity.GetIndex(Unit)] = 1
forced_time = GameRules.GetGameTime()
force_direction[i] = 0
end
else
force_direction[i] = 0
end
end
end -- auto force stuff
end
end
end
end
end
function TechiesHUD.OnPrepareUnitOrders(orders)
if not optionTotal then return true end
local myHero = Heroes.GetLocal()
if not myHero then
return true
end
if NPC.GetUnitName(myHero) ~= "npc_dota_hero_techies" then
return true
end
if CursorOnButton then
return false
end
if orders.order == Enum.UnitOrder.DOTA_UNIT_ORDER_MOVE_TO_TARGET and orders.target and Entity.IsSameTeam(myHero, orders.target)
and (NPC.GetUnitName(orders.target) == "npc_dota_techies_land_mine"
or NPC.GetUnitName(orders.target) == "npc_dota_techies_stasis_trap"
or NPC.GetUnitName(orders.target) == "npc_dota_techies_remote_mine") then
Player.PrepareUnitOrders(orders.player, Enum.UnitOrder.DOTA_UNIT_ORDER_MOVE_TO_POSITION, nil, Entity.GetAbsOrigin(orders.target), orders.ability, orders.orderIssuer, orders.npc, orders.queue, orders.showEffects)
return false
end
if orders.order ~= Enum.UnitOrder.DOTA_UNIT_ORDER_CAST_POSITION and orders.order ~= Enum.UnitOrder.DOTA_UNIT_ORDER_CAST_TOGGLE_AUTO then return true end
if not orders.ability then return true end
if Ability.GetName(orders.ability) == "techies_suicide" then
TechiesHUD.BlastPosition = orders.position
return true
end
if optionFDFailSwitch and Ability.GetName(orders.ability) == "techies_focused_detonate" then
if Input.IsKeyDown(Enum.ButtonCode.KEY_LALT) then
Player.PrepareUnitOrders(orders.player, Enum.UnitOrder.DOTA_UNIT_ORDER_CAST_POSITION, orders.target, Input.GetWorldCursorPos(), orders.ability, orders.orderIssuer, orders.npc, orders.queue, orders.showEffects)
return false
end
local visage_stack = {}
local templar_stack = {}
local visage_stack_f = {}
local templar_stack_f = {}
local hp = {}
local mp = {}
local magic_shield = {}
for i, Unit in pairs(TechiesHUD.RemoteMinesList) do
if NPC.HasModifier(Unit, "modifier_techies_remote_mine")
and NPC.IsPositionInRange(Unit, orders.position, 700, 0)
then
local num_enemy = 0
for j, v in pairs(Entity.GetHeroesInRadius(Unit, 425 - 24, Enum.TeamType.TEAM_ENEMY)) do
if Entity.IsAlive(v)
and not Entity.IsDormant(v)
and not NPC.HasModifier(Unit, "modifier_manta")
and (NPC.IsKillable(v) or (NPC.HasItem(v, "item_aegis", 1) and optionDetonateAegis)
or NPC.GetUnitName(v) == "npc_dota_hero_skeleton_king" or NPC.HasModifier(v, "modifier_templar_assassin_refraction_absorb"))
and not NPC.HasModifier(v, "modifier_dazzle_shallow_grave") and not NPC.HasModifier(v, "modifier_oracle_false_promise")
and not NPC.HasModifier(v, "modifier_item_aeon_disk_buff")
and NPC.GetMagicalArmorDamageMultiplier(v) ~= 0
then
Log.Write("check")
if hp[Entity.GetIndex(v)] == nil then
hp[Entity.GetIndex(v)] = Entity.GetHealth(v) + NPC.GetHealthRegen(v) * 0.3
mp[Entity.GetIndex(v)] = NPC.GetMana(v) + NPC.GetManaRegen(v) * 0.3
end
if hp[Entity.GetIndex(v)] > 0 or optionFDFailSwitchMode then
local calc_damage, calc_hp, calc_mp, calc_shield, calc_visage_stack, calc_templar_stack =
TechiesHUD.GetDamageAndShieldAfterDetonate(v, TechiesHUD.RemoteMinesDamage[Unit] + 150 * (NPC.HasItem(myHero, "item_ultimate_scepter", 1) and 1 or 0),
hp[Entity.GetIndex(v)], mp[Entity.GetIndex(v)], magic_shield[Entity.GetIndex(v)], visage_stack[Entity.GetIndex(v)], templar_stack[Entity.GetIndex(v)])
hp[Entity.GetIndex(v)] = calc_hp
mp[Entity.GetIndex(v)] = calc_mp
magic_shield[Entity.GetIndex(v)] = calc_shield
visage_stack[Entity.GetIndex(v)] = calc_visage_stack
templar_stack[Entity.GetIndex(v)] = calc_templar_stack
num_enemy = num_enemy + 1
end
end
end
if num_enemy ~= 0 then
Player.PrepareUnitOrders(Players.GetLocal(), Enum.UnitOrder.DOTA_UNIT_ORDER_CAST_NO_TARGET, 0, Vector(0, 0, 0), NPC.GetAbilityByIndex(Unit, 0), Enum.PlayerOrderIssuer.DOTA_ORDER_ISSUER_PASSED_UNIT_ONLY, Unit, 0, 0)
end
end
end
return false
end
-- if Ability.GetName(orders.ability) ~= "techies_remote_mines" and Ability.GetName(orders.ability) ~= "techies_land_mines" and Ability.GetName(orders.ability) ~= "techies_stasis_trap" then
-- return true
-- end
if (Ability.GetName(orders.ability) == "techies_land_mines" and GUI.IsEnabled(TechiesHUD.Identity .. "optionMinePlacerLM")) or (Ability.GetName(orders.ability) == "techies_stasis_trap" and GUI.IsEnabled(TechiesHUD.Identity .. "optionMinePlacerST")) then
local modif_name
local range
local add_h
if Ability.GetName(orders.ability) == "techies_land_mines" then
modif_name = "modifier_techies_land_mine"
range = 400
add_h = 24
else
modif_name = "modifier_techies_stasis_trap"
range = 600
add_h = 24
end
local closest_mine
local closest_mine1
for i, Unit in pairs(NPCs.GetAll()) do
if NPC.GetModifier(Unit, modif_name)
and Entity.IsAlive(Unit)
and NPC.IsPositionInRange(Unit, orders.position, range, 0)
then
if not closest_mine then
closest_mine = Unit
elseif not closest_mine1 and (Entity.GetAbsOrigin(Unit) - Entity.GetAbsOrigin(closest_mine)):Length2DSqr() > 4 then
closest_mine1 = Unit
end
if (Entity.GetAbsOrigin(Unit) - orders.position):Length2DSqr() < (Entity.GetAbsOrigin(closest_mine) - orders.position):Length2DSqr()
and (Entity.GetAbsOrigin(Unit) - Entity.GetAbsOrigin(closest_mine)):Length2DSqr() > 3 then
closest_mine1 = closest_mine
closest_mine = Unit
end
end
end
local tmp_vec
if closest_mine and closest_mine1 and (Entity.GetAbsOrigin(closest_mine) - Entity.GetAbsOrigin(closest_mine1)):Length2DSqr() > 4 then
local mine_pos = Entity.GetAbsOrigin(closest_mine)
local mine_pos1 = Entity.GetAbsOrigin(closest_mine1)
local a = (mine_pos - mine_pos1):Length2DSqr() / (2 * (mine_pos - mine_pos1):Length2D())
local d = (mine_pos - mine_pos1):Length2D()
local h = (range^2 - a^2)^0.5
local P2 = mine_pos + Vector(a, a, a) * (mine_pos1 - mine_pos) * Vector(1/d, 1/d, 1/d)
local P31 = Vector(P2:GetX() + h * (mine_pos1:GetY() - mine_pos:GetY()) / d, P2:GetY() - h * (mine_pos1:GetX() - mine_pos:GetX()) / d, P2:GetZ())
local P32 = Vector(P2:GetX() - h * (mine_pos1:GetY() - mine_pos:GetY()) / d, P2:GetY() + h * (mine_pos1:GetX() - mine_pos:GetX()) / d, P2:GetZ())
local h_pos = ((range + add_h)^2 - (d / 2)^2)^0.5
local closest_mine
local closest_mine1
local tmp_vec1 = P2 + ((P31 - P2):Normalized()):Scaled(h_pos)
local tmp_vec2 = P2 + ((P32 - P2):Normalized()):Scaled(h_pos)
for i, Unit in pairs(NPCs.GetAll()) do
if NPC.GetModifier(Unit, modif_name)
and Entity.IsAlive(Unit)
and NPC.IsPositionInRange(Unit, tmp_vec1, range, 0)
then
if not closest_mine then
closest_mine = Unit
end
if (Entity.GetAbsOrigin(Unit) - tmp_vec1):Length2DSqr() < (Entity.GetAbsOrigin(closest_mine) - tmp_vec1):Length2DSqr() then
closest_mine = Unit
end
end
end
for i, Unit in pairs(NPCs.GetAll()) do
if NPC.GetModifier(Unit, modif_name)
and Entity.IsAlive(Unit)
and NPC.IsPositionInRange(Unit, tmp_vec2, range, 0)
then
if not closest_mine1 then
closest_mine1 = Unit
end
if (Entity.GetAbsOrigin(Unit) - tmp_vec2):Length2DSqr() < (Entity.GetAbsOrigin(closest_mine1) - tmp_vec2):Length2DSqr() then
closest_mine1 = Unit
end
end
end
if (P31 - orders.position):Length2DSqr() <= (P32 - orders.position):Length2DSqr() and not closest_mine then
tmp_vec = P2 + ((P31 - P2):Normalized()):Scaled(h_pos)
elseif not closest_mine1 then
tmp_vec = P2 + ((P32 - P2):Normalized()):Scaled(h_pos)
end
elseif closest_mine then
local mine_pos = Entity.GetAbsOrigin(closest_mine)
local mine_pos1 = Entity.GetAbsOrigin(closest_mine)
local order_pos = orders.position
mine_pos1:SetZ(order_pos:GetZ())
mine_pos:SetZ(0)
order_pos:SetZ(0)
tmp_vec = mine_pos1 + ((order_pos - mine_pos):Normalized()):Scaled(range + add_h)
end
if tmp_vec then
Player.PrepareUnitOrders(orders.player, orders.order, orders.target, tmp_vec, orders.ability, orders.orderIssuer, orders.npc, orders.queue, orders.showEffects)
return false
end
end
if GUI.IsEnabled(TechiesHUD.Identity .. "optionStack") then
local closest_pos
for i = 1, NPCs.Count() do
local Unit = NPCs.Get(i)
local UnitPos = Entity.GetAbsOrigin(Unit)
if ((Ability.GetName(orders.ability) == "techies_land_mines" and (NPC.GetModifier(Unit, "modifier_techies_remote_mine") ~= nil or NPC.GetModifier(Unit, "modifier_techies_stasis_trap") ~= nil))
or (Ability.GetName(orders.ability) == "techies_stasis_trap" and (NPC.GetModifier(Unit, "modifier_techies_remote_mine") ~= nil or NPC.GetModifier(Unit, "modifier_techies_land_mine") ~= nil))
or (Ability.GetName(orders.ability) == "techies_remote_mines" and (NPC.GetModifier(Unit, "modifier_techies_land_mine") ~= nil or NPC.GetModifier(Unit, "modifier_techies_remote_mine") ~= nil or NPC.GetModifier(Unit, "modifier_techies_stasis_trap") ~= nil)))
and Entity.IsAlive(Unit)
and NPC.IsPositionInRange(Unit, orders.position, GUI.Get(TechiesHUD.Identity .. "optionStackRange"), 0)
then
if not closest_pos then
closest_pos = UnitPos
end
if (UnitPos - orders.position):Length2DSqr() < (closest_pos - orders.position):Length2DSqr() then
closest_pos = UnitPos
end
end
end
if closest_pos then
Player.PrepareUnitOrders(orders.player, orders.order, orders.target, closest_pos, orders.ability, orders.orderIssuer, orders.npc, orders.queue, orders.showEffects)
return false
end
end
return true
end
return TechiesHUD |
------------------------------------------------------------------------------
--
-- LGI Basic repo type component implementation
--
-- Copyright (c) 2010, 2011, 2012, 2013 Pavel Holejsovsky
-- Licensed under the MIT license:
-- http://www.opensource.org/licenses/mit-license.php
--
------------------------------------------------------------------------------
local assert, pcall, setmetatable, getmetatable, pairs, next, rawget, rawset,
type, select, error
= assert, pcall, setmetatable, getmetatable, pairs, next, rawget, rawset,
type, select, error
local table = require 'table'
local string = require 'string'
local core = require 'lgi.core'
-- Generic component metatable. Component is any entity in the repo,
-- e.g. record, object, enum, etc.
local component = { mt = {} }
-- Creates new component table by cloning all contents and setting
-- Gets table for category of compound (i.e. _field of struct or _property
-- for class etc). Installs metatable which performs on-demand lookup of
-- symbols.
function component.get_category(children, xform_value,
xform_name, xform_name_reverse)
-- Either none or both transform methods must be provided.
assert(not xform_name or xform_name_reverse)
-- Early shortcircuit; no elements, no table needed at all.
if #children == 0 then return nil end
-- Index contains array of indices which were still not retrieved
-- from 'children' table, and table part contains name->index
-- mapping.
local index, mt = {}, {}
for i = 1, #children do index[i] = i end
-- Fully resolves the category (i.e. loads everything remaining to
-- be loaded in given category) and disconnects on-demand loading
-- metatable.
local function resolve(category)
-- Load al values from unknown indices.
local ei, en, val
local function xvalue(arg)
if not xform_value then return arg end
if arg then
local ok, res = pcall(xform_value, arg)
return ok and res
end
end
while #index > 0 do
ei = children[table.remove(index)]
val = xvalue(ei)
if val then
en = ei.name
en = not xform_name_reverse and en or xform_name_reverse(en)
if en then category[en] = val end
end
end
-- Load all known indices.
for en, idx in pairs(index) do
val = xvalue(children[idx])
en = not xform_name_reverse and en or xform_name_reverse(en)
if en then category[en] = val end
end
-- Metatable is no longer needed, disconnect it.
return setmetatable(category, nil)
end
function mt:__index(requested_name)
-- Check if closure for fully resolving the category is needed.
if requested_name == '_resolve' then return resolve end
-- Transform name by transform function.
local name = not xform_name and requested_name
or xform_name(requested_name)
if not name then return end
-- Check, whether we already know its index.
local idx, val = index[name]
if idx then
-- We know at least the index, so get info directly.
val = children[idx]
index[name] = nil
else
-- Not yet, go through unknown indices and try to find the
-- name.
while #index > 0 do
idx = table.remove(index)
val = children[idx]
local en = val.name
if en == name then break end
val = nil
index[en] = idx
end
end
-- If there is nothing in the index, we can disconnect
-- metatable, because everything is already loaded.
if not next(index) then
setmetatable(self, nil)
end
-- Transform found value and store it into the category (self)
-- table.
if not val then return nil end
if xform_value then val = xform_value(val) end
if not val then return nil end
self[requested_name] = val
return val
end
return setmetatable({}, mt)
end
-- Creates new component table by cloning all contents and setting
-- categories table.
function component.mt:clone(type, categories)
local new_component = {}
for key, value in pairs(self) do new_component[key] = value end
new_component._type = type
if categories then
table.insert(categories, 1, '_attribute')
new_component._categories = categories
end
return new_component
end
-- __call implementation, uses _new method to create new instance of
-- component type.
function component.mt:__call(...)
return self:_new(...)
end
-- Fully resolves the whole typetable, i.e. load all symbols normally
-- loaded on-demand at once. Returns self, so that resolve can be
-- easily chained for the caller.
function component.mt:_resolve()
local categories = self._categories or {}
for i = 1, #categories do
-- Invoke '_resolve' function for all category tables, if they have it.
local category = rawget(self, categories[i])
local resolve = type(category) == 'table' and category._resolve
if resolve then resolve(category) end
end
return self
end
-- Implementation of _access method, which is called by _core when
-- repo instance is accessed for reading or writing.
function component.mt:_access(instance, symbol, ...)
-- Invoke _element, which converts symbol to element and category.
local element, category = self:_element(instance, symbol)
if not element then
error(("%s: no `%s'"):format(self._name, tostring(symbol)), 3)
end
-- Get category handler to be used, and invoke it.
if category then
local handler = self['_access' .. category]
if handler then return handler(self, instance, element, ...) end
end
-- If specific accessor does not exist, consider the element to be
-- 'static const' attribute of the class. This works well for
-- methods, constants and assorted other elements added manually
-- into the class by overrides.
if select('#', ...) > 0 then
error(("%s: `%s' is not writable"):format(self._name, symbol), 4)
end
return element
end
-- Keyword translation dictionary. Used for translating Lua keywords
-- which might appear as symbols in typelibs into Lua-neutral identifiers.
local keyword_dictionary = {
_end = 'end', _do = 'do', _then = 'then', _elseif = 'elseif', _in = 'in',
_local = 'local', _function = 'function', _nil = 'nil', _false = 'false',
_true = 'true', _and = 'and', _or = 'or', _not = 'not',
}
-- Retrieves (element, category) pair from given componenttable and
-- instance for given symbol.
function component.mt:_element(instance, symbol, origin)
-- This generic version can work only with strings. Refuse
-- everything other, hoping that some more specialized _element
-- implementation will handle it.
if type(symbol) ~= 'string' then return end
-- Check keyword translation dictionary. If the symbol can be
-- found there, try to lookup translated symbol.
symbol = keyword_dictionary[symbol] or symbol
-- Check whether symbol is directly accessible in the component.
local element = rawget(self, symbol)
if element then return element end
-- Check whether symbol is accessible in cached directory of the
-- component, packed as element value and category
local cached = rawget(self, '_cached')
if cached then
element = cached[symbol]
if element then return element[1], element[2] end
end
-- Decompose symbol name, in case that it contains category prefix
-- (e.g. '_field_name' when requesting explicitely field called
-- name).
local category, name = string.match(symbol, '^(_.-)_(.*)$')
if category and name and category ~= '_access' then
-- Check requested category.
local cat = rawget(self, category)
element = cat and cat[name]
elseif string.sub(symbol, 1, 1) ~= '_' then
-- Check all available categories.
local categories = self._categories or {}
for i = 1, #categories do
category = categories[i]
local cat = rawget(self, category)
element = cat and cat[symbol]
if element then break end
end
end
if element then
-- Make sure that table-based attributes have symbol name, so
-- that potential errors contain the name of referenced
-- attribute.
if type(element) == 'table' and category == '_attribute' then
element._name = element._name or symbol
end
-- If possible, cache the element in root table.
if not category or not (origin or self)['_access' .. category] then
-- No category or no special category handler is present,
-- store it directly, which results in fastest access. This
-- is most typical for methods.
self[symbol] = element
else
-- Store into _cached table, because we have to preserve the
-- category.
if not cached then
cached = {}
self._cached = cached
end
cached[symbol] = { element, category }
end
return element, category
end
end
-- __index implementation, uses _element method to perform lookup.
function component.mt:__index(key)
-- First try to invoke our own _element method.
local _element, mt = rawget(self, '_element')
if not _element then
mt = getmetatable(self)
_element = rawget(mt, '_element')
end
local value, category = _element(self, nil, key)
if value then
if category then
-- Mangle the result by type-specific '_index_<category>'
-- method, if present.
local index_name = '_index' .. category
local index = rawget(self, index_name)
if not index then
if not mt then mt = getmetatable(self) end
if mt then index = rawget(mt, index_name) end
end
if index then value = index(self, value) end
end
return value
end
-- If not found as object element, examine the metatable itself.
return rawget(mt or getmetatable(self), key)
end
-- Implementation of attribute accessor. Attribute is either function
-- to be directly invoked, or table containing set and get functions.
function component.mt:_access_attribute(instance, element, ...)
-- If element is a table, assume that this table contains 'get' and
-- 'set' methods. Dispatch to them, and error out if they are
-- missing.
if type(element) == 'table' then
local mode = select('#', ...) == 0 and 'get' or 'set'
if not element[mode] then
error(("%s: cannot %s `%s'"):format(
self._name, mode == 'get' and 'read' or 'write',
element._name or '<unknown>'), 5)
end
element = element[mode]
end
-- Invoke attribute access function.
return element(instance, ...)
end
-- Pretty prints type name
function component.mt:__tostring()
return self._name
end
-- Creates new component and sets up common parts according to given
-- info.
function component.create(info, mt, name)
local gtype
if core.gi.isinfo(info) then
gtype = info.gtype
name = info.fullname
else
gtype = info and core.gtype(info)
end
-- Fill in meta of the compound.
local component = { _name = name }
if gtype then
-- Bind component in repo, make the relation using GType.
component._gtype = gtype
core.index[gtype] = component
end
return setmetatable(component, mt)
end
return component
|
ITEM.name = "Leather"
ITEM.description = "itemLeatherDesc"
ITEM.price = 2
ITEM.model = "models/mosi/fallout4/props/junk/components/leather.mdl" |
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('StoryBit', {
ActivationEffects = {},
Category = "Tick_BeforeFounders",
Effects = {},
EnableChance = 40,
Enabled = true,
Image = "UI/Messages/Events/02_video_call_2.tga",
Prerequisites = {},
ScriptDone = true,
Text = T(612362415360, --[[StoryBit Boost6_SafeKeeping Text]] "“Commander, we have an offer for you. Recently our organization has run into severe problems with one of our more delicate projects. We want you to take care of it.”\n\nAll in all, the mysterious man wants you to shelter a number of Clone applicants in your project, no questions asked, no answers given."),
TextReadyForValidation = true,
TextsDone = true,
Title = T(242900907357, --[[StoryBit Boost6_SafeKeeping Title]] "Safe Keeping"),
VoicedText = T(516223096443, --[[voice:narrator]] "The message screen is dark and only a vague silhouette of a bald man can be seen. The man speaks with a modulated voice."),
group = "Pre-Founder Stage",
id = "Boost6_SafeKeeping",
qa_info = PlaceObj('PresetQAInfo', {
data = {
{
action = "Modified",
time = 1549880765,
user = "Momchil",
},
{
action = "Modified",
time = 1549984138,
user = "Kmilushev",
},
{
action = "Verified",
time = 1549987825,
user = "Lina",
},
{
action = "Modified",
time = 1550489650,
user = "Blizzard",
},
{
action = "Modified",
time = 1551966490,
user = "Radomir",
},
},
}),
PlaceObj('StoryBitParamFunding', {
'Name', "money_reward",
'Value', 1000000000,
}),
PlaceObj('StoryBitParamNumber', {
'Name', "clone_applicants",
'Value', 10,
}),
PlaceObj('StoryBitReply', {
'Text', T(586882778761, --[[StoryBit Boost6_SafeKeeping Text]] "Accept."),
'OutcomeText', "custom",
'CustomOutcomeText', T(578975104046, --[[StoryBit Boost6_SafeKeeping CustomOutcomeText]] "gain <funding(money_reward)> and <clone_applicants> Officer Clone applicants"),
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Weight', 20,
'Enables', {
"Boost6_SafeKeeping_Complication",
},
'Effects', {
PlaceObj('RewardApplicants', {
'Amount', "<clone_applicants>",
'Trait', "Clone",
'Specialization', "security",
}),
PlaceObj('RewardFunding', {
'Amount', "<money_reward>",
}),
},
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Weight', 80,
'Effects', {
PlaceObj('RewardApplicants', {
'Amount', "<clone_applicants>",
'Trait', "Clone",
'Specialization', "security",
}),
PlaceObj('RewardFunding', {
'Amount', "<money_reward>",
}),
},
}),
PlaceObj('StoryBitReply', {
'Text', T(991773665637, --[[StoryBit Boost6_SafeKeeping Text]] "Accept and have a look at the medical data."),
'OutcomeText', "custom",
'CustomOutcomeText', T(990321363155, --[[StoryBit Boost6_SafeKeeping CustomOutcomeText]] "gain <funding(money_reward)> and <clone_applicants> Security Clone applicants; reveals the Breakthrough tech Cloning"),
'Prerequisite', PlaceObj('IsCommander2', {
'CommanderProfile1', "doctor",
'CommanderProfile2', "inventor",
}),
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Weight', 20,
'Enables', {
"Boost6_SafeKeeping_Complication",
},
'Effects', {
PlaceObj('RewardApplicants', {
'Amount', "<clone_applicants>",
'Trait', "Clone",
'Specialization', "security",
}),
PlaceObj('RewardFunding', {
'Amount', "<money_reward>",
}),
PlaceObj('DiscoverTech', {
'Field', "Breakthroughs",
'Tech', "Cloning",
}),
},
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Weight', 80,
'Effects', {
PlaceObj('RewardApplicants', {
'Amount', "<clone_applicants>",
'Trait', "Clone",
'Specialization', "security",
}),
PlaceObj('RewardFunding', {
'Amount', "<money_reward>",
}),
PlaceObj('DiscoverTech', {
'Field', "Breakthroughs",
'Tech', "Cloning",
}),
},
}),
PlaceObj('StoryBitReply', {
'Text', T(616074144012, --[[StoryBit Boost6_SafeKeeping Text]] "Decline."),
}),
})
|
local parser = require("hotfix-gen.lua-parser.parser")
local function compare_name(index, name)
local k = name:find("[%.:][^%.:]+$")
if k then
return index.tag == "Index"
and (name:sub(k, k) == ":") == (index.is_method == true)
and index[2].tag == "String"
and index[2][1] == name:sub(k+1)
and compare_name(index[1], name:sub(1, k-1))
else
if index.tag == "Index" then
return index[2].tag == "String" and index[2][1] == name
elseif index.tag == "Id" then
return index[1] == name
end
return false
end
end
local function compare_names(index, names)
for _, name in ipairs(names) do
if compare_name(index, name) then return true end
end
return false
end
local function get_path(index, ans)
if index.tag == "Index" and index[2].tag == "String" then
table.insert(ans, 1, index[2][1])
if index.is_method then
ans.is_method = true
end
ans = get_path(index[1], ans)
elseif index.tag == "Id" then
table.insert(ans, 1, index[1])
else
ans = nil
end
return ans
end
local function walk(up, localvals, node, ans)
if type(node) ~= "table" then return ans end
local tag = node.tag
if tag == "Local" then
local names, exps = table.unpack(node)
walk(up, localvals, exps, ans)
for _, name in ipairs(names) do
localvals[name[1]] = true
end
elseif tag == "Localrec" then
local left, right = table.unpack(node)
local name, func = left[1], right[1]
localvals[name[1]] = true
walk(up, localvals, func, ans)
elseif tag == "Forin" then
local names, exps, block = table.unpack(node)
walk(up, localvals, exps, ans)
local newlocal = setmetatable({}, {__index = localvals})
for _, name in ipairs(names) do
newlocal[name[1]] = true
end
walk(up, newlocal, block, ans)
elseif tag == "Fornum" then
local name, start, stop = table.unpack(node, 1, 3)
local step, block
if #node == 4 then
block = node[4]
else
step, block = table.unpack(node, 4, 5)
end
walk(up, localvals, start, ans)
walk(up, localvals, stop, ans)
walk(up, localvals, step, ans)
local newlocal = setmetatable({}, {__index = localvals})
newlocal[name[1]] = true
walk(up, newlocal, block, ans)
elseif tag == "Function" then
local args, block = table.unpack(node)
local newlocal = setmetatable({}, {__index = localvals})
for _, arg in ipairs(args) do
if arg.tag == "Id" then
newlocal[arg[1]] = true
end
end
walk(up, newlocal, block, ans)
elseif tag == "Id" then
local id = node[1]
if not localvals[id] and up[id] then
ans[up[id]] = true
end
elseif tag == "Block" then
local newlocal = setmetatable({}, {__index = localvals})
for _, statement in ipairs(node) do
walk(up, newlocal, statement, ans)
end
else
for _, statement in ipairs(node) do
walk(up, localvals, statement, ans)
end
end
return ans
end
local is_expr = {
Nil = 1, Dots = 1, Boolean = 1, Number = 1, String = 1,
Function = 1, Table = 1, Pair = 1, Op = 1, Paren = 1,
Call = 1, Invoke = 1, Id = 1, Index = 1,
}
local function dependences(up, expr, ans)
if type(expr) ~= "table" then return ans end
assert(is_expr[expr.tag], expr.tag)
if expr.tag == "Id" then
local id = expr[1]
if up[id] then
ans[up[id]] = true
end
elseif expr.tag == "Function" then
walk(up, {}, expr, ans)
else
for _, e in ipairs(expr) do
dependences(up, e, ans)
end
end
return ans
end
local function get_requires(list, i, ans)
ans[#ans+1] = i
for j in pairs(list[i].deps) do
get_requires(list, j, ans)
end
end
local function pick(statements, names)
local n2i = {}
local list = {}
local funcs = {}
local returns = {}
for _, statement in ipairs(statements) do
if statement.tag == "Local" then
local left, right = table.unpack(statement)
for i, id in ipairs(left) do
local exp = right[i]
list[#list+1] = {
type = "local",
name = id[1],
deps = dependences(n2i, right[i], {}),
exp = exp,
}
n2i[id[1]] = #list
end
elseif statement.tag == "Localrec" then
local left, right = table.unpack(statement)
local id, exp = left[1], right[1]
local i = #list + 1
n2i[id[1]] = i
list[i] = {
type = "lfunc",
name = id[1],
deps = dependences(n2i, exp, {}),
pos = statement.pos,
to = statement.to
}
list[i].deps[i] = nil
elseif statement.tag == "Return" then
for _, exp in ipairs(statement) do
if exp.tag == "Id" and n2i[exp[1]] then
returns[n2i[exp[1]]] = true
end
end
elseif statement.tag == "Set" then
local left, right = table.unpack(statement)
local n = math.min(#left, #right)
for j = 1, n do
local tar, exp = left[j], right[j]
if compare_names(tar, names) and exp.tag == "Function" then
local p = get_path(tar, {})
if p then
local f = {
deps = dependences(n2i, exp, {}),
type = "func",
path = p,
pos = exp.pos,
to = exp.to,
}
if n2i[p[1]] then
f.deps[n2i[p[1]]] = true
end
list[#list+1] = f
funcs[#funcs+1] = #list
end
end
end
end
end
local requries = {}
for _, i in ipairs(funcs) do
get_requires(list, i, requries)
end
table.sort(requries)
local last
local ans = {}
for _, i in ipairs(requries) do
if i ~= last then
local s = list[i]
if returns[i] then
s.type = "require"
end
ans[#ans+1] = s
last = i
end
end
return ans
end
local unaryop = {
["not"] = "not ",
["unm"] = "-",
["len"] = "#",
["bnot"] = "~",
}
local function assemble(module, code, statements)
local ans = ""
for _, st in ipairs(statements) do
local type = st.type
local s
if type == "require" then
s = ("local %s = require(%q)\n"):format(st.name, module)
elseif type == "local" then
if not st.exp then
s = ("local %s\n"):format(st.name)
else
local e = code:sub(st.exp.pos, st.exp.to)
if st.exp.tag == "Function" then
e = "function" .. e
elseif st.exp.tag == "Op" and #st.exp == 2 then
e = unaryop[st.exp[1]] .. e
end
s = ("local %s = %s\n"):format(st.name, e)
end
elseif type == "lfunc" then
s = "local " .. code:sub(st.pos, st.to)
elseif type == "func" then
local name = table.concat(st.path, '.', 1, #st.path-1)
local sep = ""
if name ~= "" then
sep = st.path.is_method and ':' or '.'
end
name = name .. sep .. st.path[#st.path]
s = "function " .. name .. code:sub(st.pos, st.to)
end
ans = ans .. s
end
return ans
end
local export = {}
function export.make(module, code, funcs)
local ast, msg = parser.parse(code, module)
if not ast then
error(msg)
end
assert(ast.tag == "Block")
return assemble(module, code, pick(ast, funcs))
end
function export.gen(module, funcs)
local filename = module:gsub("%.", package.config:sub(1, 1)) .. ".lua"
local f = io.open(filename)
assert(f, ("load module '%s' failed\n"):format(module))
local code = f:read('a')
f:close()
return export.make(module, code, funcs)
end
return export
|
local Tunnel = module('_core', 'lib/Tunnel')
local Proxy = module('_core', 'lib/Proxy')
API = Proxy.getInterface('API')
cAPI = Tunnel.getInterface('API')
RegisterServerEvent('FRP:IDENTITY:DisplayCharSelection')
AddEventHandler(
'FRP:IDENTITY:DisplayCharSelection',
function(User)
if User == nil then
return
end
local appearence = {}
if User:getCharacters() ~= nil then
for i = 1, #User:getCharacters() do
local userId = User:getCharacters()[i].charid
table.insert(appearence,User:getCharacterAppearenceFromId(userId))
end
end
TriggerClientEvent('FRP:IDENTITY:DisplayCharSelection', User:getSource(), User:getCharacters(), appearence)
end
)
RegisterServerEvent('FRP:IDENTITY:DisplayCharSelectionWithUser')
AddEventHandler(
'FRP:IDENTITY:DisplayCharSelectionWithUser',
function(User)
if User == nil then
return
end
local appearence = {}
for i = 1, #User:getCharacters() do
local userId = User:getCharacters()[i].charid
table.insert(appearence,User:getCharacterAppearenceFromId(userId))
end
TriggerClientEvent('FRP:IDENTITY:DisplayCharSelection', User:getSource(), User:getCharacters(), appearence)
end
)
RegisterServerEvent('FRP:IDENTITY:selectCharacter')
AddEventHandler(
'FRP:IDENTITY:selectCharacter',
function(cid)
local _source = source
local User = API.getUserFromSource(_source)
User:setCharacter(cid)
end
)
RegisterServerEvent('FRP:IDENTITY:deleteCharacter')
AddEventHandler(
'FRP:IDENTITY:deleteCharacter',
function(cid)
local _source = source
local User = API.getUserFromSource(_source)
User:deleteCharacter(cid)
TriggerEvent('FRP:IDENTITY:DisplayCharSelection', source, _source)
end
)
|
---------------------------------------------------------------------------------------------------
-- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0293-vehicle-type-filter.md
---------------------------------------------------------------------------------------------------
-- Description: Check that SDL is able to provide all vehicle type data in StartServiceAck right after receiving
-- BC.GetSystemInfo and VI.GetVehicleType responses with all parameters
--
-- Steps:
-- 1. HMI provides all vehicle type data in BC.GetSystemInfo(ccpu_version, systemHardwareVersion)
-- and VI.GetVehicleType(make, model, modelYear, trim) responses
-- 2. App requests StartService(RPC) via 5th protocol
-- SDL does:
-- - Provide the vehicle type info with all parameter values received from HMI in StartServiceAck to the app
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local common = require("test_scripts/Protocol/commonProtocol")
--[[ Local Variables ]]
local hmiCap = common.setHMIcap(common.vehicleTypeInfoParams.default)
local rpcServiceAckParams = common.getRpcServiceAckParams(hmiCap)
--[[ Scenario ]]
common.Title("Preconditions")
common.Step("Clean environment", common.preconditions)
common.Step("Start SDL, HMI, connect Mobile, start Session", common.start, { hmiCap })
common.Title("Test")
common.Step("Start RPC Service, Vehicle type data in StartServiceAck", common.startRpcService, { rpcServiceAckParams })
common.Title("Postconditions")
common.Step("Stop SDL", common.postconditions)
|
TestAbstract = {}
function TestAbstract:testNew()
local b, err = pcall( function()
EmptyAbstract:New()
end )
lu.assertEquals( b, false )
lu.assertStrContains( err, " Cannot create an instance of an abstract, interface or mixin class" )
end |
--cache_row_cfg.lua
--luacheck: ignore 631
--获取配置表
local config_mgr = quanta.get("config_mgr")
local cache_row = config_mgr:get_table("cache_row")
--导出版本号
cache_row:set_version(10000)
--导出配置内容
cache_row:upsert({
cache_name = 'account',
cache_table = 'account',
cache_key = 'open_id',
})
cache_row:upsert({
cache_name = 'career_image',
cache_table = 'career_image',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_role_info',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_role_skin',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_setting',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_bag',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_attribute',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_reward',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_vcard',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_prepare',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_career',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_buff',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_achieve',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_standings',
cache_key = 'player_id',
})
cache_row:upsert({
cache_name = 'player',
cache_table = 'player_battlepass',
cache_key = 'player_id',
})
|
--------------------------------
-- @module EventListener
-- @extend Ref
--------------------------------
-- @function [parent=#EventListener] setEnabled
-- @param self
-- @param #bool bool
--------------------------------
-- @function [parent=#EventListener] clone
-- @param self
-- @return EventListener#EventListener ret (return value: cc.EventListener)
--------------------------------
-- @function [parent=#EventListener] isEnabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#EventListener] checkAvailable
-- @param self
-- @return bool#bool ret (return value: bool)
return nil
|
---@class CS.FairyGUI.GLoader : CS.FairyGUI.GObject
---@field public showErrorSign boolean
---@field public url string
---@field public icon string
---@field public align number
---@field public verticalAlign number
---@field public fill number
---@field public shrinkOnly boolean
---@field public autoSize boolean
---@field public playing boolean
---@field public frame number
---@field public timeScale number
---@field public ignoreEngineTimeScale boolean
---@field public material CS.UnityEngine.Material
---@field public shader string
---@field public color CS.UnityEngine.Color
---@field public fillMethod number
---@field public fillOrigin number
---@field public fillClockwise boolean
---@field public fillAmount number
---@field public image CS.FairyGUI.Image
---@field public movieClip CS.FairyGUI.MovieClip
---@field public component CS.FairyGUI.GComponent
---@field public texture CS.FairyGUI.NTexture
---@field public filter CS.FairyGUI.IFilter
---@field public blendMode number
---@type CS.FairyGUI.GLoader
CS.FairyGUI.GLoader = { }
---@return CS.FairyGUI.GLoader
function CS.FairyGUI.GLoader.New() end
function CS.FairyGUI.GLoader:Dispose() end
---@param time number
function CS.FairyGUI.GLoader:Advance(time) end
---@param buffer CS.FairyGUI.Utils.ByteBuffer
---@param beginPos number
function CS.FairyGUI.GLoader:Setup_BeforeAdd(buffer, beginPos) end
return CS.FairyGUI.GLoader
|
#!/usr/bin/lua
require "ubus"
function log_sys(msg,logfile)
local reset = string.format("%s[%sm",string.char(27), tostring(0))
local green = string.format("%s[%sm",string.char(27), tostring(32))
local message = string.format("%s%s [info] %s %s",green,os.date("%Y-%m-%d %H:%M:%S"),msg,reset)
if logfile == nil then
print(message)
else
logfile:write(message .. "\n")
end
io.flush()
end
function ubus.start()
conn = ubus.connect()
if not conn then error("Failed to connect to ubusd.") end
end
function ubus.stop()
conn:close()
end
function get_wlan_list()
data = {}
local status = conn:call("iwinfo", "devices", {})
for _, v in pairs(status) do
for _,wlan in pairs(v) do
table.insert(data,wlan)
end
end
return data
end
function check_mhz(wlan)
local status = conn:call("iwinfo","freqlist",{device=wlan})
for _, v in pairs(status) do
for _,freqlist in pairs(v) do
if freqlist["channel"] == 1 then return 2.4
elseif freqlist["channel"] == 36 then return 5
else return -1 end
end
end
end
function get_mac_list(wlan)
data = {}
local status = conn:call("iwinfo","assoclist",{device=wlan})
for _, v in pairs(status) do
for _,client in pairs(v) do
table.insert(data,client["mac"])
end
end
return data
end
function get_mac_list2(wlan)
data = {}
local status = conn:call("hostapd." .. wlan,"get_clients",{})
if status ~= nil then
for index,value in pairs(status) do
if index == "clients" then
for mac,client in pairs(value) do
table.insert(data,mac)
print("mac",mac)
end
end
end
end
return data
end
function get_signal(wlan, mac_client)
local signal = 0
local status = conn:call("iwinfo","assoclist",{device=wlan,mac=mac_client})
if status ~= nil then
for i, v in pairs(status) do
if i ~= "results" then
if string.upper(status["mac"]) == string.upper(mac_client) then
signal = status["signal_avg"]
end
end
end
end
return signal
end
function kick_out(wlan, mac_client, ban_time_num)
if mac_client == nil then return end
local status = conn:call("hostapd."..wlan,"del_client",{addr=mac_client,reason=5,deauth=true,ban_time=ban_time_num})
if status ~= nil then print("del client:",status) end
local status = conn:call("hostapd."..wlan,"list_bans",{})
if status ~= nil then
for _, v in pairs(status) do
for _,client in pairs(v) do
print("list bans client:",client)
end
end
end
end
function table.match(tbl,value)
for k,v in ipairs(tbl) do
if v == value then
return true,k
end
end
return false,nil
end
function arg_check(arg,check)
if arg == nil then
return false
else
if string.upper(arg) == string.upper(check) then
return true
end
end
end
local black_list = {"00:00:00:00:00:00"}
local white_list = {"00:00:00:00:00:00"}
local only24g_list = {"00:00:00:00:00:00"} --对应仅支持2.4G的终端
local only_5g = false --对应路由器仅支持5G
local only_24g = false --对应路由器仅支持2.4G
local kickout_24G = -85
local kickout_5G = -76
local kickout_24G_5G = -60
logtofile = "/var/log/wifi-kickout.log"
logfile = io.open(logtofile, "a")
io.output(logfile)
--log_sys(string.format("Start wifi Kickout script."), logfile)
ubus.start()
local wlan = {}
for index,value in pairs(get_wlan_list()) do
wlan[value] = {}
wlan[value]["Name"] = value
wlan[value]["MHz"] = check_mhz(value)
end
--命令行参数,设置是否一直循环
if arg_check(arg[1],"ALWAYS") then always = true else always = false end
--命令行参数,设置是否仅监测2.4G网络或者仅监测5G网络
if arg_check(arg[2],"ONLY_24G") then
only_24g = true
only_5g = false
elseif arg_check(arg[2],"ONLY_5G") then
only_5g = true
only_24g = false
else
local only_5g = false
local only_24g = false
end
repeat
local mac = {}
for _,value in pairs(wlan) do
local value_mac_array = get_mac_list(value["Name"])
for _,value_mac in pairs(value_mac_array) do
mac[value_mac] = {}
mac[value_mac]["5G"] = 0
mac[value_mac]["2.4G"] = 0
for index_wlan,_ in pairs(wlan) do
local signal = get_signal(index_wlan, value_mac)
if signal ~= 0 then
--log_sys(string.format("Client %s. connect the %s(%s),signal:%s",value_mac,index_wlan,wlan[index_wlan]["MHz"],signal), logfile)
mac[value_mac]["WLAN"] = index_wlan
if wlan[index_wlan]["MHz"] == 5 then
mac[value_mac]["5G"] = signal
elseif wlan[index_wlan]["MHz"] == 2.4 then
mac[value_mac]["2.4G"] = signal
end
end
end
end
end
for mac_index,value_mac_array in pairs(mac) do
local wlan_name = mac[mac_index]["WLAN"]
local signal_24g = mac[mac_index]["2.4G"]
local signal_5g = mac[mac_index]["5G"]
--print(mac_index,wlan_name,signal_24g,signal_5g)
if not table.match(white_list, mac_index) then
if table.match(black_list, mac_index ) then
kick_out(wlan_name, mac_index, 3000)
log_sys(string.format("Kickout the client %s , because in black list", mac_index), logfile)
elseif (only_24g == true) and (only_5g == true) then
log_sys(string.format("logical error"), logfile)
elseif (only_5g == false) and (signal_24g < kickout_24G) then
log_sys(string.format("Kickout the client %s , %d > %d (2.4G)", mac_index, signal_24g, kickout_24G), logfile)
kick_out(wlan_name, mac_index, 3000)
elseif (only_24g == false) and (signal_5g < kickout_5G) then
log_sys(string.format("Kickout the client %s , %d > %d (5G)", mac_index, signal_5g, kickout_5G), logfile)
kick_out(wlan_name, mac_index, 3000)
elseif (only_5g == false and only_24g == false) and (signal_24g ~= 0) and (signal_5g == 0) and (signal_24g > kickout_24G_5G) then
if not table.match(only24g_list, mac_index ) then
log_sys(string.format("Kickout the client %s , %d < %d (change 2.4G to 5G)", mac_index, signal_24g, kickout_24G_5G), logfile)
kick_out(wlan_name, mac_index, 3000)
end
end
end
end
if always then
os.execute("sleep 30")
end
until not always
logfile:close()
ubus.stop(conn)
|
--Annoyingly there isn't a way to remotely disable the escape callback(from what I know) so this should do.
function RaidMenuSceneManager:disable_back(disable)
self._back_disabled = disable
end
function RaidMenuSceneManager:ignore_back_once()
self._ignore_back_once = true
end
RaidMenuSceneManager.orig_on_escape = RaidMenuSceneManager.orig_on_escape or RaidMenuSceneManager.on_escape
function RaidMenuSceneManager:on_escape(...)
if self._back_disabled then
return
end
if self._ignore_back_once then
self._ignore_back_once = nil
managers.menu:active_menu().renderer:disable_input(0.2)
return
end
if BLT.Dialogs:DialogOpened() then
BLT.Dialogs:CloseLastDialog()
managers.menu:active_menu().renderer:disable_input(0.2)
return
else
self:orig_on_escape(...)
end
end |
--
-- Created by IntelliJ IDEA.
-- User: RJ
-- Date: 22/02/2017
-- Time: 11:30
-- To change this template use File | Settings | File Templates.
--
require "StashDescriptions/StashUtil";
-- well
local stashMap1 = StashUtil.newStash("BallincoolinStashMap1", "Map", "Base.BallincoolinMap", "Stash_AnnotedMap");
stashMap1.spawnOnlyOnZed = true;
--stashMap1.daysToSpawn = "0-30";
stashMap1.zombies = 4;
stashMap1:addStamp("media/ui/LootableMaps/map_arrowsouth.png",nil,677,1968,0,0,0);
stashMap1:addStamp(nil,"Hidden well behind first house on this road",702,1977,0,0,0);
-- campsite
local stashMap1 = StashUtil.newStash("BallincoolinStashMap2", "Map", "Base.BallincoolinMap", "Stash_AnnotedMap");
--stashMap1.daysToSpawn = "0-30";
stashMap1.spawnOnlyOnZed = true;
--stashMap1.zombies = 1;
stashMap1.buildingX = 8948;
stashMap1.buildingY = 9906;
--stashMap1.spawnTable = "SurvivorCache2";
--stashMap1:addContainer("SurvivorCrate","carpentry_01_16",nil,nil,nil,nil);
stashMap1:addStamp("media/ui/LootableMaps/map_x.png",nil,1300,1886,0,0,0);
stashMap1:addStamp(nil,"campsite",1262,1912,0,0,0);
--crazy church/danger
local stashMap1 = StashUtil.newStash("BallincoolinStashMap3", "Map", "Base.BallincoolinMap", "Stash_AnnotedMap");
--stashMap1.spawnOnlyOnZed = true;
stashMap1.zombies = 20;
stashMap1.buildingX = 8797;
stashMap1.buildingY = 9689;
--stashMap1.spawnTable = "SurvivorCache2";
stashMap1:addStamp("media/ui/LootableMaps/map_skull.png",nil,550,799,1,0,0);
stashMap1:addStamp("media/ui/LootableMaps/map_skull.png",nil,559,840,1,0,0);
stashMap1:addStamp("media/ui/LootableMaps/map_skull.png",nil,544,881,1,0,0);
stashMap1:addStamp("media/ui/LootableMaps/map_skull.png",nil,551,905,1,0,0);
stashMap1:addStamp("media/ui/LootableMaps/map_skull.png",nil,549,930,1,0,0);
stashMap1:addStamp("media/ui/LootableMaps/map_skull.png",nil,550,954,1,0,0);
stashMap1:addStamp("media/ui/LootableMaps/map_skull.png",nil,549,978,1,0,0);
stashMap1:addStamp("media/ui/LootableMaps/map_skull.png",nil,610,854,1,0,0);
stashMap1:addStamp("media/ui/LootableMaps/map_skull.png",nil,494,853,1,0,0);
stashMap1:addStamp(nil,"I TOLD YOU DEATH WAS COMING",432,1006,1,0,0);
stashMap1:addStamp(nil,"I TOLD YOU DEATH WAS COMING",435,1030,1,0,0);
stashMap1:addStamp(nil,"I TOLD YOU DEATH WAS COMING",425,1055,1,0,0);
stashMap1:addStamp(nil,"I TOLD YOU DEATH WAS COMING",415,1081,1,0,0);
stashMap1:addStamp(nil,"god does not see us",152,793,1,0,0);
stashMap1:addStamp(nil,"god does not hear us",160,810,1,0,0);
stashMap1:addStamp(nil,"god does not smell us",140,833,1,0,0);
stashMap1:addStamp(nil,"but those things do!",155,852,1,0,0);
stashMap1:addStamp(nil,"god will eat our souls",197,951,1,0,0);
stashMap1:addStamp(nil,"BUT THEY WILL EAT OUR BODIES",187,975,1,0,0);
--Survivor cabin stash
local stashMap1 = StashUtil.newStash("BallincoolinStashMap4", "Map", "Base.BallincoolinMap", "Stash_AnnotedMap");
stashMap1.spawnOnlyOnZed = true;
stashMap1.zombies = 3;
stashMap1.barricades = 80;
stashMap1.buildingX = 8869;
stashMap1.buildingY = 9800;
--stashMap1.spawnTable = "SurvivorCache2";
stashMap1:addContainer("SurvivorCrate","floors_interior_tilesandwood_01_62",nil,nil,nil,nil);
stashMap1:addStamp("media/ui/LootableMaps/map_o.png",nil,825,1368,0,0,0);
stashMap1:addStamp(nil,"stash in front hall of cabin",850,1370,0,0,1);
--gun duffelbag cache
local stashMap1 = StashUtil.newStash("BallincoolinStashMap5", "Map", "Base.BallincoolinMap", "Stash_AnnotedMap");
--stashMap1.daysToSpawn = "0-30";
stashMap1.spawnOnlyOnZed = true;
--stashMap1.zombies = 1;
stashMap1.buildingX = 8793;
stashMap1.buildingY = 9807;
--stashMap1.spawnTable = "GunCache1";
stashMap1:addContainer("GunBox",nil,"Base.Garbagebag",nil,nil,nil,nil);
stashMap1:addStamp("media/ui/LootableMaps/map_target.png",nil,526,1429,1,0,0);
|
local BaseInstance = import("./BaseInstance")
local InstanceProperty = import("../InstanceProperty")
local UDim = import("../types/UDim")
local UIPadding = BaseInstance:extend("UIPadding", {
creatable = true,
})
UIPadding.properties.PaddingBottom = InstanceProperty.typed("UDim", {
getDefault = function()
return UDim.new()
end,
})
UIPadding.properties.PaddingLeft = InstanceProperty.typed("UDim", {
getDefault = function()
return UDim.new()
end,
})
UIPadding.properties.PaddingRight = InstanceProperty.typed("UDim", {
getDefault = function()
return UDim.new()
end,
})
UIPadding.properties.PaddingTop = InstanceProperty.typed("UDim", {
getDefault = function()
return UDim.new()
end,
})
return UIPadding |
require "stdlib/event/event"
local cryolimits
local cryotargets
local function initLocals ()
cryolimits = global.MacroFusion.cryogrenade_limits
cryotargets = global.MacroFusion.cryogrenade_targets
end
script.on_init(function ()
global.MacroFusion = global.MacroFusion or {}
global.MacroFusion.cryogrenade_limits = global.MacroFusion.cryogrenade_limits or {}
global.MacroFusion.cryogrenade_targets = global.MacroFusion.cryogrenade_targets or {}
global.MacroFusion.cryogrenades = global.MacroFusion.cryogrenades or 0
initLocals()
end)
script.on_load(function ()
initLocals()
end)
-- TODO get cryogrenade's timeout and range (settings?)
local function addCryoTarget(entity, tick)
cryolimits[entity.unit_number] = tick
cryotargets[tick] = cryotargets[tick] or {}
table.insert(cryotargets[tick], {id=entity.unit_number, entity=entity})
entity.active = false
end
local function unfreezecryolimits(tick)
for time, targets in pairs(cryotargets) do
if time > tick then break end
for i=1, #targets do
local entity = targets[i].entity
if not(entity) or not(entity.valid) then
cryolimits[targets[i].id] = nil
else
if cryolimits[entity.unit_number] > tick then
cryotargets[tick] = cryotargets[tick] or {}
table.insert(cryotargets[tick], entity)
else
entity.active = true
cryolimits[entity.unit_number] = nil
end
end
end
cryotargets[time] = nil
end
end
Event.register(defines.events.on_trigger_created_entity, function(event)
if event.entity.name == "macro-fusion-cryogrenade-start-script" then
global.MacroFusion.cryogrenades = global.MacroFusion.cryogrenades + 1
event.entity.destructible = false
elseif event.entity.name == "macro-fusion-cryogrenade-flag-script" then
local entity = event.entity
local targets = entity.surface.find_entities_filtered {
position = entity.position
}
for _, target in pairs(targets) do
if target.valid and target.unit_number and target.force and
not(entity.force.get_cease_fire(target.force)) then
log(entity.force.name.."-"..target.force.name)
addCryoTarget(target, event.tick + 60 * 10 )
end
end
event.entity.destroy()
elseif event.entity.name == "macro-fusion-cryogrenade-end-script" then
unfreezecryolimits(event.tick)
global.MacroFusion.cryogrenades = global.MacroFusion.cryogrenades - 1
if global.MacroFusion.cryogrenades <= 0 then
cryotargets = {}
cryolimits = {}
end
event.entity.destroy()
end
end) |
-- local dbg = require("debugger")
-- dbg.auto_where = 2
local fn = require'tools.fn'
describe("curry", function()
local function add(a, b) return a + b end
local inc = fn.curry(add, 1)
local answer = fn.curry(add, 1, 41)
it("can increment", function()
assert.is_equal(42, inc(41))
end)
it("can be called", function()
assert.is_equal(42, answer())
end)
describe("this can be very useful with fn tools", function()
it("e.g. with map", function()
assert.are.same({1, 2}, fn.map({0, 1}, inc))
end)
it("can simulate foldl", function()
local result = {}
local add_to = fn.curry(table.insert, result)
fn.each({1, 2}, add_to)
assert.are.same({1, 2}, result)
end)
end)
end)
describe("positional curry", function()
local function four(a,b,c,d) return 1000*a + 100*b + 10*c + d end
describe("fixed units", function()
local fixed = fn.curry_at(four, fn.free, fn.free, fn.free, 1)
it("delivers", function()
assert.is_equal(4321, fixed(4, 3, 2))
end)
end)
describe("two twos", function()
local fixed = fn.curry_at(four, fn.free, 2, 3)
it("delivers", function()
assert.is_equal(1234, fixed(1, 4))
end)
end)
describe("all given", function()
local fixed = fn.curry_at(four, 9, 8, 7, 6)
it("delivers", function()
assert.is_equal(9876, fixed())
end)
end)
end)
describe("keyword curry", function()
local function comp(data)
return data.factor * 10 + data.offset
end
local hundred = fn.curry_kwd(comp, {factor = 10})
it("can curry the factor", function()
assert.is_equal(101, hundred{offset = 1})
end)
it("can override", function()
assert.is_equal(202, hundred{factor=20, offset = 2})
end)
end)
|
--[[
Model - Public Transport Route Choice
Type - MNL
Authors - Rui Tan
]]
--Estimated values for all betas
--Note: the betas that not estimated are fixed to zero.
local beta_in_vehicle = -0.315324638
local beta_walk = -0.6152576346
local beta_wait = -0.4252576346
local beta_no_txf = -4.2752576346
local beta_cost = -0.1254734748
local beta_path_size = 0.8347423654
--local beta_in_vehicle = -0.315324638
--local beta_walk = -0.6152576346
--local beta_wait = -0.4252576346
--local beta_no_txf = -4.2752576346
--local beta_cost = -0.1254734748
--local beta_path_size = 0.8347423654
--utility
-- utility[i] for choice[i]
local utility = {}
local choice = {}
local availability = {}
local function computeUtilities(params, N_choice)
local log = math.log
utility = {}
choice = {}
availability = {}
for i = 1,N_choice do
choice[i] = i
availability[i] = 1
end
for i = 1,N_choice do
utility[i] = beta_in_vehicle * params:total_in_vehicle_time(i) / 60
+ beta_walk * params:total_walk_time(i) / 60
+ beta_wait * params:total_wait_time(i) / 60
+ beta_no_txf * params:total_no_txf(i)
+ beta_path_size * log(params:total_path_size(i))
+ beta_cost * params:total_cost(i)
end
end
--scale
local scale= 1 --for all choices
-- function to call from C++ preday simulator
-- params and dbparams tables contain data passed from C++
-- to check variable bindings in params or dbparams, refer PredayLuaModel::mapClasses() function in dev/Basic/medium/behavioral/lua/PredayLuaModel.cpp
function choose_PT_path(params, N_choice)
computeUtilities(params, N_choice)
local probability = calculate_probability("mnl", choice, utility, availability, scale)
return make_final_choice(probability)
end
|
-------------------------------------------------------------------------------
-- Module Declaration
local mod, CL = BigWigs:NewBoss("The Black Knight", 650, 637)
if not mod then return end
mod:RegisterEnableMob(35451)
mod.engageId = 2021
--mod.respawnTime = 0 -- resets, doesn't respawn
-------------------------------------------------------------------------------
-- Initialization
function mod:GetOptions()
return {
-7598, -- Ghoul Explode
67781, -- Desecration
}
end
function mod:OnBossEnable()
self:Log("SPELL_CAST_START", "Explode", 67729)
self:Log("SPELL_AURA_APPLIED", "Desecration", 67781)
end
-------------------------------------------------------------------------------
-- Event Handlers
do
local prev = 0
function mod:Explode(args)
local t = GetTime()
if t - prev > 1 then -- all remaining ghouls start casting Explode simultaneously when the boss transitions to stage 3
prev = t
self:Message(-7598, "orange", nil, CL.casting:format(self:SpellName(args.spellId)))
self:CastBar(-7598, self:Normal() and 5 or 4, args.spellId)
end
end
end
function mod:Desecration(args)
if self:Me(args.destGUID) then
self:TargetMessage(args.spellId, args.destName, "blue", "Alarm")
end
end
|
require "resources/essentialmode/lib/MySQL"
MySQL:open("127.0.0.1", "gta5_gamemode_essential", "root", "space031")
outfits = {"face","","hair","","pants","","shoes","","shirt","","","torso"}
RegisterServerEvent("skin_customization:ChoosenSkin")
AddEventHandler("skin_customization:ChoosenSkin",function(skin)
TriggerEvent('es:getPlayerFromId', source, function(user)
local player = user.identifier
local executed_query = MySQL:executeQuery("UPDATE outfits SET skin='@skin' WHERE identifier='@user'",{['@skin']=skin,['@user']=player})
local executed_query2 = MySQL:executeQuery("SELECT identifier FROM outfits WHERE identifier='@user'",{['@user']=player})
local result = MySQL:getResults(executed_query2, {'identifier'}, "identifier")
if result[1].identifier ~= nil then
TriggerClientEvent("skin_customization:Customization",source,skin)
else
TriggerClientEvent("skin_customization:Customization",source,skin)
end
end)
end)
RegisterServerEvent("skin_customization:ChoosenComponents")
AddEventHandler("skin_customization:ChoosenComponents",function()
TriggerEvent('es:getPlayerFromId', source, function(user)
--Récupération du SteamID.
local player = user.identifier
local executed_query = MySQL:executeQuery("SELECT face,face_text,hair,hair_text,pants,pants_text,shoes,shoes_text,torso,torso_text,shirt,shirt_text FROM outfits WHERE identifier='@user'",{['@user']=player})
local result = MySQL:getResults(executed_query, {'face','face_text','hair','hair_text','pants','pants_text','shoes','shoes_text','torso','torso_text','shirt','shirt_text'}, "identifier")
TriggerClientEvent("skin_customization:updateComponents",source,{result[1].face,result[1].face_text,result[1].hair,result[1].hair_text,result[1].pants,result[1].pants_text,result[1].shoes,result[1].shoes_text,result[1].torso,result[1].torso_text,result[1].shirt,result[1].shirt_text})
end)
end)
RegisterServerEvent("skin_customization:SpawnPlayer")
AddEventHandler("skin_customization:SpawnPlayer", function()
TriggerEvent('es:getPlayerFromId', source, function(user)
--Récupération du SteamID.
local player = user.identifier
--Exécution de la requêtes SQL.
local executed_query = MySQL:executeQuery("SELECT isFirstConnection FROM users WHERE identifier = '@username'", {['@username'] = player})
--Récupération des données générée par la requête.
local result = MySQL:getResults(executed_query, {'isFirstConnection'}, "identifier")
-- Vérification de la présence d'un résultat avant de lancer le traitement.
if(result[1].isFirstConnection == 1)then
local executed_query3 = MySQL:executeQuery("INSERT INTO outfits(identifier) VALUES ('@identifier')",{['@identifier']=player})
local executed_query4 = MySQL:executeQuery("UPDATE users SET isFirstConnection = 0 WHERE identifier = '@username'", {['@username'] = player})
TriggerClientEvent("skin_customization:Customization", source, "mp_m_freemode_01")
else
local executed_query2 = MySQL:executeQuery("SELECT skin FROM outfits WHERE identifier = '@username'", {['@username'] = player})
--Récupération des données générée par la requête.
local result2 = MySQL:getResults(executed_query2, {'skin'}, "identifier")
TriggerClientEvent("skin_customization:Customization", source, result2[1].skin)
end
end)
end)
RegisterServerEvent("skin_customization:SaveComponents")
AddEventHandler("skin_customization:SaveComponents",function(components)
TriggerEvent('es:getPlayerFromId', source, function(user)
local component = components[1]+1
--Récupération du SteamID.
local draw = ""..outfits[component]
local drawid = ""..components[3]
local text = outfits[component].."_text"
local textid = ""..components[4]
local player = user.identifier
local executed_query = MySQL:executeQuery("UPDATE outfits SET @a='@drawid',@b='@textureid' WHERE identifier='@user'",{['@a']=draw,['@drawid']=drawid,['@b']=text,['@textureid']=textid,['@user']=player})
end)
end)
|
local awful = require("awful")
local wp = {}
-- Load wallpaper database from file
local function load_database(root)
local index = 1
local db = {}
local lines
if pcall(function() lines = io.lines(root .. "/.db") end) then
for line in lines do
-- Timestamps are of no use here
for timestamp, width, height, path in string.gmatch(line, "([%d]+):([%d]+):([%d]+) (.+)") do
db[index] = {}
db[index].width = tonumber(width)
db[index].height = tonumber(height)
db[index].path = path
index = index + 1
end
end
return db
else
local naughty = require("naughty")
naughty.notify({title = "Wallpaper database error", text = "Cannot load database from " .. root .. "\n Maybe you should rebuild the database"} )
return {}
end
end
-- Filter images loaded from database
local function filter_image(s, images, filters)
local output = {}
local output_idx = 1
for image_idx, image in pairs(images) do
-- Only allow images that pass the check
local pass = true
for _, filter in pairs(filters) do
if not filter(s, image_idx, image) then goto fail end
end
output[output_idx] = image
output_idx = output_idx + 1
:: fail ::
end
return output
end
-- Filter the images, and set the image as wallpaper
local function do_set(s, images, filter, setter, root)
local filtered_images = filter_image(s, images, filters)
if #filtered_images == 0 then return end
local the_image = filtered_images[math.random(#filtered_images)]
setter(s, the_image, root .. "/" .. the_image.path)
end
-- Prepare the database, filters and setter for given settings
-- settings:
-- root: (required) root directory to the wallpapers
-- filters: a series of filter functions
-- setter: a function that actually set the wallpaper
local function prepare(settings)
local images = load_database(settings.root)
local filters = settings.filters or { wp.filter_by_ratio(0.8) }
local setter = settings.setter or wp.set_maximized
return images, filters, setter
end
-- Ignore images whose ratio significantly differ from the screen ratio
-- max_factor <= 1: When the image is fitted to the max size to the screen, how
-- much space is allowed to be blank
function wp.filter_by_ratio(min_factor)
local naughty = require("naughty")
return function(s, image_idx, image)
local geometry = screen[s].geometry
local fit_width_factor = geometry.width / image.width * image.height / geometry.height
local fit_height_factor = geometry.height / image.height * image.width / geometry.width
local fit_factor = math.min(fit_width_factor, fit_height_factor)
return fit_factor > min_factor
end
end
-- Default strategy: set by stretching the image (because the images have been
-- filtered by ratio already)
function wp.set_maximized(s, image, image_path)
local gears = require("gears")
gears.wallpaper.maximized(image_path, s)
end
-- Set wallpaper for one given screen
function wp.set_one(s, settings)
images, filters, setter = prepare(settings)
do_set(s, images, filters, setter, settings.root)
end
-- Set wallpaper for all screens
function wp.set_all(settings)
images, filters, setter = prepare(settings)
for s = 1, screen.count() do
do_set(s, images, filters, setter, settings.root)
end
end
math.randomseed(os.time());
return wp
|
local mod = get_mod("rwaon_talents")
mod:add_talent_buff("wood_elf", "kerillian_maidenguard_passive_stamina_regen_aura", {
range = 10,
buff_to_add = "kerillian_maidenguard_passive_stamina_regen_buff",
update_func = "activate_buff_on_distance",
})
mod:add_talent_buff("wood_elf", "kerillian_maidenguard_passive_stamina_regen_buff", {
max_stacks = 1,
icon = "kerillian_maidenguard_passive",
stat_buff = "fatigue_regen",
multiplier = 0.5,
})
PassiveAbilitySettings.rwaon_we_2 = {
description = "career_passive_desc_we_2a_2",
display_name = "career_passive_name_we_2",
icon = "kerillian_maidenguard_passive",
buffs = {
"kerillian_maidenguard_passive_dodge",
"kerillian_maidenguard_passive_dodge_speed",
"kerillian_maidenguard_passive_stamina_regen_aura",
"kerillian_maidenguard_passive_increased_stamina",
"kerillian_maidenguard_passive_uninterruptible_revive",
--"kerillian_maidenguard_ability_cooldown_on_hit",
--"kerillian_maidenguard_ability_cooldown_on_damage_taken"
},
perks = {
{
display_name = "career_passive_name_we_2b",
description = "career_passive_desc_we_2b_2"
},
{
display_name = "career_passive_name_we_2c",
description = "career_passive_desc_we_2c"
}
}
}
CareerSettings.we_maidenguard.passive_ability = PassiveAbilitySettings.rwaon_we_2
------------------------------------------------------------------------------
ActivatedAbilitySettings.rwaon_we_2 = {
description = "career_active_desc_we_2",
display_name = "career_active_name_we_2",
cooldown = 40,
icon = "kerillian_maidenguard_activated_ability",
ability_class = CareerAbilityWEMaidenGuard
}
CareerSettings.we_maidenguard.activated_ability = ActivatedAbilitySettings.rwaon_we_2 |
--=========== Copyright © 2019, Planimeter, All rights reserved. ===========--
--
-- Purpose: weapon_bow
--
--==========================================================================--
require( "game.shared.entities.item" )
require( "game" )
class "weapon_bow" ( "item" )
weapon_bow.data = {
name = "Bow",
image = "images/entities/weapon_bow.png"
}
function weapon_bow:weapon_bow()
item.item( self )
end
if ( _CLIENT ) then
function weapon_bow:pickup()
localplayer:pickup( self )
end
function weapon_bow:drop()
localplayer:drop( self.__type )
end
function weapon_bow:examine()
chat.addText( "It's a bow. What else did you expect?" )
end
end
function weapon_bow:spawn()
entity.spawn( self )
local tileSize = game.tileSize
local min = vector()
local max = vector( tileSize, -tileSize )
self:initializePhysics( "dynamic" )
self:setCollisionBounds( min, max )
local body = self:getBody()
if ( body ) then
body:setMass( 1.81437 )
end
end
entities.linkToClassname( weapon_bow, "weapon_bow" )
|
script.on_event(
defines.events.on_player_changed_position,
function(event)
local player = game.get_player(event.player_index) -- get the player that moved
-- if they're wearing our armor
if
player.character and
player.get_inventory(defines.inventory.character_armor).get_item_count("fire-armor") >= 1
then
-- create the fire where they're standing
player.surface.create_entity {name = "fire-flame", position = player.position, force = "neutral"}
end
end
)
|
-- Only do this when not yet done for this buffer
if vim.b.did_ftplugin then
return
end
vim.opt.complete:append { "kspell" }
vim.g.vim_markdown_conceal = 0
vim.g.vim_markdown_math = 1
vim.g.vim_markdown_frontmatter = 1
vim.g.vim_markdown_toml_frontmatter = 1
vim.g.vim_markdown_json_frontmatter = 1
vim.g.vim_markdown_new_list_item_indent = 2
vim.g.markdown_fenced_languages = {
"html",
"python",
"bash=sh",
"javascript",
"c++=cpp",
"viml=vim",
"ini=dosini",
}
|
--
--Make json with the proper name and value
--
function getJson(name, value)
if (name == nil or value == nil) then return nil; end
json='{"FeedID":"'..feedID..'", "FeedKeyHash":"'..feedHash..'", "deviceName":"'..deviceName..'", "deviceID":1, "objectType": "Sensor", "objectName": "'..name..'", "objectAction": "NONE", "objectValue": '..value..', "timestamp": "TSNONE"}'
return json
end
--
--Read temperature sensor value
--
function getSensorTemp()
pin = 5
status, temp, humi, temp_dec, humi_dec = dht.read(pin)
if status == dht.OK then
tmr.delay(1000000) -- wait 1.000,000 us = 1 second
return temp
elseif status == dht.ERROR_CHECKSUM then
print( "DHT Checksum error." )
return nil
elseif status == dht.ERROR_TIMEOUT then
print( "DHT timed out." )
return nil
end
end
--
--Read humidity sensor value
--
function getSensorHumi()
pin = 5
status, temp, humi, temp_dec, humi_dec = dht.read(pin)
if status == dht.OK then
tmr.delay(1000000) -- wait 1.000,000 us = 1 second
return humi
elseif status == dht.ERROR_CHECKSUM then
print( "DHT Checksum error." )
return nil
elseif status == dht.ERROR_TIMEOUT then
print( "DHT timed out." )
return nil
end
end
--
--Update sensors
--what:
--1 - Sensors
--2 -- Methods
--3 - Trigger sensors
function updateSensorsMethods(what)
if (supportedSensors == nil) then return; end
for k,v in pairs(supportedSensors) do
local json;
topic = getTopicName()
t_result = topic
if (supportedSensors[k] == 1) then
json = getJson(k, getSensorTemp())
if (json ~= nil) then reqProducer(t_result, json); end
elseif (supportedSensors[k] == 2) then
--json = getJson(k, getDoorStatus())
json = getJson(k, gpio.read(3))
if (json ~= nil) then reqProducer(t_result, json); end
elseif (supportedSensors[k] == 3) then
json = getJson(k, getSensorHumi())
if (json ~= nil) then reqProducer(t_result, json); end
else
print('Unsupported sensor update...\n')
end
end
end
function appFinalSteps()
if (deviceInitiated == 0) then
--Put here steps which should exec only after boot
end
print('Executing final steps\n')
node.task.post(globalFinalSteps);
end
--
--Main
--
function main()
counter = 0
collectgarbage();
print('\nRunning app.lua\n');
--initBoard();
--updateSensorsMethods(2); -- Update methods when boot the board
--Try to update data 3 times,
tmr.alarm(2, 10000, 1, function()
if (wifi.sta.getip() ~= nil) then
tmr.stop(2)
updateSensorsMethods(1); --Update sensors and enqueue requests
--Sensors are enqueued. Now start mqtt client. Continue after it
--is connected. Will continue with appFinalSteps
dofile("mqtt.lua");
elseif (wifi.sta.getip() == nil and counter > 2) then
print('Skip posting. Restarting...\n');
tmr.stop(2)
node.restart()
else
counter = counter + 1
ledBlink();
print('Skip posting. Reconnecting...\n');
end
end);
end
main()
|
--[[
deftcp string.pack参数 lstrlib.c 1221行
--]]
local humble = require("humble")
local string = string
local headFmt = ">HH"
local protoLens = 2
local deftcp = {}
function deftcp.Response(sock, proto, val)
local netPack
local iLens = protoLens
if val then
iLens = iLens + #val
netPack = string.pack(headFmt, iLens, proto)..val
else
netPack = string.pack(headFmt, iLens, proto)
end
humble.sendMsg(sock, netPack)
end
return deftcp
|
-- Tracing tail returns is tricky, and if you're not careful you'll end up
-- attributing time to the wrong stack frame.
-- LuaJIT reports tailcalls differently - it doesn't work yet.
luatrace = require("luatrace")
function factorial(n, p)
print(n, p)
if n == 1 then
return p or 1
end
return factorial(n - 1, (p or 1) * n)
end
luatrace.tron()
print(factorial(10))
luatrace.troff()
|
local skynet = require "skynet"
local WATCHDOG
local CMD = {}
local client_fd
local user_info
local handle={}
local gate
local room
local room_idx
local room_pos
local uid
local function send_client(v)
skynet.send(gate, "lua", "send_client", client_fd, v)
end
--进入房间
local function enter_room(req)
local room_id
if type(req) == "table" then
room_id = req.room_id
end
local con_info = {
fd = client_fd,
watchdog = WATCHDOG,
gate = gate,
uid = uid,
client = skynet.self()
}
local room_mgr = skynet.uniqueservice"room_mgr"
skynet.error("agent enter_room", room_mgr, "room_id:", room_id)
local ret, idx, pos, src = skynet.call(room_mgr, "lua", "enter", user_info, con_info, room_id)
--skynet.error("----",json.encode(ret))
room_idx = idx
room_pos = pos
room = src
if not ret then
room_idx = nil
room_pos = nil
room = nil
send_client({ false, "Enter room failed" })
end
end
local function offline()
if room then
local ret = skynet.call(room, "lua", "offline", room_pos)
room_idx = nil
room_pos = nil
end
end
handle.enter_room = enter_room
skynet.register_protocol {
name = "client",
id = skynet.PTYPE_CLIENT,
unpack = skynet.tostring,
dispatch = function (_, _, msg, ...)
local ok, req = pcall(json.decode, msg)
if ok and handle[req.cmd] then
handle[req.cmd](req)
else
send_client({ false, "Invalid command" })
end
end
}
function CMD.start(conf)
local fd = conf.client
gate = conf.gate
WATCHDOG = conf.watchdog
user_info = conf.info
uid = conf.uid
client_fd = fd
skynet.call(gate, "lua", "forward", fd)
send_client "Welcome to skynet"
end
function CMD.disconnect()
offline()
skynet.error("agent exit!")
skynet.exit()
end
skynet.start(function()
skynet.dispatch("lua",function(_,_,cmd,...)
local f = CMD[cmd]
skynet.ret(skynet.pack(f(...)))
end)
end)
|
-- Box2D premake script.
-- http://industriousone.com/premake
local action = _ACTION or ""
solution "Box2D"
location ( "Build/" .. action )
configurations { "Debug", "Release" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "Debug"
targetdir ( "Build/" .. action .. "/bin/Debug" )
flags { "Symbols" }
configuration "Release"
targetdir ( "Build/" .. action .. "/bin/Release" )
defines { "NDEBUG" }
flags { "Optimize" }
project "Box2D"
kind "StaticLib"
language "C++"
files { "Box2D/**.hpp", "Box2D/**.cpp" }
vpaths { [""] = "Box2D" }
includedirs { "." }
project "GLEW"
kind "StaticLib"
language "C++"
files { "glew/*.h", "glew/*.c" }
vpaths { ["Headers"] = "**.h", ["Sources"] = "**.c" }
includedirs { "." }
project "GLFW"
kind "StaticLib"
language "C"
files { "glfw/*.h", "glfw/*.c" }
vpaths { ["Headers"] = "**.h", ["Sources"] = "**.c" }
project "HelloWorld"
kind "ConsoleApp"
language "C++"
files { "HelloWorld/HelloWorld.cpp" }
vpaths { [""] = "HelloWorld" }
includedirs { "." }
links { "Box2D" }
project "Testbed"
kind "ConsoleApp"
language "C++"
files { "Testbed/**.hpp", "Testbed/**.cpp" }
vpaths { [""] = "Testbed" }
includedirs { "." }
links { "Box2D", "GLEW", "GLFW" }
configuration { "windows" }
links { "glu32", "opengl32", "winmm" }
configuration { "macosx" }
linkoptions { "-framework OpenGL -framework Cocoa" }
configuration { "not windows", "not macosx" }
links { "X11", "GL", "GLU" }
|
if (clink.version_encoded or 0) < 10020030 then
error("Starship requires a newer version of Clink; please upgrade to Clink v1.2.30 or later.")
end
local starship_prompt = clink.promptfilter(5)
start_time = os.clock()
end_time = 0
curr_duration = 0
is_line_empty = true
clink.onbeginedit(function ()
end_time = os.clock()
if not is_line_empty then
curr_duration = end_time - start_time
end
end)
clink.onendedit(function (curr_line)
if starship_precmd_user_func ~= nil then
starship_precmd_user_func(curr_line)
end
start_time = os.clock()
if string.len(string.gsub(curr_line, '^%s*(.-)%s*$', '%1')) == 0 then
is_line_empty = true
else
is_line_empty = false
end
end)
function starship_prompt:filter(prompt)
if starship_preprompt_user_func ~= nil then
starship_preprompt_user_func(prompt)
end
return io.popen([[::STARSHIP::]].." prompt"
.." --status="..os.geterrorlevel()
.." --cmd-duration="..math.floor(curr_duration*1000)
.." --terminal-width="..console.getwidth()
.." --keymap="..rl.getvariable('keymap')
):read("*a")
end
function starship_prompt:rightfilter(prompt)
return io.popen([[::STARSHIP::]].." prompt --right"
.." --status="..os.geterrorlevel()
.." --cmd-duration="..math.floor(curr_duration*1000)
.." --terminal-width="..console.getwidth()
.." --keymap="..rl.getvariable('keymap')
):read("*a")
end
local characterset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
local randomkey = ""
math.randomseed(os.time())
for i = 1, 16 do
local rand = math.random(#characterset)
randomkey = randomkey..string.sub(characterset, rand, rand)
end
os.setenv('STARSHIP_SHELL', 'cmd')
os.setenv('STARSHIP_SESSION_KEY', randomkey)
|
-- dynamic routing based on JWT Claim
local sub = string.sub
local type = type
local pairs = pairs
local lower = string.lower
local jwt_decoder = require "kong.plugins.jwt.jwt_parser"
local JWT2Header = {
PRIORITY = 900,
VERSION = "1.0"
}
function JWT2Header:rewrite(conf)
kong.service.request.set_header("X-Kong-JWT-Kong-Proceed", "no")
kong.log.debug(kong.request.get_header("Authorization"))
local claims = nil
local header = nil
if kong.request.get_header("Authorization") ~= nil then
kong.log.debug(kong.request.get_header("Authorization"))
if string.match(lower(kong.request.get_header("Authorization")), 'bearer') ~= nil then
kong.log.debug("2" .. kong.request.get_path())
local jwt, err = jwt_decoder:new((sub(kong.request.get_header("Authorization"), 8)))
if err then
return false, {
status = 401,
message = "Bad token; " .. tostring(err)
}
end
claims = jwt.claims
header = jwt.header
kong.service.request.set_header("X-Kong-JWT-Kong-Proceed", "yes")
end
end
if kong.request.get_header("X-Kong-JWT-Kong-Proceed") == "yes" then
for claim, value in pairs(claims) do
local claimHeader = toHeaderKey(claim)
local valueHeader = toHeaderValue(value)
kong.service.request.set_header("X-Kong-JWT-Claim-" .. claimHeader, valueHeader)
end
end
end
function JWT2Header:access(conf)
if kong.request.get_header("X-Kong-JWT-Kong-Proceed") == "yes" then
-- ctx oesn't work in kong 1.5, only in 2.x local claims = kong.ctx.plugin.claims
local claims = kong.request.get_headers();
if not claims then
kong.log.debug("empty claim")
return
end
if conf.strip_claims == "true" then
for claim, value in pairs(claims) do
kong.log.debug("found header " .. claim)
if type(claim) == "string" and string.match(claim, 'x%-kong%-jwt%-claim') ~= nil then
kong.service.request.clear_header(claim)
kong.log.debug("removed header " .. claim)
end
end
kong.service.request.clear_header("X-Kong-JWT-Kong-Proceed")
end
-- kong.ctx.plugin.claims = nil
elseif conf.token_required == "true" then
kong.service.request.clear_header("X-Kong-JWT-Kong-Proceed")
kong.response.exit(404, '{"error": "No valid JWT token found"}')
else
kong.service.request.clear_header("X-Kong-JWT-Kong-Proceed")
end
end
-- converts a key to a header compatible key
function toHeaderKey(key)
local stringkey = tostring(key)
-- quick and dirty pascal casing
local words = {}
for i, v in pairs(strsplit(stringkey, "_")) do -- grab all the words separated with a _ underscore
table.insert(words, v:sub(1, 1):upper() .. v:sub(2)) -- we take the first character, uppercase, and add the rest. Then I insert to the table
end
return table.concat(words, "") -- just concat everything inside of the table
end
-- converts a value to a header compatible value
-- will convert bool/numbers to strings, join arrays with ",", etc.
function toHeaderValue(value)
if type(value) == "string" then
return value
end
if type(value) == "boolean" then
return tostring(value)
end
if type(value) == "number" then
return tostring(value) -- might want to use string.format instead?
end
if type(value) == "nil" then
return ""
end
if type(value) == "table" then
if value[1] == nil then
-- do something here to create string from dictionary table
local joineddict = {}
for k, val in pairs(value) do
table.insert(joineddict, tostring(k) .. "=" .. tostring(val))
end
return table.concat(joineddict, ",")
end
return table.concat(value, ",") -- array value can be simply joined
end
return tostring(value)
end
function strsplit(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t = {}
for str in string.gmatch(inputstr, "([^" .. sep .. "]+)") do
table.insert(t, str)
end
return t
end
return JWT2Header
|
local Utils = require "lualib.utils"
local sformat = string.format
local M = {}
function M.print( ... )
print(...)
end
function M.fprint(fmat, ...)
local s = sformat(fmat, ...)
print(s)
end
function M.error( ... )
local n = select("#",...)
local lst = {}
for i=1,n do
local v = select(i, ...)
if type(v) == "table" then
table.insert(lst, Utils.table_str(v))
else
table.insert(lst, tostring(v))
end
end
local s = table.concat(lst," ")
local str = sformat("\27[31m%s\27[0m",s)
print(str)
end
function M.ferror(fmat, ...)
local s = sformat(fmat, ...)
local str = sformat("\27[31m%s\27[0m",s)
print(str)
end
function M.warning( ... )
local n = select("#",...)
local lst = {}
for i=1,n do
local v = select(i, ...)
if type(v) == "table" then
table.insert(lst, Utils.table_str(v))
else
table.insert(lst, tostring(v))
end
end
local s = table.concat(lst," ")
local str = sformat("\27[33m%s\27[0m",s)
print(str)
end
function M.fwarning(fmat, ...)
local s = sformat(fmat, ...)
local str = sformat("\27[33m%s\27[0m",s)
print(str)
end
function M.log_file( ... )
-- body
end
return M |
SWEP.PrintName = "Handcuffs"
SWEP.Author = "TheAsian EggrollMaker"
SWEP.Contact = "theasianeggrollmaker@gmail.com"
SWEP.Base = "weapon_base"
SWEP.UseHands = true
SWEP.Slot = 0
SWEP.SlotPos = 0
SWEP.Spawnable = false
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Ammo = "none"
SWEP.DrawAmmo = false
function SWEP:Initialize( )
self:SetHoldType( "passive" ) -- This holdtype doesn't have arm walking animations.
end
function SWEP:Holster( ) -- Shared due to prediction.
if self:GetOwner( ):GetNWBool( "EPS_Handcuffed" ) then -- No holstering if handcuffed.
return false
end
end
hook.Add( "StartCommand", "EPS_CrouchingJumpingWhileHandcuffed", function( ply, usr_cmd ) -- Shared due to prediction.
if ply:GetNWBool( "EPS_Handcuffed" ) then -- No jumping or crouching while handcuffed.
if usr_cmd:KeyDown( IN_JUMP ) then
usr_cmd:RemoveKey( IN_JUMP )
end
if usr_cmd:KeyDown( IN_DUCK ) then
usr_cmd:RemoveKey( IN_DUCK )
end
end
end )
|
urnsoris_nurse = Creature:new {
-- customName = "urnsoris_nurse",
objectName = "@mob/creature_names:urnsoris_nurse",
-- randomNameType = NAME_GENERIC,
-- randomNameTag = true,
socialGroup = "townsperson",
-- faction = "townsperson",
level = 70,
chanceHit = 0.92,
damageMin = 466,
damageMax = 745,
baseXp = 4197,
baseHAM = 9900,
baseHAMmax = 15400,
armor = 0,
resists = {62,62,62,35,62,62,62,62,-1},
meatType = "meat_insect",
meatAmount = 61,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = KILLER + PACK + HEALER,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/urnsoris_nurse.iff"},
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"strongpoison",""},
{"blindattack",""},
{"intimidationattack",""},
{"stunattack",""},
{"posturedownattack",""},
{"dizzyattack",""},
{"knockdownattack",""},
{"posturedownattack",""},
}
}
CreatureTemplates:addCreatureTemplate(urnsoris_nurse, "urnsoris_nurse")
|
shaders = require("core.shaders")
BaseEntity = require("entities.core.baseentity")
NPCBullet = require("entities.npcbullet")
Goomba = require("entities.core.goomba")
SlimeGirl = class("SlimeGirl", Goomba)
SlimeGirl.spritesheet = SpriteSheet:new("sprites/slimegirlwalk.png", 32, 32)
SlimeGirl.spritesheet2 = SpriteSheet:new("sprites/slimegirlattack.png", 32, 32)
function SlimeGirl:initialize()
Goomba.initialize(self)
-- control variables
self.type = "NPC"
self.collisiongroup = "shared"
self.attackDelay = 0.1
self.reloadDelay = 1
self.clipsize = 5
self.cone = 5 -- in radians
self.health = 100 -- health
self.range = 250 -- range of attack
self.shootFacingPlayer = false -- shoot only facing player
self.canAim = false -- can it aim at the player?
self.stopBeforeShooting = true
self.bulletOffsetX = 5
self.bulletOffsetY = -20
self.blood = {r = 0, g = 255, b = 0}
-- no touchy
self.attackAnim = 0
self.aimangle = math.pi/2
self.aimangleGoal = -math.pi/2
end
function SlimeGirl:getAimAngle()
self.aimangle = math.lerpAngle(self.aimangle, self.aimangleGoal, love.timer.getDelta()*10)
return self.aimangle
end
function SlimeGirl:update(dt)
Goomba.update(self, dt)
if self.nextReload <= 0.2 and self.attackAnim <= 0 then
self.attackAnim = 0.25
end
if self.nextReload > 0 then
self.aimangle = (1 - self.ang) * math.pi/2
end
self.attackAnim = self.attackAnim - dt
end
function SlimeGirl:drawNPC()
self.anim = math.floor(love.timer.getTime() * 10)%10
if self.attackAnim > 0 then
local a = math.floor((1 - (self.attackAnim / 0.25)) * 3) % 3
self.anim = a
self.spritesheet2:draw(self.anim, 0, -16,- 21)
else
self.spritesheet:draw(self.anim, 0, -16, -21)
end
end
function SlimeGirl:draw()
love.graphics.scale(2, 2)
love.graphics.scale(-self.ang, 1)
self:drawNPC()
if self.lastDamaged > 0 then
love.graphics.setStencil(function ()
love.graphics.setShader(shaders.mask_effect)
self:drawNPC()
love.graphics.setShader()
end)
love.graphics.setColor(255, 255, 255, 255)
love.graphics.rectangle("fill", -16, -21, 32, 32)
love.graphics.setStencil()
end
end
return SlimeGirl
|
--- Copyright (c) 2021 by Toadstone Enterprises.
--- ISC-type license, see License.txt for details.
-----------------------------------------------------------------
local util = require("utils")
local node_type = util.node_type
local link_nodes = util.link_nodes
local make_glue = util.make_glue
local make_rule = util.make_rule
local format = require("format")
local text_height = format.text_height
local top_margin = format.top_margin
local left_margin = format.left_margin
local header_height = format.header_height
local header_sep = format.header_sep
local footer_height = format.footer_height
local footer_sep = format.footer_sep
local page_number = format.page_number
local header_tbl = format.header_tbl
local footer_tbl = format.footer_tbl
local push_tbl = format.push_tbl
local pop_tbl = format.pop_tbl
local top_tbl = format.top_tbl
local reader = require("reader")
local push_reader = reader.push_reader
local pop_reader = reader.pop_reader
local main = main or require("main")
local main_loop = main.main_loop
-----------------------------------------------------------------
local par_height = function(par)
-- But can really be used on any list of lines including
-- multiple paragraphs.
local height = 0
while par do
if (node_type(par) == "hlist") then
height = height + par.height + par.depth
elseif (node_type(par) == "glue") then
height = height + par.width
else
-- A penalty has zero height, but what else might we find?
assert((node_type(par) == "penalty"), "Found a: " .. node_type(par))
end
par = par.next
end
return height
end
local build_par = function(head, tail)
-- We have a linked list of nodes, starting with head, and ending
-- with tail. We insert the initial parindent and final penalty
-- and parfillskip.
local tbl = top_tbl()
local n
if State.first_paragraph_of_chapter then
-- This is the first paragraph after a title. Do not indent.
n = make_glue(0, 0)
State.first_paragraph_of_chapter = false
else
--indent.
n = make_glue(0,
tbl.parindent or tex.parindent)
end
link_nodes(n, head)
head = n
local penalty = node.new("penalty")
penalty.penalty = 10000
local parfillskip = make_glue("parfillskip",
0,
tbl.parfillskipstretch or 2^16, 0,
tbl.parfillskipstretch_order or 2, 0)
link_nodes(tail, penalty, parfillskip)
-- hyphenate, kern, and ligature
lang.hyphenate(head)
-- With otf fonts, use this rather than kern and ligature.
nodes.simple_font_handler(head)
-- and make the paragraph.
local par = tex.linebreak(head, tbl)
return par
end
local process_par = function(par)
-- Move par to the appropriate place, based on State.mode
-- If we want to build pages as we go, instead of in batches,
-- we can call the page builder from in here.
local a_par_is_already_there
if (State.mode == "main_text") then
a_par_is_already_there = State.main
elseif (State.mode == "header") then
a_par_is_already_there = State.header
elseif (State.mode == "footer") then
a_par_is_already_there = State.footer
elseif (State.mode == "footnote") then
a_par_is_already_there = State.notes[State.max_notes]
else
assert(false, "Invalid mode seen in process_par")
end
if a_par_is_already_there then
-- at least one paragraph has already been processed, so we link
-- the new par to the old one.
local tail = node.tail(a_par_is_already_there)
if ((node_type(tail) == "hlist") and
(node_type(par) == "hlist")) then
-- add tex.baselineskip
local glue_needed = tex.baselineskip.width - (par.height + tail.depth)
local n = make_glue("baselineskip",
glue_needed)
link_nodes(tail, n, par)
else
-- tail or par is glue?
assert(((node_type(tail) == "glue") or
(node_type(par) == "glue")), "Not glue!")
-- We assume that this glue is enough.
link_nodes(tail, par)
end
else
-- This is the first par, so we just put it where it belongs.
if (State.mode == "main_text") then
State.main = par
elseif (State.mode == "header") then
State.header = par
elseif (State.mode == "footer") then
State.footer = par
elseif (State.mode == "footnote") then
State.notes[State.max_notes] = par
else
assert(false, "Invalid mode seen in process_par")
end
end
end
local pop_line = function()
-- Pop the top line from State.main.
-- This is used by build_page to incrementally build a page.
if State.main then
local line = State.main
State.main = State.main.next
if State.main then
State.main.prev = nil
end
line.next = nil
return line
else
return nil
end
end
local return_line = function(line)
-- Return a (previously popped) line to State.main
line.next = State.main
if State.main then
State.main.prev = line
end
State.main = line
end
-----------------------------------------------------------------
--- Now, on to build_page.
local make_header = function()
-- Make the header
-- The text of our header.
-- When we call main_loop, this will be the reader used.
if State.header_text then
push_reader(State.header_text)
else
push_reader("Header")
end
-- This is the tbl that will be used by main_loop.
push_tbl(header_tbl)
local old_mode = State.mode
State.mode = "header"
-- Now we do the work.
-- When pages and main became mutually dependant, I had to
-- prefix main_loop with the package name. Otherwise:
-- attempt to call a nil value (upvalue 'main_loop')
-- Similarly in make_footer.
-- Why is this?
main.main_loop()
State.mode = old_mode
-- Restore the old reader and tbl.
pop_reader()
pop_tbl()
-- We assume that the header is only one line
local line = State.header
State.header = nil
assert((line.next == nil), "Header is not just one line.")
-- We center the header (vertically) in its header_height box
local needed_height = header_height - line.height
local top_glue = make_glue(0, needed_height / 2)
local bot_glue = make_glue(0, needed_height / 2)
-- Add a rule
local header_rule = make_rule("normal", text_width, tex.sp("1pt"))
header_rule_box = node.hpack(header_rule) -- Must hpack. Why?
-- centered (vertically) in its header_sep height box
local top_sep_glue = make_glue(0, (header_sep - tex.sp("1pt") / 2))
local bot_sep_glue = make_glue(0, (header_sep - tex.sp("1pt") / 2))
-- link it al together
link_nodes(top_glue, line, bot_glue,
top_sep_glue, header_rule_box, bot_sep_glue)
-- and package it up in a vbox
local header = node.vpack(top_glue)
return header
end
local make_footer = function()
-- the text of our footer
push_reader(tostring(page_number))
push_tbl(footer_tbl)
local old_mode = State.mode
State.mode = "footer"
main.main_loop()
State.mode = old_mode
pop_reader()
pop_tbl()
local line = State.footer
State.footer = nil
assert((line.next == nil), "Footer is not just one line.")
local needed_height = footer_height - line.height
local foot_glue = make_glue(0, needed_height)
local sep_glue = make_glue(0, footer_sep)
link_nodes(sep_glue, foot_glue, line)
local footer = node.vpack(foot_glue)
return footer
end
local build_page_step_one = function(line)
-- 1) get the main text from main_text, a line at a time until
-- we either run out of lines or text_height.
local head = line
local tail = line
local note = nil
local notes = nil
local current_height = 0
while ((current_height < text_height) and line) do
if node_type(line) == "hlist" then
-- See if this line has an associated footnote.
local v, _ = node.find_attribute(line.head, 444)
if v then
-- Get the note, and account for its height.
note = State.notes[v]
local extra = par_height(note)
if notes then
-- The separation between notes.
extra = extra + tex.sp("4pt")
else
-- The separation before the first note.
extra = extra + tex.sp("8pt")
end
-- Does the line still fit on the page?
if (current_height + line.height + line.depth + extra) < text_height then
-- Add the line to the end of the text.
link_nodes(tail, line)
tail = line
current_height = (current_height + line.height + line.depth + par_height(note))
if notes then
-- Add the note to the notes.
local n = make_glue(0, tex.sp("4pt"))
link_nodes(node.tail(notes), n, note)
else
-- This is the first note.
notes = note
end
else
-- The line plus the note do not fit on the page.
return_line(line, main_text)
return current_height, head, tail, notes
end
elseif (current_height + line.height + line.depth) < text_height then
-- We have a line without a note, that fits on the page.
link_nodes(tail, line)
tail = line
current_height = (current_height + line.height + line.depth)
else
-- The line does not fit on the page.
return_line(line, main_text)
return current_height, head, tail, notes
end
elseif node_type(line) == "glue" then
-- line is glue, not an hlist.
if (current_height + line.width) < text_height then
-- line fits on the page.
link_nodes(tail, line)
tail = line
current_height = current_height + line.width
else
-- line does not fit on the page.
return_line(line, main_text)
return current_height, head, tail, notes
end
else
-- line is neither an hlist nor glue.
assert((node_type(line) == "penalty"), "Threw away a non-penalty: " .. node_type(line))
end
-- Get the next line, and go to the top of the while loop
line = pop_line()
end
return current_height, head, tail, notes
end
local build_page_step_four = function(text_box, notes, header_box, footer_box)
-- 4) put it all together
local top_margin_glue = make_glue(0, top_margin)
if State.first_page_of_chapter then
-- No header
if notes then
local n = make_glue(0, tex.sp("8pt"))
link_nodes(top_margin_glue, text_box, n, notes)
else
link_nodes(top_margin_glue, text_box)
end
State.first_page_of_chapter = false
else
-- Include a header
if notes then
local n = make_glue(0, tex.sp("8pt"))
link_nodes(top_margin_glue, header_box, text_box, n, notes, footer_box)
else
link_nodes(top_margin_glue, header_box, text_box, footer_box)
end
end
-- 4a) Finish the assembly of the page, and ship it out.
local main_box = node.vpack(top_margin_glue)
local left_margin_glue = make_glue(0, left_margin)
link_nodes(left_margin_glue, main_box)
local page_box = node.hpack(left_margin_glue)
tex.setbox(666, page_box)
tex.shipout(666)
-- Increment the page counters, both tex's and ours.
tex.count[0] = tex.count[0] + 1
page_number = page_number + 1
end
local build_page = function()
-- Build a page by:
-- 1) get the main text from main_text, a line at a time until
-- we either run out of lines or text_height.
-- 2) pad out the text to fill text_height
-- 3) make our header and footer
-- 4) put it all together
local line = pop_line()
local current_height = 0
local head, tail
local notes
-- We are at the top of the page, so we throw away anything
-- that is not an hlist
while node_type(line) ~= "hlist" do
print("Throwing away a: " .. node_type(line))
line = pop_line(main_text)
end
-- 1) get the main text from State.text, a line at a time until
-- we either run out of lines or text_height.
current_height, head, tail, notes = build_page_step_one(line)
-- We have fit all the text that will fit on the page.
-- 2) pad out the text to fill text_height
if (current_height < text_height) then
local needed_height = text_height - current_height
local n = make_glue(0, needed_height)
link_nodes(tail, n)
end
local text_box = node.vpack(head)
-- 3) make our header and footer
local header_box = make_header()
local footer_box = make_footer()
-- 4) put it all together
build_page_step_four(text_box, notes, header_box, footer_box)
end
local build_pages = function()
-- While there is text to fill a page, we build pages.
while State.main do
build_page()
end
end
return {build_par = build_par,
process_par = process_par,
build_pages = build_pages}
|
-- Topological sorting
infile = io.open("2018_advent_7a.txt")
input = infile:read("a")
infile:close()
edges = {}
nodes = {}
qnode = 0
for x, y in string.gmatch(input, "Step (%a) must be finished before step (%a) can begin.") do
edges[#edges+1] = {x, y}
nodes[x] = true
nodes[y] = true
end
for _,_ in pairs(nodes) do qnode = qnode + 1 end
print ("Read ", #edges, " edges", qnode, " nodes")
--[[ Kahn's Algorithm
L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edge
while S is non-empty do
remove a node n from S
add n to tail of L
for each node m with an edge e from n to m do
remove edge e from the graph
if m has no other incoming edges then
insert m into S
if graph has edges then
return error (graph has at least one cycle)
else
return L (a topologically sorted order)
]]
L = {}
S = {} -- initially all nodes
for k,_ in pairs(nodes) do S[k] = true end
-- remove nodes with incoming edges
for e = 1, #edges do S[edges[e][2]] = nil end
-- print ("Initial S")
-- for k,_ in pairs(S) do print(k) end
function nonempty (t)
return next(t, nil)
end
function removesmallest (t)
local smallest = 'ZZZZZ'
for k,_ in pairs(t) do
if k < smallest then smallest = k end
end
t[smallest] = nil
return smallest
end
function findedge (n)
for e = 1, #edges do
if edges[e][1] == n then
return e, edges[e][2]
end
end
return false, false
end
function noin (m)
for e = 1, #edges do
if edges[e][2] == m then
return false
end
end
return true
end
while nonempty(S) do
local n = removesmallest(S)
L[#L+1] = n
while true do
local e, m = findedge(n)
if e then
table.remove(edges, e)
if noin(m) then S[m] = true end
else
break
end
end
end
if #edges > 0 then print ("Error, graph has cycles.") end
print("Part 1: ", table.concat(L))
J = {} -- active jobs
W = { W1 = true, W2 = true, W3 = true, W4 = true, W5 = true } -- available workers
local tick = 0
while nonempty(S) or nonempty(J) do
while nonempty(S) and nonempty(w) do
local n = removesmallest(S)
local w = removesmallest(W) -- needed be smallest, but works
J[#J+1] = {n, w, tick + 60 + string.byte(n, 1) - 0x41}
print ("Start ", n, w, tick, tick + 60 + string.byte(n, 1) - 0x41)
end
if nonempty(J) then
j = removenext(J)
tick = j[3] -- time has passed
W[j[2]] = true -- worker available
local n = j[1] -- completed step
print ("Finish ", n, tick)
while true do
local e, m = findedge(n)
if e then
table.remove(edges, e)
if noin(m) then S[m] = true end
else
break
end
end
end
end
print("Part 2: ", tick)
print ("Done")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.