repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
ihcfan/NautiPlot | hmi-cocos2d-x/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua | 3 | 38022 | local itemTagBasic = 1000
local armaturePerformanceTag = 20000
local frameEventActionTag = 10000
local winSize = cc.Director:getInstance():getWinSize()
local scheduler = cc.Director:getInstance():getScheduler()
local ArmatureTestIndex =
{
TEST_ASYNCHRONOUS_LOADING = 1,
TEST_DIRECT_LOADING = 2,
TEST_COCOSTUDIO_WITH_SKELETON = 3,
TEST_DRAGON_BONES_2_0 = 4,
TEST_PERFORMANCE = 5,
TEST_PERFORMANCE_BATCHNODE = 6,
TEST_CHANGE_ZORDER = 7,
TEST_ANIMATION_EVENT = 8,
TEST_FRAME_EVENT = 9,
TEST_PARTICLE_DISPLAY = 10,
TEST_USE_DIFFERENT_PICTURE = 11,
TEST_ANCHORPOINT = 12,
TEST_ARMATURE_NESTING = 13,
TEST_ARMATURE_NESTING_2 = 14,
}
local armatureSceneIdx = ArmatureTestIndex.TEST_ASYNCHRONOUS_LOADING
local ArmatureTestScene = class("ArmatureTestScene")
ArmatureTestScene.__index = ArmatureTestScene
function ArmatureTestScene.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, ArmatureTestScene)
return target
end
function ArmatureTestScene:runThisTest()
armatureSceneIdx = ArmatureTestIndex.TEST_ASYNCHRONOUS_LOADING
self:addChild(restartArmatureTest())
end
function ArmatureTestScene.create()
local scene = ArmatureTestScene.extend(cc.Scene:create())
local bg = cc.Sprite:create("armature/bg.jpg")
bg:setPosition(VisibleRect:center())
local scaleX = VisibleRect:getVisibleRect().width / bg:getContentSize().width
local scaleY = VisibleRect:getVisibleRect().height / bg:getContentSize().height
bg:setScaleX(scaleX)
bg:setScaleY(scaleY)
scene:addChild(bg)
return scene
end
function ArmatureTestScene.toMainMenuCallback()
ccs.ArmatureDataManager:purgeArmatureSystem()
end
local ArmatureTestLayer = class("ArmatureTestLayer")
ArmatureTestLayer.__index = ArmatureTestLayer
ArmatureTestLayer._backItem = nil
ArmatureTestLayer._restarItem = nil
ArmatureTestLayer._nextItem = nil
function ArmatureTestLayer:onEnter()
end
function ArmatureTestLayer.title(idx)
if ArmatureTestIndex.TEST_ASYNCHRONOUS_LOADING == idx then
return "Test Asynchronous Loading"
elseif ArmatureTestIndex.TEST_DIRECT_LOADING == idx then
return "Test Direct Loading"
elseif ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON == idx then
return "Test Export From CocoStudio With Skeleton Effect"
elseif ArmatureTestIndex.TEST_DRAGON_BONES_2_0 == idx then
return "Test Export From DragonBones version 2.0"
elseif ArmatureTestIndex.TEST_PERFORMANCE == idx then
return "Test Performance"
elseif ArmatureTestIndex.TEST_PERFORMANCE_BATCHNODE == idx then
return "Test Performance of using BatchNode"
elseif ArmatureTestIndex.TEST_CHANGE_ZORDER == idx then
return "Test Change ZOrder Of Different Armature"
elseif ArmatureTestIndex.TEST_ANIMATION_EVENT == idx then
return "Test Armature Animation Event"
elseif ArmatureTestIndex.TEST_FRAME_EVENT == idx then
return "Test Frame Event"
elseif ArmatureTestIndex.TEST_PARTICLE_DISPLAY == idx then
return "Test Particle Display"
elseif ArmatureTestIndex.TEST_USE_DIFFERENT_PICTURE == idx then
return "Test One Armature Use Different Picture"
elseif ArmatureTestIndex.TEST_ANCHORPOINT == idx then
return "Test Set AnchorPoint"
elseif ArmatureTestIndex.TEST_ARMATURE_NESTING == idx then
return "Test Armature Nesting"
elseif ArmatureTestIndex.TEST_ARMATURE_NESTING_2 == idx then
return "Test Armature Nesting 2"
end
end
function ArmatureTestLayer.subTitle(idx)
if ArmatureTestIndex.TEST_ASYNCHRONOUS_LOADING == idx then
return "current percent :"
elseif ArmatureTestIndex.TEST_PERFORMANCE == idx then
return "Current Armature Count : "
elseif ArmatureTestIndex.TEST_PERFORMANCE_BATCHNODE == idx then
return "Current Armature Count : "
elseif ArmatureTestIndex.TEST_PARTICLE_DISPLAY == idx then
return "Touch to change animation"
elseif ArmatureTestIndex.TEST_USE_DIFFERENT_PICTURE == idx then
return "weapon and armature are in different picture"
elseif ArmatureTestIndex.TEST_ARMATURE_NESTING_2 == idx then
return "Move to a mount and press the ChangeMount Button."
else
return ""
end
end
function ArmatureTestLayer.create()
local layer = ArmatureTestLayer.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:onEnter()
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
function ArmatureTestLayer.backCallback()
local newScene = ArmatureTestScene.create()
newScene:addChild(backArmatureTest())
cc.Director:getInstance():replaceScene(newScene)
end
function ArmatureTestLayer.restartCallback()
local newScene = ArmatureTestScene.create()
newScene:addChild(restartArmatureTest())
cc.Director:getInstance():replaceScene(newScene)
end
function ArmatureTestLayer.nextCallback()
local newScene = ArmatureTestScene.create()
newScene:addChild(nextArmatureTest())
cc.Director:getInstance():replaceScene(newScene)
end
function ArmatureTestLayer:createMenu()
local menu = cc.Menu:create()
self._backItem = cc.MenuItemImage:create(s_pPathB1, s_pPathB2)
self._backItem:registerScriptTapHandler(self.backCallback)
menu:addChild(self._backItem,itemTagBasic)
self._restarItem = cc.MenuItemImage:create(s_pPathR1, s_pPathR2)
self._restarItem:registerScriptTapHandler(self.restartCallback)
menu:addChild(self._restarItem,itemTagBasic)
self._nextItem = cc.MenuItemImage:create(s_pPathF1, s_pPathF2)
menu:addChild(self._nextItem,itemTagBasic)
self._nextItem:registerScriptTapHandler(self.nextCallback)
local size = cc.Director:getInstance():getWinSize()
self._backItem:setPosition(cc.p(size.width / 2 - self._restarItem:getContentSize().width * 2, self._restarItem:getContentSize().height / 2))
self._restarItem:setPosition(cc.p(size.width / 2, self._restarItem:getContentSize().height / 2))
self._nextItem:setPosition(cc.p(size.width / 2 + self._restarItem:getContentSize().width * 2, self._restarItem:getContentSize().height / 2))
menu:setPosition(cc.p(0, 0))
self:addChild(menu)
end
function ArmatureTestLayer.toExtensionMenu()
ccs.ArmatureDataManager:destoryInstance()
local scene = CocoStudioTestMain()
if scene ~= nil then
cc.Director:getInstance():replaceScene(scene)
end
end
function ArmatureTestLayer:createToExtensionMenu()
cc.MenuItemFont:setFontName("Arial")
cc.MenuItemFont:setFontSize(24)
local menuItemFont = cc.MenuItemFont:create("Back")
menuItemFont:setPosition(cc.p(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25))
menuItemFont:registerScriptTapHandler(ArmatureTestLayer.toExtensionMenu)
local backMenu = cc.Menu:create()
backMenu:addChild(menuItemFont)
backMenu:setPosition(cc.p(0, 0))
self:addChild(backMenu,10)
end
function ArmatureTestLayer:creatTitleAndSubTitle(idx)
local title = cc.LabelTTF:create(ArmatureTestLayer.title(idx),"Arial",18)
title:setColor(cc.c3b(0,0,0))
self:addChild(title, 1, 10000)
title:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 30))
local subTitle = nil
if "" ~= ArmatureTestLayer.subTitle(idx) then
local subTitle = cc.LabelTTF:create(ArmatureTestLayer.subTitle(idx), "Arial", 18)
subTitle:setColor(cc.c3b(0,0,0))
self:addChild(subTitle, 1, 10001)
subTitle:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 60) )
end
end
local TestAsynchronousLoading = class("TestAsynchronousLoading",ArmatureTestLayer)
TestAsynchronousLoading.__index = TestAsynchronousLoading
function TestAsynchronousLoading.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestAsynchronousLoading)
return target
end
function TestAsynchronousLoading:onEnter()
self._backItem:setEnabled(false)
self._restarItem:setEnabled(false)
self._nextItem:setEnabled(false)
local title = cc.LabelTTF:create(ArmatureTestLayer.title(1),"Arial",18)
title:setColor(cc.c3b(0,0,0))
self:addChild(title, 1, 10000)
title:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 30))
local subTitle = nil
if "" ~= ArmatureTestLayer.subTitle(1) then
local subInfo = ArmatureTestLayer.subTitle(1) .. 0.0
local subTitle = cc.LabelTTF:create(subInfo, "Arial", 18)
subTitle:setColor(cc.c3b(0,0,0))
self:addChild(subTitle, 1, 10001)
subTitle:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 60) )
end
local function dataLoaded(percent)
local label = self:getChildByTag(10001)
if nil ~= label then
local subInfo = ArmatureTestLayer.subTitle(1) .. (percent * 100)
label:setString(subInfo)
end
if percent >= 1 and nil ~= self._backItem and nil ~= self._restarItem and nil ~= self._nextItem then
self._backItem:setEnabled(true)
self._restarItem:setEnabled(true)
self._nextItem:setEnabled(true)
end
end
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/knight.png", "armature/knight.plist", "armature/knight.xml", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/weapon.png", "armature/weapon.plist", "armature/weapon.xml", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/robot.png", "armature/robot.plist", "armature/robot.xml", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/cyborg.png", "armature/cyborg.plist", "armature/cyborg.xml", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/Dragon.png", "armature/Dragon.plist", "armature/Dragon.xml", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/Cowboy.ExportJson", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/hero.ExportJson", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/horse.ExportJson", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/bear.ExportJson", dataLoaded)
ccs.ArmatureDataManager:getInstance():addArmatureFileInfoAsync("armature/HeroAnimation.ExportJson", dataLoaded)
end
function TestAsynchronousLoading.restartCallback()
ccs.ArmatureDataManager:destoryInstance()
local newScene = ArmatureTestScene.create()
newScene:addChild(restartArmatureTest())
cc.Director:getInstance():replaceScene(newScene)
end
function TestAsynchronousLoading.create()
local layer = TestAsynchronousLoading.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:onEnter()
end
return layer
end
local TestDirectLoading = class("TestDirectLoading",ArmatureTestLayer)
TestDirectLoading.__index = TestDirectLoading
function TestDirectLoading.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestDirectLoading)
return target
end
function TestDirectLoading:onEnter()
ccs.ArmatureDataManager:getInstance():removeArmatureFileInfo("armature/bear.ExportJson")
ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("armature/bear.ExportJson")
local armature = ccs.Armature:create("bear")
armature:getAnimation():playByIndex(0)
armature:setPosition(cc.p(VisibleRect:center()))
self:addChild(armature)
end
function TestDirectLoading.create()
local layer = TestDirectLoading.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:onEnter()
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
local TestCSWithSkeleton = class("TestCSWithSkeleton",ArmatureTestLayer)
TestCSWithSkeleton.__index = TestCSWithSkeleton
function TestCSWithSkeleton.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestCSWithSkeleton)
return target
end
function TestCSWithSkeleton:onEnter()
local armature = ccs.Armature:create("Cowboy")
armature:getAnimation():playByIndex(0)
armature:setScale(0.2)
armature:setAnchorPoint(cc.p(0.5, 0.5))
armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2))
self:addChild(armature)
end
function TestCSWithSkeleton.create()
local layer = TestCSWithSkeleton.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:onEnter()
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
local TestDragonBones20 = class("TestDragonBones20",ArmatureTestLayer)
TestDragonBones20.__index = TestDragonBones20
function TestDragonBones20.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestDragonBones20)
return target
end
function TestDragonBones20:onEnter()
local armature = ccs.Armature:create("Dragon")
armature:getAnimation():playByIndex(1)
armature:getAnimation():setSpeedScale(0.4)
armature:setPosition(cc.p(VisibleRect:center().x, VisibleRect:center().y * 0.3))
armature:setScale(0.6)
self:addChild(armature)
end
function TestDragonBones20.create()
local layer = TestDragonBones20.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:onEnter()
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
local TestPerformance = class("TestPerformance",ArmatureTestLayer)
TestPerformance.__index = TestPerformance
TestPerformance._armatureCount = 0
TestPerformance._frames = 0
TestPerformance._times = 0
TestPerformance._lastTimes = 0
TestPerformance._generated = false
function TestPerformance.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestPerformance)
return target
end
function TestPerformance:refreshTitile()
local subTitleInfo = ArmatureTestLayer.subTitle(5) .. self._armatureCount
local label = tolua.cast(self:getChildByTag(10001),"LabelTTF")
label:setString(subTitleInfo)
end
function TestPerformance:addArmatureToParent(armature)
self:addChild(armature, 0, armaturePerformanceTag + self._armatureCount)
end
function TestPerformance:removeArmatureFromParent(tag)
self:removeChildByTag(armaturePerformanceTag + self._armatureCount, true)
end
function TestPerformance:addArmature(num)
for i = 1, num do
self._armatureCount = self._armatureCount + 1
local armature = ccs.Armature:create("Knight_f/Knight")
armature:getAnimation():playByIndex(0)
armature:setPosition(50 + self._armatureCount * 2, 150)
armature:setScale(0.6)
self:addArmatureToParent(armature)
end
self:refreshTitile()
end
function TestPerformance:onEnter()
local function onIncrease(sender)
self:addArmature(20)
end
local function onDecrease(sender)
if self._armatureCount == 0 then
return
end
for i = 1, 20 do
self:removeArmatureFromParent(armaturePerformanceTag + self._armatureCount)
self._armatureCount = self._armatureCount - 1
self:refreshTitile()
end
end
cc.MenuItemFont:setFontSize(65)
local decrease = cc.MenuItemFont:create(" - ")
decrease:setColor(cc.c3b(0,200,20))
decrease:registerScriptTapHandler(onDecrease)
local increase = cc.MenuItemFont:create(" + ")
increase:setColor(cc.c3b(0,200,20))
increase:registerScriptTapHandler(onIncrease)
local menu = cc.Menu:create(decrease, increase )
menu:alignItemsHorizontally()
menu:setPosition(cc.p(VisibleRect:getVisibleRect().width/2, VisibleRect:getVisibleRect().height-100))
self:addChild(menu, 10000)
self._armatureCount = 0
self._frames = 0
self._times = 0
self._lastTimes = 0
self._generated = false
self:addArmature(100)
end
function TestPerformance.create()
local layer = TestPerformance.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
layer:onEnter()
end
return layer
end
local TestPerformanceBatchNode = class("TestPerformanceBatchNode",TestPerformance)
TestPerformanceBatchNode.__index = TestPerformanceBatchNode
TestPerformanceBatchNode._batchNode = nil
function TestPerformanceBatchNode.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestPerformanceBatchNode)
return target
end
function TestPerformanceBatchNode:addArmatureToParent(armature)
self._batchNode:addChild(armature, 0, armaturePerformanceTag + self._armatureCount)
end
function TestPerformanceBatchNode:removeArmatureFromParent(tag)
self._batchNode:removeChildByTag(armaturePerformanceTag + self._armatureCount, true)
end
function TestPerformanceBatchNode:onEnter()
self._batchNode = ccs.BatchNode:create()
self:addChild(self._batchNode)
local function onIncrease(sender)
self:addArmature(20)
end
local function onDecrease(sender)
if self._armatureCount == 0 then
return
end
for i = 1, 20 do
self:removeArmatureFromParent(armaturePerformanceTag + self._armatureCount)
self._armatureCount = self._armatureCount - 1
self:refreshTitile()
end
end
cc.MenuItemFont:setFontSize(65)
local decrease = cc.MenuItemFont:create(" - ")
decrease:setColor(cc.c3b(0,200,20))
decrease:registerScriptTapHandler(onDecrease)
local increase = cc.MenuItemFont:create(" + ")
increase:setColor(cc.c3b(0,200,20))
increase:registerScriptTapHandler(onIncrease)
local menu = cc.Menu:create(decrease, increase )
menu:alignItemsHorizontally()
menu:setPosition(cc.p(VisibleRect:getVisibleRect().width/2, VisibleRect:getVisibleRect().height-100))
self:addChild(menu, 10000)
self._armatureCount = 0
self._frames = 0
self._times = 0
self._lastTimes = 0
self._generated = false
self:addArmature(100)
end
function TestPerformanceBatchNode.create()
local layer = TestPerformanceBatchNode.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
layer:onEnter()
end
return layer
end
local TestChangeZorder = class("TestChangeZorder",ArmatureTestLayer)
TestChangeZorder.__index = TestChangeZorder
TestChangeZorder.currentTag = -1
function TestChangeZorder.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestChangeZorder)
return target
end
function TestChangeZorder:onEnter()
self.currentTag = -1
local armature = ccs.Armature:create("Knight_f/Knight")
armature:getAnimation():playByIndex(0)
armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100 ))
armature:setScale(0.6)
self.currentTag = self.currentTag + 1
self:addChild(armature, self.currentTag, self.currentTag)
armature = ccs.Armature:create("Cowboy")
armature:getAnimation():playByIndex(0)
armature:setScale(0.24)
armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100))
self.currentTag = self.currentTag + 1
self:addChild(armature, self.currentTag, self.currentTag)
armature = ccs.Armature:create("Dragon")
armature:getAnimation():playByIndex(0)
armature:setPosition(cc.p(winSize.width / 2, winSize.height / 2 - 100))
armature:setScale(0.6)
self.currentTag = self.currentTag + 1
self:addChild(armature, self.currentTag, self.currentTag)
local function changeZorder(dt)
local node = self:getChildByTag(self.currentTag)
node:setZOrder(math.random(0,1) * 3)
self.currentTag = (self.currentTag + 1) % 3
end
schedule(self,changeZorder, 1)
end
function TestChangeZorder.create()
local layer = TestChangeZorder.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:onEnter()
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
--UNDO callback
local TestAnimationEvent = class("TestAnimationEvent",ArmatureTestLayer)
TestAnimationEvent.__index = TestAnimationEvent
function TestAnimationEvent.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestAnimationEvent)
return target
end
function TestAnimationEvent:onEnter()
local armature = ccs.Armature:create("Cowboy")
armature:getAnimation():play("Fire")
armature:setScaleX(-0.24)
armature:setScaleY(0.24)
armature:setPosition(cc.p(VisibleRect:left().x + 50, VisibleRect:left().y))
local function callback1()
armature:runAction(cc.ScaleTo:create(0.3, 0.24, 0.24))
armature:getAnimation():play("FireMax", 10)
end
local function callback2()
armature:runAction(cc.ScaleTo:create(0.3, -0.24, 0.24))
armature:getAnimation():play("Fire", 10)
end
local function animationEvent(armatureBack,movementType,movementID)
local id = movementID
if movementType == ccs.MovementEventType.LOOP_COMPLETE then
if id == "Fire" then
local actionToRight = cc.MoveTo:create(2, cc.p(VisibleRect:right().x - 50, VisibleRect:right().y))
armatureBack:stopAllActions()
armatureBack:runAction(cc.Sequence:create(actionToRight,cc.CallFunc:create(callback1)))
armatureBack:getAnimation():play("Walk")
elseif id == "FireMax" then
local actionToLeft = cc.MoveTo:create(2, cc.p(VisibleRect:left().x + 50, VisibleRect:left().y))
armatureBack:stopAllActions()
armatureBack:runAction(cc.Sequence:create(actionToLeft, cc.CallFunc:create(callback2)))
armatureBack:getAnimation():play("Walk")
end
end
end
armature:getAnimation():setMovementEventCallFunc(animationEvent)
self:addChild(armature)
end
function TestAnimationEvent.create()
local layer = TestAnimationEvent.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:onEnter()
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
local TestFrameEvent = class("TestFrameEvent",ArmatureTestLayer)
TestFrameEvent.__index = TestFrameEvent
function TestFrameEvent.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestFrameEvent)
return target
end
function TestFrameEvent:onEnter()
local armature = ccs.Armature:create("HeroAnimation")
armature:getAnimation():play("attack")
armature:getAnimation():setSpeedScale(0.5)
armature:setPosition(cc.p(VisibleRect:center().x - 50, VisibleRect:center().y -100))
local function onFrameEvent( bone,evt,originFrameIndex,currentFrameIndex)
if (not self:getActionByTag(frameEventActionTag)) or (not self:getActionByTag(frameEventActionTag):isDone()) then
self:stopAllActions()
local action = cc.ShatteredTiles3D:create(0.2, cc.size(16,12), 5, false)
action:setTag(frameEventActionTag)
self:runAction(action)
end
end
armature:getAnimation():setFrameEventCallFunc(onFrameEvent)
self:addChild(armature)
local function checkAction(dt)
if self:getNumberOfRunningActions() == 0 and self:getGrid() ~= nil then
self:setGrid(nil)
end
end
self:scheduleUpdateWithPriorityLua(checkAction,0)
local function onNodeEvent(tag)
if "exit" == tag then
self:unscheduleUpdate()
end
end
end
function TestFrameEvent.create()
local layer = TestFrameEvent.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
layer:onEnter()
end
return layer
end
local TestParticleDisplay = class("TestParticleDisplay",ArmatureTestLayer)
TestParticleDisplay.__index = TestParticleDisplay
TestParticleDisplay.animationID = 0
TestParticleDisplay.armature = nil
function TestParticleDisplay.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestParticleDisplay)
return target
end
function TestParticleDisplay:onEnter()
self:setTouchEnabled(true)
self.animationID = 0
self.armature = ccs.Armature:create("robot")
self.armature:getAnimation():playByIndex(0)
self.armature:setPosition(VisibleRect:center())
self.armature:setScale(0.48)
self:addChild(self.armature)
local p1 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist")
local p2 = cc.ParticleSystemQuad:create("Particles/SmallSun.plist")
local bone = ccs.Bone:create("p1")
bone:addDisplay(p1, 0)
bone:changeDisplayByIndex(0, true)
bone:setIgnoreMovementBoneData(true)
bone:setZOrder(100)
bone:setScale(1.2)
self.armature:addBone(bone, "bady-a3")
bone = ccs.Bone:create("p2")
bone:addDisplay(p2, 0)
bone:changeDisplayByIndex(0, true)
bone:setIgnoreMovementBoneData(true)
bone:setZOrder(100)
bone:setScale(1.2)
self.armature:addBone(bone, "bady-a30")
local function onTouchBegan(x, y)
self.animationID = (self.animationID + 1) % self.armature:getAnimation():getMovementCount()
self.armature:getAnimation():playByIndex(self.animationID)
return false
end
local function onTouch(eventType, x, y)
if eventType == "began" then
return onTouchBegan(x,y)
end
end
self:registerScriptTouchHandler(onTouch)
end
function TestParticleDisplay.create()
local layer = TestParticleDisplay.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:onEnter()
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
local TestUseMutiplePicture = class("TestUseMutiplePicture",ArmatureTestLayer)
TestUseMutiplePicture.__index = TestUseMutiplePicture
TestUseMutiplePicture.displayIndex = 0
TestUseMutiplePicture.armature = nil
function TestUseMutiplePicture.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestUseMutiplePicture)
return target
end
function TestUseMutiplePicture:onEnter()
self:setTouchEnabled(true)
self.displayIndex = 1
self.armature = ccs.Armature:create("Knight_f/Knight")
self.armature:getAnimation():playByIndex(0)
self.armature:setPosition(cc.p(VisibleRect:left().x + 70, VisibleRect:left().y))
self.armature:setScale(1.2)
self:addChild(self.armature)
local weapon =
{
"weapon_f-sword.png",
"weapon_f-sword2.png",
"weapon_f-sword3.png",
"weapon_f-sword4.png",
"weapon_f-sword5.png",
"weapon_f-knife.png",
"weapon_f-hammer.png",
}
local i = 1
for i = 1,table.getn(weapon) do
local skin = ccs.Skin:createWithSpriteFrameName(weapon[i])
self.armature:getBone("weapon"):addDisplay(skin, i - 1)
end
local function onTouchBegan(x, y)
self.displayIndex = (self.displayIndex + 1) % (table.getn(weapon) - 1)
self.armature:getBone("weapon"):changeDisplayByIndex(self.displayIndex, true)
return false
end
local function onTouch(eventType, x, y)
if eventType == "began" then
return onTouchBegan(x,y)
end
end
self:registerScriptTouchHandler(onTouch)
end
function TestUseMutiplePicture.create()
local layer = TestUseMutiplePicture.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:onEnter()
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
local TestAnchorPoint = class("TestAnchorPoint",ArmatureTestLayer)
TestAnchorPoint.__index = TestAnchorPoint
function TestAnchorPoint.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestAnchorPoint)
return target
end
function TestAnchorPoint:onEnter()
local i = 1
for i = 1 , 5 do
local armature = ccs.Armature:create("Cowboy")
armature:getAnimation():playByIndex(0)
armature:setPosition(VisibleRect:center())
armature:setScale(0.2)
self:addChild(armature, 0, i - 1)
end
self:getChildByTag(0):setAnchorPoint(cc.p(0,0))
self:getChildByTag(1):setAnchorPoint(cc.p(0,1))
self:getChildByTag(2):setAnchorPoint(cc.p(1,0))
self:getChildByTag(3):setAnchorPoint(cc.p(1,1))
self:getChildByTag(4):setAnchorPoint(cc.p(0.5,0.5))
end
function TestAnchorPoint.create()
local layer = TestAnchorPoint.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:onEnter()
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
local TestArmatureNesting = class("TestArmatureNesting",ArmatureTestLayer)
TestArmatureNesting.__index = TestArmatureNesting
TestArmatureNesting.weaponIndex = 0
TestArmatureNesting.armature = nil
function TestArmatureNesting.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestArmatureNesting)
return target
end
function TestArmatureNesting:onEnter()
self:setTouchEnabled(true)
self.weaponIndex = 0
self.armature = ccs.Armature:create("cyborg")
self.armature:getAnimation():playByIndex(1)
self.armature:setPosition(VisibleRect:center())
self.armature:setScale(1.2)
self.armature:getAnimation():setSpeedScale(0.4)
self:addChild(self.armature)
local function onTouchBegan(x, y)
self.weaponIndex = (self.weaponIndex + 1) % 4
self.armature:getBone("armInside"):getChildArmature():getAnimation():playByIndex(self.weaponIndex)
self.armature:getBone("armOutside"):getChildArmature():getAnimation():playByIndex(self.weaponIndex)
return false
end
local function onTouch(eventType, x, y)
if eventType == "began" then
return onTouchBegan(x,y)
end
end
self:registerScriptTouchHandler(onTouch)
end
function TestArmatureNesting.create()
local layer = TestArmatureNesting.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:onEnter()
layer:creatTitleAndSubTitle(armatureSceneIdx)
end
return layer
end
local Hero = class("Hero")
Hero.__index = Hero
Hero._mount = nil
Hero._layer = nil
function Hero.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, Hero)
return target
end
function Hero:changeMount(armature)
if nil == armature then
--note
self:retain()
self:playByIndex(0)
self._mount:getBone("hero"):removeDisplay(0)
self._mount:stopAllActions()
self:setPosition(self._mount:getPosition())
self._layer:addChild(self)
self:release()
self._mount = armature
else
self._mount = armature
self:retain()
self:removeFromParentAndCleanup(false)
local bone = armature:getBone("hero")
bone:addDisplay(self, 0)
bone:changeDisplayByIndex(0, true)
bone:setIgnoreMovementBoneData(true)
self:setPosition(cc.p(0,0))
self:playByIndex(1)
self:setScale(1)
self:release()
end
end
function Hero:playByIndex(index)
self:getAnimation():playByIndex(index)
if nil ~= self._mount then
self._mount:getAnimation():playByIndex(index)
end
end
function Hero.create(name)
local hero = Hero.extend(ccs.Armature:create(name))
return hero
end
local TestArmatureNesting2 = class("TestArmatureNesting",ArmatureTestLayer)
TestArmatureNesting2.__index = TestArmatureNesting2
TestArmatureNesting2._hero = nil
TestArmatureNesting2._horse = nil
TestArmatureNesting2._horse2 = nil
TestArmatureNesting2._bear = nil
TestArmatureNesting2._touchedMenu = nil
function TestArmatureNesting2.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, TestArmatureNesting2)
return target
end
function TestArmatureNesting2:onEnter()
self:setTouchEnabled(true)
local function onTouchesEnded(tableArray)
local x,y = tableArray[1],tableArray[2]
local armature = self._hero._mount and self._hero._mount or self._hero
if x < armature:getPositionX() then
armature:setScaleX(-1)
else
armature:setScaleX(1)
end
local move = cc.MoveTo:create(2, cc.p(x,y))
armature:stopAllActions()
armature:runAction(cc.Sequence:create(move))
end
local function onTouch(eventType, tableArray)
if eventType == "ended" then
return onTouchesEnded(tableArray)
end
end
self:registerScriptTouchHandler(onTouch,true)
local function changeMountCallback(sender)
self._hero:stopAllActions()
if nil ~= self._hero._mount then
self._hero:changeMount(nil)
else
if cc.pGetDistance(cc.p(self._hero:getPosition()),cc.p(self._horse:getPosition())) < 20 then
self._hero:changeMount(self._horse)
elseif cc.pGetDistance(cc.p(self._hero:getPosition()),cc.p(self._horse2:getPosition())) < 20 then
self._hero:changeMount(self._horse2)
elseif cc.pGetDistance(cc.p(self._hero:getPosition()),cc.p(self._bear:getPosition())) < 30 then
self._hero:changeMount(self._bear)
end
end
end
self._touchedMenu = false
local label = cc.LabelTTF:create("Change Mount", "Arial", 20)
local menuItem = cc.MenuItemLabel:create(label)
menuItem:registerScriptTapHandler(changeMountCallback)
local menu = cc.Menu:create(menuItem)
menu:setPosition(cc.p(0,0))
menuItem:setPosition( cc.p( VisibleRect:right().x - 67, VisibleRect:bottom().y + 50) )
self:addChild(menu, 2)
self._hero = Hero.create("hero")
self._hero._layer = self
self._hero:playByIndex(0)
self._hero:setPosition(cc.p(VisibleRect:left().x + 20, VisibleRect:left().y))
self:addChild(self._hero)
self._horse = self:createMount("horse", VisibleRect:center())
self._horse2 = self:createMount("horse", cc.p(120, 200))
self._horse2:setOpacity(200)
self._bear = self:createMount("bear", cc.p(300,70))
end
function TestArmatureNesting2:createMount(name,pt)
local armature = ccs.Armature:create(name)
armature:getAnimation():playByIndex(0)
armature:setPosition(pt)
self:addChild(armature)
return armature
end
function TestArmatureNesting2.create()
local layer = TestArmatureNesting2.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
layer:createToExtensionMenu()
layer:creatTitleAndSubTitle(armatureSceneIdx)
layer:onEnter()
end
return layer
end
local armatureSceneArr =
{
TestAsynchronousLoading.create,
TestDirectLoading.create,
TestCSWithSkeleton.create,
TestDragonBones20.create,
TestPerformance.create,
TestPerformanceBatchNode.create,
TestChangeZorder.create,
TestAnimationEvent.create,
TestFrameEvent.create,
TestParticleDisplay.create,
TestUseMutiplePicture.create,
TestAnchorPoint.create,
TestArmatureNesting.create,
TestArmatureNesting2.create,
}
function nextArmatureTest()
armatureSceneIdx = armatureSceneIdx + 1
armatureSceneIdx = armatureSceneIdx % table.getn(armatureSceneArr)
if 0 == armatureSceneIdx then
armatureSceneIdx = table.getn(armatureSceneArr)
end
return armatureSceneArr[armatureSceneIdx]()
end
function backArmatureTest()
armatureSceneIdx = armatureSceneIdx - 1
if armatureSceneIdx <= 0 then
armatureSceneIdx = armatureSceneIdx + table.getn(armatureSceneArr)
end
return armatureSceneArr[armatureSceneIdx]()
end
function restartArmatureTest()
return armatureSceneArr[armatureSceneIdx]()
end
local function addFileInfo()
end
function runArmatureTestScene()
local scene = ArmatureTestScene.create()
scene:runThisTest()
cc.Director:getInstance():replaceScene(scene)
end
| gpl-2.0 |
Rob96/GoS | SimpleKarma.lua | 1 | 4923 | class "Karma"
require 'Eternal Prediction'
local function Ready (spell)
return Game.CanUseSpell(spell) == 0
end
local function GetTarget(range)
local target = nil
if Orb == 1 then
target = EOW:GetTarget(range)
elseif Orb == 2 then
target = _G.SDK.TargetSelector:GetTarget(range)
elseif Orb == 3 then
target = GOS:GetTarget(range)
end
return target
end
function Karma:LoadSpells()
Q = {delay = 0.25, range = 950,speed = 1700, width = 50}
Qdata = {speed = Q.speed, delay = Q.delay ,range = Q.range}
Qspell = Prediction:SetSpell(Qdata, TYPE_LINE, true)
end
local intToMode = {
[0] = "",
[1] = "Combo",
[2] = "Harass",
[3] = "Lasthit",
[4] = "Clear"
}
local function GetMode()
if Orb == 1 then
return intToMode[EOW.CurrentMode]
elseif Orb == 2 then
if _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_COMBO] then
return "Combo"
elseif _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_HARASS] then
return "Harass"
elseif _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_LANECLEAR] or _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_JUNGLECLEAR] then
return "Clear"
elseif _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_LASTHIT] then
return "Lasthit"
elseif _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_FLEE] then
return "Flee"
end
else
return GOS.GetMode()
end
end
local function EnableOrb(bool)
if Orb == 1 then
EOW:SetMovements(bool)
EOW:SetAttacks(bool)
elseif Orb == 2 then
_G.SDK.Orbwalker:SetMovement(bool)
_G.SDK.Orbwalker:SetAttack(bool)
else
GOS.BlockMovement = not bool
GOS.BlockAttack = not bool
end
end
function Karma:__init()
if myHero.charName ~= "Karma" then return end
if _G.EOWLoaded then
Orb = 1
elseif _G.SDK and _G.SDK.Orbwalker then
Orb = 2
end
PrintChat("SimpleKarma loaded")
self:LoadMenu()
self:LoadSpells()
Callback.Add('Tick', function() self:Tick() end)
Callback.Add('Draw', function() self:Draw() end)
end
function Karma:LoadMenu()
self.Menu = MenuElement({type = MENU, id = "Karma", name = "SimpleKarma"})
--[[Combo]]
self.Menu:MenuElement({type = MENU, id = "Combo", name = "Combo"})
self.Menu.Combo:MenuElement({id = "Q", name = "Use Q", value = true})
self.Menu.Combo:MenuElement({id = "W", name = "Use W", value = true})
self.Menu.Combo:MenuElement({id = "E", name = "Use E", value = true})
self.Menu.Combo:MenuElement({id = "R", name = "Use R", value = true})
self.Menu.Combo:MenuElement({id = "WHP", name = "Min Hp for RW In %", value = 25, min = 0, max = 100})
--[[Draw]]
self.Menu:MenuElement({type = MENU, id = "Draw", name = "Drawings"})
self.Menu.Draw:MenuElement({id = "W", name = "Draw W Range", value = true})
self.Menu.Draw:MenuElement({id = "Q", name = "Draw Q Range", value = true})
end
function Karma:Combo()
local target = GetTarget(1200)
if target == nil then return end
if self.Menu.Combo.R:Value() and Ready(_R) then
if self.Menu.Combo.W:Value() and Ready(_W) and myHero.pos:DistanceTo(target.pos) < 675 and myHero.health/myHero.maxHealth < self.Menu.Combo.WHP:Value() / 100 then
EnableOrb(false)
Control.CastSpell(HK_R) Control.CastSpell(HK_W, target)
EnableOrb(true)
end
if self.Menu.Combo.Q:Value () and Ready(_Q) and myHero.pos:DistanceTo(target.pos) <= 1200
then
local pred = Qspell:GetPrediction(target,myHero.pos)
if pred == nil then return end
if pred and pred.hitChance >= 0.1 and pred:hCollision() == 0 and pred:mCollision() == 0 then
Control.CastSpell(HK_R) Control.CastSpell(HK_Q, pred.castPos)
end
end
end
if self.Menu.Combo.Q:Value () and Ready(_Q) and myHero.pos:DistanceTo(target.pos) <= 1200
then
local pred = Qspell:GetPrediction(target,myHero.pos)
if pred == nil then return end
if pred and pred.hitChance >= 0.1 and pred:hCollision() == 0 and pred:mCollision() == 0 then
Control.CastSpell(HK_Q, pred.castPos)
end
end
if self.Menu.Combo.W:Value() and Ready(_W) and myHero.pos:DistanceTo(target.pos) < 675 then
EnableOrb(false)
Control.CastSpell(HK_W, target)
EnableOrb(true)
end
if self.Menu.Combo.E:Value() and Ready(_E) and myHero.pos:DistanceTo(target.pos) <= 500 then
EnableOrb(false)
Control.CastSpell(HK_E, myHero)
EnableOrb(true)
end
end
function Karma:Tick()
local Mode = GetMode()
if Mode == "Combo" then
self:Combo()
end
end
function Karma:Draw()
if myHero.dead then return end
if self.Menu.Draw.Q:Value() then
Draw.Circle(myHero.pos, 950, 1, Draw.Color(200, 200, 200, 200))
end
if self.Menu.Draw.W:Value() then
Draw.Circle(myHero.pos, 675, 1, Draw.Color(255, 200, 255, 255))
end
end
function OnLoad()
Karma()
end
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Jugner_Forest/npcs/Bubchu-Bibinchu_WW.lua | 14 | 3339 | -----------------------------------
-- Area: Jugner Forest
-- NPC: Bubchu-Bibinchu, W.W.
-- Type: Outpost Conquest Guards
-- @pos 60.087 -0.602 -11.847 104
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Jugner_Forest/TextIDs");
local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = NORVALLEN;
local csid = 0x7ff7;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
yohanesyuen/mal | lua/step5_tco.lua | 40 | 3109 | #!/usr/bin/env lua
local table = require('table')
local readline = require('readline')
local utils = require('utils')
local types = require('types')
local reader = require('reader')
local printer = require('printer')
local Env = require('env')
local core = require('core')
local List, Vector, HashMap = types.List, types.Vector, types.HashMap
-- read
function READ(str)
return reader.read_str(str)
end
-- eval
function eval_ast(ast, env)
if types._symbol_Q(ast) then
return env:get(ast)
elseif types._list_Q(ast) then
return List:new(utils.map(function(x) return EVAL(x,env) end,ast))
elseif types._vector_Q(ast) then
return Vector:new(utils.map(function(x) return EVAL(x,env) end,ast))
elseif types._hash_map_Q(ast) then
local new_hm = {}
for k,v in pairs(ast) do
new_hm[EVAL(k, env)] = EVAL(v, env)
end
return HashMap:new(new_hm)
else
return ast
end
end
function EVAL(ast, env)
while true do
--print("EVAL: "..printer._pr_str(ast,true))
if not types._list_Q(ast) then return eval_ast(ast, env) end
local a0,a1,a2,a3 = ast[1], ast[2],ast[3],ast[4]
local a0sym = types._symbol_Q(a0) and a0.val or ""
if 'def!' == a0sym then
return env:set(a1, EVAL(a2, env))
elseif 'let*' == a0sym then
local let_env = Env:new(env)
for i = 1,#a1,2 do
let_env:set(a1[i], EVAL(a1[i+1], let_env))
end
env = let_env
ast = a2 -- TCO
elseif 'do' == a0sym then
local el = eval_ast(ast:slice(2,#ast-1), env)
ast = ast[#ast] -- TCO
elseif 'if' == a0sym then
local cond = EVAL(a1, env)
if cond == types.Nil or cond == false then
if a3 then ast = a3 else return types.Nil end -- TCO
else
ast = a2 -- TCO
end
elseif 'fn*' == a0sym then
return types.MalFunc:new(function(...)
return EVAL(a2, Env:new(env, a1, arg))
end, a2, env, a1)
else
local args = eval_ast(ast, env)
local f = table.remove(args, 1)
if types._malfunc_Q(f) then
ast = f.ast
env = Env:new(f.env, f.params, args) -- TCO
else
return f(unpack(args))
end
end
end
end
-- print
function PRINT(exp)
return printer._pr_str(exp, true)
end
-- repl
local repl_env = Env:new()
function rep(str)
return PRINT(EVAL(READ(str),repl_env))
end
-- core.lua: defined using Lua
for k,v in pairs(core.ns) do
repl_env:set(types.Symbol:new(k), v)
end
-- core.mal: defined using mal
rep("(def! not (fn* (a) (if a false true)))")
if #arg > 0 and arg[1] == "--raw" then
readline.raw = true
end
while true do
line = readline.readline("user> ")
if not line then break end
xpcall(function()
print(rep(line))
end, function(exc)
if exc then
if types._malexception_Q(exc) then
exc = printer._pr_str(exc.val, true)
end
print("Error: " .. exc)
print(debug.traceback())
end
end)
end
| mpl-2.0 |
angking0802wu/UniLua | Assets/StreamingAssets/LuaRoot/test/api.lua | 9 | 26940 |
if T==nil then
(Message or print)('\a\n >>> testC not active: skipping API tests <<<\n\a')
return
end
local debug = require "debug"
local pack = table.pack
function tcheck (t1, t2)
assert(t1.n == (t2.n or #t2) + 1)
for i = 2, t1.n do assert(t1[i] == t2[i - 1]) end
end
print('testing C API')
a = T.testC("pushvalue R; return 1")
assert(a == debug.getregistry())
-- absindex
assert(T.testC("settop 10; absindex -1; return 1") == 10)
assert(T.testC("settop 5; absindex -5; return 1") == 1)
assert(T.testC("settop 10; absindex 1; return 1") == 1)
assert(T.testC("settop 10; absindex R; return 1") < -10)
-- testing allignment
a = T.d2s(12458954321123)
assert(string.len(a) == 8) -- sizeof(double)
assert(T.s2d(a) == 12458954321123)
a,b,c = T.testC("pushnum 1; pushnum 2; pushnum 3; return 2")
assert(a == 2 and b == 3 and not c)
f = T.makeCfunc("pushnum 1; pushnum 2; pushnum 3; return 2")
a,b,c = f()
assert(a == 2 and b == 3 and not c)
-- test that all trues are equal
a,b,c = T.testC("pushbool 1; pushbool 2; pushbool 0; return 3")
assert(a == b and a == true and c == false)
a,b,c = T.testC"pushbool 0; pushbool 10; pushnil;\
tobool -3; tobool -3; tobool -3; return 3"
assert(a==false and b==true and c==false)
a,b,c = T.testC("gettop; return 2", 10, 20, 30, 40)
assert(a == 40 and b == 5 and not c)
t = pack(T.testC("settop 5; gettop; return .", 2, 3))
tcheck(t, {n=4,2,3})
t = pack(T.testC("settop 0; settop 15; return 10", 3, 1, 23))
assert(t.n == 10 and t[1] == nil and t[10] == nil)
t = pack(T.testC("remove -2; gettop; return .", 2, 3, 4))
tcheck(t, {n=2,2,4})
t = pack(T.testC("insert -1; gettop; return .", 2, 3))
tcheck(t, {n=2,2,3})
t = pack(T.testC("insert 3; gettop; return .", 2, 3, 4, 5))
tcheck(t, {n=4,2,5,3,4})
t = pack(T.testC("replace 2; gettop; return .", 2, 3, 4, 5))
tcheck(t, {n=3,5,3,4})
t = pack(T.testC("replace -2; gettop; return .", 2, 3, 4, 5))
tcheck(t, {n=3,2,3,5})
t = pack(T.testC("remove 3; gettop; return .", 2, 3, 4, 5))
tcheck(t, {n=3,2,4,5})
t = pack(T.testC("copy 3 4; gettop; return .", 2, 3, 4, 5))
tcheck(t, {n=4,2,3,3,5})
t = pack(T.testC("copy -3 -1; gettop; return .", 2, 3, 4, 5))
tcheck(t, {n=4,2,3,4,3})
t = pack(T.testC("insert 3; pushvalue 3; remove 3; pushvalue 2; remove 2; \
insert 2; pushvalue 1; remove 1; insert 1; \
insert -2; pushvalue -2; remove -3; gettop; return .",
2, 3, 4, 5, 10, 40, 90))
tcheck(t, {n=7,2,3,4,5,10,40,90})
t = pack(T.testC("concat 5; gettop; return .", "alo", 2, 3, "joao", 12))
tcheck(t, {n=1,"alo23joao12"})
-- testing MULTRET
t = pack(T.testC("call 2,-1; gettop; return .",
function (a,b) return 1,2,3,4,a,b end, "alo", "joao"))
tcheck(t, {n=6,1,2,3,4,"alo", "joao"})
do -- test returning more results than fit in the caller stack
local a = {}
for i=1,1000 do a[i] = true end; a[999] = 10
local b = T.testC([[pcall 1 -1; pop 1; tostring -1; return 1]],
table.unpack, a)
assert(b == "10")
end
-- testing globals
_G.a = 14; _G.b = "a31"
local a = {T.testC[[
getglobal a;
getglobal b;
getglobal b;
setglobal a;
gettop;
return .
]]}
assert(a[2] == 14 and a[3] == "a31" and a[4] == nil and _G.a == "a31")
-- testing arith
assert(T.testC("pushnum 10; pushnum 20; arith /; return 1") == 0.5)
assert(T.testC("pushnum 10; pushnum 20; arith -; return 1") == -10)
assert(T.testC("pushnum 10; pushnum -20; arith *; return 1") == -200)
assert(T.testC("pushnum 10; pushnum 3; arith ^; return 1") == 1000)
assert(T.testC("pushnum 10; pushstring 20; arith /; return 1") == 0.5)
assert(T.testC("pushstring 10; pushnum 20; arith -; return 1") == -10)
assert(T.testC("pushstring 10; pushstring -20; arith *; return 1") == -200)
assert(T.testC("pushstring 10; pushstring 3; arith ^; return 1") == 1000)
a,b,c = T.testC([[pushnum 1;
pushstring 10; arith _;
pushstring 5; return 3]])
assert(a == 1 and b == -10 and c == "5")
mt = {__add = function (a,b) return setmetatable({a[1] + b[1]}, mt) end,
__mod = function (a,b) return setmetatable({a[1] % b[1]}, mt) end,
__unm = function (a) return setmetatable({a[1]* 2}, mt) end}
a,b,c = setmetatable({4}, mt),
setmetatable({8}, mt),
setmetatable({-3}, mt)
x,y,z = T.testC("arith +; return 2", 10, a, b)
assert(x == 10 and y[1] == 12 and z == nil)
assert(T.testC("arith %; return 1", a, c)[1] == 4%-3)
assert(T.testC("arith _; arith +; arith %; return 1", b, a, c)[1] ==
8 % (4 + (-3)*2))
-- testing compare
-- EQ = 0; LT = 1; LE = 2
-- testing lessthan and lessequal
assert(T.testC("compare 2 5 1, return 1", 3, 2, 2, 4, 2, 2))
assert(T.testC("compare 2 5 2, return 1", 3, 2, 2, 4, 2, 2))
assert(not T.testC("compare 3 4 1, return 1", 3, 2, 2, 4, 2, 2))
assert(T.testC("compare 3 4 2, return 1", 3, 2, 2, 4, 2, 2))
assert(T.testC("compare 5 2 1, return 1", 4, 2, 2, 3, 2, 2))
assert(not T.testC("compare 2 -3 1, return 1", "4", "2", "2", "3", "2", "2"))
assert(not T.testC("compare -3 2 1, return 1", "3", "2", "2", "4", "2", "2"))
-- non-valid indices produce false
assert(not T.testC("compare 1 4 1, return 1"))
assert(not T.testC("compare 9 1 2, return 1"))
assert(not T.testC("compare 9 9 0, return 1"))
local b = {__lt = function (a,b) return a[1] < b[1] end}
local a1,a3,a4 = setmetatable({1}, b),
setmetatable({3}, b),
setmetatable({4}, b)
assert(T.testC("compare 2 5 1, return 1", a3, 2, 2, a4, 2, 2))
assert(T.testC("compare 2 5 2, return 1", a3, 2, 2, a4, 2, 2))
assert(T.testC("compare 5 -6 1, return 1", a4, 2, 2, a3, 2, 2))
a,b = T.testC("compare 5 -6 1, return 2", a1, 2, 2, a3, 2, 20)
assert(a == 20 and b == false)
a,b = T.testC("compare 5 -6 2, return 2", a1, 2, 2, a3, 2, 20)
assert(a == 20 and b == false)
a,b = T.testC("compare 5 -6 2, return 2", a1, 2, 2, a1, 2, 20)
assert(a == 20 and b == true)
-- testing length
local t = setmetatable({x = 20}, {__len = function (t) return t.x end})
a,b,c = T.testC([[
len 2;
Llen 2;
objsize 2;
return 3
]], t)
assert(a == 20 and b == 20 and c == 0)
t.x = "234"; t[1] = 20
a,b,c = T.testC([[
len 2;
Llen 2;
objsize 2;
return 3
]], t)
assert(a == "234" and b == 234 and c == 1)
t.x = print; t[1] = 20
a,c = T.testC([[
len 2;
objsize 2;
return 2
]], t)
assert(a == print and c == 1)
-- testing __concat
a = setmetatable({x="u"}, {__concat = function (a,b) return a.x..'.'..b.x end})
x,y = T.testC([[
pushnum 5
pushvalue 2;
pushvalue 2;
concat 2;
pushvalue -2;
return 2;
]], a, a)
assert(x == a..a and y == 5)
-- concat with 0 elements
assert(T.testC("concat 0; return 1") == "")
-- concat with 1 element
assert(T.testC("concat 1; return 1", "xuxu") == "xuxu")
-- testing lua_is
function B(x) return x and 1 or 0 end
function count (x, n)
n = n or 2
local prog = [[
isnumber %d;
isstring %d;
isfunction %d;
iscfunction %d;
istable %d;
isuserdata %d;
isnil %d;
isnull %d;
return 8
]]
prog = string.format(prog, n, n, n, n, n, n, n, n)
local a,b,c,d,e,f,g,h = T.testC(prog, x)
return B(a)+B(b)+B(c)+B(d)+B(e)+B(f)+B(g)+(100*B(h))
end
assert(count(3) == 2)
assert(count('alo') == 1)
assert(count('32') == 2)
assert(count({}) == 1)
assert(count(print) == 2)
assert(count(function () end) == 1)
assert(count(nil) == 1)
assert(count(io.stdin) == 1)
assert(count(nil, 15) == 100)
-- testing lua_to...
function to (s, x, n)
n = n or 2
return T.testC(string.format("%s %d; return 1", s, n), x)
end
assert(to("tostring", {}) == nil)
assert(to("tostring", "alo") == "alo")
assert(to("tostring", 12) == "12")
assert(to("tostring", 12, 3) == nil)
assert(to("objsize", {}) == 0)
assert(to("objsize", {1,2,3}) == 3)
assert(to("objsize", "alo\0\0a") == 6)
assert(to("objsize", T.newuserdata(0)) == 0)
assert(to("objsize", T.newuserdata(101)) == 101)
assert(to("objsize", 124) == 0)
assert(to("objsize", true) == 0)
assert(to("tonumber", {}) == 0)
assert(to("tonumber", "12") == 12)
assert(to("tonumber", "s2") == 0)
assert(to("tonumber", 1, 20) == 0)
assert(to("topointer", 10) == 0)
assert(to("topointer", true) == 0)
assert(to("topointer", T.pushuserdata(20)) == 20)
assert(to("topointer", io.read) ~= 0)
assert(to("func2num", 20) == 0)
assert(to("func2num", T.pushuserdata(10)) == 0)
assert(to("func2num", io.read) ~= 0)
a = to("tocfunction", math.deg)
assert(a(3) == math.deg(3) and a == math.deg)
-- testing deep C stack
do
collectgarbage("stop")
local s, msg = pcall(T.testC, "checkstack 1000023 XXXX") -- too deep
assert(not s and string.find(msg, "XXXX"))
s = string.rep("pushnil;checkstack 1 XX;", 1000000)
s, msg = pcall(T.testC, s)
assert(not s and string.find(msg, "XX"))
collectgarbage("restart")
end
local prog = {"checkstack 30000 msg", "newtable"}
for i = 1,12000 do
prog[#prog + 1] = "pushnum " .. i
prog[#prog + 1] = "pushnum " .. i * 10
end
prog[#prog + 1] = "rawgeti R 2" -- get global table in registry
prog[#prog + 1] = "insert " .. -(2*12000 + 2)
for i = 1,12000 do
prog[#prog + 1] = "settable " .. -(2*(12000 - i + 1) + 1)
end
prog[#prog + 1] = "return 2"
prog = table.concat(prog, ";")
local g, t = T.testC(prog)
assert(g == _G)
for i = 1,12000 do assert(t[i] == i*10); t[i] = nil end
assert(next(t) == nil)
prog, g, t = nil
-- testing errors
a = T.testC([[
loadstring 2; pcall 0,1;
pushvalue 3; insert -2; pcall 1, 1;
pcall 0, 0;
return 1
]], "x=150", function (a) assert(a==nil); return 3 end)
assert(type(a) == 'string' and x == 150)
function check3(p, ...)
local arg = {...}
assert(#arg == 3)
assert(string.find(arg[3], p))
end
check3(":1:", T.testC("loadstring 2; gettop; return .", "x="))
check3("cannot read", T.testC("loadfile 2; gettop; return .", "."))
check3("cannot open xxxx", T.testC("loadfile 2; gettop; return .", "xxxx"))
-- test errors in non protected threads
function checkerrnopro (code, msg)
L = coroutine.create(function () end)
local stt, err = pcall(T.testC, code)
assert(not stt and string.find(err, msg))
end
checkerrnopro("pushnum 3; call 0 0", "attempt to call")
function f () f() end
checkerrnopro("getglobal 'f'; call 0 0;", "stack overflow")
-- testing table access
a = {x=0, y=12}
x, y = T.testC("gettable 2; pushvalue 4; gettable 2; return 2",
a, 3, "y", 4, "x")
assert(x == 0 and y == 12)
T.testC("settable -5", a, 3, 4, "x", 15)
assert(a.x == 15)
a[a] = print
x = T.testC("gettable 2; return 1", a) -- table and key are the same object!
assert(x == print)
T.testC("settable 2", a, "x") -- table and key are the same object!
assert(a[a] == "x")
b = setmetatable({p = a}, {})
getmetatable(b).__index = function (t, i) return t.p[i] end
k, x = T.testC("gettable 3, return 2", 4, b, 20, 35, "x")
assert(x == 15 and k == 35)
getmetatable(b).__index = function (t, i) return a[i] end
getmetatable(b).__newindex = function (t, i,v ) a[i] = v end
y = T.testC("insert 2; gettable -5; return 1", 2, 3, 4, "y", b)
assert(y == 12)
k = T.testC("settable -5, return 1", b, 3, 4, "x", 16)
assert(a.x == 16 and k == 4)
a[b] = 'xuxu'
y = T.testC("gettable 2, return 1", b)
assert(y == 'xuxu')
T.testC("settable 2", b, 19)
assert(a[b] == 19)
-- testing next
a = {}
t = pack(T.testC("next; gettop; return .", a, nil))
tcheck(t, {n=1,a})
a = {a=3}
t = pack(T.testC("next; gettop; return .", a, nil))
tcheck(t, {n=3,a,'a',3})
t = pack(T.testC("next; pop 1; next; gettop; return .", a, nil))
tcheck(t, {n=1,a})
-- testing upvalues
do
local A = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]]
t, b, c = A([[pushvalue U0; pushvalue U1; pushvalue U2; return 3]])
assert(b == 10 and c == 20 and type(t) == 'table')
a, b = A([[tostring U3; tonumber U4; return 2]])
assert(a == nil and b == 0)
A([[pushnum 100; pushnum 200; replace U2; replace U1]])
b, c = A([[pushvalue U1; pushvalue U2; return 2]])
assert(b == 100 and c == 200)
A([[replace U2; replace U1]], {x=1}, {x=2})
b, c = A([[pushvalue U1; pushvalue U2; return 2]])
assert(b.x == 1 and c.x == 2)
T.checkmemory()
end
-- testing absent upvalues from C-function pointers
assert(T.testC[[isnull U1; return 1]] == true)
assert(T.testC[[isnull U100; return 1]] == true)
assert(T.testC[[pushvalue U1; return 1]] == nil)
local f = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]]
assert(T.upvalue(f, 1) == 10 and
T.upvalue(f, 2) == 20 and
T.upvalue(f, 3) == nil)
T.upvalue(f, 2, "xuxu")
assert(T.upvalue(f, 2) == "xuxu")
-- large closures
do
local A = "checkstack 300 msg;" ..
string.rep("pushnum 10;", 255) ..
"pushcclosure 255; return 1"
A = T.testC(A)
for i=1,255 do
assert(A(("pushvalue U%d; return 1"):format(i)) == 10)
end
assert(A("isnull U256; return 1"))
assert(not A("isnil U256; return 1"))
end
-- bug in 5.1.2
assert(not pcall(debug.setuservalue, 3, {}))
assert(not pcall(debug.setuservalue, nil, {}))
assert(not pcall(debug.setuservalue, T.pushuserdata(1), {}))
local b = T.newuserdata(0)
local a = {}
assert(debug.getuservalue(b) == nil)
assert(debug.setuservalue(b, a))
assert(debug.getuservalue(b) == a)
assert(debug.setuservalue(b, nil))
assert(debug.getuservalue(b) == nil)
assert(debug.getuservalue(4) == nil)
-- testing locks (refs)
-- reuse of references
local i = T.ref{}
T.unref(i)
assert(T.ref{} == i)
Arr = {}
Lim = 100
for i=1,Lim do -- lock many objects
Arr[i] = T.ref({})
end
assert(T.ref(nil) == -1 and T.getref(-1) == nil)
T.unref(-1); T.unref(-1)
for i=1,Lim do -- unlock all them
T.unref(Arr[i])
end
function printlocks ()
local f = T.makeCfunc("gettable R; return 1")
local n = f("n")
print("n", n)
for i=0,n do
print(i, f(i))
end
end
for i=1,Lim do -- lock many objects
Arr[i] = T.ref({})
end
for i=1,Lim,2 do -- unlock half of them
T.unref(Arr[i])
end
assert(type(T.getref(Arr[2])) == 'table')
assert(T.getref(-1) == nil)
a = T.ref({})
collectgarbage()
assert(type(T.getref(a)) == 'table')
-- colect in cl the `val' of all collected userdata
tt = {}
cl = {n=0}
A = nil; B = nil
local F
F = function (x)
local udval = T.udataval(x)
table.insert(cl, udval)
local d = T.newuserdata(100) -- cria lixo
d = nil
assert(debug.getmetatable(x).__gc == F)
assert(load("table.insert({}, {})"))() -- cria mais lixo
collectgarbage() -- forca coleta de lixo durante coleta!
assert(debug.getmetatable(x).__gc == F) -- coleta anterior nao melou isso?
local dummy = {} -- cria lixo durante coleta
if A ~= nil then
assert(type(A) == "userdata")
assert(T.udataval(A) == B)
debug.getmetatable(A) -- just acess it
end
A = x -- ressucita userdata
B = udval
return 1,2,3
end
tt.__gc = F
-- test whether udate collection frees memory in the right time
do
collectgarbage();
collectgarbage();
local x = collectgarbage("count");
local a = T.newuserdata(5001)
assert(T.testC("objsize 2; return 1", a) == 5001)
assert(collectgarbage("count") >= x+4)
a = nil
collectgarbage();
assert(collectgarbage("count") <= x+1)
-- udata without finalizer
x = collectgarbage("count")
collectgarbage("stop")
for i=1,1000 do T.newuserdata(0) end
assert(collectgarbage("count") > x+10)
collectgarbage()
assert(collectgarbage("count") <= x+1)
-- udata with finalizer
x = collectgarbage("count")
collectgarbage()
collectgarbage("stop")
a = {__gc = function () end}
for i=1,1000 do debug.setmetatable(T.newuserdata(0), a) end
assert(collectgarbage("count") >= x+10)
collectgarbage() -- this collection only calls TM, without freeing memory
assert(collectgarbage("count") >= x+10)
collectgarbage() -- now frees memory
assert(collectgarbage("count") <= x+1)
collectgarbage("restart")
end
collectgarbage("stop")
-- create 3 userdatas with tag `tt'
a = T.newuserdata(0); debug.setmetatable(a, tt); na = T.udataval(a)
b = T.newuserdata(0); debug.setmetatable(b, tt); nb = T.udataval(b)
c = T.newuserdata(0); debug.setmetatable(c, tt); nc = T.udataval(c)
-- create userdata without meta table
x = T.newuserdata(4)
y = T.newuserdata(0)
assert(not pcall(io.input, a))
assert(not pcall(io.input, x))
assert(debug.getmetatable(x) == nil and debug.getmetatable(y) == nil)
d=T.ref(a);
e=T.ref(b);
f=T.ref(c);
t = {T.getref(d), T.getref(e), T.getref(f)}
assert(t[1] == a and t[2] == b and t[3] == c)
t=nil; a=nil; c=nil;
T.unref(e); T.unref(f)
collectgarbage()
-- check that unref objects have been collected
assert(#cl == 1 and cl[1] == nc)
x = T.getref(d)
assert(type(x) == 'userdata' and debug.getmetatable(x) == tt)
x =nil
tt.b = b -- create cycle
tt=nil -- frees tt for GC
A = nil
b = nil
T.unref(d);
n5 = T.newuserdata(0)
debug.setmetatable(n5, {__gc=F})
n5 = T.udataval(n5)
collectgarbage()
assert(#cl == 4)
-- check order of collection
assert(cl[2] == n5 and cl[3] == nb and cl[4] == na)
collectgarbage"restart"
a, na = {}, {}
for i=30,1,-1 do
a[i] = T.newuserdata(0)
debug.setmetatable(a[i], {__gc=F})
na[i] = T.udataval(a[i])
end
cl = {}
a = nil; collectgarbage()
assert(#cl == 30)
for i=1,30 do assert(cl[i] == na[i]) end
na = nil
for i=2,Lim,2 do -- unlock the other half
T.unref(Arr[i])
end
x = T.newuserdata(41); debug.setmetatable(x, {__gc=F})
assert(T.testC("objsize 2; return 1", x) == 41)
cl = {}
a = {[x] = 1}
x = T.udataval(x)
collectgarbage()
-- old `x' cannot be collected (`a' still uses it)
assert(#cl == 0)
for n in pairs(a) do a[n] = nil end
collectgarbage()
assert(#cl == 1 and cl[1] == x) -- old `x' must be collected
-- testing lua_equal
assert(T.testC("compare 2 4 0; return 1", print, 1, print, 20))
assert(T.testC("compare 3 2 0; return 1", 'alo', "alo"))
assert(T.testC("compare 2 3 0; return 1", nil, nil))
assert(not T.testC("compare 2 3 0; return 1", {}, {}))
assert(not T.testC("compare 2 3 0; return 1"))
assert(not T.testC("compare 2 3 0; return 1", 3))
-- testing lua_equal with fallbacks
do
local map = {}
local t = {__eq = function (a,b) return map[a] == map[b] end}
local function f(x)
local u = T.newuserdata(0)
debug.setmetatable(u, t)
map[u] = x
return u
end
assert(f(10) == f(10))
assert(f(10) ~= f(11))
assert(T.testC("compare 2 3 0; return 1", f(10), f(10)))
assert(not T.testC("compare 2 3 0; return 1", f(10), f(20)))
t.__eq = nil
assert(f(10) ~= f(10))
end
print'+'
-- testing changing hooks during hooks
_G.t = {}
T.sethook([[
# set a line hook after 3 count hooks
sethook 4 0 '
getglobal t;
pushvalue -3; append -2
pushvalue -2; append -2
']], "c", 3)
local a = 1 -- counting
a = 1 -- counting
a = 1 -- count hook (set line hook)
a = 1 -- line hook
a = 1 -- line hook
debug.sethook()
t = _G.t
assert(t[1] == "line")
line = t[2]
assert(t[3] == "line" and t[4] == line + 1)
assert(t[5] == "line" and t[6] == line + 2)
assert(t[7] == nil)
-------------------------------------------------------------------------
do -- testing errors during GC
local a = {}
for i=1,20 do
a[i] = T.newuserdata(i) -- creates several udata
end
for i=1,20,2 do -- mark half of them to raise errors during GC
debug.setmetatable(a[i], {__gc = function (x) error("error inside gc") end})
end
for i=2,20,2 do -- mark the other half to count and to create more garbage
debug.setmetatable(a[i], {__gc = function (x) load("A=A+1")() end})
end
_G.A = 0
a = 0
while 1 do
local stat, msg = pcall(collectgarbage)
if stat then
break -- stop when no more errors
else
a = a + 1
assert(string.find(msg, "__gc"))
end
end
assert(a == 10) -- number of errors
assert(A == 10) -- number of normal collections
end
-------------------------------------------------------------------------
-- test for userdata vals
do
local a = {}; local lim = 30
for i=0,lim do a[i] = T.pushuserdata(i) end
for i=0,lim do assert(T.udataval(a[i]) == i) end
for i=0,lim do assert(T.pushuserdata(i) == a[i]) end
for i=0,lim do a[a[i]] = i end
for i=0,lim do a[T.pushuserdata(i)] = i end
assert(type(tostring(a[1])) == "string")
end
-------------------------------------------------------------------------
-- testing multiple states
T.closestate(T.newstate());
L1 = T.newstate()
assert(L1)
assert(T.doremote(L1, "X='a'; return 'a'") == 'a')
assert(#pack(T.doremote(L1, "function f () return 'alo', 3 end; f()")) == 0)
a, b = T.doremote(L1, "return f()")
assert(a == 'alo' and b == '3')
T.doremote(L1, "_ERRORMESSAGE = nil")
-- error: `sin' is not defined
a, _, b = T.doremote(L1, "return sin(1)")
assert(a == nil and b == 2) -- 2 == run-time error
-- error: syntax error
a, b, c = T.doremote(L1, "return a+")
assert(a == nil and c == 3 and type(b) == "string") -- 3 == syntax error
T.loadlib(L1)
a, b, c = T.doremote(L1, [[
string = require'string'
a = require'_G'; assert(a == _G and require("_G") == a)
io = require'io'; assert(type(io.read) == "function")
assert(require("io") == io)
a = require'table'; assert(type(a.insert) == "function")
a = require'debug'; assert(type(a.getlocal) == "function")
a = require'math'; assert(type(a.sin) == "function")
return string.sub('okinama', 1, 2)
]])
assert(a == "ok")
T.closestate(L1);
L1 = T.newstate()
T.loadlib(L1)
T.doremote(L1, "a = {}")
T.testC(L1, [[getglobal "a"; pushstring "x"; pushnum 1;
settable -3]])
assert(T.doremote(L1, "return a.x") == "1")
T.closestate(L1)
L1 = nil
print('+')
-------------------------------------------------------------------------
-- testing memory limits
-------------------------------------------------------------------------
assert(not pcall(T.newuserdata, 2^32-4))
collectgarbage()
T.totalmem(T.totalmem()+5000) -- set low memory limit (+5k)
assert(not pcall(load"local a={}; for i=1,100000 do a[i]=i end"))
T.totalmem(1000000000) -- restore high limit
-- test memory errors; increase memory limit in small steps, so that
-- we get memory errors in different parts of a given task, up to there
-- is enough memory to complete the task without errors
function testamem (s, f)
collectgarbage(); collectgarbage()
local M = T.totalmem()
local oldM = M
local a,b = nil
while 1 do
M = M+7 -- increase memory limit in small steps
T.totalmem(M)
a, b = pcall(f)
T.totalmem(1000000000) -- restore high limit
if a and b then break end -- stop when no more errors
collectgarbage()
if not a and not -- `real' error?
(string.find(b, "memory") or string.find(b, "overflow")) then
error(b, 0) -- propagate it
end
end
print("\nlimit for " .. s .. ": " .. M-oldM)
return b
end
-- testing memory errors when creating a new state
b = testamem("state creation", T.newstate)
T.closestate(b); -- close new state
-- testing threads
-- get main thread from registry (at index LUA_RIDX_MAINTHREAD == 1)
mt = T.testC("rawgeti R 1; return 1")
assert(type(mt) == "thread" and coroutine.running() == mt)
function expand (n,s)
if n==0 then return "" end
local e = string.rep("=", n)
return string.format("T.doonnewstack([%s[ %s;\n collectgarbage(); %s]%s])\n",
e, s, expand(n-1,s), e)
end
G=0; collectgarbage(); a =collectgarbage("count")
load(expand(20,"G=G+1"))()
assert(G==20); collectgarbage(); -- assert(gcinfo() <= a+1)
testamem("thread creation", function ()
return T.doonnewstack("x=1") == 0 -- try to create thread
end)
-- testing memory x compiler
testamem("loadstring", function ()
return load("x=1") -- try to do load a string
end)
local testprog = [[
local function foo () return end
local t = {"x"}
a = "aaa"
for i = 1, #t do a=a..t[i] end
return true
]]
-- testing memory x dofile
_G.a = nil
local t =os.tmpname()
local f = assert(io.open(t, "w"))
f:write(testprog)
f:close()
testamem("dofile", function ()
local a = loadfile(t)
return a and a()
end)
assert(os.remove(t))
assert(_G.a == "aaax")
-- other generic tests
testamem("string creation", function ()
local a, b = string.gsub("alo alo", "(a)", function (x) return x..'b' end)
return (a == 'ablo ablo')
end)
testamem("dump/undump", function ()
local a = load(testprog)
local b = a and string.dump(a)
a = b and load(b)
return a and a()
end)
local t = os.tmpname()
testamem("file creation", function ()
local f = assert(io.open(t, 'w'))
assert (not io.open"nomenaoexistente")
io.close(f);
return not loadfile'nomenaoexistente'
end)
assert(os.remove(t))
testamem("table creation", function ()
local a, lim = {}, 10
for i=1,lim do a[i] = i; a[i..'a'] = {} end
return (type(a[lim..'a']) == 'table' and a[lim] == lim)
end)
testamem("constructors", function ()
local a = {10, 20, 30, 40, 50; a=1, b=2, c=3, d=4, e=5}
return (type(a) == 'table' and a.e == 5)
end)
local a = 1
close = nil
testamem("closure creation", function ()
function close (b,c)
return function (x) return a+b+c+x end
end
return (close(2,3)(4) == 10)
end)
testamem("coroutines", function ()
local a = coroutine.wrap(function ()
coroutine.yield(string.rep("a", 10))
return {}
end)
assert(string.len(a()) == 10)
return a()
end)
print'+'
-- testing some auxlib functions
local function gsub (a, b, c)
a, b = T.testC("gsub 2 3 4; gettop; return 2", a, b, c)
assert(b == 5)
return a
end
assert(gsub("alo.alo.uhuh.", ".", "//") == "alo//alo//uhuh//")
assert(gsub("alo.alo.uhuh.", "alo", "//") == "//.//.uhuh.")
assert(gsub("", "alo", "//") == "")
assert(gsub("...", ".", "/.") == "/././.")
assert(gsub("...", "...", "") == "")
-- testing luaL_newmetatable
local mt_xuxu, res, top = T.testC("newmetatable xuxu; gettop; return 3")
assert(type(mt_xuxu) == "table" and res and top == 3)
local d, res, top = T.testC("newmetatable xuxu; gettop; return 3")
assert(mt_xuxu == d and not res and top == 3)
d, res, top = T.testC("newmetatable xuxu1; gettop; return 3")
assert(mt_xuxu ~= d and res and top == 3)
x = T.newuserdata(0);
y = T.newuserdata(0);
T.testC("pushstring xuxu; gettable R; setmetatable 2", x)
assert(getmetatable(x) == mt_xuxu)
-- testing luaL_testudata
-- correct metatable
local res1, res2, top = T.testC([[testudata -1 xuxu
testudata 2 xuxu
gettop
return 3]], x)
assert(res1 and res2 and top == 4)
-- wrong metatable
res1, res2, top = T.testC([[testudata -1 xuxu1
testudata 2 xuxu1
gettop
return 3]], x)
assert(not res1 and not res2 and top == 4)
-- non-existent type
res1, res2, top = T.testC([[testudata -1 xuxu2
testudata 2 xuxu2
gettop
return 3]], x)
assert(not res1 and not res2 and top == 4)
-- userdata has no metatable
res1, res2, top = T.testC([[testudata -1 xuxu
testudata 2 xuxu
gettop
return 3]], y)
assert(not res1 and not res2 and top == 4)
-- erase metatables
do
local r = debug.getregistry()
assert(r.xuxu == mt_xuxu and r.xuxu1 == d)
r.xuxu = nil; r.xuxu1 = nil
end
print'OK'
| mit |
GabrielGanne/vpp-flowtable | src/vpp-api/lua/examples/example-classifier.lua | 2 | 1372 | --[[
/*
* Copyright (c) 2016 Cisco and/or its affiliates.
* 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 vpp = require "vpp-lapi"
local bit = require("bit")
root_dir = "/home/ubuntu/vpp"
pneum_path = root_dir .. "/build-root/install-vpp_lite_debug-native/vpp-api/lib64/libpneum.so"
vpp:init({ pneum_path = pneum_path })
vpp:json_api(root_dir .. "/build-root/install-vpp_lite_debug-native/vpp/vpp-api/vpe.api.json")
vpp:connect("aytest")
-- api calls
print("Calling API to add a new classifier table")
reply = vpp:api_call("classify_add_del_table", {
context = 43,
memory_size = bit.lshift(2, 20),
client_index = 42,
is_add = 1,
nbuckets = 32,
skip_n_vectors = 0,
match_n_vectors = 1,
mask = "\255\255\255\255\255\255\255\255" .. "\255\255\255\255\255\255\255\255"
})
print(vpp.dump(reply))
print("---")
vpp:disconnect()
| apache-2.0 |
Scavenge/darkstar | scripts/zones/Kazham/npcs/Magriffon.lua | 29 | 4342 | -----------------------------------
-- Area: Kazham
-- NPC: Magriffon
-- Involved in Quest: Gullible's Travels, Even More Gullible's Travels,
-- Location: (I-7)
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(OUTLANDS, GULLIBLES_TRAVELS) == QUEST_ACCEPTED) then
if (trade:getGil() >= player:getVar("MAGRIFFON_GIL_REQUEST")) then
player:startEvent(0x0092);
end
elseif (player:getQuestStatus(OUTLANDS, EVEN_MORE_GULLIBLES_TRAVELS) == QUEST_ACCEPTED and player:getVar("EVEN_MORE_GULLIBLES_PROGRESS") == 0) then
if (trade:getGil() >= 35000) then
player:startEvent(0x0096, 0, 256);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local gulliblesTravelsStatus = player:getQuestStatus(OUTLANDS, GULLIBLES_TRAVELS);
local evenmoreTravelsStatus = player:getQuestStatus(OUTLANDS, EVEN_MORE_GULLIBLES_TRAVELS);
if (gulliblesTravelsStatus == QUEST_ACCEPTED) then
local magriffonGilRequest = player:getVar("MAGRIFFON_GIL_REQUEST");
player:startEvent(0x0091, 0, magriffonGilRequest);
elseif (gulliblesTravelsStatus == QUEST_AVAILABLE and player:getFameLevel(KAZHAM) >= 6) then
local gil = math.random(10, 30) * 1000;
player:setVar("MAGRIFFON_GIL_REQUEST", gil);
player:startEvent(0x0090, 0, gil);
elseif (evenmoreTravelsStatus == QUEST_ACCEPTED and player:getVar("EVEN_MORE_GULLIBLES_PROGRESS") == 0) then
player:startEvent(0x0095, 0, 256, 0, 0, 0, 35000);
elseif (evenmoreTravelsStatus == QUEST_ACCEPTED and player:getVar("EVEN_MORE_GULLIBLES_PROGRESS") == 1) then
player:startEvent(0x0097);
elseif (evenmoreTravelsStatus == QUEST_ACCEPTED and player:getVar("EVEN_MORE_GULLIBLES_PROGRESS") == 2) then
player:startEvent(0x0098, 0, 1144, 256);
elseif (gulliblesTravelsStatus == QUEST_COMPLETED) then
if (evenmoreTravelsStatus == QUEST_AVAILABLE and player:getFameLevel(KAZHAM) >= 7 and player:needToZone() == false) then
player:startEvent(0x0094, 0, 256, 0, 0, 35000);
else
player:startEvent(0x0093);
end
else
player:startEvent(0x008F);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x0090 and option == 1) then -- Gullible's Travels: First CS
player:addQuest(OUTLANDS, GULLIBLES_TRAVELS);
elseif (csid == 0x0092) then -- Gullible's Travels: Final CS
player:confirmTrade();
player:delGil(player:getVar("MAGRIFFON_GIL_REQUEST"));
player:setVar("MAGRIFFON_GIL_REQUEST", 0);
player:addFame(KAZHAM, 30);
player:setTitle(285); -- Global Variable not working for this quest
player:completeQuest(OUTLANDS, GULLIBLES_TRAVELS);
player:needToZone(true);
elseif (csid == 0x0094 and option == 1) then -- Even More Guillible's Travels First CS
player:addQuest(OUTLANDS, EVEN_MORE_GULLIBLES_TRAVELS);
elseif (csid == 0x0096) then -- Even More Guillible's Travels Second CS
player:confirmTrade();
player:delGil(35000);
player:setVar("EVEN_MORE_GULLIBLES_PROGRESS", 1);
player:setTitle(286);
player:addKeyItem(256);
player:messageSpecial(KEYITEM_OBTAINED,TREASURE_MAP);
elseif (csid == 0x0098) then
player:setVar("EVEN_MORE_GULLIBLES_PROGRESS", 0);
player:addFame(KAZHAM, 30);
player:completeQuest(OUTLANDS, EVEN_MORE_GULLIBLES_TRAVELS);
end
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Northern_San_dOria/npcs/Achantere_TK.lua | 13 | 5601 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Achatere, T.K.
-- X Grant Signet
-- X Recharge Emperor Band, Empress Band, or Chariot Band
-- X Accepts traded Crystals to fill up the Rank bar to open new Missions.
-- X Sells items in exchange for Conquest Points
-- X Start Supply Run Missions and offers a list of already-delivered supplies.
-- Start an Expeditionary Force by giving an E.F. region insignia to you.
-------------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/globals/common");
require("scripts/zones/Northern_San_dOria/TextIDs");
local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, JEUNO
local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border
local size = #SandInv;
local inventory = SandInv;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then
player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies."
local region = player:getVar("supplyQuest_region");
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region));
player:setVar("supplyQuest_started",0);
player:setVar("supplyQuest_region",0);
player:setVar("supplyQuest_fresh",0);
else
local Menu1 = getArg1(guardnation,player);
local Menu2 = getExForceAvailable(guardnation,player);
local Menu3 = conquestRanking();
local Menu4 = getSupplyAvailable(guardnation,player);
local Menu5 = player:getNationTeleport(guardnation);
local Menu6 = getArg6(player);
local Menu7 = player:getCP();
local Menu8 = getRewardExForce(guardnation,player);
player:startEvent(0x7ffa,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1;
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end;
player:updateEvent(2,CPVerify,inventory[Item + 2]);
break;
end;
end;
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break;
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
if (player:getNation() == guardnation) then
itemCP = inventory[Item + 1];
else
if (inventory[Item + 1] <= 8000) then
itemCP = inventory[Item + 1] * 2;
else
itemCP = inventory[Item + 1] + 8000;
end;
end;
if (player:hasItem(inventory[Item + 2]) == false) then
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
break;
end;
end;
elseif (option >= 65541 and option <= 65565) then -- player chose supply quest.
local region = option - 65541;
player:addKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region));
player:setVar("supplyQuest_started",vanaDay());
player:setVar("supplyQuest_region",region);
player:setVar("supplyQuest_fresh",getConquestTally());
end;
end; | gpl-3.0 |
Scavenge/darkstar | scripts/globals/items/sacred_sword.lua | 42 | 1451 | -----------------------------------------
-- ID: 17682
-- Sacred Sword
-- Additional effect: Light damage
-- Enchantment: "Enlight"
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(7,21);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0);
dmg = adjustForTarget(target,dmg,ELE_LIGHT);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_LIGHT_DAMAGE,message,dmg;
end
end;
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
return 0;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
local effect = EFFECT_ENLIGHT;
doEnspell(target,target,nil,effect);
end; | gpl-3.0 |
Scavenge/darkstar | scripts/zones/Apollyon/mobs/Jidra.lua | 22 | 2411 | -----------------------------------
-- Area: Apollyon SW
-- NPC: Jidra
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local mobID = mob:getID();
-- print(mobID);
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
if (mobID ==16932882) then
SpawnMob(16932889):updateEnmity(target);
elseif (mobID ==16932883) then
SpawnMob(16932890):updateEnmity(target);
elseif (mobID ==16932884) then
SpawnMob(16932891):updateEnmity(target);
elseif (mobID ==16932885) then
SpawnMob(16932892):updateEnmity(target);
elseif (mobID ==16932886) then
SpawnMob(16932893):updateEnmity(target);
elseif (mobID ==16932887) then
SpawnMob(16932894):updateEnmity(target);
elseif (mobID ==16932888) then
SpawnMob(16932895):updateEnmity(target);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local mobID = mob:getID();
-- print(mobID);
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
if (
IsMobDead(16932882)==true and
IsMobDead(16932883)==true and
IsMobDead(16932884)==true and
IsMobDead(16932885)==true and
IsMobDead(16932886)==true and
IsMobDead(16932887)==true and
IsMobDead(16932888)==true
) then
-- time
GetNPCByID(16932864+70):setPos(mobX+3,mobY,mobZ);
GetNPCByID(16932864+70):setStatus(STATUS_NORMAL);
-- recover
GetNPCByID(16932864+71):setPos(mobX+4,mobY,mobZ+4);
GetNPCByID(16932864+71):setStatus(STATUS_NORMAL);
-- item
GetNPCByID(16932864+72):setPos(mobX,mobY,mobZ-3);
GetNPCByID(16932864+72):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
Scavenge/darkstar | scripts/globals/items/plate_of_mushroom_risotto.lua | 12 | 1523 | -----------------------------------------
-- ID: 4434
-- Item: Plate of Mushroom Risotto
-- Food Effect: 3 Hr, All Races
-----------------------------------------
-- MP 30
-- Strength -1
-- Vitality 3
-- Mind 3
-- MP Recovered while healing 2
-- Enmity -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4434);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 30);
target:addMod(MOD_STR, -1);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_MND, 3);
target:addMod(MOD_MPHEAL, 2);
target:addMod(MOD_ENMITY, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 30);
target:delMod(MOD_STR, -1);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_MND, 3);
target:delMod(MOD_MPHEAL, 2);
target:delMod(MOD_ENMITY, -4);
end;
| gpl-3.0 |
Zero-K-Experiments/Zero-K-Experiments | units/fakeunit.lua | 3 | 1876 | unitDef = {
unitname = [[fakeunit]],
name = [[Fake radar signal]],
description = [[Created by scrambling devices.]],
acceleration = 0,
activateWhenBuilt = false,
brakeRate = 0,
buildCostEnergy = 0.45,
buildCostMetal = 0.45,
builder = false,
buildPic = [[levelterra.png]],
buildTime = 0.45,
canAttack = false,
canGuard = false,
canMove = false,
canPatrol = false,
canstop = [[0]],
category = [[SINK]],
customparams = {
completely_hidden = 1,
},
footprintX = 1,
footprintZ = 1,
iconType = [[none]],
idleAutoHeal = 10,
idleTime = 300,
kamikazeDistance = 64,
levelGround = false,
maxDamage = 100000,
maxSlope = 255,
maxVelocity = 0,
maxWaterDepth = 0,
noAutoFire = false,
noChaseCategory = [[FIXEDWING LAND SINK TURRET SHIP SATELLITE SWIM GUNSHIP FLOAT SUB HOVER]],
objectName = [[debris1x1b.s3o]],
onoffable = false,
script = [[nullscript.lua]],
seismicSignature = 16,
selfDestructCountdown = 0,
sightDistance = 0.2,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = 0,
yardMap = [[o]],
}
return lowerkeys({ fakeunit = unitDef })
| gpl-2.0 |
Scavenge/darkstar | scripts/zones/Davoi/npcs/!.lua | 14 | 2651 | -----------------------------------
-- Area: Davoi
-- NPC: !
-- Involved in Mission: The Davoi Report
-- @pos 164 0.1 -21 149
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/keyitems");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CurrentMission = player:getCurrentMission(SANDORIA)
if (CurrentMission == THE_DAVOI_REPORT and player:getVar("MissionStatus") == 1) then
player:setVar("MissionStatus",2);
player:addKeyItem(LOST_DOCUMENT);
player:messageSpecial(KEYITEM_OBTAINED,LOST_DOCUMENT);
elseif (CurrentMission == INFILTRATE_DAVOI and player:getVar("MissionStatus") >= 6 and player:getVar("MissionStatus") <= 9) then
local X = npc:getXPos();
local Z = npc:getZPos();
if (X >= 292 and X <= 296 and Z >= -30 and Z <= -26 and player:hasKeyItem(EAST_BLOCK_CODE) == false) then
player:setVar("MissionStatus",player:getVar("MissionStatus") + 1);
player:addKeyItem(EAST_BLOCK_CODE);
player:messageSpecial(KEYITEM_OBTAINED,EAST_BLOCK_CODE);
elseif (X >= 333 and X <= 337 and Z >= -138 and Z <= -134 and player:hasKeyItem(SOUTH_BLOCK_CODE) == false) then
player:setVar("MissionStatus",player:getVar("MissionStatus") + 1);
player:addKeyItem(SOUTH_BLOCK_CODE);
player:messageSpecial(KEYITEM_OBTAINED,SOUTH_BLOCK_CODE);
elseif (X >= 161 and X <= 165 and Z >= -20 and Z <= -16 and player:hasKeyItem(NORTH_BLOCK_CODE) == false) then
player:setVar("MissionStatus",player:getVar("MissionStatus") + 1);
player:addKeyItem(NORTH_BLOCK_CODE);
player:messageSpecial(KEYITEM_OBTAINED,NORTH_BLOCK_CODE);
else
player:messageSpecial(YOU_SEE_NOTHING);
end
else
player:messageSpecial(YOU_SEE_NOTHING);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
Scavenge/darkstar | scripts/globals/items/piece_of_akamochi_+1.lua | 12 | 2722 | -----------------------------------------
-- ID: 6261
-- Item: akamochi+1
-- Food Effect: 60 Min, All Races
-----------------------------------------
-- HP + 30 (Pet & Master)
-- Vitality + 4 (Pet & Master)
-- Attack + 17% Cap: 54 (Pet & Master) Pet Cap: 81
-- Accuracy + 11% Cap: 54 (Pet & Master) Pet Cap: 81
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD)) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,6261);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 30)
target:addMod(MOD_VIT, 4)
target:addMod(MOD_FOOD_ACCP, 11)
target:addMod(MOD_FOOD_ACC_CAP, 54)
target:addMod(MOD_FOOD_RACCP, 11)
target:addMod(MOD_FOOD_RACC_CAP, 54)
target:addMod(MOD_FOOD_ATTP, 17)
target:addMod(MOD_FOOD_ATT_CAP, 54)
target:addMod(MOD_FOOD_RATTP, 17)
target:addMod(MOD_FOOD_RATT_CAP, 54)
target:addPetMod(MOD_HP, 30)
target:addPetMod(MOD_VIT, 4)
target:addPetMod(MOD_FOOD_ACCP, 11)
target:addPetMod(MOD_FOOD_ACC_CAP, 81)
target:addPetMod(MOD_FOOD_RACCP, 11)
target:addPetMod(MOD_FOOD_RACC_CAP, 81)
target:addPetMod(MOD_FOOD_ATTP, 17)
target:addPetMod(MOD_FOOD_ATT_CAP, 82)
target:addPetMod(MOD_FOOD_RATTP, 17)
target:addPetMod(MOD_FOOD_RATT_CAP, 82)
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 30)
target:delMod(MOD_VIT, 4)
target:delMod(MOD_FOOD_ACCP, 11)
target:delMod(MOD_FOOD_ACC_CAP, 54)
target:delMod(MOD_FOOD_RACCP, 11)
target:delMod(MOD_FOOD_RACC_CAP, 54)
target:delMod(MOD_FOOD_ATTP, 17)
target:delMod(MOD_FOOD_ATT_CAP, 54)
target:delMod(MOD_FOOD_RATTP, 17)
target:delMod(MOD_FOOD_RATT_CAP, 54)
target:delPetMod(MOD_HP, 30)
target:delPetMod(MOD_VIT, 4)
target:delPetMod(MOD_FOOD_ACCP, 11)
target:delPetMod(MOD_FOOD_ACC_CAP, 81)
target:delPetMod(MOD_FOOD_RACCP, 11)
target:delPetMod(MOD_FOOD_RACC_CAP, 81)
target:delPetMod(MOD_FOOD_ATTP, 17)
target:delPetMod(MOD_FOOD_ATT_CAP, 82)
target:delPetMod(MOD_FOOD_RATTP, 17)
target:delPetMod(MOD_FOOD_RATT_CAP, 82)
end;
| gpl-3.0 |
Tele-Fox/self | plugins/ctrl.lua | 3 | 1602 | local function is_channel_disabled( receiver )
if not _config.disabled_channels then
return false
end
if _config.disabled_channels[receiver] == nil then
return false
end
return _config.disabled_channels[receiver]
end
local function enable_channel(receiver, to_id)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
if _config.disabled_channels[receiver] == nil then
return lang_text(to_id, 'botOn')..''
end
_config.disabled_channels[receiver] = false
save_config()
return lang_text(to_id, 'botOn')..''
end
local function disable_channel(receiver, to_id)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return lang_text(to_id, 'botOff')..' '
end
local function pre_process(msg)
local receiver = get_receiver(msg)
-- If sender is sudo then re-enable the channel
if is_sudo(msg) then
if msg.text == "#bot on" then
enable_channel(receiver, msg.to.id)
end
end
if is_channel_disabled(receiver) then
msg.text = ""
end
return msg
end
local function run(msg, matches)
if permissions(msg.from.id, msg.to.id, "bot") then
local receiver = get_receiver(msg)
-- Enable a channel
if matches[1] == 'on' then
return enable_channel(receiver, msg.to.id)
end
-- Disable a channel
if matches[1] == 'off' then
return disable_channel(receiver, msg.to.id)
end
else
return '🚫 '..lang_text(msg.to.id, 'require_sudo')
end
end
return {
patterns = {
"^#bot? (on)",
"^#bot? (off)" },
run = run,
pre_process = pre_process
}
| gpl-2.0 |
Kyklas/luci-proto-hso | applications/luci-transmission/luasrc/model/cbi/transmission.lua | 75 | 13259 | --[[
LuCI - Lua Configuration Interface - Transmission support
Copyright 2012 Gabor Varga <vargagab@gmail.com>
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
$Id$
]]--
require("luci.sys")
require("luci.util")
require("luci.model.ipkg")
local uci = require "luci.model.uci".cursor()
local trport = uci:get_first("transmission", "transmission", "rpc_port") or 9091
local running = (luci.sys.call("pidof transmission-daemon > /dev/null") == 0)
local webinstalled = luci.model.ipkg.installed("transmission-web")
local button = ""
if running and webinstalled then
button = " <input type=\"button\" value=\" " .. translate("Open Web Interface") .. " \" onclick=\"window.open('http://'+window.location.hostname+':" .. trport .. "')\"/>"
end
m = Map("transmission", "Transmission", translate("Transmission daemon is a simple bittorrent client, here you can configure the settings.") .. button)
s=m:section(TypedSection, "transmission", translate("Global settings"))
s.addremove=false
s.anonymous=true
enable=s:option(Flag, "enabled", translate("Enabled"))
enable.rmempty=false
config_dir=s:option(Value, "config_dir", translate("Config file directory"))
user=s:option(ListValue, "user", translate("Run daemon as user"))
local p_user
for _, p_user in luci.util.vspairs(luci.util.split(luci.sys.exec("cat /etc/passwd | cut -f 1 -d :"))) do
user:value(p_user)
end
cache_size_mb=s:option(Value, "cache_size_mb", translate("Cache size in MB"))
bandwidth=m:section(TypedSection, "transmission", translate("Bandwidth settings"))
bandwidth.anonymous=true
alt_speed_enabled=bandwidth:option(Flag, "alt_speed_enabled", translate("Alternative speed enabled"))
alt_speed_enabled.enabled="true"
alt_speed_enabled.disabled="false"
alt_speed_down=bandwidth:option(Value, "alt_speed_down", translate("Alternative download speed"), "KB/s")
alt_speed_down:depends("alt_speed_enabled", "true")
alt_speed_up=bandwidth:option(Value, "alt_speed_up", translate("Alternative upload speed"), "KB/s")
alt_speed_up:depends("alt_speed_enabled", "true")
speed_limit_down_enabled=bandwidth:option(Flag, "speed_limit_down_enabled", translate("Speed limit down enabled"))
speed_limit_down_enabled.enabled="true"
speed_limit_down_enabled.disabled="false"
speed_limit_down=bandwidth:option(Value, "speed_limit_down", translate("Speed limit down"), "KB/s")
speed_limit_down:depends("speed_limit_down_enabled", "true")
speed_limit_up_enabled=bandwidth:option(Flag, "speed_limit_up_enabled", translate("Speed limit up enabled"))
speed_limit_up_enabled.enabled="true"
speed_limit_up_enabled.disabled="false"
speed_limit_up=bandwidth:option(Value, "speed_limit_up", translate("Speed limit up"), "KB/s")
speed_limit_up:depends("speed_limit_up_enabled", "true")
upload_slots_per_torrent=bandwidth:option(Value, "upload_slots_per_torrent", translate("Upload slots per torrent"))
blocklists=m:section(TypedSection, "transmission", translate("Blocklists"))
blocklists.anonymous=true
blocklist_enabled=blocklists:option(Flag, "blocklist_enabled", translate("Block list enabled"))
blocklist_enabled.enabled="true"
blocklist_enabled.disabled="false"
blocklist_url=blocklists:option(Value, "blocklist_url", translate("Blocklist URL"))
blocklist_url:depends("blocklist_enabled", "true")
fileslocations=m:section(TypedSection, "transmission", translate("Files and Locations"))
fileslocations.anonymous=true
download_dir=fileslocations:option(Value, "download_dir", translate("Download directory"))
incomplete_dir_enabled=fileslocations:option(Flag, "incomplete_dir_enabled", translate("Incomplete directory enabled"))
incomplete_dir_enabled.enabled="true"
incomplete_dir_enabled.disabled="false"
incomplete_dir=fileslocations:option(Value, "incomplete_dir", translate("Incomplete directory"))
incomplete_dir:depends("incomplete_dir_enabled", "true")
preallocation=fileslocations:option(ListValue, "preallocation", translate("preallocation"))
preallocation:value("0", translate("Off"))
preallocation:value("1", translate("Fast"))
preallocation:value("2", translate("Full"))
prefetch_enabled=fileslocations:option(Flag, "prefetch_enabled", translate("Prefetch enabled"))
rename_partial_files=fileslocations:option(Flag, "rename_partial_files", translate("Rename partial files"))
rename_partial_files.enableid="true"
rename_partial_files.disabled="false"
start_added_torrents=fileslocations:option(Flag, "start_added_torrents", translate("Automatically start added torrents"))
start_added_torrents.enabled="true"
start_added_torrents.disabled="false"
trash_original_torrent_files=fileslocations:option(Flag, "trash_original_torrent_files", translate("Trash original torrent files"))
trash_original_torrent_files.enabled="true"
trash_original_torrent_files.disabled="false"
umask=fileslocations:option(Value, "umask", "umask")
watch_dir_enabled=fileslocations:option(Flag, "watch_dir_enabled", translate("Enable watch directory"))
watch_dir_enabled.enabled="true"
watch_dir_enabled.disabled="false"
watch_dir=fileslocations:option(Value, "watch_dir", translate("Watch directory"))
watch_dir:depends("watch_dir_enabled", "true")
misc=m:section(TypedSection, "transmission", translate("Miscellaneous"))
misc.anonymous=true
dht_enabled=misc:option(Flag, "dht_enabled", translate("DHT enabled"))
dht_enabled.enabled="true"
dht_enabled.disabled="false"
encryption=misc:option(ListValue, "encryption", translate("Encryption"))
encryption:value("0", translate("Off"))
encryption:value("1", translate("Preferred"))
encryption:value("2", translate("Forced"))
lazy_bitfield_enabled=misc:option(Flag, "lazy_bitfield_enabled", translate("Lazy bitfield enabled"))
lazy_bitfield_enabled.enabled="true"
lazy_bitfield_enabled.disabled="false"
lpd_enabled=misc:option(Flag, "lpd_enabled", translate("LPD enabled"))
lpd_enabled.enabled="true"
lpd_enabled.disabled="false"
message_level=misc:option(ListValue, "message_level", translate("Message level"))
message_level:value("0", translate("None"))
message_level:value("1", translate("Error"))
message_level:value("2", translate("Info"))
message_level:value("3", translate("Debug"))
pex_enabled=misc:option(Flag, "pex_enabled", translate("PEX enabled"))
pex_enabled.enabled="true"
pex_enabled.disabled="false"
script_torrent_done_enabled=misc:option(Flag, "script_torrent_done_enabled", translate("Script torrent done enabled"))
script_torrent_done_enabled.enabled="true"
script_torrent_done_enabled.disabled="false"
script_torrent_done_filename=misc:option(Value, "script_torrent_done_filename", translate("Script torrent done filename"))
script_torrent_done_filename:depends("script_torrent_done_enabled", "true")
idle_seeding_limit_enabled=misc:option(Flag, "idle_seeding_limit_enabled", translate("Idle seeding limit enabled"))
idle_seeding_limit_enabled.enabled="true"
idle_seeding_limit_enabled.disabled="false"
idle_seeding_limit=misc:option(Value, "idle_seeding_limit", translate("Idle seeding limit"))
idle_seeding_limit:depends("idle_seeding_limit_enabled", "true")
utp_enabled=misc:option(Flag, "utp_enabled", translate("uTP enabled"))
utp_enabled.enabled="true"
utp_enabled.disabled="false"
peers=m:section(TypedSection, "transmission", translate("Peer settings"))
peers.anonymous=true
bind_address_ipv4=peers:option(Value, "bind_address_ipv4", translate("Binding address IPv4"))
bind_address_ipv4.default="0.0.0.0"
bind_address_ipv6=peers:option(Value, "bind_address_ipv6", translate("Binding address IPv6"))
bind_address_ipv6.default="::"
peer_congestion_algorithm=peers:option(Value, "peer_congestion_algorithm", translate("Peer congestion algorithm"))
peer_limit_global=peers:option(Value, "peer_limit_global", translate("Global peer limit"))
peer_limit_per_torrent=peers:option(Value, "peer_limit_per_torrent", translate("Peer limit per torrent"))
peer_socket_tos=peers:option(Value, "peer_socket_tos", translate("Peer socket tos"))
peerport=m:section(TypedSection, "transmission", translate("Peer Port settings"))
peerport.anonymous=true
peer_port=peerport:option(Value, "peer_port", translate("Peer port"))
peer_port_random_on_start=peerport:option(Flag, "peer_port_random_on_start", translate("Peer port random on start"))
peer_port_random_on_start.enabled="true"
peer_port_random_on_start.disabled="false"
peer_port_random_high=peerport:option(Value, "peer_port_random_high", translate("Peer port random high"))
peer_port_random_high:depends("peer_port_random_on_start", "true")
peer_port_random_low=peerport:option(Value, "peer_port_random_low", translate("Peer port random low"))
peer_port_random_low:depends("peer_port_random_on_start", "true")
port_forwarding_enabled=peerport:option(Flag, "port_forwarding_enabled", translate("Port forwarding enabled"))
port_forwarding_enabled.enabled="true"
port_forwarding_enabled.disabled="false"
rpc=m:section(TypedSection, "transmission", translate("RPC settings"))
rpc.anonymous=true
rpc_enabled=rpc:option(Flag, "rpc_enabled", translate("RPC enabled"))
rpc_enabled.enabled="true"
rpc_enabled.disabled="false"
rpc_port=rpc:option(Value, "rpc_port", translate("RPC port"))
rpc_port:depends("rpc_enabled", "true")
rpc_bind_address=rpc:option(Value, "rpc_bind_address", translate("RPC bind address"))
rpc_bind_address:depends("rpc_enabled", "true")
rpc_url=rpc:option(Value, "rpc_url", translate("RPC URL"))
rpc_url:depends("rpc_enabled", "true")
rpc_whitelist_enabled=rpc:option(Flag, "rpc_whitelist_enabled", translate("RPC whitelist enabled"))
rpc_whitelist_enabled.enabled="true"
rpc_whitelist_enabled.disabled="false"
rpc_whitelist_enabled:depends("rpc_enabled", "true")
rpc_whitelist=rpc:option(Value, "rpc_whitelist", translate("RPC whitelist"))
rpc_whitelist:depends("rpc_whitelist_enabled", "true")
rpc_authentication_required=rpc:option(Flag, "rpc_authentication_required", translate("RPC authentication required"))
rpc_authentication_required.enabled="true"
rpc_authentication_required.disabled="false"
rpc_authentication_required:depends("rpc_enabled", "true")
rpc_username=rpc:option(Value, "rpc_username", translate("RPC username"))
rpc_username:depends("rpc_authentication_required", "true")
rpc_password=rpc:option(Value, "rpc_password", translate("RPC password"))
rpc_password:depends("rpc_authentication_required", "true")
rpc_password.password = true
scheduling=m:section(TypedSection, "transmission", translate("Scheduling"))
scheduling.anonymous=true
alt_speed_time_enabled=scheduling:option(Flag, "alt_speed_time_enabled", translate("Alternative speed timing enabled"))
alt_speed_time_enabled.enabled="true"
alt_speed_time_enabled.disabled="false"
alt_speed_time_enabled.default="false"
alt_speed_time_enabled:depends("alt_speed_enabled", "true")
alt_speed_time_day=scheduling:option(Value, "alt_speed_time_day", translate("Alternative speed time day"), translate("Number/bitfield. Start with 0, then for each day you want the scheduler enabled, add a value. For Sunday - 1, Monday - 2, Tuesday - 4, Wednesday - 8, Thursday - 16, Friday - 32, Saturday - 64"))
alt_speed_time_day:depends("alt_speed_time_enabled", "true")
alt_speed_time_begin=scheduling:option(Value, "alt_speed_time_begin", translate("Alternative speed time begin"), translate("in minutes from midnight"))
alt_speed_time_begin:depends("alt_speed_time_enabled", "true")
alt_speed_time_end=scheduling:option(Value, "alt_speed_time_end", translate("Alternative speed time end"), translate("in minutes from midnight"))
alt_speed_time_end:depends("alt_speed_time_enabled", "true")
ratio_limit_enabled=scheduling:option(Flag, "ratio_limit_enabled", translate("Ratio limit enabled"))
ratio_limit_enabled.enabled="true"
ratio_limit_enabled.disabled="false"
ratio_limit=scheduling:option(Value, "ratio_limit", translate("Ratio limit"))
ratio_limit:depends("ratio_limit_enabled", "true")
queueing=m:section(TypedSection, "transmission", translate("Queueing"))
queueing.anonymous=true
download_queue_enabled=queueing:option(Flag, "download_queue_enabled", translate("Download queue enabled"))
download_queue_enabled.enabled="true"
download_queue_enabled.disabled="false"
download_queue_size=queueing:option(Value, "download_queue_size", translate("Download queue size"))
download_queue_size:depends("download_queue_enabled", "true")
queue_stalled_enabled=queueing:option(Flag, "queue_stalled_enabled", translate("Queue stalled enabled"))
queue_stalled_enabled.enabled="true"
queue_stalled_enabled.disabled="false"
queue_stalled_minutes=queueing:option(Value, "queue_stalled_minutes", translate("Queue stalled minutes"))
queue_stalled_minutes:depends("queue_stalled_enabled", "true")
seed_queue_enabled=queueing:option(Flag, "seed_queue_enabled", translate("Seed queue enabled"))
seed_queue_enabled.enabled="true"
seed_queue_enabled.disabled="false"
seed_queue_size=queueing:option(Value, "seed_queue_size", translate("Seed queue size"))
seed_queue_size:depends("seed_queue_enabled", "true")
scrape_paused_torrents_enabled=queueing:option(Flag, "scrape_paused_torrents_enabled", translate("Scrape paused torrents enabled"))
scrape_paused_torrents_enabled.enabled="true"
scrape_paused_torrents_enabled.disabled="false"
return m
| apache-2.0 |
yriveiro/nvim-files | lua/plugins/configs/telescope.lua | 1 | 2531 | -- Borrowed from https://github.com/thanhvule0310/dotfiles/blob/main/nvim/lua/plugins/configs/telescope.lua
local ok, telescope = pcall(require, 'telescope')
if not ok then
local u = require 'utils'
u.nok_plugin 'telescope'
return
end
telescope.setup {
picker = {
hidden = false,
},
defaults = {
vimgrep_arguments = {
'rg',
'--color=never',
'--no-heading',
'--with-filename',
'--line-number',
'--column',
'--no-ignore',
'--smart-case',
'--hidden',
},
prompt_prefix = ' ',
selection_caret = ' ',
entry_prefix = ' ',
initial_mode = 'insert',
selection_strategy = 'reset',
sorting_strategy = 'ascending',
layout_strategy = 'horizontal',
layout_config = {
horizontal = {
prompt_position = 'top',
preview_width = 0.55,
results_width = 0.8,
},
vertical = {
mirror = false,
},
width = 0.80,
height = 0.85,
preview_cutoff = 120,
},
file_sorter = require('telescope.sorters').get_fuzzy_file,
file_ignore_patterns = { 'node_modules', '.git/', 'dist/' },
generic_sorter = require('telescope.sorters').get_generic_fuzzy_sorter,
path_display = { 'absolute' },
winblend = 0,
border = {},
borderchars = { '' },
color_devicons = true,
use_less = true,
set_env = { ['COLORTERM'] = 'truecolor' },
file_previewer = require('telescope.previewers').vim_buffer_cat.new,
grep_previewer = require('telescope.previewers').vim_buffer_vimgrep.new,
qflist_previewer = require('telescope.previewers').vim_buffer_qflist.new,
buffer_previewer_maker = require('telescope.previewers').buffer_previewer_maker,
mappings = {
i = {
['<Tab>'] = 'move_selection_next',
['<S-Tab>'] = 'move_selection_previous',
},
n = {
['<Tab>'] = 'move_selection_next',
['<S-Tab>'] = 'move_selection_previous',
},
},
},
extensions = {
fzf = {
fuzzy = true,
override_generic_sorter = true,
override_file_sorter = true,
case_mode = 'smart_case',
},
file_browse = {
hijack_netrw = true,
depth = false,
},
project = {
display_type = 'full',
},
},
}
telescope.load_extension 'dap'
telescope.load_extension 'fzf'
telescope.load_extension 'notify'
telescope.load_extension 'project'
telescope.load_extension 'file_browser'
telescope.load_extension 'git_worktree'
telescope.load_extension 'ui-select'
| mit |
Scavenge/darkstar | scripts/zones/Bastok_Markets/npcs/Foss.lua | 17 | 2236 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Foss
-- Starts & Finishes Repeatable Quest: Buckets of Gold
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
BucketsOfGold = player:getQuestStatus(BASTOK,BUCKETS_OF_GOLD);
if (BucketsOfGold >= QUEST_ACCEPTED) then
count = trade:getItemCount();
RustyBucket = trade:hasItemQty(90,5);
if (RustyBucket == true and count == 5) then
player:startEvent(0x0110);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
BucketsOfGold = player:getQuestStatus(BASTOK,BUCKETS_OF_GOLD);
if (BucketsOfGold == QUEST_AVAILABLE) then
player:startEvent(0x010f);
else
player:startEvent(0x010e);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x010f and option == 0) then
player:addQuest(BASTOK,BUCKETS_OF_GOLD);
elseif (csid == 0x0110) then
BucketsOfGold = player:getQuestStatus(BASTOK,BUCKETS_OF_GOLD);
if (BucketsOfGold == QUEST_ACCEPTED) then
player:completeQuest(BASTOK,BUCKETS_OF_GOLD);
player:addFame(BASTOK,75);
player:addTitle(BUCKET_FISHER);
else
player:addFame(BASTOK,8);
end
player:tradeComplete();
player:addGil(GIL_RATE*300);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*300);
end
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Pihra_Rhebenslo.lua | 16 | 4335 | -----------------------------------
-- Area: Windurst Waters [S]
-- NPC: Pihra_Rhebenslo
-- Armor Storage NPC
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/armorstorage");
require("scripts/zones/Windurst_Waters_[S]/TextIDs");
Deposit = 0x01ba;
Withdrawl = 0x01bb;
ArraySize = #StorageArray;
G1 = 0;
G2 = 0;
G3 = 0;
G4 = 0;
G5 = 0;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
for SetId = 1,ArraySize,11 do
TradeCount = trade:getItemCount();
T1 = trade:hasItemQty(StorageArray[SetId + 5],1);
if (T1 == true) then
if (player:hasKeyItem(StorageArray[SetId + 10]) == false) then
if (TradeCount == StorageArray[SetId + 3]) then
T2 = trade:hasItemQty(StorageArray[SetId + 4],1);
T3 = trade:hasItemQty(StorageArray[SetId + 6],1);
T4 = trade:hasItemQty(StorageArray[SetId + 7],1);
T5 = trade:hasItemQty(StorageArray[SetId + 8],1);
if (StorageArray[SetId + 4] == 0) then
T2 = true;
end;
if (StorageArray[SetId + 6] == 0) then
T3 = true;
end;
if (StorageArray[SetId + 7] == 0) then
T4 = true;
end;
if (StorageArray[SetId + 8] == 0) then
T5 = true;
end;
if (T2 == true and T3 == true and T4 == true and T5 == true) then
player:startEvent(Deposit,0,0,0,0,0,StorageArray[SetId + 9]);
player:addKeyItem(StorageArray[SetId + 10]);
player:messageSpecial(KEYITEM_OBTAINED,StorageArray[SetId + 10]);
break;
end;
end;
end;
end;
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
CurrGil = player:getGil();
for KeyItem = 11,ArraySize,11 do
if player:hasKeyItem(StorageArray[KeyItem]) then
if StorageArray[KeyItem - 9] == 1 then
G1 = G1 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 2 then
G2 = G2 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 3 then
G3 = G3 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 4 then
G4 = G4 + StorageArray[KeyItem - 8];
elseif StorageArray[KeyItem - 9] == 6 then
G5 = G5 + StorageArray[KeyItem - 8];
end;
end;
end;
player:startEvent(Withdrawl,G1,G2,G3,G4,CurrGil,G5);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
if (csid == Withdrawl) then
player:updateEvent(StorageArray[option * 11 - 6],
StorageArray[option * 11 - 5],
StorageArray[option * 11 - 4],
StorageArray[option * 11 - 3],
StorageArray[option * 11 - 2],
StorageArray[option * 11 - 1]);
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == Withdrawl) then
if (option > 0 and option <= StorageArray[ArraySize] - 10) then
if (player:getFreeSlotsCount() >= StorageArray[option * 11 - 7]) then
for Item = 2,6,1 do
if (StorageArray[option * 11 - Item] > 0) then
player:addItem(StorageArray[option * 11 - Item],1);
player:messageSpecial(ITEM_OBTAINED,StorageArray[option * 11 - Item]);
end;
end;
player:delKeyItem(StorageArray[option * 11]);
player:setGil(player:getGil() - StorageArray[option * 11 - 1]);
else
for Item = 2,6,1 do
if (StorageArray[option * 11 - Item] > 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,StorageArray[option * 11 - Item]);
end;
end;
end;
end;
end;
if (csid == Deposit) then
player:tradeComplete();
end;
end; | gpl-3.0 |
TeamFSIModding/FS17_Goweil_LT_Master | src/scripts/overwrites/AnimatedVehicle.lua | 1 | 8400 | --
--Goweil LT Master
--
--TyKonKet (Team FSI Modding)
--
--18/05/2017
function AnimatedVehicle.initializeParts(self, animation)
local numParts = table.getn(animation.parts);
for i = 1, numParts do
local part = animation.parts[i];
-- find the next rot part
if part.endRot ~= nil then
for j = i + 1, numParts do
local part2 = animation.parts[j];
if part.node == part2.node and part2.endRot ~= nil then
if part.startTime + part.duration > part2.startTime + 0.001 and part.direction == part2.direction then
print("Warning: overlapping rotation parts for node " .. getName(part.node) .. " in " .. animation.name .. " " .. self.configFileName);
end
part.nextRotPart = part2;
part2.prevRotPart = part;
if part2.startRot == nil then
part2.startRot = {part.endRot[1], part.endRot[2], part.endRot[3]};
end
break;
end
end
end
-- find the next trans part
if part.endTrans ~= nil then
for j = i + 1, numParts do
local part2 = animation.parts[j];
if part.node == part2.node and part2.endTrans ~= nil then
if part.startTime + part.duration > part2.startTime + 0.001 and part.direction == part2.direction then
print("Warning: overlapping translation parts for node " .. getName(part.node) .. " in " .. animation.name .. " " .. self.configFileName);
end
part.nextTransPart = part2;
part2.prevTransPart = part;
if part2.startTrans == nil then
part2.startTrans = {part.endTrans[1], part.endTrans[2], part.endTrans[3]};
end
break;
end
end
end
-- find the next scale part
if part.endScale ~= nil then
for j = i + 1, numParts do
local part2 = animation.parts[j];
if part.node == part2.node and part2.endScale ~= nil then
if part.startTime + part.duration > part2.startTime + 0.001 and part.direction == part2.direction then
print("Warning: overlapping scale parts for node " .. getName(part.node) .. " in " .. animation.name .. " " .. self.configFileName);
end
part.nextScalePart = part2;
part2.prevScalePart = part;
if part2.startScale == nil then
part2.startScale = {part.endScale[1], part.endScale[2], part.endScale[3]};
end
break;
end
end
end
-- find the next shader part
if part.shaderEndValues ~= nil then
for j = i + 1, numParts do
local part2 = animation.parts[j];
if part.node == part2.node and part2.shaderEndValues ~= nil then
if part.startTime + part.duration > part2.startTime + 0.001 and part.direction == part2.direction then
print("Warning: overlapping shaderParameter parts for node " .. getName(part.node) .. " in " .. animation.name .. " " .. self.configFileName);
end
part.nextShaderPart = part2;
part2.prevShaderPart = part;
if part2.shaderStartValues == nil then
part2.shaderStartValues = {part.shaderEndValues[1], part.shaderEndValues[2], part.shaderEndValues[3], part.shaderEndValues[4]};
end
break;
end
end
end
if self.isServer then
-- find the next joint rot limit part
if part.endRotMinLimit ~= nil then
for j = i + 1, numParts do
local part2 = animation.parts[j];
if part.componentJoint == part2.componentJoint and (part2.endRotMinLimit ~= nil and part2.endRotMaxLimit ~= nil) then
if part.startTime + part.duration > part2.startTime + 0.001 and part.direction == part2.direction then
print("Warning: overlapping joint rot limit parts for component joint " .. getName(part.componentJoint.jointNode) .. " in " .. animation.name .. " " .. self.configFileName);
end
part.nextRotLimitPart = part2;
part2.prevRotLimitPart = part;
if part2.startRotMinLimit == nil then
part2.startRotMinLimit = {part.endRotMinLimit[1], part.endRotMinLimit[2], part.endRotMinLimit[3]};
end
if part2.startRotMaxLimit == nil then
part2.startRotMaxLimit = {part.endRotMaxLimit[1], part.endRotMaxLimit[2], part.endRotMaxLimit[3]};
end
break;
end
end
end
-- find the next joint trans limit part
if part.endTransMinLimit ~= nil then
for j = i + 1, numParts do
local part2 = animation.parts[j];
if part.componentJoint == part2.componentJoint and (part2.endTransMinLimit ~= nil and part2.endTransMaxLimit ~= nil) then
if part.startTime + part.duration > part2.startTime + 0.001 and part.direction == part2.direction then
print("Warning: overlapping joint trans limit parts for component joint " .. getName(part.componentJoint.jointNode) .. " in " .. animation.name .. " " .. self.configFileName);
end
part.nextTransLimitPart = part2;
part2.prevTransLimitPart = part;
if part2.startTransMinLimit == nil then
part2.startTransMinLimit = {part.endTransMinLimit[1], part.endTransMinLimit[2], part.endTransMinLimit[3]};
end
if part2.startTransMaxLimit == nil then
part2.startTransMaxLimit = {part.endTransMaxLimit[1], part.endTransMaxLimit[2], part.endTransMaxLimit[3]};
end
break;
end
end
end
end
end
-- default start values to the value stored in the i3d (if not set by the end value of the previous part)
for i = 1, numParts do
local part = animation.parts[i];
if part.endRot ~= nil and part.startRot == nil then
local x, y, z = getRotation(part.node);
part.startRot = {x, y, z};
end
if part.endTrans ~= nil and part.startTrans == nil then
local x, y, z = getTranslation(part.node);
part.startTrans = {x, y, z};
end;
if part.endScale ~= nil and part.startScale == nil then
local x, y, z = getScale(part.node);
part.startScale = {x, y, z};
end;
if self.isServer then
if part.endRotMinLimit ~= nil and part.startRotMinLimit == nil then
local rotLimit = part.componentJoint.rotMinLimit;
part.startRotMinLimit = {rotLimit[1], rotLimit[2], rotLimit[3]};
end
if part.endRotMaxLimit ~= nil and part.startRotMaxLimit == nil then
local rotLimit = part.componentJoint.rotLimit;
part.startRotMaxLimit = {rotLimit[1], rotLimit[2], rotLimit[3]};
end
if part.endTransMinLimit ~= nil and part.startTransMinLimit == nil then
local transLimit = part.componentJoint.transMinLimit;
part.startTransMinLimit = {transLimit[1], transLimit[2], transLimit[3]};
end
if part.endTransMaxLimit ~= nil and part.startTransMaxLimit == nil then
local transLimit = part.componentJoint.transLimit;
part.startTransMaxLimit = {transLimit[1], transLimit[2], transLimit[3]};
end
end
end
end
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Bhaflau_Thickets/npcs/Harvesting_Point.lua | 17 | 1106 | -----------------------------------
-- Area: Bhaflau Thickets
-- NPC: Harvesting Point
-----------------------------------
package.loaded["scripts/zones/Bhaflau_Thickets/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/harvesting");
require("scripts/zones/Bhaflau_Thickets/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startHarvesting(player,player:getZoneID(),npc,trade,0x01F7);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(HARVESTING_IS_POSSIBLE_HERE,1020);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
Zero-K-Experiments/Zero-K-Experiments | effects/blacksmoke.lua | 7 | 3192 | return {
["blacksmoke"] = {
dirtg = {
air = true,
class = [[CSimpleParticleSystem]],
count = 2,
ground = true,
water = true,
properties = {
airdrag = 0.7,
--alwaysvisible = true,
colormap = [[1 0.5 0 1.0 1 0.5 0 1.0 0.9 0.4 0 1.0 0.6 0.2 0 1.0 0.3 0.1 0 1.0 0 0 0 1.0 0 0 0 0.5 0 0 0 0.1]],
directional = true,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.3, 0]],
numparticles = 4,
particlelife = 60,
particlelifespread = 20,
particlesize = 1,
particlesizespread = 2,
particlespeed = 1,
particlespeedspread = 4,
sizegrowth = 1,
sizemod = 0.9,
texture = [[new_dirta]],
useairlos = false,
--colorchange = "stuffs",
},
},
},
["blacksmokebubbles"] = {
dirtg = {
air = true,
class = [[CSimpleParticleSystem]],
count = 2,
ground = true,
water = true,
underwater = false,
properties = {
airdrag = 0.7,
--alwaysvisible = true,
colormap = [[1 0.5 0 1.0 1 0.5 0 1.0 0.9 0.4 0 1.0 0.6 0.2 0 1.0 0.3 0.1 0 1.0 0 0 0 1.0 0 0 0 0.5 0 0 0 0.1]],
directional = true,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.3, 0]],
numparticles = 4,
particlelife = 60,
particlelifespread = 20,
particlesize = 1,
particlesizespread = 2,
particlespeed = 1,
particlespeedspread = 4,
sizegrowth = 1,
sizemod = 0.9,
texture = [[new_dirta]],
useairlos = false,
--colorchange = "stuffs",
},
},
bubblesuw = {
air = false,
class = [[CSimpleParticleSystem]],
count = 2,
ground = false,
water = false,
underwater = true,
properties = {
airdrag = 0.7,
--alwaysvisible = true,
colormap = [[1 1 1 0.5 0.5 0.5 1 0.8 0 0 0 0.0]],
directional = true,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.3, 0]],
numparticles = 4,
particlelife = 60,
particlelifespread = 20,
particlesize = 1,
particlesizespread = 2,
particlespeed = 1,
particlespeedspread = 4,
sizegrowth = 1,
sizemod = 0.9,
texture = [[randdots]],
useairlos = false,
--colorchange = "stuffs",
},
},
},
} | gpl-2.0 |
Scavenge/darkstar | scripts/globals/items/cone_of_snoll_gelato.lua | 12 | 1324 | -----------------------------------------
-- ID: 5147
-- Item: cone_of_snoll_gelato
-- Food Effect: 30Min, All Races
-----------------------------------------
-- MP % 16 (cap 75)
-- MP Recovered While Healing 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5147);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_MPP, 16);
target:addMod(MOD_FOOD_MP_CAP, 75);
target:addMod(MOD_MPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_MPP, 16);
target:delMod(MOD_FOOD_MP_CAP, 75);
target:delMod(MOD_MPHEAL, 1);
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/globals/items/opo-opo_tart.lua | 12 | 1364 | -----------------------------------------
-- ID: 4287
-- Item: opo-opo_tart
-- Food Effect: 1hour, All Races
-----------------------------------------
-- HP 12
-- MP 12
-- Intelligence 4
-- MP Recovered While Healing 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,4287);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 12);
target:addMod(MOD_MP, 12);
target:addMod(MOD_INT, 4);
target:addMod(MOD_MPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 12);
target:delMod(MOD_MP, 12);
target:delMod(MOD_INT, 4);
target:delMod(MOD_MPHEAL, 3);
end;
| gpl-3.0 |
Zero-K-Experiments/Zero-K-Experiments | effects/raider.lua | 25 | 5577 | -- raidshells
-- raiddust
-- raidmuzzle
return {
["raidshells"] = {
muzzleflash = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.90,
colormap = [[1 0.7 0.2 0.01 1 0.7 0.2 0.01 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 90,
emitvector = [[dir]],
gravity = [[0, 0, 0]],
numparticles = 5,
particlelife = 2,
particlelifespread = 5,
particlesize = 1,
particlesizespread = 0.3,
particlespeed = 0.4,
particlespeedspread = 0.4,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[plasma]],
},
},
shells = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.97,
colormap = [[1 1 1 1 1 1 1 1]],
directional = true,
emitrot = 0,
emitrotspread = 10,
emitvector = [[dir]],
gravity = [[0, -0.5, 0]],
numparticles = 1,
particlelife = 25,
particlelifespread = 0,
particlesize = 3,
particlesizespread = 0,
particlespeed = 4,
particlespeedspread = 0,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[shell]],
},
},
},
["raiddust"] = {
groundflash = {
circlealpha = 1,
circlegrowth = 0,
flashalpha = 0.9,
flashsize = 60,
ttl = 4,
color = {
[1] = 1,
[2] = 0.5,
[3] = 0,
},
},
muzzleflash = {
air = true,
class = [[CSimpleParticleSystem]],
count = 0,
ground = true,
water = true,
properties = {
airdrag = 0.8,
colormap = [[0.72 0.61 0.41 1 0 0 0 0.01]],
directional = false,
emitrot = 90,
emitrotspread = 10,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.05, 0]],
numparticles = 20,
particlelife = 30,
particlelifespread = 0,
particlesize = 1,
particlesizespread = 2,
particlespeed = 6,
particlespeedspread = 6,
pos = [[0, 0, 0]],
sizegrowth = 1,
sizemod = 1.0,
texture = [[smokesmall]],
},
},
},
["raidmuzzle"] = {
bitmapmuzzleflame = {
air = true,
class = [[CBitmapMuzzleFlame]],
count = 1,
ground = true,
underwater = 1,
water = true,
properties = {
colormap = [[1 1 0.5 0.01 1 0.7 0 0.01 0 0 0 0.01]],
dir = [[dir]],
frontoffset = 0.3,
fronttexture = [[plasma0029]],
length = 1,
sidetexture = [[plasma2]],
size = 0.5,
sizegrowth = 70,
ttl = 5,
},
},
muzzleflash = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.90,
colormap = [[1 0.7 0.2 0.01 1 0.7 0.2 0.01 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 10,
emitvector = [[dir]],
gravity = [[0, 0, 0]],
numparticles = 20,
particlelife = 18,
particlelifespread = 5,
particlesize = 1,
particlesizespread = 0.3,
particlespeed = 2,
particlespeedspread = 4,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[plasma]],
},
},
muzzlesmoke = {
air = true,
class = [[CSimpleParticleSystem]],
count = 10,
ground = true,
water = true,
properties = {
airdrag = 0.8,
colormap = [[0 0 0 0.01 0.5 0.5 0.5 0.5 0 0 0 0.01]],
directional = false,
emitrot = 0,
emitrotspread = 10,
emitvector = [[dir]],
gravity = [[0, 0, 0]],
numparticles = 1,
particlelife = 20,
particlelifespread = 0,
particlesize = [[7 i-0.4]],
particlesizespread = 1,
particlespeed = [[10 i-1]],
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[smokesmall]],
},
},
},
}
| gpl-2.0 |
ramindel0761/tele_ir | libs/dateparser.lua | 502 | 6212 | local difftime, time, date = os.difftime, os.time, os.date
local format = string.format
local tremove, tinsert = table.remove, table.insert
local pcall, pairs, ipairs, tostring, tonumber, type, setmetatable = pcall, pairs, ipairs, tostring, tonumber, type, setmetatable
local dateparser={}
--we shall use the host OS's time conversion facilities. Dealing with all those leap seconds by hand can be such a bore.
local unix_timestamp
do
local now = time()
local local_UTC_offset_sec = difftime(time(date("!*t", now)), time(date("*t", now)))
unix_timestamp = function(t, offset_sec)
local success, improper_time = pcall(time, t)
if not success or not improper_time then return nil, "invalid date. os.time says: " .. (improper_time or "nothing") end
return improper_time - local_UTC_offset_sec - offset_sec
end
end
local formats = {} -- format names
local format_func = setmetatable({}, {__mode='v'}) --format functions
---register a date format parsing function
function dateparser.register_format(format_name, format_function)
if type(format_name)~="string" or type(format_function)~='function' then return nil, "improper arguments, can't register format handler" end
local found
for i, f in ipairs(format_func) do --for ordering
if f==format_function then
found=true
break
end
end
if not found then
tinsert(format_func, format_function)
end
formats[format_name] = format_function
return true
end
---register a date format parsing function
function dateparser.unregister_format(format_name)
if type(format_name)~="string" then return nil, "format name must be a string" end
formats[format_name]=nil
end
---return the function responsible for handling format_name date strings
function dateparser.get_format_function(format_name)
return formats[format_name] or nil, ("format %s not registered"):format(format_name)
end
---try to parse date string
--@param str date string
--@param date_format optional date format name, if known
--@return unix timestamp if str can be parsed; nil, error otherwise.
function dateparser.parse(str, date_format)
local success, res, err
if date_format then
if not formats[date_format] then return 'unknown date format: ' .. tostring(date_format) end
success, res = pcall(formats[date_format], str)
else
for i, func in ipairs(format_func) do
success, res = pcall(func, str)
if success and res then return res end
end
end
return success and res
end
dateparser.register_format('W3CDTF', function(rest)
local year, day_of_year, month, day, week
local hour, minute, second, second_fraction, offset_hours
local alt_rest
year, rest = rest:match("^(%d%d%d%d)%-?(.*)$")
day_of_year, alt_rest = rest:match("^(%d%d%d)%-?(.*)$")
if day_of_year then rest=alt_rest end
month, rest = rest:match("^(%d%d)%-?(.*)$")
day, rest = rest:match("^(%d%d)(.*)$")
if #rest>0 then
rest = rest:match("^T(.*)$")
hour, rest = rest:match("^([0-2][0-9]):?(.*)$")
minute, rest = rest:match("^([0-6][0-9]):?(.*)$")
second, rest = rest:match("^([0-6][0-9])(.*)$")
second_fraction, alt_rest = rest:match("^%.(%d+)(.*)$")
if second_fraction then
rest=alt_rest
end
if rest=="Z" then
rest=""
offset_hours=0
else
local sign, offset_h, offset_m
sign, offset_h, rest = rest:match("^([+-])(%d%d)%:?(.*)$")
local offset_m, alt_rest = rest:match("^(%d%d)(.*)$")
if offset_m then rest=alt_rest end
offset_hours = tonumber(sign .. offset_h) + (tonumber(offset_m) or 0)/60
end
if #rest>0 then return nil end
end
year = tonumber(year)
local d = {
year = year and (year > 100 and year or (year < 50 and (year + 2000) or (year + 1900))),
month = tonumber(month) or 1,
day = tonumber(day) or 1,
hour = tonumber(hour) or 0,
min = tonumber(minute) or 0,
sec = tonumber(second) or 0,
isdst = false
}
local t = unix_timestamp(d, (offset_hours or 0) * 3600)
if second_fraction then
return t + tonumber("0."..second_fraction)
else
return t
end
end)
do
local tz_table = { --taken from http://www.timeanddate.com/library/abbreviations/timezones/
A = 1, B = 2, C = 3, D = 4, E=5, F = 6, G = 7, H = 8, I = 9,
K = 10, L = 11, M = 12, N = -1, O = -2, P = -3, Q = -4, R = -5,
S = -6, T = -7, U = -8, V = -9, W = -10, X = -11, Y = -12,
Z = 0,
EST = -5, EDT = -4, CST = -6, CDT = -5,
MST = -7, MDT = -6, PST = -8, PDT = -7,
GMT = 0, UT = 0, UTC = 0
}
local month_val = {Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12}
dateparser.register_format('RFC2822', function(rest)
local year, month, day, day_of_year, week_of_year, weekday
local hour, minute, second, second_fraction, offset_hours
local alt_rest
weekday, alt_rest = rest:match("^(%w%w%w),%s+(.*)$")
if weekday then rest=alt_rest end
day, rest=rest:match("^(%d%d?)%s+(.*)$")
month, rest=rest:match("^(%w%w%w)%s+(.*)$")
month = month_val[month]
year, rest = rest:match("^(%d%d%d?%d?)%s+(.*)$")
hour, rest = rest:match("^(%d%d?):(.*)$")
minute, rest = rest:match("^(%d%d?)(.*)$")
second, alt_rest = rest:match("^:(%d%d)(.*)$")
if second then rest = alt_rest end
local tz, offset_sign, offset_h, offset_m
tz, alt_rest = rest:match("^%s+(%u+)(.*)$")
if tz then
rest = alt_rest
offset_hours = tz_table[tz]
else
offset_sign, offset_h, offset_m, rest = rest:match("^%s+([+-])(%d%d)(%d%d)%s*(.*)$")
offset_hours = tonumber(offset_sign .. offset_h) + (tonumber(offset_m) or 0)/60
end
if #rest>0 or not (year and day and month and hour and minute) then
return nil
end
year = tonumber(year)
local d = {
year = year and ((year > 100) and year or (year < 50 and (year + 2000) or (year + 1900))),
month = month,
day = tonumber(day),
hour= tonumber(hour) or 0,
min = tonumber(minute) or 0,
sec = tonumber(second) or 0,
isdst = false
}
return unix_timestamp(d, offset_hours * 3600)
end)
end
dateparser.register_format('RFC822', formats.RFC2822) --2822 supercedes 822, but is not a strict superset. For our intents and purposes though, it's perfectly good enough
dateparser.register_format('RFC3339', formats.W3CDTF) --RFC3339 is a subset of W3CDTF
return dateparser | gpl-3.0 |
Scavenge/darkstar | scripts/globals/spells/maidens_virelai.lua | 12 | 1568 | -----------------------------------------
-- Spell: Maiden's Virelai
-- Charms pet
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/pets");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
if (caster:getPet() ~= nil) then
return MSGBASIC_ALREADY_HAS_A_PET;
elseif (target:getMaster() ~= nil and target:getMaster():isPC()) then
return MSGBASIC_THAT_SOMEONES_PET;
end
-- Per wiki, Virelai wipes all shadows even if it resists or the target is immune to charm
-- This can't be done in the onSpellCast function (that runs after it "hits")
spell:setFlag(SPELLFLAG_WIPE_SHADOWS);
return 0;
end;
function onSpellCast(caster,target,spell)
local dCHR = (caster:getStat(MOD_CHR) - target:getStat(MOD_CHR));
local bonus = 0; -- No idea what value, but seems likely to need this edited later to get retail resist rates.
local resist = applyResistanceEffect(caster,spell,target,dCHR,SINGING_SKILL,bonus,EFFECT_CHARM_I);
-- print(resist);
if (resist >= 0.25 and caster:getCharmChance(target, false) > 0) then
spell:setMsg(236);
if (caster:isMob())then
target:addStatusEffect(EFFECT_CHARM_I, 0, 0, 30*resist);
caster:charm(target);
else
caster:charmPet(target);
end
else
-- Resist
spell:setMsg(85);
end
return EFFECT_CHARM_I;
end; | gpl-3.0 |
Scavenge/darkstar | scripts/zones/Castle_Oztroja/npcs/_m71.lua | 14 | 1243 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _m71 (Torch Stand)
-- Involved in Mission: Magicite
-- @pos -99 24 -105 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Castle_Oztroja/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(YAGUDO_TORCH)) then
player:startEvent(0x000b);
else
player:messageSpecial(PROBABLY_WORKS_WITH_SOMETHING_ELSE);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
Scavenge/darkstar | scripts/zones/Giddeus/npcs/qm1.lua | 14 | 1757 | -----------------------------------
-- Area: Giddeus
-- NPC: ???
-- Involved In Quest: Dark Legacy
-- @zone 145
-- @pos -58 0 -449
-----------------------------------
package.loaded["scripts/zones/Giddeus/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Giddeus/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
darkLegacyCS = player:getVar("darkLegacyCS");
if (darkLegacyCS == 3 or darkLegacyCS == 4) then
if (trade:hasItemQty(4445,1) and trade:getItemCount() == 1) then -- Trade Yagudo Cherries
player:tradeComplete();
player:messageSpecial(SENSE_OF_FOREBODING);
SpawnMob(17371579):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("darkLegacyCS") == 5 and player:hasKeyItem(DARKSTEEL_FORMULA) == false) then
player:addKeyItem(DARKSTEEL_FORMULA);
player:messageSpecial(KEYITEM_OBTAINED,DARKSTEEL_FORMULA);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
Zero-K-Experiments/Zero-K-Experiments | units/corcan.lua | 3 | 4490 | unitDef = {
unitname = [[corcan]],
name = [[Jack]],
description = [[Melee Assault Jumper]],
acceleration = 0.16,
brakeRate = 0.2,
buildCostEnergy = 600,
buildCostMetal = 600,
builder = false,
buildPic = [[CORCAN.png]],
buildTime = 600,
canAttack = true,
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
corpse = [[DEAD]],
customParams = {
canjump = 1,
jump_range = 400,
jump_speed = 4,
jump_reload = 10,
jump_from_midair = 1,
description_fr = [[Robot d'Assaut]],
description_de = [[Melee Sturmangriff Springer]],
helptext = [[The Jack is a melee assault walker with jumpjets. A few Jacks can easily level most fortification lines. Its small range and very low speed make it very vulnerable to skirmishers.]],
helptext_fr = [[Le Jack est un robot extr?mement bien blind? ?quip? d'un jetpack et d'un lance a syst?me hydrolique. Il ne frappe qu'au corps ? corps, mais il frappe fort. ]],
helptext_de = [[Der Jack ist ein Melee Sturmangriff Roboter mit Sprungdüsen. Ein paar Jacks können schnell die meisten Verteidigungslinien egalisieren. Seine kleine Reichweite und die Langsamkeit machen ihn aber sehr verwundbar gegen Skirmisher.]],
},
explodeAs = [[BIG_UNITEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[jumpjetassault]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 5000,
maxSlope = 36,
maxVelocity = 1.81,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[KBOT2]],
noAutoFire = false,
noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE GUNSHIP SUB]],
objectName = [[corcan.s3o]],
script = [[corcan.lua]],
seismicSignature = 4,
selfDestructAs = [[BIG_UNITEX]],
sfxtypes = {
explosiongenerators = {
[[custom:RAIDMUZZLE]],
[[custom:VINDIBACK]],
},
},
sightDistance = 350,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 22,
turnRate = 1200,
upright = true,
workerTime = 0,
weapons = {
{
def = [[Spike]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP FIXEDWING]],
},
},
weaponDefs = {
Spike = {
name = [[Spike]],
areaOfEffect = 8,
beamTime = 4/30,
canattackground = true,
cegTag = [[orangelaser]],
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
light_camera_height = 1000,
light_color = [[1 1 0.7]],
light_radius = 150,
light_beam_start = 0.25,
combatrange = 60,
},
damage = {
default = 300.1,
subs = 15,
},
explosionGenerator = [[custom:BEAMWEAPON_HIT_ORANGE]],
fireStarter = 90,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 0,
lodDistance = 10000,
noSelfDamage = true,
range = 125,
reloadtime = 1,
rgbColor = [[1 0.25 0]],
soundStart = [[explosion/ex_large7]],
targetborder = 1,
thickness = 0,
tolerance = 10000,
turret = true,
waterweapon = true,
weaponType = [[BeamLaser]],
weaponVelocity = 2000,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[corcan_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2a.s3o]],
},
},
}
return lowerkeys({ corcan = unitDef })
| gpl-2.0 |
Grade-A-Software/Comcast-DASH-VLC | share/lua/extensions/VLSub.lua | 11 | 52410 | --[[
VLSub Extension for VLC media player 1.1 and 2.0
Copyright 2013 Guillaume Le Maout
Authors: Guillaume Le Maout
Contact: http://addons.videolan.org/messages/?action=newmessage&username=exebetche
Bug report: http://addons.videolan.org/content/show.php/?content=148752
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
--[[ Global var ]]--
-- You can set here your default language by replacing nil with your language code (see below)
-- Example:
-- language = "fre",
-- language = "ger",
-- language = "eng",
-- ...
local options = {
language = nil,
downloadBehaviour = 'save',
langExt = false,
removeTag = false,
showMediaInformation = true,
progressBarSize = 80,
intLang = 'eng',
translations_avail = {
eng = 'English',
cze = 'Czech',
dan = 'Danish',
fre = 'Français',
ell = 'Greek',
baq = 'Basque',
pob = 'Brazilian Portuguese',
slo = 'Slovak',
spa = 'Spanish',
swe = 'Swedish',
ukr = 'Ukrainian'
},
translation = {
int_all = 'All',
int_descr = 'Download subtitles from OpenSubtitles.org',
int_research = 'Research',
int_config = 'Config',
int_configuration = 'Configuration',
int_help = 'Help',
int_search_hash = 'Search by hash',
int_search_name = 'Search by name',
int_title = 'Title',
int_season = 'Season (series)',
int_episode = 'Episode (series)',
int_show_help = 'Show help',
int_show_conf = 'Show config',
int_dowload_sel = 'Download selection',
int_close = 'Close',
int_ok = 'Ok',
int_save = 'Save',
int_cancel = 'Cancel',
int_bool_true = 'Yes',
int_bool_false = 'No',
int_search_transl = 'Search translations',
int_searching_transl = 'Searching translations ...',
int_int_lang = 'Interface language',
int_default_lang = 'Subtitles language',
int_dowload_behav = 'What to do with subtitles',
int_dowload_save = 'Load and save',
int_dowload_load = 'Load only',
int_dowload_manual = 'Manual download',
int_display_code = 'Display language code in file name',
int_remove_tag = 'Remove tags',
int_vlsub_work_dir = 'VLSub working directory',
int_os_username = 'Username',
int_os_password = 'Password',
int_help_mess = " Download subtittles from <a href='http://www.opensubtitles.org/'>opensubtitles.org</a> and display them while watching a video.<br>"..
" <br>"..
" <b><u>Usage:</u></b><br>"..
" <br>"..
" VLSub is meant to be used while your watching the video, so start it first (if nothing is playing you will get a link to download the subtitles in your browser).<br>"..
" <br>"..
" Choose the language for your subtitles and click on the button corresponding to one of the two research method provided by VLSub:<br>"..
" <br>"..
" <b>Method 1: Search by hash</b><br>"..
" It is recommended to try this method first, because it performs a research based on the video file print, so you can find subtitles synchronized with your video.<br>"..
" <br>"..
" <b>Method 2: Search by name</b><br>"..
" If you have no luck with the first method, just check the title is correct before clicking. If you search subtitles for a serie, you can also provide a season and episode number.<br>"..
" <br>"..
" <b>Downloading Subtitles</b><br>"..
" Select one subtitle in the list and click on 'Download'.<br>"..
" It will be put in the same directory that your video, with the same name (different extension)"..
" so Vlc will load them automatically the next time you'll start the video.<br>"..
" <br>"..
" <b>/!\\ Beware :</b> Existing subtitles are overwrited without asking confirmation, so put them elsewhere if thet're important.<br>"..
" <br>"..
" Find more Vlc extensions at <a href='http://addons.videolan.org'>addons.videolan.org</a>.",
action_login = 'Logging in',
action_logout = 'Logging out',
action_noop = 'Checking session',
action_search = 'Searching subtitles',
action_hash = 'Calculating movie hash',
mess_success = 'Success',
mess_error = 'Error',
mess_no_response = 'Server not responding',
mess_unauthorized = 'Request unauthorized',
mess_expired = 'Session expired, retrying',
mess_overloaded = 'Server overloaded, please retry later',
mess_no_input = 'Please use this method during playing',
mess_not_local = 'This method works with local file only (for now)',
mess_not_found = 'File not found',
mess_not_found2 = 'File not found (illegal character?)',
mess_no_selection = 'No subtitles selected',
mess_save_fail = 'Unable to save subtitles',
mess_click_link = 'Click here to open the file',
mess_complete = 'Research complete',
mess_no_res = 'No result',
mess_res = 'result(s)',
mess_loaded = 'Subtitles loaded',
mess_downloading = 'Downloading subtitle',
mess_dowload_link = 'Download link',
mess_err_conf_access ='Can\'t fount a suitable path to save config, please set it manually',
mess_err_wrong_path ='the path contains illegal character, please correct it'
}
}
local languages = {
{'alb', 'Albanian'},
{'ara', 'Arabic'},
{'arm', 'Armenian'},
{'baq', 'Basque'},
{'ben', 'Bengali'},
{'bos', 'Bosnian'},
{'bre', 'Breton'},
{'bul', 'Bulgarian'},
{'bur', 'Burmese'},
{'cat', 'Catalan'},
{'chi', 'Chinese'},
{'hrv', 'Croatian'},
{'cze', 'Czech'},
{'dan', 'Danish'},
{'dut', 'Dutch'},
{'eng', 'English'},
{'epo', 'Esperanto'},
{'est', 'Estonian'},
{'fin', 'Finnish'},
{'fre', 'French'},
{'glg', 'Galician'},
{'geo', 'Georgian'},
{'ger', 'German'},
{'ell', 'Greek'},
{'heb', 'Hebrew'},
{'hin', 'Hindi'},
{'hun', 'Hungarian'},
{'ice', 'Icelandic'},
{'ind', 'Indonesian'},
{'ita', 'Italian'},
{'jpn', 'Japanese'},
{'kaz', 'Kazakh'},
{'khm', 'Khmer'},
{'kor', 'Korean'},
{'lav', 'Latvian'},
{'lit', 'Lithuanian'},
{'ltz', 'Luxembourgish'},
{'mac', 'Macedonian'},
{'may', 'Malay'},
{'mal', 'Malayalam'},
{'mon', 'Mongolian'},
{'nor', 'Norwegian'},
{'oci', 'Occitan'},
{'per', 'Persian'},
{'pol', 'Polish'},
{'por', 'Portuguese'},
{'pob', 'Brazilian Portuguese'},
{'rum', 'Romanian'},
{'rus', 'Russian'},
{'scc', 'Serbian'},
{'sin', 'Sinhalese'},
{'slo', 'Slovak'},
{'slv', 'Slovenian'},
{'spa', 'Spanish'},
{'swa', 'Swahili'},
{'swe', 'Swedish'},
{'syr', 'Syriac'},
{'tgl', 'Tagalog'},
{'tel', 'Telugu'},
{'tha', 'Thai'},
{'tur', 'Turkish'},
{'ukr', 'Ukrainian'},
{'urd', 'Urdu'},
{'vie', 'Vietnamese'}
}
-- Languages code conversion table: iso-639-1 to iso-639-3
-- See https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
local lang_os_to_iso = {
sq = "alb",
ar = "ara",
hy = "arm",
eu = "baq",
bn = "ben",
bs = "bos",
br = "bre",
bg = "bul",
my = "bur",
ca = "cat",
zh = "chi",
hr = "hrv",
cs = "cze",
da = "dan",
nl = "dut",
en = "eng",
eo = "epo",
et = "est",
fi = "fin",
fr = "fre",
gl = "glg",
ka = "geo",
de = "ger",
el = "ell",
he = "heb",
hi = "hin",
hu = "hun",
is = "ice",
id = "ind",
it = "ita",
ja = "jpn",
kk = "kaz",
km = "khm",
ko = "kor",
lv = "lav",
lt = "lit",
lb = "ltz",
mk = "mac",
ms = "may",
ml = "mal",
mn = "mon",
no = "nor",
oc = "oci",
fa = "per",
pl = "pol",
pt = "por",
po = "pob",
ro = "rum",
ru = "rus",
sr = "scc",
si = "sin",
sk = "slo",
sl = "slv",
es = "spa",
sw = "swa",
sv = "swe",
tl = "tgl",
te = "tel",
th = "tha",
tr = "tur",
uk = "ukr",
ur = "urd",
vi = "vie"
}
local dlg = nil
local input_table = {} -- General widget id reference
local select_conf = {} -- Drop down widget / option table association
--[[ Vlc extension stuff ]]--
function descriptor()
return {
title = "VLsub 0.9.10",
version = "0.9.10",
author = "exebetche",
url = 'http://www.opensubtitles.org/',
shortdesc = "Download Subtitles";
description = options.translation.int_descr,
capabilities = {"menu", "input-listener" }
}
end
function activate()
vlc.msg.dbg("[VLsub] Welcome")
check_config()
if vlc.input.item() then
openSub.getFileInfo()
openSub.getMovieInfo()
end
show_main()
end
function close()
deactivate()
end
function deactivate()
vlc.msg.dbg("[VLsub] Bye bye!")
if dlg then
dlg:hide()
end
if openSub.session.token and openSub.session.token ~= "" then
openSub.request("LogOut")
end
vlc.deactivate()
end
function menu()
return {
lang.int_research,
lang.int_config,
lang.int_help
}
end
function meta_changed()
return false
end
function input_changed()
collectgarbage()
set_interface_main()
collectgarbage()
end
--[[ Interface data ]]--
function interface_main()
dlg:add_label(lang["int_default_lang"]..':', 1, 1, 1, 1)
input_table['language'] = dlg:add_dropdown(2, 1, 2, 1)
dlg:add_button(lang["int_search_hash"], searchHash, 4, 1, 1, 1)
dlg:add_label(lang["int_title"]..':', 1, 2, 1, 1)
input_table['title'] = dlg:add_text_input(openSub.movie.title or "", 2, 2, 2, 1)
dlg:add_button(lang["int_search_name"], searchIMBD, 4, 2, 1, 1)
dlg:add_label(lang["int_season"]..':', 1, 3, 1, 1)
input_table['seasonNumber'] = dlg:add_text_input(openSub.movie.seasonNumber or "", 2, 3, 2, 1)
dlg:add_label(lang["int_episode"]..':', 1, 4, 1, 1)
input_table['episodeNumber'] = dlg:add_text_input(openSub.movie.episodeNumber or "", 2, 4, 2, 1)
input_table['mainlist'] = dlg:add_list(1, 5, 4, 1)
input_table['message'] = nil
input_table['message'] = dlg:add_label(' ', 1, 6, 4, 1)
dlg:add_button(lang["int_show_help"], show_help, 1, 7, 1, 1)
dlg:add_button(' '..lang["int_show_conf"]..' ', show_conf, 2, 7, 1, 1)
dlg:add_button(lang["int_dowload_sel"], download_subtitles, 3, 7, 1, 1)
dlg:add_button(lang["int_close"], deactivate, 4, 7, 1, 1)
assoc_select_conf('language', 'language', openSub.conf.languages, 2, lang["int_all"])
display_subtitles()
end
function set_interface_main()
-- Update movie title and co. if video input change
if not type(input_table['title']) == 'userdata' then return false end
openSub.getFileInfo()
openSub.getMovieInfo()
input_table['title']:set_text(openSub.movie.title or "")
input_table['episodeNumber']:set_text(openSub.movie.episodeNumber or "")
input_table['seasonNumber']:set_text(openSub.movie.seasonNumber or "")
end
function interface_config()
input_table['intLangLab'] = dlg:add_label(lang["int_int_lang"]..':', 1, 1, 1, 1)
input_table['intLangBut'] = dlg:add_button(lang["int_search_transl"], get_available_translations, 2, 1, 1, 1)
input_table['intLang'] = dlg:add_dropdown(3, 1, 1, 1)
dlg:add_label(lang["int_default_lang"]..':', 1, 2, 2, 1)
input_table['default_language'] = dlg:add_dropdown(3, 2, 1, 1)
dlg:add_label(lang["int_dowload_behav"]..':', 1, 3, 2, 1)
input_table['downloadBehaviour'] = dlg:add_dropdown(3, 3, 1, 1)
dlg:add_label(lang["int_display_code"]..':', 1, 4, 0, 1)
input_table['langExt'] = dlg:add_dropdown(3, 4, 1, 1)
dlg:add_label(lang["int_remove_tag"]..':', 1, 5, 0, 1)
input_table['removeTag'] = dlg:add_dropdown(3, 5, 1, 1)
if openSub.conf.dirPath then
if openSub.conf.os == "win" then
dlg :add_label("<a href='file:///"..openSub.conf.dirPath.."'>"..lang["int_vlsub_work_dir"].."</a>", 1, 6, 2, 1)
else
dlg :add_label("<a href='"..openSub.conf.dirPath.."'>"..lang["int_vlsub_work_dir"].."</a>", 1, 6, 2, 1)
end
else
dlg :add_label(lang["int_vlsub_work_dir"], 1, 6, 2, 1)
end
input_table['dir_path'] = dlg:add_text_input(openSub.conf.dirPath, 2, 6, 2, 1)
dlg:add_label(lang["int_os_username"]..':', 1, 7, 0, 1)
input_table['os_username'] = dlg:add_text_input(openSub.option.os_username or "", 2, 7, 2, 1)
dlg:add_label(lang["int_os_password"]..':', 1, 8, 0, 1)
input_table['os_password'] = dlg:add_text_input(openSub.option.os_password or "", 2, 8, 2, 1)
input_table['message'] = nil
input_table['message'] = dlg:add_label(' ', 1, 9, 3, 1)
dlg:add_button(lang["int_cancel"], show_main, 2, 10, 1, 1)
dlg:add_button(lang["int_save"], apply_config, 3, 10, 1, 1)
input_table['langExt']:add_value(lang["int_bool_"..tostring(openSub.option.langExt)], 1)
input_table['langExt']:add_value(lang["int_bool_"..tostring(not openSub.option.langExt)], 2)
input_table['removeTag']:add_value(lang["int_bool_"..tostring(openSub.option.removeTag)], 1)
input_table['removeTag']:add_value(lang["int_bool_"..tostring(not openSub.option.removeTag)], 2)
assoc_select_conf('intLang', 'intLang', openSub.conf.translations_avail, 2)
assoc_select_conf('default_language', 'language', openSub.conf.languages, 2, lang["int_all"])
assoc_select_conf('downloadBehaviour', 'downloadBehaviour', openSub.conf.downloadBehaviours, 1)
end
function interface_help()
local help_html = lang["int_help_mess"]
input_table['help'] = dlg:add_html(help_html, 1, 1, 4, 1)
dlg:add_label(string.rep (" ", 100), 1, 2, 3, 1)
dlg:add_button(lang["int_ok"], show_main, 4, 2, 1, 1)
end
function trigger_menu(dlg_id)
if dlg_id == 1 then
close_dlg()
dlg = vlc.dialog(openSub.conf.useragent)
interface_main()
elseif dlg_id == 2 then
close_dlg()
dlg = vlc.dialog(openSub.conf.useragent..': '..lang["int_configuration"])
interface_config()
elseif dlg_id == 3 then
close_dlg()
dlg = vlc.dialog(openSub.conf.useragent..': '..lang["int_help"])
interface_help()
end
collectgarbage() --~ !important
end
function show_main()
trigger_menu(1)
end
function show_conf()
trigger_menu(2)
end
function show_help()
trigger_menu(3)
end
function close_dlg()
vlc.msg.dbg("[VLSub] Closing dialog")
if dlg ~= nil then
--~ dlg:delete() -- Throw an error
dlg:hide()
end
dlg = nil
input_table = nil
input_table = {}
collectgarbage() --~ !important
end
--[[ Drop down / config association]]--
function assoc_select_conf(select_id, option, conf, ind, default)
-- Helper for i/o interaction betwenn drop down and option list (lang...)
select_conf[select_id] = {cf = conf, opt = option, dflt = default, ind = ind}
set_default_option(select_id)
display_select(select_id)
end
function set_default_option(select_id)
-- Put the selected option of a list in first place of the associated table
local opt = select_conf[select_id].opt
local cfg = select_conf[select_id].cf
local ind = select_conf[select_id].ind
if openSub.option[opt] then
table.sort(cfg, function(a, b)
if a[1] == openSub.option[opt] then
return true
elseif b[1] == openSub.option[opt] then
return false
else
return a[ind] < b[ind]
end
end)
end
end
function display_select(select_id)
-- Display the drop down values with an optionnal default value at the top
local conf = select_conf[select_id].cf
local opt = select_conf[select_id].opt
local option = openSub.option[opt]
local default = select_conf[select_id].dflt
local default_isset = false
if not default then
default_isset = true
end
for k, l in ipairs(conf) do
if default_isset then
input_table[select_id]:add_value(l[2], k)
else
if option then
input_table[select_id]:add_value(l[2], k)
input_table[select_id]:add_value(default, 0)
else
input_table[select_id]:add_value(default, 0)
input_table[select_id]:add_value(l[2], k)
end
default_isset = true
end
end
end
--[[ Config & interface localization]]--
function check_config()
-- Make a copy of english translation to use it as default
-- in case some element aren't translated in other translations
eng_translation = {}
for k, v in pairs(openSub.option.translation) do
eng_translation[k] = v
end
-- Get available translation full name from code
trsl_names = {}
for i, lg in ipairs(languages) do
trsl_names[lg[1]] = lg[2]
end
if is_window_path(vlc.config.datadir()) then
openSub.conf.os = "win"
slash = "\\"
else
openSub.conf.os = "lin"
slash = "/"
end
local path_generic = {"lua", "extensions", "userdata", "vlsub"}
local dirPath = slash..table.concat(path_generic, slash)
local filePath = slash.."vlsub_conf.xml"
local config_saved = false
sub_dir = slash.."vlsub_subtitles"
-- Check if config file path is stored in vlc config
local other_dirs = {}
for path in vlc.config.get("sub-autodetect-path"):gmatch("[^,]+") do
if path:match(".*"..sub_dir.."$") then
openSub.conf.dirPath = path:gsub("%s*(.*)"..sub_dir.."%s*$", "%1")
config_saved = true
end
table.insert(other_dirs, path)
end
-- if not stored in vlc config
-- try to find a suitable config file path
if openSub.conf.dirPath then
if not is_dir(openSub.conf.dirPath) and
(openSub.conf.os == "lin" or
is_win_safe(openSub.conf.dirPath)) then
mkdir_p(openSub.conf.dirPath)
end
else
local userdatadir = vlc.config.userdatadir()
local datadir = vlc.config.datadir()
-- check if the config already exist
if file_exist(userdatadir..dirPath..filePath) then
openSub.conf.dirPath = userdatadir..dirPath
config_saved = true
elseif file_exist(datadir..dirPath..filePath) then
openSub.conf.dirPath = datadir..dirPath
config_saved = true
else
local extension_path = slash..path_generic[1]
..slash..path_generic[2]
-- use the same folder as the extension if accessible
if is_dir(userdatadir..extension_path)
and file_touch(userdatadir..dirPath..filePath) then
openSub.conf.dirPath = userdatadir..dirPath
elseif file_touch(datadir..dirPath..filePath) then
openSub.conf.dirPath = datadir..dirPath
end
-- try to create working dir in user folder
if not openSub.conf.dirPath
and is_dir(userdatadir) then
if not is_dir(userdatadir..dirPath) then
mkdir_p(userdatadir..dirPath)
end
if is_dir(userdatadir..dirPath) and
file_touch(userdatadir..dirPath..filePath) then
openSub.conf.dirPath = userdatadir..dirPath
end
end
-- try to create working dir in vlc folder
if not openSub.conf.dirPath and
is_dir(datadir) then
if not is_dir(datadir..dirPath) then
mkdir_p(datadir..dirPath)
end
if file_touch(datadir..dirPath..filePath) then
openSub.conf.dirPath = datadir..dirPath
end
end
end
end
if openSub.conf.dirPath then
vlc.msg.dbg("[VLSub] Working directory: " ..
(openSub.conf.dirPath or "not found"))
openSub.conf.filePath = openSub.conf.dirPath..filePath
openSub.conf.localePath = openSub.conf.dirPath..slash.."locale"
if config_saved
and file_exist(openSub.conf.filePath) then
vlc.msg.dbg("[VLSub] Loading config file: "..openSub.conf.filePath)
load_config()
else
vlc.msg.dbg("[VLSub] No config file")
getenv_lang()
config_saved = save_config()
if not config_saved then
vlc.msg.dbg("[VLSub] Unable to save config")
end
end
-- Check presence of a translation file in "%vlsub_directory%/locale"
-- Add translation files to available translation list
local file_list = list_dir(openSub.conf.localePath)
local translations_avail = openSub.conf.translations_avail
if file_list then
for i, file_name in ipairs(file_list) do
local lg = string.gsub(file_name, "^(%w%w%w).xml$", "%1")
if lg and not translations_avail[lg] then
table.insert(translations_avail, {lg, trsl_names[lg]})
end
end
end
-- Load selected translation from file
if openSub.option.intLang ~= "eng"
and not openSub.conf.translated
then
local transl_file_path = openSub.conf.localePath..slash..openSub.option.intLang..".xml"
if file_exist(transl_file_path) then
vlc.msg.dbg("[VLSub] Loadin translation from file: " .. transl_file_path)
load_transl(transl_file_path)
end
end
else
vlc.msg.dbg("[VLSub] Unable fount a suitable path to save config, please set it manually")
end
lang = nil
lang = options.translation -- just a shortcut
SetDownloadBehaviours()
if not openSub.conf.dirPath then
setError(lang["mess_err_conf_access"])
end
-- Set table list of available traduction from assoc. array
-- so it is sortable
for k, l in pairs(openSub.option.translations_avail) do
if k == openSub.option.int_research then
table.insert(openSub.conf.translations_avail, 1, {k, l})
else
table.insert(openSub.conf.translations_avail, {k, l})
end
end
collectgarbage()
end
function load_config()
-- Overwrite default conf with loaded conf
local tmpFile = io.open(openSub.conf.filePath, "rb")
if not tmpFile then return false end
local resp = tmpFile:read("*all")
tmpFile:flush()
tmpFile:close()
local option = parse_xml(resp)
for key, value in pairs(option) do
if type(value) == "table" then
if key == "translation" then
openSub.conf.translated = true
for k, v in pairs(value) do
openSub.option.translation[k] = v
end
else
openSub.option[key] = value
end
else
if value == "true" then
openSub.option[key] = true
elseif value == "false" then
openSub.option[key] = false
else
openSub.option[key] = value
end
end
end
collectgarbage()
end
function load_transl(path)
-- Overwrite default conf with loaded conf
local tmpFile = assert(io.open(path, "rb"))
local resp = tmpFile:read("*all")
tmpFile:flush()
tmpFile:close()
openSub.option.translation = nil
openSub.option.translation = parse_xml(resp)
collectgarbage()
end
function apply_translation()
-- Overwrite default conf with loaded conf
for k, v in pairs(eng_translation) do
if not openSub.option.translation[k] then
openSub.option.translation[k] = eng_translation[k]
end
end
end
function getenv_lang()
-- Retrieve the user OS language
local os_lang = os.getenv("LANG")
if os_lang then -- unix, mac
os_lang = string.sub(os_lang, 0, 2)
if type(lang_os_to_iso[os_lang]) then
openSub.option.language = lang_os_to_iso[os_lang]
end
else -- Windows
local lang_w = string.match(os.setlocale("", "collate"), "^[^_]+")
for i, v in ipairs(openSub.conf.languages) do
if v[2] == lang_w then
openSub.option.language = v[1]
end
end
end
end
function apply_config()
-- Apply user config selection to local config
local lg_sel = input_table['intLang']:get_value()
local sel_val
local opt
if lg_sel and lg_sel ~= 1
and openSub.conf.translations_avail[lg_sel] then
local lg = openSub.conf.translations_avail[lg_sel][1]
set_translation(lg)
SetDownloadBehaviours()
end
for select_id, v in pairs(select_conf) do
if input_table[select_id] and select_conf[select_id] then
sel_val = input_table[select_id]:get_value()
opt = select_conf[select_id].opt
if sel_val == 0 then
openSub.option[opt] = nil
else
openSub.option[opt] = select_conf[select_id].cf[sel_val][1]
end
set_default_option(select_id)
end
end
openSub.option.os_username = input_table['os_username']:get_text()
openSub.option.os_password = input_table['os_password']:get_text()
if input_table["langExt"]:get_value() == 2 then
openSub.option.langExt = not openSub.option.langExt
end
if input_table["removeTag"]:get_value() == 2 then
openSub.option.removeTag = not openSub.option.removeTag
end
-- Set a custom working directory
local dir_path = input_table['dir_path']:get_text()
local dir_path_err = false
if trim(dir_path) == "" then dir_path = nil end
if dir_path ~= openSub.conf.dirPath then
if openSub.conf.os == "lin"
or is_win_safe(dir_path)
or not dir_path then
local other_dirs = {}
for path in vlc.config.get("sub-autodetect-path"):gmatch("[^,]+") do
path = trim(path)
if path ~= (openSub.conf.dirPath or "")..sub_dir then
table.insert(other_dirs, path)
end
end
openSub.conf.dirPath = dir_path
if dir_path then
table.insert(other_dirs,
string.gsub(dir_path, "^(.-)[\\/]?$", "%1")..sub_dir)
if not is_dir(dir_path) then
mkdir_p(dir_path)
end
openSub.conf.filePath = openSub.conf.dirPath..slash.."vlsub_conf.xml"
openSub.conf.localePath = openSub.conf.dirPath..slash.."locale"
else
openSub.conf.filePath = nil
openSub.conf.localePath = nil
end
vlc.config.set("sub-autodetect-path", table.concat(other_dirs, ", "))
else
dir_path_err = true
setError(lang["mess_err_wrong_path"].."<br><b>"..string.gsub(dir_path, "[^%:%w%p%s§¤]+", "<span style='color:#B23'>%1</span>").."</b>")
end
end
if openSub.conf.dirPath and
not dir_path_err then
local config_saved = save_config()
trigger_menu(1)
if not config_saved then
setError(lang["mess_err_conf_access"])
end
else
setError(lang["mess_err_conf_access"])
end
end
function save_config()
-- Dump local config into config file
if openSub.conf.dirPath
and openSub.conf.filePath then
vlc.msg.dbg("[VLSub] Saving config file: " .. openSub.conf.filePath)
if file_touch(openSub.conf.filePath) then
local tmpFile = assert(io.open(openSub.conf.filePath, "wb"))
local resp = dump_xml(openSub.option)
tmpFile:write(resp)
tmpFile:flush()
tmpFile:close()
tmpFile = nil
else
return false
end
collectgarbage()
return true
else
vlc.msg.dbg("[VLSub] Unable fount a suitable path to save config, please set it manually")
setError(lang["mess_err_conf_access"])
return false
end
end
function SetDownloadBehaviours()
openSub.conf.downloadBehaviours = nil
openSub.conf.downloadBehaviours = {
{'save', lang["int_dowload_save"]},
{'load', lang["int_dowload_load"]},
{'manual', lang["int_dowload_manual"]}
}
end
function get_available_translations()
-- Get all available translation files from the internet
-- (drop previous direct download from github repo because of problem with github https CA certficate on OS X an XP)
-- https://github.com/exebetche/vlsub/tree/master/locale
local translations_url = "http://addons.videolan.org/CONTENT/content-files/148752-vlsub_translations.xml"
if input_table['intLangBut']:get_text() == lang["int_search_transl"] then
openSub.actionLabel = lang["int_searching_transl"]
local translations_content, lol = get(translations_url)
all_trsl = parse_xml(translations_content)
local lg, trsl
for lg, trsl in pairs(all_trsl) do
if lg ~= options.intLang[1] and not openSub.option.translations_avail[lg] then
openSub.option.translations_avail[lg] = trsl_names[lg] or ""
table.insert(openSub.conf.translations_avail, {lg, trsl_names[lg]})
input_table['intLang']:add_value(trsl_names[lg], #openSub.conf.translations_avail)
end
end
setMessage(success_tag(lang["mess_complete"]))
collectgarbage()
end
end
function set_translation(lg)
openSub.option.translation = nil
openSub.option.translation = {}
if lg == 'eng' then
for k, v in pairs(eng_translation) do
openSub.option.translation[k] = v
end
else
-- If translation file exists in /locale directory load it
if openSub.conf.localePath
and file_exist(openSub.conf.localePath..slash..lg..".xml") then
local transl_file_path = openSub.conf.localePath..slash..lg..".xml"
vlc.msg.dbg("[VLSub] Loading translation from file: " .. transl_file_path)
load_transl(transl_file_path)
apply_translation()
else
-- Load translation file from internet
if not all_trsl then
get_available_translations()
end
if not all_trsl or not all_trsl[lg] then
vlc.msg.dbg("[VLSub] Error, translation not found")
return false
end
openSub.option.translation = all_trsl[lg]
apply_translation()
all_trsl = nil
end
end
lang = nil
lang = openSub.option.translation
collectgarbage()
end
--[[ Core ]]--
openSub = {
itemStore = nil,
actionLabel = "",
conf = {
url = "http://api.opensubtitles.org/xml-rpc",
path = nil,
userAgentHTTP = "VLSub",
useragent = "VLSub 0.9",
translations_avail = {},
downloadBehaviours = nil,
languages = languages
},
option = options,
session = {
loginTime = 0,
token = ""
},
file = {
hasInput = false,
uri = nil,
ext = nil,
name = nil,
path = nil,
protocol = nil,
cleanName = nil,
dir = nil,
hash = nil,
bytesize = nil,
fps = nil,
timems = nil,
frames = nil
},
movie = {
title = "",
seasonNumber = "",
episodeNumber = "",
sublanguageid = ""
},
request = function(methodName)
local params = openSub.methods[methodName].params()
local reqTable = openSub.getMethodBase(methodName, params)
local request = "<?xml version='1.0'?>"..dump_xml(reqTable)
local host, path = parse_url(openSub.conf.url)
local header = {
"POST "..path.." HTTP/1.1",
"Host: "..host,
"User-Agent: "..openSub.conf.userAgentHTTP,
"Content-Type: text/xml",
"Content-Length: "..string.len(request),
"",
""
}
request = table.concat(header, "\r\n")..request
local response
local status, responseStr = http_req(host, 80, request)
if status == 200 then
response = parse_xmlrpc(responseStr)
if response then
if response.status == "200 OK" then
return openSub.methods[methodName].callback(response)
elseif response.status == "406 No session" then
openSub.request("LogIn")
elseif response then
setError("code '"..response.status.."' ("..status..")")
return false
end
else
setError("Server not responding")
return false
end
elseif status == 401 then
setError("Request unauthorized")
response = parse_xmlrpc(responseStr)
if openSub.session.token ~= response.token then
setMessage("Session expired, retrying")
openSub.session.token = response.token
openSub.request(methodName)
end
return false
elseif status == 503 then
setError("Server overloaded, please retry later")
return false
end
end,
getMethodBase = function(methodName, param)
if openSub.methods[methodName].methodName then
methodName = openSub.methods[methodName].methodName
end
local request = {
methodCall={
methodName=methodName,
params={ param=param }}}
return request
end,
methods = {
LogIn = {
params = function()
openSub.actionLabel = lang["action_login"]
return {
{ value={ string=openSub.option.os_username } },
{ value={ string=openSub.option.os_password } },
{ value={ string=openSub.movie.sublanguageid } },
{ value={ string=openSub.conf.useragent } }
}
end,
callback = function(resp)
openSub.session.token = resp.token
openSub.session.loginTime = os.time()
return true
end
},
LogOut = {
params = function()
openSub.actionLabel = lang["action_logout"]
return {
{ value={ string=openSub.session.token } }
}
end,
callback = function()
return true
end
},
NoOperation = {
params = function()
openSub.actionLabel = lang["action_noop"]
return {
{ value={ string=openSub.session.token } }
}
end,
callback = function(resp)
return true
end
},
SearchSubtitlesByHash = {
methodName = "SearchSubtitles",
params = function()
openSub.actionLabel = lang["action_search"]
setMessage(openSub.actionLabel..": "..progressBarContent(0))
return {
{ value={ string=openSub.session.token } },
{ value={
array={
data={
value={
struct={
member={
{ name="sublanguageid", value={
string=openSub.movie.sublanguageid } },
{ name="moviehash", value={
string=openSub.file.hash } },
{ name="moviebytesize", value={
double=openSub.file.bytesize } } }}}}}}}
}
end,
callback = function(resp)
openSub.itemStore = resp.data
end
},
SearchSubtitles = {
methodName = "SearchSubtitles",
params = function()
openSub.actionLabel = lang["action_search"]
setMessage(openSub.actionLabel..": "..progressBarContent(0))
local member = {
{ name="sublanguageid", value={
string=openSub.movie.sublanguageid } },
{ name="query", value={
string=openSub.movie.title } } }
if openSub.movie.seasonNumber ~= nil then
table.insert(member, { name="season", value={
string=openSub.movie.seasonNumber } })
end
if openSub.movie.episodeNumber ~= nil then
table.insert(member, { name="episode", value={
string=openSub.movie.episodeNumber } })
end
return {
{ value={ string=openSub.session.token } },
{ value={
array={
data={
value={
struct={
member=member
}}}}}}
}
end,
callback = function(resp)
openSub.itemStore = resp.data
end
}
},
getInputItem = function()
return vlc.item or vlc.input.item()
end,
getFileInfo = function()
-- Get video file path, name, extension from input uri
local item = openSub.getInputItem()
local file = openSub.file
if not item then
file.hasInput = false;
file.cleanName = nil;
file.protocol = nil;
file.path = nil;
file.ext = nil;
file.uri = nil;
else
vlc.msg.dbg("[VLSub] Video URI: "..item:uri())
local parsed_uri = vlc.net.url_parse(item:uri())
file.uri = item:uri()
file.protocol = parsed_uri["protocol"]
file.path = parsed_uri["path"]
-- Corrections
-- For windows
file.path = string.match(file.path, "^/(%a:/.+)$") or file.path
-- For file in archive
local archive_path, name_in_archive = string.match(file.path, '^([^!]+)!/([^!/]*)$')
if archive_path and archive_path ~= "" then
file.path = string.gsub(archive_path, '\063', '%%')
file.path = vlc.strings.decode_uri(file.path)
file.completeName = string.gsub(name_in_archive, '\063', '%%')
file.completeName = vlc.strings.decode_uri(file.completeName)
file.is_archive = true
else -- "classic" input
file.path = vlc.strings.decode_uri(file.path)
file.dir, file.completeName = string.match(file.path, '^(.+/)([^/]*)$')
local file_stat = vlc.net.stat(file.path)
if file_stat
then
file.stat = file_stat
end
file.is_archive = false
end
file.name, file.ext = string.match(file.completeName, '^([^/]-)%.?([^%.]*)$')
if file.ext == "part" then
file.name, file.ext = string.match(file.name, '^([^/]+)%.([^%.]+)$')
end
file.hasInput = true;
file.cleanName = string.gsub(file.name, "[%._]", " ")
vlc.msg.dbg("[VLSub] file info "..(dump_xml(file)))
end
collectgarbage()
end,
getMovieInfo = function()
-- Clean video file name and check for season/episode pattern in title
if not openSub.file.name then
openSub.movie.title = ""
openSub.movie.seasonNumber = ""
openSub.movie.episodeNumber = ""
return false
end
local showName, seasonNumber, episodeNumber = string.match(openSub.file.cleanName, "(.+)[sS](%d%d)[eE](%d%d).*")
if not showName then
showName, seasonNumber, episodeNumber = string.match(openSub.file.cleanName, "(.+)(%d)[xX](%d%d).*")
end
if showName then
openSub.movie.title = showName
openSub.movie.seasonNumber = seasonNumber
openSub.movie.episodeNumber = episodeNumber
else
openSub.movie.title = openSub.file.cleanName
openSub.movie.seasonNumber = ""
openSub.movie.episodeNumber = ""
end
collectgarbage()
end,
getMovieHash = function()
-- Calculate movie hash
openSub.actionLabel = lang["action_hash"]
setMessage(openSub.actionLabel..": "..progressBarContent(0))
local item = openSub.getInputItem()
if not item then
setError(lang["mess_no_input"])
return false
end
openSub.getFileInfo()
if not openSub.file.path then
setError(lang["mess_not_found"])
return false
end
local data_start = ""
local data_end = ""
local size
local chunk_size = 65536
-- Get data for hash calculation
if openSub.file.is_archive then
vlc.msg.dbg("[VLSub] Read hash data from stream")
local file = vlc.stream(openSub.file.uri)
local dataTmp1 = ""
local dataTmp2 = ""
size = chunk_size
data_start = file:read(chunk_size)
while data_end do
size = size + string.len(data_end)
dataTmp1 = dataTmp2
dataTmp2 = data_end
data_end = file:read(chunk_size)
collectgarbage()
end
data_end = string.sub((dataTmp1..dataTmp2), -chunk_size)
elseif not file_exist(openSub.file.path)
and openSub.file.stat then
vlc.msg.dbg("[VLSub] Read hash data from stream")
local file = vlc.stream(openSub.file.uri)
if not file then
vlc.msg.dbg("[VLSub] No stream")
return false
end
size = openSub.file.stat.size
local decal = size%chunk_size
data_start = file:read(chunk_size)
-- "Seek" to the end
file:read(decal)
for i = 1, math.floor(((size-decal)/chunk_size))-2 do
file:read(chunk_size)
end
data_end = file:read(chunk_size)
file = nil
else
vlc.msg.dbg("[VLSub] Read hash data from file")
local file = io.open( openSub.file.path, "rb")
if not file then
vlc.msg.dbg("[VLSub] No stream")
return false
end
data_start = file:read(chunk_size)
size = file:seek("end", -chunk_size) + chunk_size
data_end = file:read(chunk_size)
file = nil
end
-- Hash calculation
local lo = size
local hi = 0
local o,a,b,c,d,e,f,g,h
local hash_data = data_start..data_end
local max_size = 4294967296
local overflow
for i = 1, #hash_data, 8 do
a,b,c,d,e,f,g,h = hash_data:byte(i,i+7)
lo = lo + a + b*256 + c*65536 + d*16777216
hi = hi + e + f*256 + g*65536 + h*16777216
if lo > max_size then
overflow = math.floor(lo/max_size)
lo = lo-(overflow*max_size)
hi = hi+overflow
end
if hi > max_size then
overflow = math.floor(hi/max_size)
hi = hi-(overflow*max_size)
end
end
openSub.file.bytesize = size
openSub.file.hash = string.format("%08x%08x", hi,lo)
vlc.msg.dbg("[VLSub] Video hash: "..openSub.file.hash)
vlc.msg.dbg("[VLSub] Video bytesize: "..size)
collectgarbage()
return true
end,
checkSession = function()
if openSub.session.token == "" then
openSub.request("LogIn")
else
openSub.request("NoOperation")
end
end
}
function searchHash()
local sel = input_table["language"]:get_value()
if sel == 0 then
openSub.movie.sublanguageid = 'all'
else
openSub.movie.sublanguageid = openSub.conf.languages[sel][1]
end
openSub.getMovieHash()
if openSub.file.hash then
openSub.checkSession()
openSub.request("SearchSubtitlesByHash")
display_subtitles()
end
end
function searchIMBD()
openSub.movie.title = trim(input_table["title"]:get_text())
openSub.movie.seasonNumber = tonumber(input_table["seasonNumber"]:get_text())
openSub.movie.episodeNumber = tonumber(input_table["episodeNumber"]:get_text())
local sel = input_table["language"]:get_value()
if sel == 0 then
openSub.movie.sublanguageid = 'all'
else
openSub.movie.sublanguageid = openSub.conf.languages[sel][1]
end
if openSub.movie.title ~= "" then
openSub.checkSession()
openSub.request("SearchSubtitles")
display_subtitles()
end
end
function display_subtitles()
local mainlist = input_table["mainlist"]
mainlist:clear()
if openSub.itemStore == "0" then
mainlist:add_value(lang["mess_no_res"], 1)
setMessage("<b>"..lang["mess_complete"]..":</b> "..lang["mess_no_res"])
elseif openSub.itemStore then
for i, item in ipairs(openSub.itemStore) do
mainlist:add_value(
item.SubFileName..
" ["..item.SubLanguageID.."]"..
" ("..item.SubSumCD.." CD)", i)
end
setMessage("<b>"..lang["mess_complete"]..":</b> "..#(openSub.itemStore).." "..lang["mess_res"])
end
end
function get_first_sel(list)
local selection = list:get_selection()
for index, name in pairs(selection) do
return index
end
return 0
end
function download_subtitles()
local index = get_first_sel(input_table["mainlist"])
if index == 0 then
setMessage(lang["mess_no_selection"])
return false
end
openSub.actionLabel = lang["mess_downloading"]
display_subtitles() -- reset selection
local item = openSub.itemStore[index]
if openSub.option.downloadBehaviour == 'manual' then
local link = "<span style='color:#181'>"
link = link.."<b>"..lang["mess_dowload_link"]..":</b>"
link = link.."</span> "
link = link.."</span> <a href='"..item.ZipDownloadLink.."'>"
link = link..item.MovieReleaseName.."</a>"
setMessage(link)
return false
elseif openSub.option.downloadBehaviour == 'load' then
if add_sub("zip://"..item.ZipDownloadLink.."!/"..item.SubFileName) then
setMessage(success_tag(lang["mess_loaded"]))
end
return false
end
local message = ""
local subfileName = openSub.file.name
if openSub.option.langExt then
subfileName = subfileName.."."..item.SubLanguageID
end
subfileName = subfileName.."."..item.SubFormat
local tmp_dir
local file_target_access = true
if is_dir(openSub.file.dir) then
tmp_dir = openSub.file.dir
elseif openSub.conf.dirPath then
tmp_dir = openSub.conf.dirPath
message = "<br> "..error_tag(lang["mess_save_fail"].." "..
"<a href='"..vlc.strings.make_uri(openSub.conf.dirPath).."'>"..
lang["mess_click_link"].."</a>")
else
setError(lang["mess_save_fail"].." "..
"<a href='"..item.ZipDownloadLink.."'>"..
lang["mess_click_link"].."</a>")
return false
end
local tmpFileURI, tmpFileName = dump_zip(
item.ZipDownloadLink,
tmp_dir,
item.SubFileName)
vlc.msg.dbg("[VLsub] tmpFileName: "..tmpFileName)
-- Determine if the path to the video file is accessible for writing
local target = openSub.file.dir..subfileName
if not file_touch(target) then
if openSub.conf.dirPath then
target = openSub.conf.dirPath..slash..subfileName
message = "<br> "..error_tag(lang["mess_save_fail"].." "..
"<a href='"..vlc.strings.make_uri(openSub.conf.dirPath).."'>"..
lang["mess_click_link"].."</a>")
else
setError(lang["mess_save_fail"].." "..
"<a href='"..item.ZipDownloadLink.."'>"..
lang["mess_click_link"].."</a>")
return false
end
end
vlc.msg.dbg("[VLsub] Subtitles files: "..target)
-- Unzipped data into file target
local stream = vlc.stream(tmpFileURI)
local data = ""
local subfile = io.open(target, "wb")
while data do
subfile:write(data)
data = stream:read(65536)
end
subfile:flush()
subfile:close()
stream = nil
collectgarbage()
if not os.remove(tmpFileName) then
vlc.msg.err("[VLsub] Unable to remove temp: "..tmpFileName)
end
subfileURI = vlc.strings.make_uri(target)
if not subfileURI then
subfileURI = make_uri(target, true)
end
-- load subtitles
if add_sub(subfileURI) then
message = success_tag(lang["mess_loaded"]) .. message
end
setMessage(message)
end
function dump_zip(url, dir, subfileName)
-- Dump zipped data in a temporary file
setMessage(openSub.actionLabel..": "..progressBarContent(0))
local resp = get(url)
if not resp then
setError(lang["mess_no_response"])
return false
end
local tmpFileName = dir..slash..subfileName..".gz"
if not file_touch(tmpFileName) then
return false
end
local tmpFile = assert(io.open(tmpFileName, "wb"))
tmpFile:write(resp)
tmpFile:flush()
tmpFile:close()
tmpFile = nil
collectgarbage()
return "zip://"..make_uri(tmpFileName, true).."!/"..subfileName, tmpFileName
end
function add_sub(subfileURI)
if vlc.item or vlc.input.item() then
vlc.msg.dbg("[VLsub] Adding subtitle :" .. subfileURI)
return vlc.input.add_subtitle(subfileURI)
end
return false
end
--[[ Interface helpers]]--
function progressBarContent(pct)
local accomplished = math.ceil(openSub.option.progressBarSize*pct/100)
local left = openSub.option.progressBarSize - accomplished
local content = "<span style='background-color:#181;color:#181;'>"..
string.rep ("-", accomplished).."</span>"..
"<span style='background-color:#fff;color:#fff;'>"..
string.rep ("-", left)..
"</span>"
return content
end
function setMessage(str)
if input_table["message"] then
input_table["message"]:set_text(str)
dlg:update()
end
end
function setError(mess)
setMessage(error_tag(mess))
end
function success_tag(str)
return "<span style='color:#181'><b>"..
lang["mess_success"]..":</b></span> "..str..""
end
function error_tag(str)
return "<span style='color:#B23'><b>"..
lang["mess_error"]..":</b></span> "..str..""
end
--[[ Network utils]]--
function get(url)
local host, path = parse_url(url)
local header = {
"GET "..path.." HTTP/1.1",
"Host: "..host,
"User-Agent: "..openSub.conf.userAgentHTTP,
"",
""
}
local request = table.concat(header, "\r\n")
local response
local status, response = http_req(host, 80, request)
if status == 200 then
return response
else
return false, status, response
end
end
function http_req(host, port, request)
local fd = vlc.net.connect_tcp(host, port)
if not fd then return false end
local pollfds = {}
pollfds[fd] = vlc.net.POLLIN
vlc.net.send(fd, request)
vlc.net.poll(pollfds)
local response = vlc.net.recv(fd, 1024)
local headerStr, body = string.match(response, "(.-\r?\n)\r?\n(.*)")
local header = parse_header(headerStr)
local contentLength = tonumber(header["Content-Length"])
local TransferEncoding = header["Transfer-Encoding"]
local status = tonumber(header["statuscode"])
local bodyLenght = string.len(body)
local pct = 0
--~ if status ~= 200 then return status end
while contentLength and bodyLenght < contentLength do
vlc.net.poll(pollfds)
response = vlc.net.recv(fd, 1024)
if response then
body = body..response
else
vlc.net.close(fd)
return false
end
bodyLenght = string.len(body)
pct = bodyLenght / contentLength * 100
setMessage(openSub.actionLabel..": "..progressBarContent(pct))
end
vlc.net.close(fd)
return status, body
end
function parse_header(data)
local header = {}
for name, s, val in string.gfind(data, "([^%s:]+)(:?)%s([^\n]+)\r?\n") do
if s == "" then header['statuscode'] = tonumber(string.sub (val, 1 , 3))
else header[name] = val end
end
return header
end
function parse_url(url)
local url_parsed = vlc.net.url_parse(url)
return url_parsed["host"], url_parsed["path"], url_parsed["option"]
end
--[[ XML utils]]--
function parse_xml(data)
local tree = {}
local stack = {}
local tmp = {}
local level = 0
local op, tag, p, empty, val
table.insert(stack, tree)
for op, tag, p, empty, val in string.gmatch(
data,
"[%s\r\n\t]*<(%/?)([%w:_]+)(.-)(%/?)>[%s\r\n\t]*([^<]*)[%s\r\n\t]*"
) do
if op=="/" then
if level>0 then
level = level - 1
table.remove(stack)
end
else
level = level + 1
if val == "" then
if type(stack[level][tag]) == "nil" then
stack[level][tag] = {}
table.insert(stack, stack[level][tag])
else
if type(stack[level][tag][1]) == "nil" then
tmp = nil
tmp = stack[level][tag]
stack[level][tag] = nil
stack[level][tag] = {}
table.insert(stack[level][tag], tmp)
end
tmp = nil
tmp = {}
table.insert(stack[level][tag], tmp)
table.insert(stack, tmp)
end
else
if type(stack[level][tag]) == "nil" then
stack[level][tag] = {}
end
stack[level][tag] = vlc.strings.resolve_xml_special_chars(val)
table.insert(stack, {})
end
if empty ~= "" then
stack[level][tag] = ""
level = level - 1
table.remove(stack)
end
end
end
collectgarbage()
return tree
end
function parse_xmlrpc(data)
local tree = {}
local stack = {}
local tmp = {}
local tmpTag = ""
local level = 0
local op, tag, p, empty, val
table.insert(stack, tree)
for op, tag, p, empty, val in string.gmatch(
data,
"<(%/?)([%w:]+)(.-)(%/?)>[%s\r\n\t]*([^<]*)"
) do
if op=="/" then
if tag == "member" or tag == "array" then
if level>0 then
level = level - 1
table.remove(stack)
end
end
elseif tag == "name" then
level = level + 1
if val~= "" then tmpTag = vlc.strings.resolve_xml_special_chars(val) end
if type(stack[level][tmpTag]) == "nil" then
stack[level][tmpTag] = {}
table.insert(stack, stack[level][tmpTag])
else
tmp = nil
tmp = {}
table.insert(stack[level-1], tmp)
stack[level] = nil
stack[level] = tmp
table.insert(stack, tmp)
end
if empty ~= "" then
level = level - 1
stack[level][tmpTag] = ""
table.remove(stack)
end
elseif tag == "array" then
level = level + 1
tmp = nil
tmp = {}
table.insert(stack[level], tmp)
table.insert(stack, tmp)
elseif val ~= "" then
stack[level][tmpTag] = vlc.strings.resolve_xml_special_chars(val)
end
end
collectgarbage()
return tree
end
function dump_xml(data)
local level = 0
local stack = {}
local dump = ""
local function parse(data, stack)
local data_index = {}
local k
local v
local i
local tb
for k,v in pairs(data) do
table.insert(data_index, {k, v})
table.sort(data_index, function(a, b)
return a[1] < b[1]
end)
end
for i,tb in pairs(data_index) do
k = tb[1]
v = tb[2]
if type(k)=="string" then
dump = dump.."\r\n"..string.rep (" ", level).."<"..k..">"
table.insert(stack, k)
level = level + 1
elseif type(k)=="number" and k ~= 1 then
dump = dump.."\r\n"..string.rep (" ", level-1).."<"..stack[level]..">"
end
if type(v)=="table" then
parse(v, stack)
elseif type(v)=="string" then
dump = dump..(vlc.strings.convert_xml_special_chars(v) or v)
elseif type(v)=="number" then
dump = dump..v
else
dump = dump..tostring(v)
end
if type(k)=="string" then
if type(v)=="table" then
dump = dump.."\r\n"..string.rep (" ", level-1).."</"..k..">"
else
dump = dump.."</"..k..">"
end
table.remove(stack)
level = level - 1
elseif type(k)=="number" and k ~= #data then
if type(v)=="table" then
dump = dump.."\r\n"..string.rep (" ", level-1).."</"..stack[level]..">"
else
dump = dump.."</"..stack[level]..">"
end
end
end
end
parse(data, stack)
collectgarbage()
return dump
end
--[[ Misc utils]]--
function make_uri(str, encode)
local windowdrive = string.match(str, "^(%a:%).+$")
if encode then
local encodedPath = ""
for w in string.gmatch(str, "/([^/]+)") do
encodedPath = encodedPath.."/"..vlc.strings.encode_uri_component(w)
end
str = encodedPath
end
if windowdrive then
return "file:///"..windowdrive..str
else
return "file://"..str
end
end
function file_touch(name) -- test writetability
if not name or trim(name) == ""
then return false end
local f=io.open(name ,"w")
if f~=nil then
io.close(f)
return true
else
return false
end
end
function file_exist(name) -- test readability
if not name or trim(name) == ""
then return false end
local f=io.open(name ,"r")
if f~=nil then
io.close(f)
return true
else
return false
end
end
function is_dir(path)
if not path or trim(path) == ""
then return false end
-- Remove slash at the or it won't work on Windows
path = string.gsub(path, "^(.-)[\\/]?$", "%1")
local f, _, code = io.open(path, "rb")
if f then
_, _, code = f:read("*a")
f:close()
if code == 21 then
return true
end
elseif code == 13 then
return true
end
return false
end
function list_dir(path)
if not path or trim(path) == ""
then return false end
local dir_list_cmd
local list = {}
if not is_dir(path) then return false end
if openSub.conf.os == "win" then
dir_list_cmd = io.popen('dir /b "'..path..'"')
elseif openSub.conf.os == "lin" then
dir_list_cmd = io.popen('ls -1 "'..path..'"')
end
if dir_list_cmd then
for filename in dir_list_cmd:lines() do
if string.match(filename, "^[^%s]+.+$") then
table.insert(list, filename)
end
end
return list
else
return false
end
end
function mkdir_p(path)
if not path or trim(path) == ""
then return false end
if openSub.conf.os == "win" then
os.execute('mkdir "' .. path..'"')
elseif openSub.conf.os == "lin" then
os.execute("mkdir -p '" .. path.."'")
end
end
function is_window_path(path)
return string.match(path, "^(%a:%).+$")
end
function is_win_safe(path)
if not path or trim(path) == ""
or not is_window_path(path)
then return false end
return string.match(path, "^%a?%:?[\\%w%p%s§¤]+$")
end
function trim(str)
if not str then return "" end
return string.gsub(str, "^[\r\n%s]*(.-)[\r\n%s]*$", "%1")
end
function remove_tag(str)
return string.gsub(str, "{[^}]+}", "")
end
function sleep(sec)
local t = vlc.misc.mdate()
vlc.misc.mwait(t + sec*1000*1000)
end
| gpl-2.0 |
Zero-K-Experiments/Zero-K-Experiments | units/panther.lua | 3 | 4934 | unitDef = {
unitname = [[panther]],
name = [[Panther]],
description = [[Lightning Assault/Raider Tank]],
acceleration = 0.125,
brakeRate = 0.1375,
buildCostEnergy = 300,
buildCostMetal = 300,
builder = false,
buildPic = [[panther.png]],
buildTime = 300,
canAttack = true,
canGuard = true,
canMove = true,
canPatrol = true,
canstop = [[1]],
category = [[LAND]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[28 12 28]],
collisionVolumeType = [[box]],
corpse = [[DEAD]],
customParams = {
description_fr = [[Tank Pilleur]],
description_de = [[Blitzschlag Raider Panzer]],
helptext = [[The Panther is a high-tech raider. Its weapon, a lightning gun, deals mostly paralyze damage. This way, the Panther can disable turrets, waltz through the defensive line, and proceed to level the economic heart of the opponent's base. When killed, it sets off an EMP explosion that can stun surrounding raiders.]],
helptext_fr = [[Le Panther est un pilleur high-tech. Son canon principal sert ? paralyser l'ennemi, lui permettant de traverser les d?fenses afin de s'attaquer au coeur ?conomique d'une base]],
helptext_de = [[Der Panther ist ein hoch entwickelter Raider, dessen Waffe, eine Blitzkanone, hauptsächlich paralysierenden Schaden austeilt. Auf diesem Wege kann der Panther Türme ausschalten und sich so durch die feindlichen Verteidigungslinien walzen, bis zur Egalisierung der feindlichen, ökonimischen Grundversorgung.]],
modelradius = [[10]],
stats_show_death_explosion = 1,
},
explodeAs = [[PANTHER_DEATH]],
footprintX = 3,
footprintZ = 3,
iconType = [[tankraider]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 1100,
maxSlope = 18,
maxVelocity = 3.4,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[TANK3]],
noAutoFire = false,
noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE SUB]],
objectName = [[corseal.s3o]],
script = [[panther.lua]],
seismicSignature = 4,
selfDestructAs = [[PANTHER_DEATH]],
sfxtypes = {
explosiongenerators = {
[[custom:PANTHER_SPARK]],
},
},
sightDistance = 450,
trackOffset = 6,
trackStrength = 5,
trackStretch = 1,
trackType = [[StdTank]],
trackWidth = 30,
turninplace = 0,
turnRate = 616,
workerTime = 0,
weapons = {
{
def = [[ARMLATNK_WEAPON]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
},
weaponDefs = {
ARMLATNK_WEAPON = {
name = [[Lightning Gun]],
areaOfEffect = 8,
craterBoost = 0,
craterMult = 0,
customParams = {
extra_damage = [[190]],
light_camera_height = 1600,
light_color = [[0.85 0.85 1.2]],
light_radius = 180,
},
cylinderTargeting = 0,
damage = {
default = 500,
empresistant75 = 125,
empresistant99 = 5,
},
duration = 10,
explosionGenerator = [[custom:LIGHTNINGPLOSION]],
fireStarter = 150,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0,
intensity = 12,
interceptedByShieldType = 1,
paralyzer = true,
paralyzeTime = 1,
range = 260,
reloadtime = 3,
rgbColor = [[0.5 0.5 1]],
soundStart = [[weapon/more_lightning_fast]],
soundTrigger = true,
texture1 = [[lightning]],
thickness = 10,
turret = true,
weaponType = [[LightningCannon]],
weaponVelocity = 400,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[corseal_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2c.s3o]],
},
},
}
return lowerkeys({ panther = unitDef })
| gpl-2.0 |
Kyklas/luci-proto-hso | applications/luci-statistics/luasrc/statistics/rrdtool/definitions/processes.lua | 78 | 2188 | --[[
Luci statistics - processes plugin diagram definition
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
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
$Id$
]]--
module("luci.statistics.rrdtool.definitions.processes", package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
return {
{
title = "%H: Processes",
vlabel = "Processes/s",
data = {
instances = {
ps_state = {
"sleeping", "running", "paging", "blocked", "stopped", "zombies"
}
},
options = {
ps_state_sleeping = { color = "0000ff" },
ps_state_running = { color = "008000" },
ps_state_paging = { color = "ffff00" },
ps_state_blocked = { color = "ff5000" },
ps_state_stopped = { color = "555555" },
ps_state_zombies = { color = "ff0000" }
}
}
},
{
title = "%H: CPU time used by %pi",
vlabel = "Jiffies",
data = {
sources = {
ps_cputime = { "syst", "user" }
},
options = {
ps_cputime__user = {
color = "0000ff",
overlay = true
},
ps_cputime__syst = {
color = "ff0000",
overlay = true
}
}
}
},
{
title = "%H: Threads and processes belonging to %pi",
vlabel = "Count",
detail = true,
data = {
sources = {
ps_count = { "threads", "processes" }
},
options = {
ps_count__threads = { color = "00ff00" },
ps_count__processes = { color = "0000bb" }
}
}
},
{
title = "%H: Page faults in %pi",
vlabel = "Pagefaults",
detail = true,
data = {
sources = {
ps_pagefaults = { "minflt", "majflt" }
},
options = {
ps_pagefaults__minflt = { color = "ff0000" },
ps_pagefaults__majflt = { color = "ff5500" }
}
}
},
{
title = "%H: Virtual memory size of %pi",
vlabel = "Bytes",
detail = true,
number_format = "%5.1lf%sB",
data = {
types = { "ps_rss" },
options = {
ps_rss = { color = "0000ff" }
}
}
}
}
end
| apache-2.0 |
Scavenge/darkstar | scripts/zones/Chateau_dOraguille/npcs/Mistaravant.lua | 14 | 1062 | -----------------------------------
-- Area: Chateau d'Oraguille
-- NPC: Mistaravant
-- Type: Standard NPC
-- @zone 233
-- @pos 7.097 -3.999 67.988
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x020c);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Kyklas/luci-proto-hso | modules/admin-mini/luasrc/model/cbi/mini/dhcp.lua | 82 | 2998 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
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
$Id$
]]--
local uci = require "luci.model.uci".cursor()
local sys = require "luci.sys"
local wa = require "luci.tools.webadmin"
local fs = require "nixio.fs"
m = Map("dhcp", "DHCP")
s = m:section(TypedSection, "dhcp", "DHCP-Server")
s.anonymous = true
s.addremove = false
s.dynamic = false
s:depends("interface", "lan")
enable = s:option(ListValue, "ignore", translate("enable"), "")
enable:value(0, translate("enable"))
enable:value(1, translate("disable"))
start = s:option(Value, "start", translate("First leased address"))
start.rmempty = true
start:depends("ignore", "0")
limit = s:option(Value, "limit", translate("Number of leased addresses"), "")
limit:depends("ignore", "0")
function limit.cfgvalue(self, section)
local value = Value.cfgvalue(self, section)
if value then
return tonumber(value) + 1
end
end
function limit.write(self, section, value)
value = tonumber(value) - 1
return Value.write(self, section, value)
end
limit.rmempty = true
time = s:option(Value, "leasetime")
time:depends("ignore", "0")
time.rmempty = true
local leasefn, leasefp, leases
uci:foreach("dhcp", "dnsmasq",
function(section)
leasefn = section.leasefile
end
)
local leasefp = leasefn and fs.access(leasefn) and io.lines(leasefn)
if leasefp then
leases = {}
for lease in leasefp do
table.insert(leases, luci.util.split(lease, " "))
end
end
if leases then
v = m:section(Table, leases, translate("Active Leases"))
name = v:option(DummyValue, 4, translate("Hostname"))
function name.cfgvalue(self, ...)
local value = DummyValue.cfgvalue(self, ...)
return (value == "*") and "?" or value
end
ip = v:option(DummyValue, 3, translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
mac = v:option(DummyValue, 2, translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"))
ltime = v:option(DummyValue, 1, translate("Leasetime remaining"))
function ltime.cfgvalue(self, ...)
local value = DummyValue.cfgvalue(self, ...)
return wa.date_format(os.difftime(tonumber(value), os.time()))
end
end
s2 = m:section(TypedSection, "host", translate("Static Leases"))
s2.addremove = true
s2.anonymous = true
s2.template = "cbi/tblsection"
name = s2:option(Value, "name", translate("Hostname"))
mac = s2:option(Value, "mac", translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"))
ip = s2:option(Value, "ip", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
sys.net.arptable(function(entry)
ip:value(entry["IP address"])
mac:value(
entry["HW address"],
entry["HW address"] .. " (" .. entry["IP address"] .. ")"
)
end)
return m
| apache-2.0 |
Zero-K-Experiments/Zero-K-Experiments | LuaRules/Gadgets/CAI/xponenUnitCluster.lua | 9 | 4397 |
local UnitListHandler = VFS.Include("LuaRules/Gadgets/CAI/UnitListHandler.lua")
local xponenUnitCluster = {}
function xponenUnitCluster.CreateUnitCluster(static)
local unitList = UnitListHandler.CreateUnitList(static)
local clusterInitialized, clusterExtracted = false,false
local clusterFeed_UnitPos = {}
local clusterRaw_Objects = {}
local clusterList_UnitIDs = {}
local clusterNoiseList_UnitIDs = {}
local clusterCircle_Pos = {}
local function UpdateClustering(minimumUnitCount,maximumConnectionDistance)
-- This local function translate unit position into an ordered objects than hint a clustering information,
-- big "maximumConnectionDistance" allow multiple cluster 'view' to be created later for wide range of connection distance with almost no cost at all,
-- however big "maximumConnectionDistance" will increase code running time significantly because each iteration will loop over bigger number of neighbor.
-- Honestly, a 600 TIGHTLY PACKED unit will cause the code to loop over every unit for each unit, test shows that it can run for 1.93 second (bad!).
-- Its advised to not use big value for "maximumConnectionDistance" to avoid above situation. (Worse case is experimented using widget version)
for unitID,_ in unitList.Iterator() do
local x,_,z = unitList.GetUnitPosition(unitID)
local y = 0
clusterFeed_UnitPos[unitID] = {x,y,z}
end
minimumUnitCount = minimumUnitCount or 2
maximumConnectionDistance = maximumConnectionDistance or 350
clusterRaw_Objects = Spring.Utilities.Run_OPTIC(clusterFeed_UnitPos,maximumConnectionDistance,minimumUnitCount)
clusterInitialized = true
end
local function ExtractCluster(desiredConnectionDistance)
-- This local function translate OPTIC's result into clusters,
-- this can be called multiple time for different input without needing to redo the cluster algorithm,
-- the "desiredConnectionDistance" must be less than "maximumConnectionDistance".
-- Can be used to find clusters that match weapon AOE
if not clusterInitialized then
UpdateClustering(2,350)
end
desiredConnectionDistance = desiredConnectionDistance or 300 --must be less or equal to maximumConnectionDistance
clusterList_UnitIDs, clusterNoiseList_UnitIDs = Spring.Utilities.Extract_Cluster(clusterRaw_Objects,desiredConnectionDistance)
clusterExtracted = true
return clusterList_UnitIDs, clusterNoiseList_UnitIDs
end
local function GetClusterCoordinates()
--This will return a table of {x,0,z,clusterAvgRadius+100,unitCount}
--Can be used to see where unit is concentrating.
if not clusterExtracted then
ExtractCluster(300)
end
clusterCircle_Pos = Spring.Utilities.Convert_To_Circle(clusterList_UnitIDs, clusterNoiseList_UnitIDs,clusterFeed_UnitPos)
clusterExtracted = true
return clusterCircle_Pos
end
local function GetClusterCostCentroid()
--This will return a table of {weightedX,0,weightedZ,totalCost,unitCount}
if not clusterExtracted then
ExtractCluster(300)
end
local costCentroids = {}
for i=1 , #clusterList_UnitIDs do
local sumX, sumY,sumZ, meanX, meanY, meanZ,totalCost,count= 0,0 ,0 ,0,0,0,0,0
for j=1, #clusterList_UnitIDs[i] do
local unitID = clusterList_UnitIDs[i][j]
local unitIndex = unitMap[unitID]
local x,z = GetUnitLocation(unitList[unitIndex])
local y,cost = 0,unitList[unitIndex].cost --// get stored unit position
sumX= sumX+x*cost; sumY = sumY+y*cost; sumZ = sumZ+z*cost
totalCost = totalCost + cost
count = count + 1
end
meanX = sumX/totalCost; meanY = sumY/totalCost; meanZ = sumZ/totalCost --//calculate center of cost
costCentroids[#costCentroids+1] = {meanX,0,meanZ,totalCost,#clusterList_UnitIDs[i]}
end
if #clusterNoiseList_UnitIDs>0 then --//IF outlier list is not empty
for j= 1 ,#clusterNoiseList_UnitIDs do
local unitID = clusterNoiseList_UnitIDs[j]
local unitIndex = unitMap[unitID]
local x,z = GetUnitLocation(unitList[unitIndex])
local y,cost = 0,unitList[unitIndex].cost --// get stored unit position
costCentroids[#costCentroids+1] = {x,0,z,cost,1}
end
end
return costCentroids
end
unitList.UpdateClustering = UpdateClustering
unitList.ExtractCluster = ExtractCluster
unitList.GetClusterCoordinates = GetClusterCoordinates
unitList.GetClusterCostCentroid = GetClusterCostCentroid
return unitList
end
return xponenUnitCluster | gpl-2.0 |
Kyklas/luci-proto-hso | libs/nixio/docsrc/nixio.UnifiedIO.lua | 157 | 5891 | --- Unified high-level I/O utility API for Files, Sockets and TLS-Sockets.
-- These functions are added to the object function tables by doing <strong>
-- require "nixio.util"</strong>, can be used on all nixio IO Descriptors and
-- are based on the shared low-level read() and write() functions.
-- @cstyle instance
module "nixio.UnifiedIO"
--- Test whether the I/O-Descriptor is a socket.
-- @class function
-- @name UnifiedIO.is_socket
-- @return boolean
--- Test whether the I/O-Descriptor is a TLS socket.
-- @class function
-- @name UnifiedIO.is_tls_socket
-- @return boolean
--- Test whether the I/O-Descriptor is a file.
-- @class function
-- @name UnifiedIO.is_file
-- @return boolean
--- Read a block of data and wait until all data is available.
-- @class function
-- @name UnifiedIO.readall
-- @usage This function uses the low-level read function of the descriptor.
-- @usage If the length parameter is ommited, this function returns all data
-- that can be read before an end-of-file, end-of-stream, connection shutdown
-- or similar happens.
-- @usage If the descriptor is non-blocking this function may fail with EAGAIN.
-- @param length Bytes to read (optional)
-- @return data that was successfully read if no error occured
-- @return - reserved for error code -
-- @return - reserved for error message -
-- @return data that was successfully read even if an error occured
--- Write a block of data and wait until all data is written.
-- @class function
-- @name UnifiedIO.writeall
-- @usage This function uses the low-level write function of the descriptor.
-- @usage If the descriptor is non-blocking this function may fail with EAGAIN.
-- @param block Bytes to write
-- @return bytes that were successfully written if no error occured
-- @return - reserved for error code -
-- @return - reserved for error message -
-- @return bytes that were successfully written even if an error occured
--- Create a line-based iterator.
-- Lines may end with either \n or \r\n, these control chars are not included
-- in the return value.
-- @class function
-- @name UnifiedIO.linesource
-- @usage This function uses the low-level read function of the descriptor.
-- @usage <strong>Note:</strong> This function uses an internal buffer to read
-- ahead. Do NOT mix calls to read(all) and the returned iterator. If you want
-- to stop reading line-based and want to use the read(all) functions instead
-- you can pass "true" to the iterator which will flush the buffer
-- and return the bufferd data.
-- @usage If the limit parameter is ommited, this function uses the nixio
-- buffersize (8192B by default).
-- @usage If the descriptor is non-blocking the iterator may fail with EAGAIN.
-- @usage The iterator can be used as an LTN12 source.
-- @param limit Line limit
-- @return Line-based Iterator
--- Create a block-based iterator.
-- @class function
-- @name UnifiedIO.blocksource
-- @usage This function uses the low-level read function of the descriptor.
-- @usage The blocksize given is only advisory and to be seen as an upper limit,
-- if an underlying read returns less bytes the chunk is nevertheless returned.
-- @usage If the limit parameter is ommited, the iterator returns data
-- until an end-of-file, end-of-stream, connection shutdown or similar happens.
-- @usage The iterator will not buffer so it is safe to mix with calls to read.
-- @usage If the descriptor is non-blocking the iterator may fail with EAGAIN.
-- @usage The iterator can be used as an LTN12 source.
-- @param blocksize Advisory blocksize (optional)
-- @param limit Amount of data to consume (optional)
-- @return Block-based Iterator
--- Create a sink.
-- This sink will simply write all data that it receives and optionally
-- close the descriptor afterwards.
-- @class function
-- @name UnifiedIO.sink
-- @usage This function uses the writeall function of the descriptor.
-- @usage If the descriptor is non-blocking the sink may fail with EAGAIN.
-- @usage The iterator can be used as an LTN12 sink.
-- @param close_when_done (optional, boolean)
-- @return Sink
--- Copy data from the current descriptor to another one.
-- @class function
-- @name UnifiedIO.copy
-- @usage This function uses the blocksource function of the source descriptor
-- and the sink function of the target descriptor.
-- @usage If the limit parameter is ommited, data is copied
-- until an end-of-file, end-of-stream, connection shutdown or similar happens.
-- @usage If the descriptor is non-blocking the function may fail with EAGAIN.
-- @param fdout Target Descriptor
-- @param size Bytes to copy (optional)
-- @return bytes that were successfully written if no error occured
-- @return - reserved for error code -
-- @return - reserved for error message -
-- @return bytes that were successfully written even if an error occured
--- Copy data from the current descriptor to another one using kernel-space
-- copying if possible.
-- @class function
-- @name UnifiedIO.copyz
-- @usage This function uses the sendfile() syscall to copy the data or the
-- blocksource function of the source descriptor and the sink function
-- of the target descriptor as a fallback mechanism.
-- @usage If the limit parameter is ommited, data is copied
-- until an end-of-file, end-of-stream, connection shutdown or similar happens.
-- @usage If the descriptor is non-blocking the function may fail with EAGAIN.
-- @param fdout Target Descriptor
-- @param size Bytes to copy (optional)
-- @return bytes that were successfully written if no error occured
-- @return - reserved for error code -
-- @return - reserved for error message -
-- @return bytes that were successfully written even if an error occured
--- Close the descriptor.
-- @class function
-- @name UnifiedIO.close
-- @usage If the descriptor is a TLS-socket the underlying descriptor is
-- closed without touching the TLS connection.
-- @return true | apache-2.0 |
Scavenge/darkstar | scripts/globals/items/cheese_sandwich.lua | 12 | 1191 | -----------------------------------------
-- ID: 5686
-- Item: cheese_sandwich
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP 10
-- Agility 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5686);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_AGI, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_AGI, 1);
end;
| gpl-3.0 |
hdinsight/hue | tools/wrk-scripts/lib/old/argparse.lua | 23 | 28068 | local Parser, Command, Argument, Option
local function require_30log()
-------------------------------------------------------------------------------
local assert = assert
local pairs = pairs
local type = type
local tostring = tostring
local setmetatable = setmetatable
local baseMt = {}
local _instances = setmetatable({},{__mode='k'})
local _classes = setmetatable({},{__mode='k'})
local class
local function deep_copy(t, dest, aType)
local t = t or {}
local r = dest or {}
for k,v in pairs(t) do
if aType and type(v)==aType then
r[k] = v
elseif not aType then
if type(v) == 'table' and k ~= "__index" then
r[k] = deep_copy(v)
else
r[k] = v
end
end
end
return r
end
local function instantiate(self,...)
assert(_classes[self], 'new() should be called from a class.')
local instance = deep_copy(self)
_instances[instance] = tostring(instance)
setmetatable(instance,self)
if self.__init then
if type(self.__init) == 'table' then
deep_copy(self.__init, instance)
else
self.__init(instance, ...)
end
end
return instance
end
local function extends(self,extra_params)
local heir = {}
_classes[heir] = tostring(heir)
deep_copy(extra_params, deep_copy(self, heir))
heir.__index = heir
heir.super = self
return setmetatable(heir,self)
end
baseMt = {
__call = function (self,...)
return self:new(...)
end,
__tostring = function(self,...)
if _instances[self] then
return
('object(of %s):<%s>')
:format((rawget(getmetatable(self),'__name') or '?'), _instances[self])
end
return
_classes[self] and
('class(%s):<%s>')
:format((rawget(self,'__name') or '?'),_classes[self]) or
self
end
}
class = function(attr)
local c = deep_copy(attr)
_classes[c] = tostring(c)
c.include = function(self,include)
assert(_classes[self], 'Mixins can only be used on classes.')
return deep_copy(include, self, 'function')
end
c.new = instantiate
c.extends = extends
c.__index = c
c.__call = baseMt.__call
c.__tostring = baseMt.__tostring
c.is = function(self, kind)
local super
while true do
super = getmetatable(super or self)
if super == kind or super == nil then break end
end
return kind and (super == kind)
end
return setmetatable(c, baseMt)
end
return class
-------------------------------------------------------------------------------
end
do -- Create classes with setters
local class = require_30log()
local function add_setters(cl, fields)
for field, setter in pairs(fields) do
cl[field] = function(self, value)
setter(self, value)
self["_"..field] = value
return self
end
end
cl.__init = function(self, ...)
return self(...)
end
cl.__call = function(self, ...)
local name_or_options
for i=1, select("#", ...) do
name_or_options = select(i, ...)
if type(name_or_options) == "string" then
if self._aliases then
table.insert(self._aliases, name_or_options)
end
if not self._aliases or not self._name then
self._name = name_or_options
end
elseif type(name_or_options) == "table" then
for field in pairs(fields) do
if name_or_options[field] ~= nil then
self[field](self, name_or_options[field])
end
end
end
end
return self
end
return cl
end
local typecheck = setmetatable({}, {
__index = function(self, type_)
local typechecker_factory = function(field)
return function(_, value)
if type(value) ~= type_ then
error(("bad field '%s' (%s expected, got %s)"):format(field, type_, type(value)))
end
end
end
self[type_] = typechecker_factory
return typechecker_factory
end
})
local function aliased_name(self, name)
typecheck.string "name" (self, name)
table.insert(self._aliases, name)
end
local function aliased_aliases(self, aliases)
typecheck.table "aliases" (self, aliases)
if not self._name then
self._name = aliases[1]
end
end
local function parse_boundaries(boundaries)
if tonumber(boundaries) then
return tonumber(boundaries), tonumber(boundaries)
end
if boundaries == "*" then
return 0, math.huge
end
if boundaries == "+" then
return 1, math.huge
end
if boundaries == "?" then
return 0, 1
end
if boundaries:match "^%d+%-%d+$" then
local min, max = boundaries:match "^(%d+)%-(%d+)$"
return tonumber(min), tonumber(max)
end
if boundaries:match "^%d+%+$" then
local min = boundaries:match "^(%d+)%+$"
return tonumber(min), math.huge
end
end
local function boundaries(field)
return function(self, value)
local min, max = parse_boundaries(value)
if not min then
error(("bad field '%s'"):format(field))
end
self["_min"..field], self["_max"..field] = min, max
end
end
local function convert(self, value)
if type(value) ~= "function" then
if type(value) ~= "table" then
error(("bad field 'convert' (function or table expected, got %s)"):format(type(value)))
end
end
end
local function argname(self, value)
if type(value) ~= "string" then
if type(value) ~= "table" then
error(("bad field 'argname' (string or table expected, got %s)"):format(type(value)))
end
end
end
local function add_help(self, param)
if self._has_help then
table.remove(self._options)
self._has_help = false
end
if param then
local help = self:flag()
:description "Show this help message and exit. "
:action(function()
io.stdout:write(self:get_help() .. "\r\n")
os.exit(0)
end)(param)
if not help._name then
help "-h" "--help"
end
self._has_help = true
end
end
Parser = add_setters(class {
__name = "Parser",
_arguments = {},
_options = {},
_commands = {},
_mutexes = {},
_require_command = true
}, {
name = typecheck.string "name",
description = typecheck.string "description",
epilog = typecheck.string "epilog",
require_command = typecheck.boolean "require_command",
usage = typecheck.string "usage",
help = typecheck.string "help",
add_help = add_help
})
Command = add_setters(Parser:extends {
__name = "Command",
_aliases = {}
}, {
name = aliased_name,
aliases = aliased_aliases,
description = typecheck.string "description",
epilog = typecheck.string "epilog",
target = typecheck.string "target",
require_command = typecheck.boolean "require_command",
action = typecheck["function"] "action",
usage = typecheck.string "usage",
help = typecheck.string "help",
add_help = add_help
})
Argument = add_setters(class {
__name = "Argument",
_minargs = 1,
_maxargs = 1,
_mincount = 1,
_maxcount = 1,
_defmode = "unused",
_show_default = true
}, {
name = typecheck.string "name",
description = typecheck.string "description",
target = typecheck.string "target",
args = boundaries "args",
default = typecheck.string "default",
defmode = typecheck.string "defmode",
convert = convert,
argname = argname,
show_default = typecheck.boolean "show_default"
})
Option = add_setters(Argument:extends {
__name = "Option",
_aliases = {},
_mincount = 0,
_overwrite = true
}, {
name = aliased_name,
aliases = aliased_aliases,
description = typecheck.string "description",
target = typecheck.string "target",
args = boundaries "args",
count = boundaries "count",
default = typecheck.string "default",
defmode = typecheck.string "defmode",
convert = convert,
overwrite = typecheck.boolean "overwrite",
action = typecheck["function"] "action",
argname = argname,
show_default = typecheck.boolean "show_default"
})
end
function Argument:_get_argument_list()
local buf = {}
local i = 1
while i <= math.min(self._minargs, 3) do
local argname = self:_get_argname(i)
if self._default and self._defmode:find "a" then
argname = "[" .. argname .. "]"
end
table.insert(buf, argname)
i = i+1
end
while i <= math.min(self._maxargs, 3) do
table.insert(buf, "[" .. self:_get_argname(i) .. "]")
i = i+1
if self._maxargs == math.huge then
break
end
end
if i < self._maxargs then
table.insert(buf, "...")
end
return buf
end
function Argument:_get_usage()
local usage = table.concat(self:_get_argument_list(), " ")
if self._default and self._defmode:find "u" then
if self._maxargs > 1 or (self._minargs == 1 and not self._defmode:find "a") then
usage = "[" .. usage .. "]"
end
end
return usage
end
function Argument:_get_type()
if self._maxcount == 1 then
if self._maxargs == 0 then
return "flag"
elseif self._maxargs == 1 and (self._minargs == 1 or self._mincount == 1) then
return "arg"
else
return "multiarg"
end
else
if self._maxargs == 0 then
return "counter"
elseif self._maxargs == 1 and self._minargs == 1 then
return "multicount"
else
return "twodimensional"
end
end
end
-- Returns placeholder for `narg`-th argument.
function Argument:_get_argname(narg)
local argname = self._argname or self:_get_default_argname()
if type(argname) == "table" then
return argname[narg]
else
return argname
end
end
function Argument:_get_default_argname()
return "<" .. self._name .. ">"
end
function Option:_get_default_argname()
return "<" .. self:_get_default_target() .. ">"
end
-- Returns label to be shown in the help message.
function Argument:_get_label()
return self._name
end
function Option:_get_label()
local variants = {}
local argument_list = self:_get_argument_list()
table.insert(argument_list, 1, nil)
for _, alias in ipairs(self._aliases) do
argument_list[1] = alias
table.insert(variants, table.concat(argument_list, " "))
end
return table.concat(variants, ", ")
end
function Command:_get_label()
return table.concat(self._aliases, ", ")
end
function Argument:_get_description()
if self._default and self._show_default then
if self._description then
return ("%s (default: %s)"):format(self._description, self._default)
else
return ("default: %s"):format(self._default)
end
else
return self._description or ""
end
end
function Command:_get_description()
return self._description or ""
end
function Option:_get_usage()
local usage = self:_get_argument_list()
table.insert(usage, 1, self._name)
usage = table.concat(usage, " ")
if self._mincount == 0 or self._default then
usage = "[" .. usage .. "]"
end
return usage
end
function Option:_get_default_target()
local res
for _, alias in ipairs(self._aliases) do
if alias:sub(1, 1) == alias:sub(2, 2) then
res = alias:sub(3)
break
end
end
res = res or self._name:sub(2)
return (res:gsub("-", "_"))
end
function Option:_is_vararg()
return self._maxargs ~= self._minargs
end
function Parser:_get_fullname()
local parent = self._parent
local buf = {self._name}
while parent do
table.insert(buf, 1, parent._name)
parent = parent._parent
end
return table.concat(buf, " ")
end
function Parser:_update_charset(charset)
charset = charset or {}
for _, command in ipairs(self._commands) do
command:_update_charset(charset)
end
for _, option in ipairs(self._options) do
for _, alias in ipairs(option._aliases) do
charset[alias:sub(1, 1)] = true
end
end
return charset
end
function Parser:argument(...)
local argument = Argument:new(...)
table.insert(self._arguments, argument)
return argument
end
function Parser:option(...)
local option = Option:new(...)
if self._has_help then
table.insert(self._options, #self._options, option)
else
table.insert(self._options, option)
end
return option
end
function Parser:flag(...)
return self:option():args(0)(...)
end
function Parser:command(...)
local command = Command:new():add_help(true)(...)
command._parent = self
table.insert(self._commands, command)
return command
end
function Parser:mutex(...)
local options = {...}
for i, option in ipairs(options) do
assert(getmetatable(option) == Option, ("bad argument #%d to 'mutex' (Option expected)"):format(i))
end
table.insert(self._mutexes, options)
return self
end
local max_usage_width = 70
local usage_welcome = "Usage: "
function Parser:get_usage()
if self._usage then
return self._usage
end
local lines = {usage_welcome .. self:_get_fullname()}
local function add(s)
if #lines[#lines]+1+#s <= max_usage_width then
lines[#lines] = lines[#lines] .. " " .. s
else
lines[#lines+1] = (" "):rep(#usage_welcome) .. s
end
end
-- This can definitely be refactored into something cleaner
local mutex_options = {}
local vararg_mutexes = {}
-- First, put mutexes which do not contain vararg options and remember those which do
for _, mutex in ipairs(self._mutexes) do
local buf = {}
local is_vararg = false
for _, option in ipairs(mutex) do
if option:_is_vararg() then
is_vararg = true
end
table.insert(buf, option:_get_usage())
mutex_options[option] = true
end
local repr = "(" .. table.concat(buf, " | ") .. ")"
if is_vararg then
table.insert(vararg_mutexes, repr)
else
add(repr)
end
end
-- Second, put regular options
for _, option in ipairs(self._options) do
if not mutex_options[option] and not option:_is_vararg() then
add(option:_get_usage())
end
end
-- Put positional arguments
for _, argument in ipairs(self._arguments) do
add(argument:_get_usage())
end
-- Put mutexes containing vararg options
for _, mutex_repr in ipairs(vararg_mutexes) do
add(mutex_repr)
end
for _, option in ipairs(self._options) do
if not mutex_options[option] and option:_is_vararg() then
add(option:_get_usage())
end
end
if #self._commands > 0 then
if self._require_command then
add("<command>")
else
add("[<command>]")
end
add("...")
end
return table.concat(lines, "\r\n")
end
local margin_len = 3
local margin_len2 = 25
local margin = (" "):rep(margin_len)
local margin2 = (" "):rep(margin_len2)
local function make_two_columns(s1, s2)
if s2 == "" then
return margin .. s1
end
s2 = s2:gsub("[\r\n][\r\n]?", function(sub)
if #sub == 1 or sub == "\r\n" then
return "\r\n" .. margin2
else
return "\r\n\r\n" .. margin2
end
end)
if #s1 < (margin_len2-margin_len) then
return margin .. s1 .. (" "):rep(margin_len2-margin_len-#s1) .. s2
else
return margin .. s1 .. "\r\n" .. margin2 .. s2
end
end
function Parser:get_help()
if self._help then
return self._help
end
local blocks = {self:get_usage()}
if self._description then
table.insert(blocks, self._description)
end
local labels = {"Arguments: ", "Options: ", "Commands: "}
for i, elements in ipairs{self._arguments, self._options, self._commands} do
if #elements > 0 then
local buf = {labels[i]}
for _, element in ipairs(elements) do
table.insert(buf, make_two_columns(element:_get_label(), element:_get_description()))
end
table.insert(blocks, table.concat(buf, "\r\n"))
end
end
if self._epilog then
table.insert(blocks, self._epilog)
end
return table.concat(blocks, "\r\n\r\n")
end
local function get_tip(context, wrong_name)
local context_pool = {}
local possible_name
local possible_names = {}
for name in pairs(context) do
for i=1, #name do
possible_name = name:sub(1, i-1) .. name:sub(i+1)
if not context_pool[possible_name] then
context_pool[possible_name] = {}
end
table.insert(context_pool[possible_name], name)
end
end
for i=1, #wrong_name+1 do
possible_name = wrong_name:sub(1, i-1) .. wrong_name:sub(i+1)
if context[possible_name] then
possible_names[possible_name] = true
elseif context_pool[possible_name] then
for _, name in ipairs(context_pool[possible_name]) do
possible_names[name] = true
end
end
end
local first = next(possible_names)
if first then
if next(possible_names, first) then
local possible_names_arr = {}
for name in pairs(possible_names) do
table.insert(possible_names_arr, "'" .. name .. "'")
end
table.sort(possible_names_arr)
return "\r\nDid you mean one of these: " .. table.concat(possible_names_arr, " ") .. "?"
else
return "\r\nDid you mean '" .. first .. "'?"
end
else
return ""
end
end
local function plural(x)
if x == 1 then
return ""
end
return "s"
end
-- Compatibility with strict.lua and other checkers:
local default_cmdline = rawget(_G, "arg") or {}
function Parser:_parse(args, errhandler)
args = args or default_cmdline
local parser
local charset
local options = {}
local arguments = {}
local commands
local option_mutexes = {}
local used_mutexes = {}
local opt_context = {}
local com_context
local result = {}
local invocations = {}
local passed = {}
local cur_option
local cur_arg_i = 1
local cur_arg
local targets = {}
local function error_(fmt, ...)
return errhandler(parser, fmt:format(...))
end
local function assert_(assertion, ...)
return assertion or error_(...)
end
local function convert(element, data)
if element._convert then
local ok, err
if type(element._convert) == "function" then
ok, err = element._convert(data)
else
ok, err = element._convert[data]
end
assert_(ok ~= nil, "%s", err or "malformed argument '" .. data .. "'")
data = ok
end
return data
end
local invoke, pass, close
function invoke(element)
local overwrite = false
if invocations[element] == element._maxcount then
if element._overwrite then
overwrite = true
else
error_("option '%s' must be used at most %d time%s", element._name, element._maxcount, plural(element._maxcount))
end
else
invocations[element] = invocations[element]+1
end
passed[element] = 0
local type_ = element:_get_type()
local target = targets[element]
if type_ == "flag" then
result[target] = true
elseif type_ == "multiarg" then
result[target] = {}
elseif type_ == "counter" then
if not overwrite then
result[target] = result[target]+1
end
elseif type_ == "multicount" then
if overwrite then
table.remove(result[target], 1)
end
elseif type_ == "twodimensional" then
table.insert(result[target], {})
if overwrite then
table.remove(result[target], 1)
end
end
if element._maxargs == 0 then
close(element)
end
end
function pass(element, data)
passed[element] = passed[element]+1
data = convert(element, data)
local type_ = element:_get_type()
local target = targets[element]
if type_ == "arg" then
result[target] = data
elseif type_ == "multiarg" or type_ == "multicount" then
table.insert(result[target], data)
elseif type_ == "twodimensional" then
table.insert(result[target][#result[target]], data)
end
if passed[element] == element._maxargs then
close(element)
end
end
local function complete_invocation(element)
while passed[element] < element._minargs do
pass(element, element._default)
end
end
function close(element)
if passed[element] < element._minargs then
if element._default and element._defmode:find "a" then
complete_invocation(element)
else
error_("too few arguments")
end
else
if element == cur_option then
cur_option = nil
elseif element == cur_arg then
cur_arg_i = cur_arg_i+1
cur_arg = arguments[cur_arg_i]
end
end
end
local function switch(p)
parser = p
for _, option in ipairs(parser._options) do
table.insert(options, option)
for _, alias in ipairs(option._aliases) do
opt_context[alias] = option
end
local type_ = option:_get_type()
targets[option] = option._target or option:_get_default_target()
if type_ == "counter" then
result[targets[option]] = 0
elseif type_ == "multicount" or type_ == "twodimensional" then
result[targets[option]] = {}
end
invocations[option] = 0
end
for _, mutex in ipairs(parser._mutexes) do
for _, option in ipairs(mutex) do
if not option_mutexes[option] then
option_mutexes[option] = {mutex}
else
table.insert(option_mutexes[option], mutex)
end
end
end
for _, argument in ipairs(parser._arguments) do
table.insert(arguments, argument)
invocations[argument] = 0
targets[argument] = argument._target or argument._name
invoke(argument)
end
cur_arg = arguments[cur_arg_i]
commands = parser._commands
com_context = {}
for _, command in ipairs(commands) do
targets[command] = command._target or command._name
for _, alias in ipairs(command._aliases) do
com_context[alias] = command
end
end
end
local function get_option(name)
return assert_(opt_context[name], "unknown option '%s'%s", name, get_tip(opt_context, name))
end
local function do_action(element)
if element._action then
element._action()
end
end
local function handle_argument(data)
if cur_option then
pass(cur_option, data)
elseif cur_arg then
pass(cur_arg, data)
else
local com = com_context[data]
if not com then
if #commands > 0 then
error_("unknown command '%s'%s", data, get_tip(com_context, data))
else
error_("too many arguments")
end
else
result[targets[com]] = true
do_action(com)
switch(com)
end
end
end
local function handle_option(data)
if cur_option then
close(cur_option)
end
cur_option = opt_context[data]
if option_mutexes[cur_option] then
for _, mutex in ipairs(option_mutexes[cur_option]) do
if used_mutexes[mutex] and used_mutexes[mutex] ~= cur_option then
error_("option '%s' can not be used together with option '%s'", data, used_mutexes[mutex]._name)
else
used_mutexes[mutex] = cur_option
end
end
end
do_action(cur_option)
invoke(cur_option)
end
local function mainloop()
local handle_options = true
for _, data in ipairs(args) do
local plain = true
local first, name, option
if handle_options then
first = data:sub(1, 1)
if charset[first] then
if #data > 1 then
plain = false
if data:sub(2, 2) == first then
if #data == 2 then
if cur_option then
close(cur_option)
end
handle_options = false
else
local equal = data:find "="
if equal then
name = data:sub(1, equal-1)
option = get_option(name)
assert_(option._maxargs > 0, "option '%s' does not take arguments", name)
handle_option(data:sub(1, equal-1))
handle_argument(data:sub(equal+1))
else
get_option(data)
handle_option(data)
end
end
else
for i = 2, #data do
name = first .. data:sub(i, i)
option = get_option(name)
handle_option(name)
if i ~= #data and option._minargs > 0 then
handle_argument(data:sub(i+1))
break
end
end
end
end
end
end
if plain then
handle_argument(data)
end
end
end
switch(self)
charset = parser:_update_charset()
mainloop()
if cur_option then
close(cur_option)
end
while cur_arg do
if passed[cur_arg] == 0 and cur_arg._default and cur_arg._defmode:find "u" then
complete_invocation(cur_arg)
else
close(cur_arg)
end
end
if parser._require_command and #commands > 0 then
error_("a command is required")
end
for _, option in ipairs(options) do
if invocations[option] == 0 then
if option._default and option._defmode:find "u" then
invoke(option)
complete_invocation(option)
close(option)
end
end
if invocations[option] < option._mincount then
if option._default and option._defmode:find "a" then
while invocations[option] < option._mincount do
invoke(option)
close(option)
end
else
error_("option '%s' must be used at least %d time%s", option._name, option._mincount, plural(option._mincount))
end
end
end
return result
end
function Parser:error(msg)
io.stderr:write(("%s\r\n\r\nError: %s\r\n"):format(self:get_usage(), msg))
os.exit(1)
end
function Parser:parse(args)
return self:_parse(args, Parser.error)
end
function Parser:pparse(args)
local errmsg
local ok, result = pcall(function()
return self:_parse(args, function(_, err)
errmsg = err
return error()
end)
end)
if ok then
return true, result
else
assert(errmsg, result)
return false, errmsg
end
end
return function(...)
return Parser(default_cmdline[0]):add_help(true)(...)
end
| apache-2.0 |
ihcfan/NautiPlot | hmi-cocos2d-x/samples/Lua/TestLua/Resources/luaScript/OpenGLTest/OpenGLTest.lua | 4 | 45383 | require "OpenglConstants"
require "Cocos2dConstants"
require "Opengl"
local function OpenGLTestMainLayer()
local kItemTagBasic = 1000
local testCount = 16
local maxCases = testCount
local curCase = 0
local accum = 0
local labelBMFont = nil
local size = cc.Director:getInstance():getWinSize()
local curLayer = nil
local schedulEntry = nil
local function OrderCallbackMenu()
local function backCallback()
curCase = curCase - 1
if curCase < 0 then
curCase = curCase + maxCases
end
ShowCurrentTest()
end
local function restartCallback()
ShowCurrentTest()
end
local function nextCallback()
curCase = curCase + 1
curCase = curCase % maxCases
ShowCurrentTest()
end
local ordercallbackmenu = cc.Menu:create()
local size = cc.Director:getInstance():getWinSize()
local item1 = cc.MenuItemImage:create(s_pPathB1, s_pPathB2)
item1:registerScriptTapHandler(backCallback)
ordercallbackmenu:addChild(item1,kItemTagBasic)
local item2 = cc.MenuItemImage:create(s_pPathR1, s_pPathR2)
item2:registerScriptTapHandler(restartCallback)
ordercallbackmenu:addChild(item2,kItemTagBasic)
local item3 = cc.MenuItemImage:create(s_pPathF1, s_pPathF2)
ordercallbackmenu:addChild(item3,kItemTagBasic)
item3:registerScriptTapHandler(nextCallback)
item1:setPosition(cc.p(size.width / 2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2))
item2:setPosition(cc.p(size.width / 2, item2:getContentSize().height / 2))
item3:setPosition(cc.p(size.width / 2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2))
ordercallbackmenu:setPosition(cc.p(0, 0))
return ordercallbackmenu
end
local function GetTitle()
if 0 == curCase then
return "Shader Retro Effect"
elseif 1 == curCase then
return "Shader Monjori Test"
elseif 2 == curCase then
return "Shader Mandelbrot Test"
elseif 3 == curCase then
return "Shader Heart Test"
elseif 4 == curCase then
return "Shader Plasma Test"
elseif 5 == curCase then
return "Shader Flower Test"
elseif 6 == curCase then
return "Shader Julia Test"
elseif 7 == curCase then
return "gl.getActive***"
elseif 8 == curCase then
return "TexImage2DTest"
elseif 9 == curCase then
return "GetSupportedExtensionsTest"
elseif 10 == curCase then
return "gl.ReadPixels()"
elseif 11 == curCase then
return "gl.clear(gl.COLOR_BUFFER_BIT)"
elseif 12 == curCase then
return "GLNode + WebGL API"
elseif 13 == curCase then
return "GLNode + cocos2d API"
elseif 14 == curCase then
return "GLTexParamterTest"
elseif 15 == curCase then
return "GLGetUniformTest"
end
end
local function GetSubTitle()
if 0 == curCase then
return "Should see moving colors, and a sin effect on the letters"
elseif 1 == curCase then
return "Monjori plane deformations"
elseif 2 == curCase then
return "Mandelbrot shader with Zoom"
elseif 3 == curCase then
return "You should see a heart in the center"
elseif 4 == curCase then
return "You should see a plasma in the center"
elseif 5 == curCase then
return "You should see a moving Flower in the center"
elseif 6 == curCase then
return "You should see Julia effect"
elseif 7 == curCase then
return "Tests gl.getActiveUniform / getActiveAttrib. See console"
elseif 8 == curCase then
return "Testing Texture creation"
elseif 9 == curCase then
return "See console for the supported GL extensions"
elseif 10 == curCase then
return "Tests ReadPixels. See console"
elseif 11 == curCase then
return "Testing gl.clear() with cc.GLNode"
elseif 12 == curCase then
return "blue background with a red triangle in the middle"
elseif 13 == curCase then
return "blue background with a red triangle in the middle"
elseif 14 == curCase then
return "tests texParameter()"
elseif 15 == curCase then
return "tests texParameter()"
end
end
local function InitTitle(layer)
--Title
local lableTitle = cc.LabelTTF:create(GetTitle(), "Arial", 40)
layer:addChild(lableTitle, 15)
lableTitle:setPosition(cc.p(size.width/2, size.height-32))
lableTitle:setColor(cc.c3b(255,255,40))
--SubTitle
local subLabelTitle = cc.LabelTTF:create(GetSubTitle(), "Thonburi", 16)
layer:addChild(subLabelTitle, 15)
subLabelTitle:setPosition(cc.p(size.width/2, size.height-80))
end
local function updateRetroEffect(fTime)
if nil == labelBMFont then
return
end
accum = accum + fTime
local children = labelBMFont:getChildren()
if nil == children then
return
end
local i = 0
local len = table.getn(children)
for i= 0 ,len - 1 do
local child = tolua.cast(children[i + 1], "Sprite")
local oldPosX,oldPosY = child:getPosition()
child:setPosition(oldPosX,math.sin(accum * 2 + i / 2.0) * 20)
local scaleY = math.sin(accum * 2 + i / 2.0 + 0.707)
child:setScaleY(scaleY)
end
end
local function createShaderRetroEffect()
local RetroEffectlayer = cc.Layer:create()
InitTitle(RetroEffectlayer)
local program = cc.GLProgram:create("Shaders/example_ColorBars.vsh", "Shaders/example_ColorBars.fsh")
program:addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION)
program:addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS)
program:link()
program:updateUniforms()
label = cc.LabelBMFont:create("RETRO EFFECT","fonts/west_england-64.fnt")
label:setShaderProgram( program )
label:setPosition(size.width/2, size.height/2)
RetroEffectlayer:addChild(label)
labelBMFont = label
RetroEffectlayer:scheduleUpdateWithPriorityLua(updateRetroEffect,0)
return RetroEffectlayer
end
local function createShaderMajoriTest()
local uniformCenter = 0
local uniformResolution = 0
local time = 0
local squareVertexPositionBuffer = {}
local majorLayer = cc.Layer:create()
InitTitle(majorLayer)
--loadShaderVertex
local shader = cc.GLProgram:create("Shaders/example_Monjori.vsh", "Shaders/example_Monjori.fsh")
shader:addAttribute("aVertex", cc.VERTEX_ATTRIB_POSITION)
shader:link()
shader:updateUniforms()
local program = shader:getProgram()
local glNode = gl.glNodeCreate()
glNode:setContentSize(cc.size(256,256))
glNode:setAnchorPoint(cc.p(0.5, 0.5))
uniformCenter = gl.getUniformLocation(program,"center")
uniformResolution = gl.getUniformLocation( program, "resolution")
glNode:setShaderProgram(shader)
local function initBuffer()
squareVertexPositionBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer)
local vertices = { 256,256,0,256,256,0,0,0}
gl.bufferData(gl.ARRAY_BUFFER,8,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
local function updateMajori(fTime)
time = time + fTime
end
local function majoriDraw()
if nil ~= shader then
shader:use()
shader:setUniformsForBuiltins()
--Uniforms
shader:setUniformLocationF32( uniformCenter, size.width/2, size.height/2)
shader:setUniformLocationF32( uniformResolution, 256, 256)
gl.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION)
--Draw fullscreen Square
gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer)
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_STRIP,0,4)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
end
initBuffer()
majorLayer:scheduleUpdateWithPriorityLua(updateMajori,0)
glNode:registerScriptDrawHandler(majoriDraw)
time = 0
majorLayer:addChild(glNode,-10)
glNode:setPosition( size.width/2, size.height/2)
return majorLayer
end
local function createShaderMandelbrotTest()
local uniformCenter = 0
local uniformResolution = 0
local time = 0
local squareVertexPositionBuffer = {}
local mandelbrotLayer = cc.Layer:create()
InitTitle(mandelbrotLayer)
--loadShaderVertex
local shader = cc.GLProgram:create("Shaders/example_Mandelbrot.vsh", "Shaders/example_Mandelbrot.fsh")
shader:addAttribute("aVertex", 0)
shader:link()
shader:updateUniforms()
local program = shader:getProgram()
local glNode = gl.glNodeCreate()
glNode:setContentSize(cc.size(256,256))
glNode:setAnchorPoint(cc.p(0.5, 0.5))
uniformCenter = gl.getUniformLocation(program,"center")
uniformResolution = gl.getUniformLocation( program, "resolution")
glNode:setShaderProgram(shader)
local function initBuffer()
squareVertexPositionBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer.buffer_id)
local vertices = { 256,256,0,256,256,0,0,0}
gl.bufferData(gl.ARRAY_BUFFER,8,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
local function updateMandelbrot(fTime)
time = time + fTime
end
local function mandelbrotDraw()
if nil ~= shader then
shader:use()
shader:setUniformsForBuiltins()
--Uniforms
shader:setUniformLocationF32( uniformCenter, size.width/2, size.height/2)
shader:setUniformLocationF32( uniformResolution, 256, 256)
gl.glEnableVertexAttribs(0x1)
--Draw fullscreen Square
gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer.buffer_id)
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_STRIP,0,4)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
end
initBuffer()
mandelbrotLayer:scheduleUpdateWithPriorityLua(updateMandelbrot,0)
glNode:registerScriptDrawHandler(mandelbrotDraw)
time = 0
mandelbrotLayer:addChild(glNode,-10)
glNode:setPosition( size.width/2, size.height/2)
return mandelbrotLayer
end
local function createShaderHeartTest()
local uniformCenter = 0
local uniformResolution = 0
local time = 0
local squareVertexPositionBuffer = {}
local heartLayer = cc.Layer:create()
InitTitle(heartLayer)
--loadShaderVertex
local shader = cc.GLProgram:create("Shaders/example_Heart.vsh", "Shaders/example_Heart.fsh")
shader:addAttribute("aVertex", 0)
shader:link()
shader:updateUniforms()
local program = shader:getProgram()
local glNode = gl.glNodeCreate()
glNode:setContentSize(cc.size(256,256))
glNode:setAnchorPoint(cc.p(0.5, 0.5))
uniformCenter = gl.getUniformLocation(program,"center")
uniformResolution = gl.getUniformLocation( program, "resolution")
glNode:setShaderProgram(shader)
local function initBuffer()
squareVertexPositionBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer.buffer_id)
local vertices = { 256,256,0,256,256,0,0,0}
gl.bufferData(gl.ARRAY_BUFFER,8,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
local function updateHeart(fTime)
time = time + fTime
end
local function heartDraw()
if nil ~= shader then
shader:use()
shader:setUniformsForBuiltins()
--Uniforms
shader:setUniformLocationF32( uniformCenter, size.width/2, size.height/2)
shader:setUniformLocationF32( uniformResolution, 256, 256)
gl.glEnableVertexAttribs(0x1)
--Draw fullscreen Square
gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer.buffer_id)
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_STRIP,0,4)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
end
initBuffer()
heartLayer:scheduleUpdateWithPriorityLua(updateHeart,0)
glNode:registerScriptDrawHandler(heartDraw)
time = 0
heartLayer:addChild(glNode,-10)
glNode:setPosition( size.width/2, size.height/2)
return heartLayer
end
local function createShaderPlasmaTest()
local uniformCenter = 0
local uniformResolution = 0
local time = 0
local squareVertexPositionBuffer = {}
local plasmaLayer = cc.Layer:create()
InitTitle(plasmaLayer)
--loadShaderVertex
local shader = cc.GLProgram:create("Shaders/example_Plasma.vsh", "Shaders/example_Plasma.fsh")
shader:addAttribute("aVertex", 0)
shader:link()
shader:updateUniforms()
local program = shader:getProgram()
local glNode = gl.glNodeCreate()
glNode:setContentSize(cc.size(256,256))
glNode:setAnchorPoint(cc.p(0.5, 0.5))
uniformCenter = gl.getUniformLocation(program,"center")
uniformResolution = gl.getUniformLocation( program, "resolution")
glNode:setShaderProgram(shader)
local function initBuffer()
squareVertexPositionBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer.buffer_id)
local vertices = { 256,256,0,256,256,0,0,0}
gl.bufferData(gl.ARRAY_BUFFER,8,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
local function updatePlasma(fTime)
time = time + fTime
end
local function plasmaDraw()
if nil ~= shader then
shader:use()
shader:setUniformsForBuiltins()
--Uniforms
shader:setUniformLocationF32( uniformCenter, size.width/2, size.height/2)
shader:setUniformLocationF32( uniformResolution, 256, 256)
gl.glEnableVertexAttribs(0x1)
--Draw fullscreen Square
gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer.buffer_id)
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_STRIP,0,4)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
end
initBuffer()
plasmaLayer:scheduleUpdateWithPriorityLua(updatePlasma,0)
glNode:registerScriptDrawHandler(plasmaDraw)
time = 0
plasmaLayer:addChild(glNode,-10)
glNode:setPosition( size.width/2, size.height/2)
return plasmaLayer
end
local function createShaderFlowerTest()
local uniformCenter = 0
local uniformResolution = 0
local time = 0
local squareVertexPositionBuffer = {}
local flowerLayer = cc.Layer:create()
InitTitle(flowerLayer)
--loadShaderVertex
local shader = cc.GLProgram:create("Shaders/example_Flower.vsh", "Shaders/example_Flower.fsh")
shader:addAttribute("aVertex", 0)
shader:link()
shader:updateUniforms()
local program = shader:getProgram()
local glNode = gl.glNodeCreate()
glNode:setContentSize(cc.size(256,256))
glNode:setAnchorPoint(cc.p(0.5, 0.5))
uniformCenter = gl.getUniformLocation(program,"center")
uniformResolution = gl.getUniformLocation( program, "resolution")
glNode:setShaderProgram(shader)
local function initBuffer()
squareVertexPositionBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer.buffer_id)
local vertices = { 256,256,0,256,256,0,0,0}
gl.bufferData(gl.ARRAY_BUFFER,8,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
local function updateFlower(fTime)
time = time + fTime
end
local function flowerDraw()
if nil ~= shader then
shader:use()
shader:setUniformsForBuiltins()
--Uniforms
shader:setUniformLocationF32( uniformCenter, size.width/2, size.height/2)
shader:setUniformLocationF32( uniformResolution, 256, 256)
gl.glEnableVertexAttribs(0x1)
--Draw fullscreen Square
gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer.buffer_id)
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_STRIP,0,4)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
end
initBuffer()
flowerLayer:scheduleUpdateWithPriorityLua(updateFlower,0)
glNode:registerScriptDrawHandler(flowerDraw)
time = 0
flowerLayer:addChild(glNode,-10)
glNode:setPosition( size.width/2, size.height/2)
return flowerLayer
end
local function createShaderJuliaTest()
local uniformCenter = 0
local uniformResolution = 0
local time = 0
local squareVertexPositionBuffer = {}
local juliaLayer = cc.Layer:create()
InitTitle(juliaLayer)
--loadShaderVertex
local shader = cc.GLProgram:create("Shaders/example_Julia.vsh", "Shaders/example_Julia.fsh")
shader:addAttribute("aVertex", 0)
shader:link()
shader:updateUniforms()
local program = shader:getProgram()
local glNode = gl.glNodeCreate()
glNode:setContentSize(cc.size(256,256))
glNode:setAnchorPoint(cc.p(0.5, 0.5))
uniformCenter = gl.getUniformLocation(program,"center")
uniformResolution = gl.getUniformLocation( program, "resolution")
glNode:setShaderProgram(shader)
local function initBuffer()
squareVertexPositionBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer.buffer_id)
local vertices = { 256,256,0,256,256,0,0,0}
gl.bufferData(gl.ARRAY_BUFFER,8,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
local function updateJulia(fTime)
time = time + fTime
end
local function juliaDraw()
if nil ~= shader then
shader:use()
shader:setUniformsForBuiltins()
--Uniforms
shader:setUniformLocationF32( uniformCenter, size.width/2, size.height/2)
shader:setUniformLocationF32( uniformResolution, 256, 256)
gl.glEnableVertexAttribs(0x1)
--Draw fullscreen Square
gl.bindBuffer(gl.ARRAY_BUFFER,squareVertexPositionBuffer.buffer_id)
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_STRIP,0,4)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
end
initBuffer()
juliaLayer:scheduleUpdateWithPriorityLua(updateJulia,0)
glNode:registerScriptDrawHandler(juliaDraw)
time = 0
juliaLayer:addChild(glNode,-10)
glNode:setPosition( size.width/2, size.height/2)
return juliaLayer
end
local function createGLGetActiveTest()
local glGetActiveLayer = cc.Layer:create()
InitTitle(glGetActiveLayer)
local sprite = cc.Sprite:create("Images/grossini.png")
sprite:setPosition( size.width/2, size.height/2)
glGetActiveLayer:addChild(sprite)
local glNode = gl.glNodeCreate()
glGetActiveLayer:addChild(glNode,-10)
local scheduler = cc.Director:getInstance():getScheduler()
local function getCurrentResult()
local var = {}
local glProgam = tolua.cast(sprite:getShaderProgram(),"GLProgram")
if nil ~= glProgam then
local p = glProgam:getProgram()
local aaSize,aaType,aaName = gl.getActiveAttrib(p,0)
local strFmt = "size:"..aaSize.." type:"..aaType.." name:"..aaName
print(strFmt)
local auSize,auType,auName = gl.getActiveUniform(p,0)
strFmt = "size:"..auSize.." type:"..auType.." name:"..auName
print(strFmt)
local shadersTable = gl.getAttachedShaders(p)
if type(shadersTable) == "table" then
local count = table.getn(shadersTable)
local i = 1
strFmt = ""
for i=1, count do
strFmt = strFmt..shadersTable[i].." "
end
print(strFmt)
end
if nil ~= schedulEntry then
scheduler:unscheduleScriptEntry(schedulEntry)
end
end
end
if nil ~= schedulEntry then
scheduler:unscheduleScriptEntry(schedulEntry)
end
schedulEntry = scheduler:scheduleScriptFunc(getCurrentResult, 0.5, false)
return glGetActiveLayer
end
--Have problem
local function createTexImage2DTest()
local texture = {}
local squareVertexPositionBuffer = {}
local squareVertexTextureBuffer = {}
local texImage2dLayer = cc.Layer:create()
InitTitle(texImage2dLayer)
local glNode = gl.glNodeCreate()
texImage2dLayer:addChild(glNode, 10)
glNode:setPosition(size.width/2, size.height/2)
glNode:setContentSize(cc.size(128,128))
glNode:setAnchorPoint(cc.p(0.5,0.5))
local shaderCache = cc.ShaderCache:getInstance()
local shader = shaderCache:getProgram("ShaderPositionTexture")
local function initGL()
texture.texture_id = gl.createTexture()
gl.bindTexture(gl.TEXTURE_2D,texture.texture_id )
local pixels = {}
local i = 1
while i <= 4096 do
pixels[i] = math.floor(i / 4)
i = i + 1
pixels[i] = math.floor(i / 16)
i = i + 1
pixels[i] = math.floor(i / 8)
i = i + 1
pixels[i] = 255
i = i + 1
end
gl._texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 32, 32, 0, gl.RGBA, gl.UNSIGNED_BYTE, table.getn(pixels),pixels)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.bindTexture(gl.TEXTURE_2D, 0)
--Square
squareVertexPositionBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer.buffer_id)
local vertices = { 128, 128, 0, 128, 128, 0, 0, 0 }
gl.bufferData(gl.ARRAY_BUFFER,table.getn(vertices),vertices,gl.STATIC_DRAW)
squareVertexTextureBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexTextureBuffer.buffer_id)
local texcoords = { 1, 1, 0, 1, 1, 0, 0, 0 }
gl.bufferData(gl.ARRAY_BUFFER,table.getn(texcoords),texcoords,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
local function TexImage2DDraw()
if nil ~= shader then
shader:use()
shader:setUniformsForBuiltins()
gl.bindTexture(gl.TEXTURE_2D, texture.texture_id)
gl.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_TEX_COORDS or cc.VERTEX_ATTRIB_FLAG_POSITION)
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer.buffer_id)
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION,2,gl.FLOAT,false,0,0)
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexTextureBuffer.buffer_id)
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS,2,gl.FLOAT,false,0,0)
gl.drawArrays(gl.TRIANGLE_STRIP,0,4)
gl.bindTexture(gl.TEXTURE_2D,0)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
end
initGL()
glNode:registerScriptDrawHandler(TexImage2DDraw)
return texImage2dLayer
end
local function CreateSupportedExtensionsLayer()
local extensionsLayer = cc.Layer:create()
InitTitle(extensionsLayer)
local glNode = gl.glNodeCreate()
extensionsLayer:addChild(glNode,-10)
local supportExtensions = gl.getSupportedExtensions()
if type(supportExtensions) ~= "table" then
print("error:return value not table")
return
end
local count = table.getn(supportExtensions)
local i = 1
for i=1,count do
print(supportExtensions[i])
end
return extensionsLayer
end
local function CreateReadPixelsTest()
local readPixelsLayer = cc.Layer:create()
InitTitle(readPixelsLayer)
local glNode = gl.glNodeCreate()
readPixelsLayer:addChild(glNode,-10)
local x = size.width
local y = size.height
local blue = cc.LayerColor:create(cc.c4b(0, 0, 255, 255))
local red = cc.LayerColor:create(cc.c4b(255, 0, 0, 255))
local green = cc.LayerColor:create(cc.c4b(0, 255, 0, 255))
local white = cc.LayerColor:create(cc.c4b(255, 255, 255, 255))
blue:setScale(0.5)
blue:setPosition(-x / 4, -y / 4)
red:setScale(0.5)
red:setPosition(x / 4, -y / 4)
green:setScale(0.5)
green:setPosition(-x / 4, y / 4)
white:setScale(0.5)
white:setPosition(x / 4, y / 4)
readPixelsLayer:addChild(blue,10)
readPixelsLayer:addChild(white,11)
readPixelsLayer:addChild(green,12)
readPixelsLayer:addChild(red,13)
local scheduler = cc.Director:getInstance():getScheduler()
local function getCurrentResult()
local x = size.width
local y = size.height
local pixelCount = 4
local i = 1
local strFmt = ""
--blue
local bPixels = gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixelCount)
for i=1,pixelCount do
local strTmp = string.format("%d:%d ",i,bPixels[i])
strFmt = strFmt .. strTmp
end
print(strFmt)
strFmt = ""
--red
local rPixels = gl.readPixels(x-1, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixelCount)
for i=1,pixelCount do
local strTmp = string.format("%d:%d ",i,rPixels[i])
strFmt = strFmt .. strTmp
end
print(strFmt)
strFmt = ""
--green
local gPixels = gl.readPixels(0, y-1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixelCount)
for i=1,pixelCount do
local strTmp = string.format("%d:%d ",i,gPixels[i])
strFmt = strFmt .. strTmp
end
print(strFmt)
strFmt = ""
--white
local wPixels = gl.readPixels(x-1, y-1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixelCount)
for i=1,pixelCount do
local strTmp = string.format("%d:%d ",i,wPixels[i])
strFmt = strFmt .. strTmp
end
print(strFmt)
if nil ~= schedulEntry then
scheduler:unscheduleScriptEntry(schedulEntry)
end
end
if nil ~= schedulEntry then
scheduler:unscheduleScriptEntry(schedulEntry)
end
schedulEntry = scheduler:scheduleScriptFunc(getCurrentResult, 0.5, false)
return readPixelsLayer
end
local function createClearTest()
local clearLayer = cc.Layer:create()
InitTitle(clearLayer)
local blue = cc.LayerColor:create(cc.c4b(0, 0, 255, 255))
clearLayer:addChild( blue, 1 )
local glNode = gl.glNodeCreate()
clearLayer:addChild(glNode,10)
--gl.init()
local scheduler = cc.Director:getInstance():getScheduler()
local function clearDraw()
gl.clear(gl.COLOR_BUFFER_BIT)
end
local function getCurrentResult()
local pixels = gl.readPixels(math.floor(size.width/2), math.floor(size.height/2), 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, 4)
local strFmt = ""
for i=1,4 do
local strTmp = string.format("%d:%d ",i,pixels[i])
strFmt = strFmt .. strTmp
end
print(strFmt)
if nil ~= schedulEntry then
scheduler:unscheduleScriptEntry(schedulEntry)
end
end
glNode:setPosition( size.width/2, size.height/2 )
glNode:registerScriptDrawHandler(clearDraw)
if nil ~= schedulEntry then
scheduler:unscheduleScriptEntry(schedulEntry)
end
schedulEntry = scheduler:scheduleScriptFunc(getCurrentResult, 0.5, false)
return clearLayer
end
local function createNodeWebGLAPITest()
local nodeWebGLAPILayer = cc.Layer:create()
InitTitle(nodeWebGLAPILayer)
local glNode = gl.glNodeCreate()
nodeWebGLAPILayer:addChild(glNode,10)
local shaderProgram = {}
local triangleVertexPositionBuffer = {}
local triangleVertexColorBuffer = {}
local squareVertexPositionBuffer = {}
local squareVertexColorBuffer = {}
local pMatrix = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}
local mvMatrix = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}
local vsh = "\n".."attribute vec3 aVertexPosition;\n".."attribute vec4 aVertexColor;\n"..
"uniform mat4 uMVMatrix;\n".."uniform mat4 uPMatrix;\n".."varying vec4 vColor;\n"..
"void main(void) {\n".." gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n".." vColor = aVertexColor;\n"..
"}\n"
local fsh = "\n"..
"#ifdef GL_ES\n"..
"precision mediump float;\n"..
"#endif\n"..
"varying vec4 vColor;\n"..
"void main(void) {\n"..
" gl_FragColor = vColor;\n"..
"}\n"
local function compileShader(source,type)
local shader
if type == "fragment" then
shader = gl.createShader(gl.FRAGMENT_SHADER)
else
shader = gl.createShader(gl.VERTEX_SHADER)
end
gl.shaderSource(shader,source)
gl.compileShader(shader)
local ret = gl.getShaderParameter(shader,gl.COMPILE_STATUS)
if not ret then
--throw
print("Could not compile "..type.." shader")
end
return shader
end
local function initBuffers()
triangleVertexPositionBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer.buffer_id)
local vertices = {
0.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0
}
gl.bufferData(gl.ARRAY_BUFFER, 9, vertices,gl.STATIC_DRAW)
triangleVertexPositionBuffer.itemSize = 3
triangleVertexPositionBuffer.numItems = 3
triangleVertexColorBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer.buffer_id)
local colors = {
1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0
}
gl.bufferData(gl.ARRAY_BUFFER, 12, colors , gl.STATIC_DRAW)
triangleVertexColorBuffer.itemSize = 4
triangleVertexColorBuffer.numItems = 3
squareVertexPositionBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer.buffer_id)
vertices = {
1.0, 1.0, 0.0,
-1.0, 1.0, 0.0,
1.0, -1.0, 0.0,
-1.0, -1.0, 0.0
}
gl.bufferData(gl.ARRAY_BUFFER, 12, vertices,gl.STATIC_DRAW)
squareVertexPositionBuffer.itemSize = 3
squareVertexPositionBuffer.numItems = 4
squareVertexColorBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexColorBuffer.buffer_id)
colors = {
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0
}
gl.bufferData(gl.ARRAY_BUFFER, 16,colors, gl.STATIC_DRAW)
squareVertexColorBuffer.itemSize = 4
squareVertexColorBuffer.numItems = 4
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
local function setMatrixUniforms()
gl.uniformMatrix4fv(shaderProgram.pMatrixUniform,false,table.getn(pMatrix), pMatrix)
gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform,false,table.getn(mvMatrix),mvMatrix)
end
local function nodeWebGLDraw()
gl.useProgram(shaderProgram.program_id)
gl.uniformMatrix4fv(shaderProgram.pMatrixUniform,false,table.getn(pMatrix),pMatrix)
gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform,false,table.getn(mvMatrix),mvMatrix)
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute)
gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute)
--Draw
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer.buffer_id)
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, squareVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0)
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexColorBuffer.buffer_id)
gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, squareVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0)
setMatrixUniforms()
gl.drawArrays(gl.TRIANGLE_STRIP, 0, squareVertexPositionBuffer.numItems)
--DrawArray
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer.buffer_id)
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0)
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer.buffer_id)
gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, triangleVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
local fshader = compileShader(fsh, 'fragment')
local vshader = compileShader(vsh, 'vertex')
shaderProgram.program_id = gl.createProgram()
gl.attachShader(shaderProgram.program_id,vshader)
gl.attachShader(shaderProgram.program_id,fshader)
gl.linkProgram(shaderProgram.program_id)
if not gl.getProgramParameter(shaderProgram.program_id, gl.LINK_STATUS) then
--throw
print("Could not initialise shaders")
end
gl.useProgram(shaderProgram.program_id)
shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram.program_id,"aVertexPosition")
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute)
shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram.program_id,"aVertexColor")
gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute)
shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram.program_id, "uPMatrix")
shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram.program_id, "uMVMatrix")
initBuffers()
glNode:registerScriptDrawHandler(nodeWebGLDraw)
return nodeWebGLAPILayer
end
local function createGLNodeCCAPITest()
local nodeCCAPILayer = cc.Layer:create()
InitTitle(nodeCCAPILayer)
local glNode = gl.glNodeCreate()
nodeCCAPILayer:addChild(glNode,10)
local shader = cc.ShaderCache:getInstance():getProgram("ShaderPositionColor")
local triangleVertexPositionBuffer = {}
local triangleVertexColorBuffer = {}
local squareVertexPositionBuffer = {}
local squareVertexColorBuffer = {}
local function initBuffers()
triangleVertexPositionBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer.buffer_id)
local vertices = {
size.width / 2, size.height,
0, 0,
size.width, 0
}
gl.bufferData(gl.ARRAY_BUFFER, table.getn(vertices), vertices, gl.STATIC_DRAW)
triangleVertexColorBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer.buffer_id)
local colors = {
1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 1.0
}
gl.bufferData(gl.ARRAY_BUFFER, table.getn(colors),colors, gl.STATIC_DRAW)
--Square
squareVertexPositionBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer.buffer_id)
vertices = {
size.width, size.height,
0, size.height,
size.width, 0,
0, 0
}
gl.bufferData(gl.ARRAY_BUFFER, table.getn(vertices), vertices, gl.STATIC_DRAW)
squareVertexColorBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexColorBuffer.buffer_id)
colors = {
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0
};
gl.bufferData(gl.ARRAY_BUFFER, table.getn(colors), colors, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
local function GLNodeCCAPIDraw()
shader:use()
shader:setUniformsForBuiltins()
gl.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_COLOR or cc.VERTEX_ATTRIB_FLAG_POSITION)
--
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer.buffer_id)
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexColorBuffer.buffer_id)
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer.buffer_id)
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer.buffer_id)
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 3)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffers()
glNode:registerScriptDrawHandler(GLNodeCCAPIDraw)
return nodeCCAPILayer
end
local function createGLTexParamterTest()
local glTexParamLayer = cc.Layer:create()
InitTitle(glTexParamLayer)
local glNode = gl.glNodeCreate()
glTexParamLayer:addChild(glNode,10)
local function getTexValues()
gl.bindTexture(gl.TEXTURE_2D, 0)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE )
gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE )
local mag = gl.getTexParameter(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER)
local min = gl.getTexParameter(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER)
local w_s = gl.getTexParameter(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S)
local w_t = gl.getTexParameter(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S)
local strFmt = string.format("%d %d %d %d",mag,min,w_s,w_t)
print(strFmt)
end
getTexValues()
return glTexParamLayer
end
local function createGetUniformTest()
local getUniformLayer = cc.Layer:create()
InitTitle(getUniformLayer)
local glNode = gl.glNodeCreate()
getUniformLayer:addChild(glNode,10)
local pMatrix = {1,2,3,4, 4,3,2,1, 1,2,4,8, 1.1,1.2,1.3,1.4}
local function runTest()
local shader = cc.ShaderCache:getInstance():getProgram("ShaderPositionTextureColor")
local program = shader:getProgram()
shader:use()
local loc = gl.getUniformLocation( program, "CC_MVPMatrix")
gl.uniformMatrix4fv(loc, false, table.getn(pMatrix), pMatrix)
local uniformTable = gl.getUniform( program, loc )
local count = table.getn(uniformTable)
local strFmt = ""
for i=1,count do
local strTmp = string.format("%d: %.16f ",i - 1, uniformTable[i])
strFmt = strFmt..strTmp
end
print(strFmt)
end
runTest()
return getUniformLayer
end
local function createLayerByCurCase(curCase)
if 0 == curCase then
return createShaderRetroEffect()
elseif 1 == curCase then
return createShaderMajoriTest()
elseif 2 == curCase then
return createShaderMandelbrotTest()
elseif 3 == curCase then
return createShaderHeartTest()
elseif 4 == curCase then
return createShaderPlasmaTest()
elseif 5 == curCase then
return createShaderFlowerTest()
elseif 6 == curCase then
return createShaderJuliaTest()
elseif 7 == curCase then
return createGLGetActiveTest()
elseif 8 == curCase then
return createTexImage2DTest()
elseif 9 == curCase then
return CreateSupportedExtensionsLayer()
elseif 10 == curCase then
return CreateReadPixelsTest()
elseif 11 == curCase then
return createClearTest()
elseif 12 == curCase then
return createNodeWebGLAPITest()
elseif 13 == curCase then
return createGLNodeCCAPITest()
elseif 14 == curCase then
return createGLTexParamterTest()
elseif 15 == curCase then
return createGetUniformTest()
end
end
function ShowCurrentTest()
local curScene = cc.Scene:create()
if nil ~= curScene then
if nil ~= curLayer then
local scheduler = cc.Director:getInstance():getScheduler()
if nil ~= schedulEntry then
scheduler:unscheduleScriptEntry(schedulEntry)
end
end
curLayer = createLayerByCurCase(curCase)
if nil ~= curLayer then
curScene:addChild(curLayer)
curLayer:addChild(OrderCallbackMenu(),15)
curScene:addChild(CreateBackMenuItem())
cc.Director:getInstance():replaceScene(curScene)
end
end
end
curLayer = createLayerByCurCase(curCase)
curLayer:addChild(OrderCallbackMenu(),15)
return curLayer
end
function OpenGLTestMain()
local scene = cc.Scene:create()
scene:addChild(OpenGLTestMainLayer())
scene:addChild(CreateBackMenuItem())
return scene
end
| gpl-2.0 |
Zero-K-Experiments/Zero-K-Experiments | LuaUI/Widgets/chili/Headers/skinutils.lua | 2 | 36409 | --//=============================================================================
--//
function _DrawTextureAspect(x,y,w,h ,tw,th)
local twa = w/tw
local tha = h/th
local aspect = 1
if (twa < tha) then
aspect = twa
y = y + h*0.5 - th*aspect*0.5
h = th*aspect
else
aspect = tha
x = x + w*0.5 - tw*aspect*0.5
w = tw*aspect
end
local right = math.ceil(x+w)
local bottom = math.ceil(y+h)
x = math.ceil(x)
y = math.ceil(y)
gl.TexRect(x,y,right,bottom,false,true)
end
local _DrawTextureAspect = _DrawTextureAspect
function _DrawTiledTexture(x,y,w,h, skLeft,skTop,skRight,skBottom, texw,texh, texIndex)
texIndex = texIndex or 0
local txLeft = skLeft/texw
local txTop = skTop/texh
local txRight = skRight/texw
local txBottom = skBottom/texh
--//scale down the texture if we don't have enough space
local scaleY = h/(skTop+skBottom)
local scaleX = w/(skLeft+skRight)
local scale = (scaleX < scaleY) and scaleX or scaleY
if (scale<1) then
skTop = skTop * scale
skBottom = skBottom * scale
skLeft = skLeft * scale
skRight = skRight * scale
end
--//topleft
gl.MultiTexCoord(texIndex,0,0)
gl.Vertex(x, y)
gl.MultiTexCoord(texIndex,0,txTop)
gl.Vertex(x, y+skTop)
gl.MultiTexCoord(texIndex,txLeft,0)
gl.Vertex(x+skLeft, y)
gl.MultiTexCoord(texIndex,txLeft,txTop)
gl.Vertex(x+skLeft, y+skTop)
--//topcenter
gl.MultiTexCoord(texIndex,1-txRight,0)
gl.Vertex(x+w-skRight, y)
gl.MultiTexCoord(texIndex,1-txRight,txTop)
gl.Vertex(x+w-skRight, y+skTop)
--//topright
gl.MultiTexCoord(texIndex,1,0)
gl.Vertex(x+w, y)
gl.MultiTexCoord(texIndex,1,txTop)
gl.Vertex(x+w, y+skTop)
--//right center
gl.MultiTexCoord(texIndex,1,1-txBottom)
gl.Vertex(x+w, y+h-skBottom) --//degenerate
gl.MultiTexCoord(texIndex,1-txRight,txTop)
gl.Vertex(x+w-skRight, y+skTop)
gl.MultiTexCoord(texIndex,1-txRight,1-txBottom)
gl.Vertex(x+w-skRight, y+h-skBottom)
--//background
gl.MultiTexCoord(texIndex,txLeft,txTop)
gl.Vertex(x+skLeft, y+skTop)
gl.MultiTexCoord(texIndex,txLeft,1-txBottom)
gl.Vertex(x+skLeft, y+h-skBottom)
--//left center
gl.MultiTexCoord(texIndex,0,txTop)
gl.Vertex(x, y+skTop)
gl.MultiTexCoord(texIndex,0,1-txBottom)
gl.Vertex(x, y+h-skBottom)
--//bottom right
gl.MultiTexCoord(texIndex,0,1)
gl.Vertex(x, y+h) --//degenerate
gl.MultiTexCoord(texIndex,txLeft,1-txBottom)
gl.Vertex(x+skLeft, y+h-skBottom)
gl.MultiTexCoord(texIndex,txLeft,1)
gl.Vertex(x+skLeft, y+h)
--//bottom center
gl.MultiTexCoord(texIndex,1-txRight,1-txBottom)
gl.Vertex(x+w-skRight, y+h-skBottom)
gl.MultiTexCoord(texIndex,1-txRight,1)
gl.Vertex(x+w-skRight, y+h)
--//bottom right
gl.MultiTexCoord(texIndex,1,1-txBottom)
gl.Vertex(x+w, y+h-skBottom)
gl.MultiTexCoord(texIndex,1,1)
gl.Vertex(x+w, y+h)
end
local _DrawTiledTexture = _DrawTiledTexture
function _DrawTiledBorder(x,y,w,h, skLeft,skTop,skRight,skBottom, texw,texh, texIndex)
texIndex = texIndex or 0
local txLeft = skLeft/texw
local txTop = skTop/texh
local txRight = skRight/texw
local txBottom = skBottom/texh
--//scale down the texture if we don't have enough space
local scaleY = h/(skTop+skBottom)
local scaleX = w/(skLeft+skRight)
local scale = (scaleX < scaleY) and scaleX or scaleY
if (scale<1) then
skTop = skTop * scale
skBottom = skBottom * scale
skLeft = skLeft * scale
skRight = skRight * scale
end
--//topleft
gl.MultiTexCoord(texIndex,0,0)
gl.Vertex(x, y)
gl.MultiTexCoord(texIndex,0,txTop)
gl.Vertex(x, y+skTop)
gl.MultiTexCoord(texIndex,txLeft,0)
gl.Vertex(x+skLeft, y)
gl.MultiTexCoord(texIndex,txLeft,txTop)
gl.Vertex(x+skLeft, y+skTop)
--//topcenter
gl.MultiTexCoord(texIndex,1-txRight,0)
gl.Vertex(x+w-skRight, y)
gl.MultiTexCoord(texIndex,1-txRight,txTop)
gl.Vertex(x+w-skRight, y+skTop)
--//topright
gl.MultiTexCoord(texIndex,1,0)
gl.Vertex(x+w, y)
gl.MultiTexCoord(texIndex,1,txTop)
gl.Vertex(x+w, y+skTop)
--//right center
gl.Vertex(x+w, y+skTop) --//degenerate
gl.MultiTexCoord(texIndex,1-txRight,txTop)
gl.Vertex(x+w-skRight, y+skTop)
gl.MultiTexCoord(texIndex,1,1-txBottom)
gl.Vertex(x+w, y+h-skBottom)
gl.MultiTexCoord(texIndex,1-txRight,1-txBottom)
gl.Vertex(x+w-skRight, y+h-skBottom)
--//bottom right
gl.MultiTexCoord(texIndex,1,1)
gl.Vertex(x+w, y+h)
gl.MultiTexCoord(texIndex,1-txRight,1)
gl.Vertex(x+w-skRight, y+h)
--//bottom center
gl.Vertex(x+w-skRight, y+h) --//degenerate
gl.MultiTexCoord(texIndex,1-txRight,1-txBottom)
gl.Vertex(x+w-skRight, y+h-skBottom)
gl.MultiTexCoord(texIndex,txLeft,1)
gl.Vertex(x+skLeft, y+h)
gl.MultiTexCoord(texIndex,txLeft,1-txBottom)
gl.Vertex(x+skLeft, y+h-skBottom)
--//bottom left
gl.MultiTexCoord(texIndex,0,1)
gl.Vertex(x, y+h)
gl.MultiTexCoord(texIndex,0,1-txBottom)
gl.Vertex(x, y+h-skBottom)
--//left center
gl.Vertex(x, y+h-skBottom) --//degenerate
gl.MultiTexCoord(texIndex,0,txTop)
gl.Vertex(x, y+skTop)
gl.MultiTexCoord(texIndex,txLeft,1-txBottom)
gl.Vertex(x+skLeft, y+h-skBottom)
gl.MultiTexCoord(texIndex,txLeft,txTop)
gl.Vertex(x+skLeft, y+skTop)
end
local _DrawTiledBorder = _DrawTiledBorder
local function _DrawDragGrip(obj)
local x = obj.x + 13
local y = obj.y + 8
local w = obj.dragGripSize[1]
local h = obj.dragGripSize[2]
gl.Color(0.8,0.8,0.8,0.9)
gl.Vertex(x, y + h*0.5)
gl.Vertex(x + w*0.5, y)
gl.Vertex(x + w*0.5, y + h*0.5)
gl.Color(0.3,0.3,0.3,0.9)
gl.Vertex(x + w*0.5, y + h*0.5)
gl.Vertex(x + w*0.5, y)
gl.Vertex(x + w, y + h*0.5)
gl.Vertex(x + w*0.5, y + h)
gl.Vertex(x, y + h*0.5)
gl.Vertex(x + w*0.5, y + h*0.5)
gl.Color(0.1,0.1,0.1,0.9)
gl.Vertex(x + w*0.5, y + h)
gl.Vertex(x + w*0.5, y + h*0.5)
gl.Vertex(x + w, y + h*0.5)
end
local function _DrawResizeGrip(obj)
if (obj.resizable) then
local x = obj.x
local y = obj.y
local resizeBox = GetRelativeObjBox(obj,obj.boxes.resize)
x = x-1
y = y-1
gl.Color(1,1,1,0.2)
gl.Vertex(x + resizeBox[1], y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2])
gl.Vertex(x + resizeBox[1] + math.ceil((resizeBox[3] - resizeBox[1])*0.33), y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2] + math.ceil((resizeBox[4] - resizeBox[2])*0.33))
gl.Vertex(x + resizeBox[1] + math.ceil((resizeBox[3] - resizeBox[1])*0.66), y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2] + math.ceil((resizeBox[4] - resizeBox[2])*0.66))
x = x+1
y = y+1
gl.Color(0.1, 0.1, 0.1, 0.9)
gl.Vertex(x + resizeBox[1], y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2])
gl.Vertex(x + resizeBox[1] + math.ceil((resizeBox[3] - resizeBox[1])*0.33), y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2] + math.ceil((resizeBox[4] - resizeBox[2])*0.33))
gl.Vertex(x + resizeBox[1] + math.ceil((resizeBox[3] - resizeBox[1])*0.66), y + resizeBox[4])
gl.Vertex(x + resizeBox[3], y + resizeBox[2] + math.ceil((resizeBox[4] - resizeBox[2])*0.66))
end
end
local function _DrawCursor(x, y, w, h)
gl.Vertex(x, y)
gl.Vertex(x, y + h)
gl.Vertex(x + w, y)
gl.Vertex(x + w, y + h)
end
local function _DrawSelection(x, y, w, h)
gl.Vertex(x, y)
gl.Vertex(x, y + h)
gl.Vertex(x + w, y)
gl.Vertex(x + w, y + h)
end
--//=============================================================================
--//
function DrawWindow(obj)
local x = obj.x
local y = obj.y
local w = obj.width
local h = obj.height
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
local c = obj.color
if (c) then
gl.Color(c)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,obj.TileImage,obj)
local texInfo = gl.TextureInfo(obj.TileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th)
gl.Texture(0,false)
if (obj.caption) then
obj.font:Print(obj.caption, x+w*0.5, y+9, "center")
end
end
--//=============================================================================
--//
function DrawButton(obj)
local x = obj.x
local y = obj.y
local w = obj.width
local h = obj.height
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
local bgcolor = obj.backgroundColor
if not obj.supressButtonReaction then
if (obj.state.pressed) then
bgcolor = obj.pressBackgroundColor or mulColor(bgcolor, 0.4)
elseif (obj.state.hovered) --[[ or (obj.state.focused)]] then
bgcolor = obj.focusColor
--bgcolor = mixColors(bgcolor, obj.focusColor, 0.5)
end
end
gl.Color(bgcolor)
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
local fgcolor = obj.borderColor
if not obj.supressButtonReaction then
if (obj.state.pressed) then
fgcolor = obj.pressForegroundColor or mulColor(fgcolor, 0.4)
elseif (obj.state.hovered) --[[ or (obj.state.focused)]] then
fgcolor = obj.focusColor
end
end
gl.Color(fgcolor)
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
if (obj.caption) then
obj.font:Print(obj.caption, x+w*0.5, y+h*0.5, "center", "center")
end
end
function DrawComboBox(self)
DrawButton(self)
if (self.state.pressed) then
gl.Color(self.focusColor)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,self.TileImageArrow,self)
local texInfo = gl.TextureInfo(self.TileImageArrow) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
_DrawTextureAspect(self.x + self.width - self.padding[3], self.y, self.padding[3], self.height, tw,th)
gl.Texture(0,false)
end
function DrawEditBox(obj)
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
gl.Translate(obj.x, obj.y, 0) -- Remove with new chili, does translates for us.
gl.Color(obj.backgroundColor)
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0, 0, obj.width, obj.height, skLeft,skTop,skRight,skBottom, tw,th)
--gl.Texture(0,false)
if obj.state.focused or obj.state.hovered then
gl.Color(obj.focusColor)
else
gl.Color(obj.borderColor)
end
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, 0, 0, obj.width, obj.height, skLeft,skTop,skRight,skBottom, tw,th)
gl.Texture(0,false)
local text = obj.text
local font = obj.font
local displayHint = false
if text == "" and not obj.state.focused then
text = obj.hint
displayHint = true
font = obj.hintFont
end
if (text) then
if obj.passwordInput and not displayHint then
text = string.rep("*", #text)
end
if (obj.offset > obj.cursor) and not obj.multiline then
obj.offset = obj.cursor
end
local clientX,clientY,clientWidth,clientHeight = unpack4(obj.clientArea)
--// make cursor pos always visible (when text is longer than editbox!)
if not obj.multiline then
repeat
local txt = text:sub(obj.offset, obj.cursor)
local wt = font:GetTextWidth(txt)
if (wt <= clientWidth) then
break
end
if (obj.offset >= obj.cursor) then
break
end
obj.offset = obj.offset + 1
until (false)
end
local txt = text:sub(obj.offset)
--// strip part at the end that exceeds the editbox
local lsize = math.max(0, font:WrapText(txt, clientWidth, clientHeight):len() - 3) -- find a good start (3 dots at end if stripped)
while (lsize <= txt:len()) do
local wt = font:GetTextWidth(txt:sub(1, lsize))
if (wt > clientWidth) then
break
end
lsize = lsize + 1
end
txt = txt:sub(1, lsize - 1)
gl.Color(1,1,1,1)
if obj.multiline then
if obj.parent and obj.parent:InheritsFrom("scrollpanel") then
local scrollPosY = obj.parent.scrollPosY
local scrollHeight = obj.parent.clientArea[4]
local h, d, numLines = obj.font:GetTextHeight(obj.text);
local minDrawY = scrollPosY - (h or 0)
local maxDrawY = scrollPosY + scrollHeight + (h or 0)
for _, line in pairs(obj.physicalLines) do
local drawPos = clientY + line.y
if drawPos > minDrawY and drawPos < maxDrawY then
font:Draw(line.text, clientX, clientY + line.y)
end
end
else
for _, line in pairs(obj.physicalLines) do
font:Draw(line.text, clientX, clientY + line.y)
end
end
else
font:DrawInBox(txt, clientX, clientY, clientWidth, clientHeight, obj.align, obj.valign)
end
if obj.state.focused and obj.editable then
local cursorTxt = text:sub(obj.offset, obj.cursor - 1)
local cursorX = font:GetTextWidth(cursorTxt)
local dt = Spring.DiffTimers(Spring.GetTimer(), obj._interactedTime)
local alpha
if obj.cursorFramerate then
if math.floor(dt*obj.cursorFramerate)%2 == 0 then
alpha = 0.8
else
alpha = 0
end
else
local as = math.sin(dt * 8);
local ac = math.cos(dt * 8);
if (as < 0) then
as = 0
end
if (ac < 0) then
ac = 0
end
alpha = as + ac
if (alpha > 1) then
alpha = 1
end
alpha = 0.8 * alpha
end
local cc = obj.cursorColor
gl.Color(cc[1], cc[2], cc[3], cc[4] * alpha)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawCursor, cursorX + clientX - 1, clientY, 3, clientHeight)
end
if obj.selStart and obj.state.focused then
local cc = obj.selectionColor
gl.Color(cc[1], cc[2], cc[3], cc[4])
local top, bottom = obj.selStartPhysicalY, obj.selEndPhysicalY
local left, right = obj.selStartPhysical, obj.selEndPhysical
if obj.multiline and top > bottom then
top, bottom = bottom, top
left, right = right, left
elseif top == bottom and left > right then
left, right = right, left
end
local y = clientY
local height = clientHeight
if obj.multiline and top == bottom then
local line = obj.physicalLines[top]
text = line.text
y = y + line.y
height = line.lh
end
if not obj.multiline or top == bottom then
local leftTxt = text:sub(obj.offset, left - 1)
local leftX = font:GetTextWidth(leftTxt)
local rightTxt = text:sub(obj.offset, right - 1)
local rightX = font:GetTextWidth(rightTxt)
local w = rightX - leftX
-- limit the selection to the editbox width
w = math.min(w, obj.width - leftX - 3)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawSelection, leftX + clientX - 1, y, w, height)
else
local topLine, bottomLine = obj.physicalLines[top], obj.physicalLines[bottom]
local leftTxt = topLine.text:sub(obj.offset, left - 1)
local leftX = font:GetTextWidth(leftTxt)
local rightTxt = bottomLine.text:sub(obj.offset, right - 1)
local rightX = font:GetTextWidth(rightTxt)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawSelection, leftX + clientX - 1, clientY + topLine.y, topLine.tw - leftX, topLine.lh)
for i = top+1, bottom-1 do
local line = obj.physicalLines[i]
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawSelection, clientX - 1, clientY + line.y, line.tw, line.lh)
end
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawSelection, clientX - 1, clientY + bottomLine.y, rightX, bottomLine.lh)
end
end
end
gl.Translate(-obj.x, -obj.y, 0) -- Remove with new chili, does translates for us.
end
--//=============================================================================
--//
function DrawPanel(obj)
local x = obj.x
local y = obj.y
local w = obj.width
local h = obj.height
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
gl.Color(obj.backgroundColor)
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
gl.Color(obj.borderColor)
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawItemBkGnd(obj,x,y,w,h,state)
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
if (state=="selected") then
gl.Color(obj.colorBK_selected)
else
gl.Color(obj.colorBK)
end
TextureHandler.LoadTexture(0,obj.imageBK,obj)
local texInfo = gl.TextureInfo(obj.imageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if (state=="selected") then
gl.Color(obj.colorFG_selected)
else
gl.Color(obj.colorFG)
end
TextureHandler.LoadTexture(0,obj.imageFG,obj)
local texInfo = gl.TextureInfo(obj.imageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawScrollPanelBorder(self)
local clientX,clientY,clientWidth,clientHeight = unpack4(self.clientArea)
local contX,contY,contWidth,contHeight = unpack4(self.contentArea)
do
TextureHandler.LoadTexture(0,self.BorderTileImage,self)
local texInfo = gl.TextureInfo(self.BorderTileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
local skLeft,skTop,skRight,skBottom = unpack4(self.bordertiles)
local width = self.width
local height = self.height
if (self._vscrollbar) then
width = width - self.scrollbarSize - 1
end
if (self._hscrollbar) then
height = height - self.scrollbarSize - 1
end
gl.Color(self.borderColor)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledBorder, self.x,self.y,width,height, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
end
--//=============================================================================
--//
function DrawScrollPanel(obj)
local clientX,clientY,clientWidth,clientHeight = unpack4(obj.clientArea)
local contX,contY,contWidth,contHeight = unpack4(obj.contentArea)
if (obj.BackgroundTileImage) then
TextureHandler.LoadTexture(0,obj.BackgroundTileImage,obj)
local texInfo = gl.TextureInfo(obj.BackgroundTileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
local skLeft,skTop,skRight,skBottom = unpack4(obj.bkgndtiles)
local width = obj.width
local height = obj.height
if (obj._vscrollbar) then
width = width - obj.scrollbarSize - 1
end
if (obj._hscrollbar) then
height = height - obj.scrollbarSize - 1
end
gl.Color(obj.backgroundColor)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, obj.x,obj.y,width,height, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
if obj._vscrollbar then
local x = obj.x + obj.width - obj.scrollbarSize
local y = obj.y
local w = obj.scrollbarSize
local h = obj.height --FIXME what if hscrollbar is visible
if (obj._hscrollbar) then
h = h - obj.scrollbarSize
end
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
TextureHandler.LoadTexture(0,obj.TileImage,obj)
local texInfo = gl.TextureInfo(obj.TileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if obj._vscrolling or obj._vHovered then
gl.Color(obj.KnobColorSelected)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,obj.KnobTileImage,obj)
texInfo = gl.TextureInfo(obj.KnobTileImage) or {xsize=1, ysize=1}
tw,th = texInfo.xsize, texInfo.ysize
skLeft,skTop,skRight,skBottom = unpack4(obj.KnobTiles)
local pos = obj.scrollPosY / contHeight
local visible = clientHeight / contHeight
local gripy = math.floor(y + h * pos) + 0.5
local griph = math.floor(h * visible)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,gripy,obj.scrollbarSize,griph, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
gl.Color(1,1,1,1)
end
if obj._hscrollbar then
gl.Color(1,1,1,1)
local x = obj.x
local y = obj.y + obj.height - obj.scrollbarSize
local w = obj.width
local h = obj.scrollbarSize
if (obj._vscrollbar) then
w = w - obj.scrollbarSize
end
local skLeft,skTop,skRight,skBottom = unpack4(obj.htiles)
TextureHandler.LoadTexture(0,obj.HTileImage,obj)
local texInfo = gl.TextureInfo(obj.HTileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if obj._hscrolling or obj._hHovered then
gl.Color(obj.KnobColorSelected)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,obj.HKnobTileImage,obj)
texInfo = gl.TextureInfo(obj.HKnobTileImage) or {xsize=1, ysize=1}
tw,th = texInfo.xsize, texInfo.ysize
skLeft,skTop,skRight,skBottom = unpack4(obj.HKnobTiles)
local pos = obj.scrollPosX / contWidth
local visible = clientWidth / contWidth
local gripx = math.floor(x + w * pos) + 0.5
local gripw = math.floor(w * visible)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, gripx,y,gripw,obj.scrollbarSize, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
end
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawCheckbox(obj)
local boxSize = obj.boxsize
local x = obj.x + obj.width - boxSize
local y = obj.y + obj.height*0.5 - boxSize*0.5
local w = boxSize
local h = boxSize
local tx = 0
local ty = obj.height * 0.5 --// verticale center
if obj.boxalign == "left" then
x = obj.x
tx = boxSize + 2
end
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
if (obj.state.hovered) then
gl.Color(obj.focusColor)
else
gl.Color(1,1,1,1)
end
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if (obj.state.checked) then
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
end
gl.Texture(0,false)
gl.Color(1,1,1,1)
if (obj.caption) then
obj.font:Print(obj.caption, obj.x + tx, obj.y + ty, nil, "center")
end
end
--//=============================================================================
--//
function DrawProgressbar(obj)
local x = obj.x
local y = obj.y
local w = obj.width
local h = obj.height
local percent = (obj.value-obj.min)/(obj.max-obj.min)
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
gl.Color(obj.backgroundColor)
if not obj.noSkin then
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
end
gl.Color(obj.color)
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
-- workaround for catalyst >12.6 drivers: do the "clipping" by multiplying width by percentage in glBeginEnd instead of using glClipPlane
-- fuck AMD
--gl.ClipPlane(1, -1,0,0, x+w*percent)
if obj.fillPadding then
x, y = x + obj.fillPadding[1], y + obj.fillPadding[2]
w, h = w - (obj.fillPadding[1] + obj.fillPadding[3]), h - (obj.fillPadding[2] + obj.fillPadding[4])
end
if (obj.orientation == "horizontal") then
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w*percent,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
else
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y + (h - h*percent),w,h*percent, skLeft,skTop,skRight,skBottom, tw,th, 0)
end
--gl.ClipPlane(1, false)
gl.Texture(0,false)
if (obj.caption) then
(obj.font):Print(obj.caption, x+w*0.5, y+h*0.5, "center", "center")
end
end
--//=============================================================================
--//
function DrawTrackbar(self)
local percent = self:_GetPercent()
local x = self.x
local y = self.y
local w = self.width
local h = self.height
local skLeft,skTop,skRight,skBottom = unpack4(self.tiles)
local pdLeft,pdTop,pdRight,pdBottom = unpack4(self.hitpadding)
gl.Color(1,1,1,1)
if not self.noDrawBar then
TextureHandler.LoadTexture(0,self.TileImage,self)
local texInfo = gl.TextureInfo(self.TileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
end
if not self.noDrawStep then
TextureHandler.LoadTexture(0,self.StepImage,self)
local texInfo = gl.TextureInfo(self.StepImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
--// scale the thumb down if we don't have enough space
if (th>h) then
tw = math.ceil(tw*(h/th))
th = h
end
if (tw>w) then
th = math.ceil(th*(w/tw))
tw = w
end
local barWidth = w - (pdLeft + pdRight)
local stepWidth = barWidth / ((self.max - self.min)/self.step)
if ((self.max - self.min)/self.step)<20 then
local newStepWidth = stepWidth
if (newStepWidth<20) then
newStepWidth = stepWidth*2
end
if (newStepWidth<20) then
newStepWidth = stepWidth*5
end
if (newStepWidth<20) then
newStepWidth = stepWidth*10
end
stepWidth = newStepWidth
local my = y+h*0.5
local mx = x+pdLeft+stepWidth
while (mx<(x+pdLeft+barWidth)) do
gl.TexRect(math.ceil(mx-tw*0.5),math.ceil(my-th*0.5),math.ceil(mx+tw*0.5),math.ceil(my+th*0.5),false,true)
mx = mx+stepWidth
end
end
end
if (self.state.hovered) then
gl.Color(self.focusColor)
else
gl.Color(1,1,1,1)
end
if not self.noDrawThumb then
TextureHandler.LoadTexture(0,self.ThumbImage,self)
local texInfo = gl.TextureInfo(self.ThumbImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
--// scale the thumb down if we don't have enough space
tw = math.ceil(tw * (h / th))
th = h
local barWidth = w - (pdLeft + pdRight)
local mx = x + pdLeft + barWidth * percent
local my = y + h * 0.5
mx = math.floor(mx - tw * 0.5)
my = math.floor(my - th * 0.5)
gl.TexRect(mx, my, mx + tw, my + th, false, true)
end
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawTreeviewNode(self)
if CompareLinks(self.treeview.selected,self) then
local x = self.x + self.clientArea[1]
local y = self.y
local w = self.children[1].width
local h = self.clientArea[2] + self.children[1].height
local skLeft,skTop,skRight,skBottom = unpack4(self.treeview.tiles)
gl.Color(1,1,1,1)
TextureHandler.LoadTexture(0,self.treeview.ImageNodeSelected,self)
local texInfo = gl.TextureInfo(self.treeview.ImageNodeSelected) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
end
end
local function _DrawLineV(x, y1, y2, width, next_func, ...)
gl.Vertex(x-width*0.5, y1)
gl.Vertex(x+width*0.5, y1)
gl.Vertex(x-width*0.5, y2)
gl.Vertex(x+width*0.5, y1)
gl.Vertex(x-width*0.5, y2)
gl.Vertex(x+width*0.5, y2)
if (next_func) then
next_func(...)
end
end
local function _DrawLineH(x1, x2, y, width, next_func, ...)
gl.Vertex(x1, y-width*0.5)
gl.Vertex(x1, y+width*0.5)
gl.Vertex(x2, y-width*0.5)
gl.Vertex(x1, y+width*0.5)
gl.Vertex(x2, y-width*0.5)
gl.Vertex(x2, y+width*0.5)
if (next_func) then
next_func(...)
end
end
function DrawTreeviewNodeTree(self)
local x1 = self.x + math.ceil(self.padding[1]*0.5)
local x2 = self.x + self.padding[1]
local y1 = self.y
local y2 = self.y + self.height
local y3 = self.y + self.padding[2] + math.ceil(self.children[1].height*0.5)
if (self.parent)and(CompareLinks(self,self.parent.nodes[#self.parent.nodes])) then
y2 = y3
end
gl.Color(self.treeview.treeColor)
gl.BeginEnd(GL.TRIANGLES, _DrawLineV, x1-0.5, y1, y2, 1, _DrawLineH, x1, x2, y3-0.5, 1)
if (not self.nodes[1]) then
return
end
gl.Color(1,1,1,1)
local image = self.ImageExpanded or self.treeview.ImageExpanded
if (not self.expanded) then
image = self.ImageCollapsed or self.treeview.ImageCollapsed
end
TextureHandler.LoadTexture(0, image, self)
local texInfo = gl.TextureInfo(image) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
_DrawTextureAspect(self.x,self.y,math.ceil(self.padding[1]),math.ceil(self.children[1].height) ,tw,th)
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawLine(self)
gl.Color(self.borderColor)
if (self.style:find("^v")) then
local skLeft,skTop,skRight,skBottom = unpack4(self.tilesV)
TextureHandler.LoadTexture(0,self.TileImageV,self)
local texInfo = gl.TextureInfo(self.TileImageV) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, self.x + self.width * 0.5 - 2, self.y, 4, self.height, skLeft,skTop,skRight,skBottom, tw,th, 0)
else
local skLeft,skTop,skRight,skBottom = unpack4(self.tiles)
TextureHandler.LoadTexture(0,self.TileImage,self)
local texInfo = gl.TextureInfo(self.TileImage) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, self.x, self.y + self.height * 0.5 - 2, self.width, 4, skLeft,skTop,skRight,skBottom, tw,th, 0)
end
gl.Texture(0,false)
end
--//=============================================================================
--//
function DrawTabBarItem(obj)
local x = obj.x
local y = obj.y
local w = obj.width
local h = obj.height
local skLeft,skTop,skRight,skBottom = unpack4(obj.tiles)
if (obj.state.pressed) then
gl.Color(mulColor(obj.backgroundColor,0.4))
elseif (obj.state.hovered) then
gl.Color(obj.focusColor)
elseif (obj.state.selected) then
gl.Color(obj.focusColor)
else
gl.Color(obj.backgroundColor)
end
TextureHandler.LoadTexture(0,obj.TileImageBK,obj)
local texInfo = gl.TextureInfo(obj.TileImageBK) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
--gl.Texture(0,false)
if (obj.state.pressed) then
gl.Color(0.6,0.6,0.6,1) --FIXME
elseif (obj.state.selected) then
gl.Color(obj.focusColor)
else
gl.Color(obj.borderColor)
end
TextureHandler.LoadTexture(0,obj.TileImageFG,obj)
local texInfo = gl.TextureInfo(obj.TileImageFG) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
gl.BeginEnd(GL.TRIANGLE_STRIP, _DrawTiledTexture, x,y,w,h, skLeft,skTop,skRight,skBottom, tw,th, 0)
gl.Texture(0,false)
if (obj.caption) then
local cx,cy,cw,ch = unpack4(obj.clientArea)
obj.font:DrawInBox(obj.caption, x + cx, y + cy, cw, ch, "center", "center")
end
end
--//=============================================================================
--//
function DrawDragGrip(obj)
gl.BeginEnd(GL.TRIANGLES, _DrawDragGrip, obj)
end
function DrawResizeGrip(obj)
gl.BeginEnd(GL.LINES, _DrawResizeGrip, obj)
end
--//=============================================================================
--// HitTest helpers
function _ProcessRelative(code, total)
--// FIXME: duplicated in control.lua!
if (type(code) == "string") then
local percent = tonumber(code:sub(1,-2)) or 0
if (percent<0) then
percent = 0
elseif (percent>100) then
percent = 100
end
return math.floor(total * percent)
elseif (code<0) then
return math.floor(total + code)
else
return math.floor(code)
end
end
function GetRelativeObjBox(obj,boxrelative)
return {
_ProcessRelative(boxrelative[1], obj.width),
_ProcessRelative(boxrelative[2], obj.height),
_ProcessRelative(boxrelative[3], obj.width),
_ProcessRelative(boxrelative[4], obj.height)
}
end
--//=============================================================================
--//
function NCHitTestWithPadding(obj,mx,my)
local hp = obj.hitpadding
local x = hp[1]
local y = hp[2]
local w = obj.width - hp[1] - hp[3]
local h = obj.height - hp[2] - hp[4]
--// early out
if (not InRect({x,y,w,h},mx,my)) then
return false
end
local resizable = obj.resizable
local draggable = obj.draggable
local dragUseGrip = obj.dragUseGrip
if IsTweakMode() then
resizable = resizable or obj.tweakResizable
draggable = draggable or obj.tweakDraggable
dragUseGrip = draggable and obj.tweakDragUseGrip
end
if (resizable) then
local resizeBox = GetRelativeObjBox(obj,obj.boxes.resize)
if (InRect(resizeBox,mx,my)) then
return obj
end
end
if (dragUseGrip) then
local dragBox = GetRelativeObjBox(obj,obj.boxes.drag)
if (InRect(dragBox,mx,my)) then
return obj
end
elseif (draggable) then
return obj
end
end
function WindowNCMouseDown(obj,x,y)
local resizable = obj.resizable
local draggable = obj.draggable
local dragUseGrip = obj.dragUseGrip
if IsTweakMode() then
resizable = resizable or obj.tweakResizable
draggable = draggable or obj.tweakDraggable
dragUseGrip = draggable and obj.tweakDragUseGrip
end
if (resizable) then
local resizeBox = GetRelativeObjBox(obj,obj.boxes.resize)
if (InRect(resizeBox,x,y)) then
obj:StartResizing(x,y)
return obj
end
end
if (dragUseGrip) then
local dragBox = GetRelativeObjBox(obj,obj.boxes.drag)
if (InRect(dragBox,x,y)) then
obj:StartDragging()
return obj
end
end
end
function WindowNCMouseDownPostChildren(obj,x,y)
local draggable = obj.draggable
local dragUseGrip = obj.dragUseGrip
if IsTweakMode() then
draggable = draggable or obj.tweakDraggable
dragUseGrip = draggable and obj.tweakDragUseGrip
end
if (draggable and not dragUseGrip) then
obj:StartDragging()
return obj
end
end
--//=============================================================================
| gpl-2.0 |
Scavenge/darkstar | scripts/zones/Open_sea_route_to_Al_Zahbi/npcs/Adeben.lua | 14 | 1153 | -----------------------------------
-- Area: Open_sea_route_to_Al_Zahbi
-- NPC: Adeben
-- Notes: Tells ship ETA time
-- @pos 0.340 -12.232 -4.120 46
-----------------------------------
package.loaded["scripts/zones/Open_sea_route_to_Al_Zahbi/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Open_sea_route_to_Al_Zahbi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(ON_WAY_TO_AL_ZAHBI,0,0); -- Earth Time, Vana Hours. Needs a get-time function for boat?
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Upper_Jeuno/npcs/Renik.lua | 17 | 1376 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Renik
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Upper_Jeuno/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatJeuno = player:getVar("WildcatJeuno");
if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,8) == false) then
player:startEvent(10086);
else
player:startEvent(0x00A8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 10086) then
player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",8,true);
end
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Pashhow_Marshlands/npcs/Ioupie_RK.lua | 14 | 3344 | -----------------------------------
-- Area: Pashhow Marshlands
-- NPC: Ioupie, R.K.
-- Type: Border Conquest Guards
-- @pos 536.291 23.517 694.063 109
-----------------------------------
package.loaded["scripts/zones/Pashhow_Marshlands/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Pashhow_Marshlands/TextIDs");
local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = DERFLAND;
local csid = 0x7ffa;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
ghoghnousteam/ghoghnous | plugins/isX.lua | 605 | 2031 | local https = require "ssl.https"
local ltn12 = require "ltn12"
local function request(imageUrl)
-- Edit data/mashape.lua with your Mashape API key
-- http://docs.mashape.com/api-keys
local mashape = load_from_file('data/mashape.lua', {
api_key = ''
})
local api_key = mashape.api_key
if api_key:isempty() then
return nil, 'Configure your Mashape API Key'
end
local api = "https://sphirelabs-advanced-porn-nudity-and-adult-content-detection.p.mashape.com/v1/get/index.php?"
local parameters = "&url="..(URL.escape(imageUrl) or "")
local url = api..parameters
local respbody = {}
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "Accept: application/json"
}
print(url)
local body, code, headers, status = https.request{
url = url,
method = "GET",
headers = headers,
sink = ltn12.sink.table(respbody),
protocol = "tlsv1"
}
if code ~= 200 then return "", code end
local body = table.concat(respbody)
return body, code
end
local function parseData(data)
local jsonBody = json:decode(data)
local response = ""
print(data)
if jsonBody["Error Occured"] ~= nil then
response = response .. jsonBody["Error Occured"]
elseif jsonBody["Is Porn"] == nil or jsonBody["Reason"] == nil then
response = response .. "I don't know if that has adult content or not."
else
if jsonBody["Is Porn"] == "True" then
response = response .. "Beware!\n"
end
response = response .. jsonBody["Reason"]
end
return jsonBody["Is Porn"], response
end
local function run(msg, matches)
local data, code = request(matches[1])
if code ~= 200 then return "There was an error. "..code end
local isPorn, result = parseData(data)
return result
end
return {
description = "Does this photo contain adult content?",
usage = {
"!isx [url]",
"!isporn [url]"
},
patterns = {
"^!is[x|X] (.*)$",
"^!is[p|P]orn (.*)$"
},
run = run
} | gpl-2.0 |
Scavenge/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Kemha_Flasehp.lua | 29 | 2315 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Kemha Flasehp
-- Type: Fishing Normal/Adv. Image Support
-- @pos -28.4 -6 -98 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local guildMember = isGuildMember(player,5);
if (guildMember == 1) then
if (trade:hasItemQty(2184,1) and trade:getItemCount() == 1) then
if (player:hasStatusEffect(EFFECT_FISHING_IMAGERY) == false) then
player:tradeComplete();
player:startEvent(0x0283,8,0,0,0,188,0,6,0);
else
npc:showText(npc, IMAGE_SUPPORT_ACTIVE);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,5);
local SkillLevel = player:getSkillLevel(SKILL_FISHING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_FISHING_IMAGERY) == false) then
player:startEvent(0x0282,8,0,0,511,1,0,0,2184);
else
player:startEvent(0x0282,8,0,0,511,1,19267,0,2184);
end
else
player:startEvent(0x0282,0,0,0,0,0,0,0,0); -- Standard Dialogue
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0282 and option == 1) then
player:messageSpecial(IMAGE_SUPPORT,0,0,1);
player:addStatusEffect(EFFECT_FISHING_IMAGERY,1,0,3600);
elseif (csid == 0x0283) then
player:messageSpecial(IMAGE_SUPPORT,0,0,0);
player:addStatusEffect(EFFECT_FISHING_IMAGERY,2,0,7200);
end
end; | gpl-3.0 |
Scavenge/darkstar | scripts/zones/Maze_of_Shakhrami/npcs/Ahko_Mhalijikhari.lua | 14 | 2050 | -----------------------------------
-- Area: Maze of Shakhrami
-- NPC: Ahko Mhalijikhari
-- Type: Quest NPC
-- @pos -344.617 -12.226 -166.233 198
-- 0x003d 0x003e 0x003f 0x0040 0x0041
-----------------------------------
package.loaded["scripts/zones/Maze_of_Shakhrami/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Maze_of_Shakhrami/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:startEvent(0x0040);
if (player:getQuestStatus(WINDURST,ECO_WARRIOR_WIN) ~= QUEST_AVAILABLE and player:getVar("ECO_WARRIOR_ACTIVE") == 238) then
if (player:hasKeyItem(INDIGESTED_MEAT)) then
player:startEvent(0x0041); -- After NM's dead
elseif (player:hasStatusEffect(EFFECT_LEVEL_RESTRICTION) == false) then
player:startEvent(0x003e); --
else
player:startEvent(0x0040);
end
else
player:startEvent(0x003d); -- default
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
printf("RESULT: %u",option);
if (csid == 0x003e and option == 1) then
player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,20,0,0);
elseif (csid == 0x0041) then
player:setVar("ECOR_WAR_WIN-NMs_killed",0);
player:delStatusEffect(EFFECT_LEVEL_RESTRICTION);
elseif (csid == 0x0040) then
player:delStatusEffect(EFFECT_LEVEL_RESTRICTION);
end
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/globals/items/coin_cookie.lua | 12 | 1338 | -----------------------------------------
-- ID: 4520
-- Item: coin_cookie
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Magic Regen While Healing 6
-- Vermin Killer 12
-- Poison Resist 12
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4520);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MPHEAL, 6);
target:addMod(MOD_VERMIN_KILLER, 12);
target:addMod(MOD_POISONRES, 12);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MPHEAL, 6);
target:delMod(MOD_VERMIN_KILLER, 12);
target:delMod(MOD_POISONRES, 12);
end;
| gpl-3.0 |
LuaDist2/lustache | spec/context_spec.lua | 8 | 1615 | local lustache = require "lustache" -- only needed to set string.split
local topic = function()
local view = { name = 'parent', message = 'hi', a = { b = 'b' } }
local context = require("lustache.context"):new(view)
return context, view
end
local push = function(context)
local child_view = { name = 'child', c = { d = 'd' } }
return context:push(child_view), child_view
end
describe("context specs", function()
local context, view = topic()
before_each(function()
context, view = topic()
end)
it("looks up contexts", function()
assert.equal(context:lookup("name"), view.name)
end)
it("looks up nested contexts", function()
assert.equal(context:lookup("a.b"), view.a.b)
end)
it("looks up child contexts", function()
local child_context, child_view = push(context)
assert.equal(child_context.view.name, child_view.name)
end)
it("looks up child context view properties", function()
local child_context, child_view = push(context)
assert.equal(child_context:lookup("name"), child_view.name)
end)
it("looks up child context parent view properties", function()
local child_context, child_view = push(context)
assert.equal(child_context:lookup("message"), view.message)
end)
it("looks up child context nested view properties", function()
local child_context, child_view = push(context)
assert.equal(child_context:lookup("c.d"), "d")
end)
it("looks up child context parent nested view properties", function()
local child_context, child_view = push(context)
assert.equal(child_context:lookup("a.b"), "b")
end)
end)
| mit |
Zero-K-Experiments/Zero-K-Experiments | LuaRules/Gadgets/CAI/BattlegroupHandler.lua | 9 | 2717 | --[[ Handles grounds of combat units working together as a squad
--]]
local UnitListHandler = VFS.Include("LuaRules/Gadgets/CAI/UnitListHandler.lua")
local HeatmapHandler = VFS.Include("LuaRules/Gadgets/CAI/HeatmapHandler.lua")
local spIsPosInLos = Spring.IsPosInLos
local spGetCommandQueue = Spring.GetCommandQueue
local GiveClampedOrderToUnit = Spring.Utilities.GiveClampedOrderToUnit
local CMD_FIGHT = CMD.FIGHT
local scoutHandler = {}
function scoutHandler.CreateScoutHandler(allyTeamID)
local SCOUT_DECAY_TIME = 2000
local scoutList = UnitListHandler.CreateUnitList()
local scoutHeatmap = HeatmapHandler.CreateHeatmap(512, false, true, -SCOUT_DECAY_TIME)
local HEAT_SIZE_X = scoutHeatmap.HEAT_SIZE_X
local HEAT_SIZE_Z = scoutHeatmap.HEAT_SIZE_Z
local TOTAL_HEAT_POINTS = HEAT_SIZE_X*HEAT_SIZE_Z
local unscoutedPoints = {}
local unscoutedCount = 0
local unscoutedUnweightedCount = 0
local function AddUnscoutedPoint(i,j, pos)
unscoutedCount = unscoutedCount + 1
unscoutedPoints[unscoutedCount] = pos
if i <= 1 or HEAT_SIZE_X - i <= 2 then -- twice really weights towards the corners
unscoutedCount = unscoutedCount + 1
unscoutedPoints[unscoutedCount] = pos
end
if j <= 1 or HEAT_SIZE_Z - j <= 2 then -- weight scouting towards the edges
unscoutedCount = unscoutedCount + 1
unscoutedPoints[unscoutedCount] = pos
end
end
local function UpdateHeatmap(GameFrameUpdate)
unscoutedCount = 0
unscoutedUnweightedCount = 0
for i, j in scoutHeatmap.Iterator() do
local x, y, z = scoutHeatmap.ArrayToWorld(i,j)
if spIsPosInLos(x, 0, z, allyTeamID) then
scoutHeatmap.SetHeatPointByIndex(i, j, GameFrameUpdate)
else
if scoutHeatmap.GetValueByIndex(i, j) + SCOUT_DECAY_TIME < GameFrameUpdate then
unscoutedUnweightedCount = unscoutedUnweightedCount + 1
AddUnscoutedPoint(i,j, {x, y, z})
end
end
end
end
local function RunJobHandler()
if unscoutedCount > 0 then
for unitID,_ in scoutList.Iterator() do
local cQueue = spGetCommandQueue(unitID, 1)
if cQueue then
if #cQueue == 0 then
local randIndex = math.floor(math.random(1,unscoutedCount))
GiveClampedOrderToUnit(unitID, CMD_FIGHT , unscoutedPoints[randIndex], {})
end
else
scoutList.RemoveUnit(unitID)
end
end
end
end
local function GetScoutedProportion()
return 1 - unscoutedUnweightedCount/TOTAL_HEAT_POINTS
end
local newScoutHandler = {
UpdateHeatmap = UpdateHeatmap,
RunJobHandler = RunJobHandler,
GetScoutedProportion = GetScoutedProportion,
AddUnit = scoutList.AddUnit,
RemoveUnit = scoutList.RemoveUnit,
GetTotalCost = scoutList.GetTotalCost,
}
return newScoutHandler
end
return scoutHandler | gpl-2.0 |
sil3ntboyy/TGuard1.0.0 | plugins/filter.lua | 1 | 2441 | local function addword(msg, name)
local hash = 'chat:'..msg.to.id..':badword'
redis:hset(hash, name, 'newword')
return "New word has been added to filter list\n>"..name
end
local function get_variables_hash(msg)
return 'chat:'..msg.to.id..':badword'
end
local function list_variablesbad(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'Filtered words list :\n\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
else
return
end
end
function clear_commandbad(msg, var_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:del(hash, var_name)
return 'پاک شدند'
end
local function list_variables2(msg, value)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(value, names[i]) and not is_momod(msg) then
if msg.to.type == 'channel' then
delete_msg(msg.id,ok_cb,false)
else
kick_user(msg.from.id, msg.to.id)
end
return
end
--text = text..names[i]..'\n'
end
end
end
local function get_valuebad(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
function clear_commandsbad(msg, cmd_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:hdel(hash, cmd_name)
return ''..cmd_name..' پاک شد'
end
local function run(msg, matches)
if matches[2] == 'filter' then
if not is_momod(msg) then
return 'only for moderators'
end
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[2] == 'filterlist' then
return list_variablesbad(msg)
elseif matches[2] == 'clean' then
if not is_momod(msg) then return '_|_' end
local asd = '1'
return clear_commandbad(msg, asd)
elseif matches[2] == 'unfilter' or matches[2] == 'rw' then
if not is_momod(msg) then return '_|_' end
return clear_commandsbad(msg, matches[3])
else
local name = user_print_name(msg.from)
return list_variables2(msg, matches[1])
end
end
return {
patterns = {
"^([!/#])(rw) (.*)$",
"^([!/#])(filter) (.*)$",
"^([!/#])(unfilter) (.*)$",
"^([!/#])(filterlist)$",
"^([!/#])(clean) filterlist$",
"^(.+)$",
},
run = run
}
| gpl-2.0 |
cohadar/tanks-of-harmony-and-love | main.lua | 1 | 4750 | --- @module main
local main = {}
io.stdout:setvbuf("no")
local conf = require "conf"
local text = require "text"
local utils = require "utils"
local history = require "history"
local gui = require "gui"
local quickie = require "libs.quickie"
local terrain = require "terrain"
local tank = require "tank"
local client = require "client"
local tests = require "tests"
local world = require "world"
local bullets = require "bullets"
local ticker = require "ticker"
local effects = require "effects"
local _tankCommand = tank.newCommand()
-------------------------------------------------------------------------------
function love.load()
conf.SCREEN_WIDTH = love.graphics.getWidth()
conf.SCREEN_HEIGHT = love.graphics.getHeight()
conf.SCREEN_WIDTH_HALF = math.floor( conf.SCREEN_WIDTH / 2 )
conf.SCREEN_HEIGHT_HALF = math.floor( conf.SCREEN_HEIGHT / 2 )
if conf.GAME_DEBUG then
love.window.setMode(
conf.SCREEN_WIDTH * conf.SCALE_GRAPHICS,
conf.SCREEN_HEIGHT * conf.SCALE_GRAPHICS,
{ vsync = true, resizable = false }
)
end
text.init()
tank.init()
client.init()
bullets.init()
ticker.init( love.timer.getTime() )
love.mouse.setVisible( true )
love.window.setTitle( "Not Connected" )
tests.runAll()
end
-------------------------------------------------------------------------------
function love.update( dt )
gui.update()
local mark = love.timer.getTime()
local count = 0
while ticker.tick( mark ) and count < 10 do
count = count + 1
local localhost_tank = world.getTank( 0 )
_tankCommand.client_tick = client.incTick()
tank.update( localhost_tank, _tankCommand )
terrain.camera_x, terrain.camera_y = localhost_tank.x, localhost_tank.y
world.updateTank( 0, localhost_tank )
history.set( _tankCommand.client_tick, localhost_tank )
bullets.update()
effects.update()
end
if count > 0 then
client.update( _tankCommand )
_tankCommand.fire = false
end
if count > 9 then
-- TODO: proper disconnect here
error "you lag too much"
end
end
-------------------------------------------------------------------------------
function love.draw()
love.graphics.push()
love.graphics.scale( conf.SCALE_GRAPHICS )
love.graphics.translate(
conf.SCREEN_WIDTH_HALF - terrain.camera_x,
conf.SCREEN_HEIGHT_HALF - terrain.camera_y
)
terrain.draw()
love.graphics.setColor(0xFF, 0xFF, 0xFF, 0xFF)
if client.isConnected() then
for key, tnk in world.tankPairs() do
if key == 0 then
love.graphics.setColor(0xFF, 0xFF, 0x00, 0xFF)
else
love.graphics.setColor(0xFF, 0xFF, 0xFF, 0xFF)
end
tank.draw( tnk )
end
else
tank.draw( world.getTank( 0 ) )
end
bullets.draw()
effects.draw()
love.graphics.pop()
text.draw()
quickie.core.draw()
end
-------------------------------------------------------------------------------
function love.keypressed( key, unicode )
if key == "up" or key == "w" then
_tankCommand.up = true
elseif key == "down" or key == "s" then
_tankCommand.down = true
elseif key == "left" or key == "a" then
_tankCommand.left = true
elseif key == "right" or key == "d" then
_tankCommand.right = true
end
quickie.keyboard.pressed( key )
utils.keypressed( key )
end
-------------------------------------------------------------------------------
function love.keyreleased( key )
if key == "up" or key == "w" then
_tankCommand.up = false
elseif key == "down" or key == "s" then
_tankCommand.down = false
elseif key == "left" or key == "a" then
_tankCommand.left = false
elseif key == "right" or key == "d" then
_tankCommand.right = false
elseif key == " " then
_tankCommand.fire = true
end
gui.keyreleased( key )
end
-------------------------------------------------------------------------------
function love.mousereleased( x, y, button )
_tankCommand.fire = true
end
-------------------------------------------------------------------------------
function love.textinput( text )
quickie.keyboard.textinput( text )
end
-------------------------------------------------------------------------------
function love.mousemoved( mouse_x, mouse_y, dx, dy )
local mouse_angle = math.atan2(
mouse_y - conf.SCREEN_HEIGHT_HALF * conf.SCALE_GRAPHICS,
mouse_x - conf.SCREEN_WIDTH_HALF * conf.SCALE_GRAPHICS
)
_tankCommand.mouse_angle = utils.cleanAngle( mouse_angle )
end
-------------------------------------------------------------------------------
function love.threaderror( thread, errorstr )
text.status( errorstr )
text.print( errorstr )
end
-------------------------------------------------------------------------------
function love.quit()
client.quit()
end
-------------------------------------------------------------------------------
return main
| mit |
taxler/radish | lua/parse/substitution/charset/csISO886916.lua | 1 | 2462 |
local byte = require 'parse.substitution.charset.byte'
return byte + {
['\xa1'] = '\u{104}'; -- latin capital letter a with ogonek
['\xa2'] = '\u{105}'; -- latin small letter a with ogonek
['\xa3'] = '\u{141}'; -- latin capital letter l with stroke
['\xa4'] = '\u{20ac}'; -- euro sign
['\xa5'] = '\u{201e}'; -- double low-9 quotation mark
['\xa6'] = '\u{160}'; -- latin capital letter s with caron
['\xa8'] = '\u{161}'; -- latin small letter s with caron
['\xaa'] = '\u{218}'; -- latin capital letter s with comma below
['\xac'] = '\u{179}'; -- latin capital letter z with acute
['\xae'] = '\u{17a}'; -- latin small letter z with acute
['\xaf'] = '\u{17b}'; -- latin capital letter z with dot above
['\xb2'] = '\u{10c}'; -- latin capital letter c with caron
['\xb3'] = '\u{142}'; -- latin small letter l with stroke
['\xb4'] = '\u{17d}'; -- latin capital letter z with caron
['\xb5'] = '\u{201d}'; -- right double quotation mark
['\xb8'] = '\u{17e}'; -- latin small letter z with caron
['\xb9'] = '\u{10d}'; -- latin small letter c with caron
['\xba'] = '\u{219}'; -- latin small letter s with comma below
['\xbc'] = '\u{152}'; -- latin capital ligature oe
['\xbd'] = '\u{153}'; -- latin small ligature oe
['\xbe'] = '\u{178}'; -- latin capital letter y with diaeresis
['\xbf'] = '\u{17c}'; -- latin small letter z with dot above
['\xc3'] = '\u{102}'; -- latin capital letter a with breve
['\xc5'] = '\u{106}'; -- latin capital letter c with acute
['\xd0'] = '\u{110}'; -- latin capital letter d with stroke
['\xd1'] = '\u{143}'; -- latin capital letter n with acute
['\xd5'] = '\u{150}'; -- latin capital letter o with double acute
['\xd7'] = '\u{15a}'; -- latin capital letter s with acute
['\xd8'] = '\u{170}'; -- latin capital letter u with double acute
['\xdd'] = '\u{118}'; -- latin capital letter e with ogonek
['\xde'] = '\u{21a}'; -- latin capital letter t with comma below
['\xe3'] = '\u{103}'; -- latin small letter a with breve
['\xe5'] = '\u{107}'; -- latin small letter c with acute
['\xf0'] = '\u{111}'; -- latin small letter d with stroke
['\xf1'] = '\u{144}'; -- latin small letter n with acute
['\xf5'] = '\u{151}'; -- latin small letter o with double acute
['\xf7'] = '\u{15b}'; -- latin small letter s with acute
['\xf8'] = '\u{171}'; -- latin small letter u with double acute
['\xfd'] = '\u{119}'; -- latin small letter e with ogonek
['\xfe'] = '\u{21b}'; -- latin small letter t with comma below
}
| mit |
Kyklas/luci-proto-hso | applications/luci-asterisk/luasrc/model/cbi/asterisk/phones.lua | 80 | 2946 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Jo-Philipp Wich <xm@subsignal.org>
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
$Id$
]]--
local ast = require("luci.asterisk")
cbimap = Map("asterisk", "Registered Phones")
cbimap.pageaction = false
local sip_peers = { }
cbimap.uci:foreach("asterisk", "sip",
function(s)
if s.type ~= "peer" then
s.name = s['.name']
s.info = ast.sip.peer(s.name)
sip_peers[s.name] = s
end
end)
sip_table = cbimap:section(TypedSection, "sip", "SIP Phones")
sip_table.template = "cbi/tblsection"
sip_table.extedit = luci.dispatcher.build_url("admin", "asterisk", "phones", "sip", "%s")
sip_table.addremove = true
function sip_table.filter(self, s)
return s and not cbimap.uci:get_bool("asterisk", s, "provider")
end
function sip_table.create(self, section)
if TypedSection.create(self, section) then
created = section
cbimap.uci:tset("asterisk", section, {
type = "friend",
qualify = "yes",
provider = "no",
host = "dynamic",
nat = "no",
canreinvite = "no",
extension = section:match("^%d+$") and section or "",
username = section:match("^%d+$") and section or ""
})
else
self.invalid_cts = true
end
end
function sip_table.parse(self, ...)
TypedSection.parse(self, ...)
if created then
cbimap.uci:save("asterisk")
luci.http.redirect(luci.dispatcher.build_url(
"admin", "asterisk", "phones", "sip", created
))
end
end
user = sip_table:option(DummyValue, "username", "Username")
function user.cfgvalue(self, s)
return sip_peers[s] and sip_peers[s].callerid or
AbstractValue.cfgvalue(self, s)
end
host = sip_table:option(DummyValue, "host", "Hostname")
function host.cfgvalue(self, s)
if sip_peers[s] and sip_peers[s].info.address then
return "%s:%i" %{ sip_peers[s].info.address, sip_peers[s].info.port }
else
return "n/a"
end
end
context = sip_table:option(DummyValue, "context", "Dialplan")
context.href = luci.dispatcher.build_url("admin", "asterisk", "dialplan")
online = sip_table:option(DummyValue, "online", "Registered")
function online.cfgvalue(self, s)
if sip_peers[s] and sip_peers[s].info.online == nil then
return "n/a"
else
return sip_peers[s] and sip_peers[s].info.online
and "yes" or "no (%s)" % {
sip_peers[s] and sip_peers[s].info.Status:lower() or "unknown"
}
end
end
delay = sip_table:option(DummyValue, "delay", "Delay")
function delay.cfgvalue(self, s)
if sip_peers[s] and sip_peers[s].info.online then
return "%i ms" % sip_peers[s].info.delay
else
return "n/a"
end
end
info = sip_table:option(Button, "_info", "Info")
function info.write(self, s)
luci.http.redirect(luci.dispatcher.build_url(
"admin", "asterisk", "phones", "sip", s, "info"
))
end
return cbimap
| apache-2.0 |
kjc88/sl4a | lua/json4lua/json/rpcserver.lua | 22 | 3155 | -----------------------------------------------------------------------------
-- JSONRPC4Lua: JSON RPC server for exposing Lua objects as JSON RPC callable
-- objects via http.
-- json.rpcserver Module.
-- Author: Craig Mason-Jones
-- Homepage: http://json.luaforge.net/
-- Version: 0.9.10
-- This module is released under the The GNU General Public License (GPL).
-- Please see LICENCE.txt for details.
--
-- USAGE:
-- This module exposes one function:
-- server(luaClass, packReturn)
-- Manages incoming JSON RPC request forwarding the method call to the given
-- object. If packReturn is true, multiple return values are packed into an
-- array on return.
--
-- IMPORTANT NOTES:
-- 1. This version ought really not be 0.9.10, since this particular part of the
-- JSONRPC4Lua package is very first-draft. However, the JSON4Lua package with which
-- it comes is quite solid, so there you have it :-)
-- 2. This has only been tested with Xavante webserver, with which it works
-- if you patch CGILua to accept 'text/plain' content type. See doc\cgilua_patch.html
-- for details.
----------------------------------------------------------------------------
module ('json.rpcserver')
---
-- Implements a JSON RPC Server wrapping for luaClass, exposing each of luaClass's
-- methods as JSON RPC callable methods.
-- @param luaClass The JSON RPC class to expose.
-- @param packReturn If true, the server will automatically wrap any
-- multiple-value returns into an array. Single returns remain single returns. If
-- false, when a function returns multiple values, only the first of these values will
-- be returned.
--
function serve(luaClass, packReturn)
cgilua.contentheader('text','plain')
require('cgilua')
require ('json')
local postData = ""
if not cgilua.servervariable('CONTENT_LENGTH') then
cgilua.put("Please access JSON Request using HTTP POST Request")
return 0
else
postData = cgi[1] -- SAPI.Request.getpostdata() --[[{ "id":1, "method":"echo","params":["Hi there"]}]] --
end
-- @TODO Catch an error condition on decoding the data
local jsonRequest = json.decode(postData)
local jsonResponse = {}
jsonResponse.id = jsonRequest.id
local method = luaClass[ jsonRequest.method ]
if not method then
jsonResponse.error = 'Method ' .. jsonRequest.method .. ' does not exist at this server.'
else
local callResult = { pcall( method, unpack( jsonRequest.params ) ) }
if callResult[1] then -- Function call successfull
table.remove(callResult,1)
if packReturn and table.getn(callResult)>1 then
jsonResponse.result = callResult
else
jsonResponse.result = unpack(callResult) -- NB: Does not support multiple argument returns
end
else
jsonResponse.error = callResult[2]
end
end
-- Output the result
-- TODO: How to be sure that the result and error tags are there even when they are nil in Lua?
-- Can force them by hand... ?
cgilua.contentheader('text','plain')
cgilua.put( json.encode( jsonResponse ) )
end
| apache-2.0 |
mymedia2/GroupButler | plugins/service.lua | 7 | 2909 | local config = require 'config'
local u = require 'utilities'
local api = require 'methods'
local plugin = {}
function plugin.onTextMessage(msg, blocks)
if not msg.service then return end
if blocks[1] == 'new_chat_member:bot' or blocks[1] == 'migrate_from_chat_id' then
-- set the language
--[[locale.language = db:get(string.format('lang:%d', msg.from.id)) or 'en'
if not config.available_languages[locale.language] then
locale.language = 'en'
end]]
if u.is_blocked_global(msg.from.id) then
api.sendMessage(msg.chat.id, _("_You (user ID: %d) are in the blocked list_"):format(msg.from.id), true)
api.leaveChat(msg.chat.id)
return
end
if config.bot_settings.admin_mode and not u.is_superadmin(msg.from.id) then
api.sendMessage(msg.chat.id, _("_Admin mode is on: only the bot admin can add me to a new group_"), true)
api.leaveChat(msg.chat.id)
return
end
-- save language
--[[if locale.language then
db:set(string.format('lang:%d', msg.chat.id), locale.language)
end]]
u.initGroup(msg.chat.id)
-- send manuals
local text
if blocks[1] == 'new_chat_member:bot' then
text = _("Hello everyone!\n"
.. "My name is %s, and I'm a bot made to help administrators in their hard work.\n")
:format(bot.first_name:escape())
else
text = _("Yay! This group has been upgraded. You are great! Now I can work properly :)\n")
end
--[[if not u.is_admin(msg.chat.id, bot.id) then
if u.is_owner(msg.chat.id, msg.from.id) then
text = text .. _("Hmm… apparently I'm not an administrator. "
.. "I can be more useful if you make me an admin. "
.. "See [here](https://telegram.me/GroupButler_ch/104) how to do it.\n")
else
text = text .. _("Hmm… apparently I'm not an administrator. "
.. "I can be more useful if I'm an admin. Ask a creator to make me an admin. "
.. "If he doesn't know how, there is a good [guide](https://telegram.me/GroupButler_ch/104).\n")
end
end
text = text .. _("I can do a lot of cool things. To discover about them, "
-- TODO: old link, update it
.. "watch this [video-tutorial](https://youtu.be/uqNumbcUyzs).") ]]
api.sendMessage(msg.chat.id, text, true)
elseif blocks[1] == 'left_chat_member:bot' then
local realm_id = db:get('chat:'..msg.chat.id..':realm')
if realm_id then
if db:hget('realm:'..realm_id..':subgroups', msg.chat.id) then
api.sendMessage(realm_id, _("I've been removed from %s [<code>%d</code>], one of your subgroups"):format(msg.chat.title:escape_html(), msg.chat.id), 'html')
end
end
u.remGroup(msg.chat.id, true)
else
u.logEvent(blocks[1], msg)
end
end
plugin.triggers = {
onTextMessage = {
'^###(new_chat_member:bot)',
'^###(migrate_from_chat_id)',
'^###(left_chat_member:bot)',
'^###(pinned_message)$',
'^###(new_chat_title)$',
'^###(new_chat_photo)$',
'^###(delete_chat_photo)$'
}
}
return plugin
| gpl-2.0 |
jchuang1977/openwrt | package/lean/luci-app-unblockmusic/luasrc/model/cbi/unblockmusic/unblockmusic.lua | 1 | 5004 | local fs = require "nixio.fs"
mp = Map("unblockmusic", translate("解锁网易云灰色歌曲"))
mp.description = translate("采用 [QQ/百度/酷狗/酷我/咪咕/JOOX]等音源,替换网易云变灰歌曲链接")
mp:section(SimpleSection).template = "unblockmusic/unblockmusic_status"
s = mp:section(TypedSection, "unblockmusic")
s.anonymous=true
s.addremove=false
enabled = s:option(Flag, "enabled", translate("启用"))
enabled.default = 0
enabled.rmempty = false
enabled.description = translate("启用后,路由器自动分流解锁,大部分设备无需设置代理")
apptype = s:option(ListValue, "apptype", translate("解锁程序选择"))
if nixio.fs.access("/usr/bin/UnblockNeteaseMusic") then
apptype:value("go", translate("Golang 版本"))
end
if nixio.fs.access("/usr/share/UnblockNeteaseMusic/app.js") then
apptype:value("nodejs", translate("NodeJS 版本"))
end
apptype:value("cloud", translate("云解锁( [CTCGFW] 云服务器)"))
speedtype = s:option(Value, "musicapptype", translate("音源选择"))
speedtype:value("default", translate("默认"))
speedtype:value("netease", translate("网易云音乐"))
speedtype:value("qq", translate("QQ音乐"))
speedtype:value("baidu", translate("百度音乐"))
speedtype:value("kugou", translate("酷狗音乐"))
speedtype:value("kuwo", translate("酷我音乐"))
speedtype:value("migu", translate("咪咕音乐"))
speedtype:value("joox", translate("JOOX音乐"))
speedtype.default = "kuwo"
speedtype:depends("apptype", "nodejs")
speedtype:depends("apptype", "go")
cloudserver = s:option(Value, "cloudserver", translate("服务器位置"))
cloudserver:value("cdn-shanghai.service.project-openwrt.eu.org:30000:30001", translate("[CTCGFW] 腾讯云上海(高音质)"))
cloudserver.description = translate("自定义服务器格式为 IP[域名]:HTTP端口:HTTPS端口<br />如果服务器为LAN内网IP,需要将这个服务器IP放入例外客户端 (不代理HTTP和HTTPS)")
cloudserver.default = "cdn-shanghai.service.project-openwrt.eu.org:30000:30001"
cloudserver.rmempty = true
cloudserver:depends("apptype", "cloud")
search_limit = s:option(Value, "search_limit", translate("搜索结果限制"))
search_limit.description = translate("在搜索页面显示其他平台搜索结果个数,可填(0-3)")
search_limit.default = "0"
search_limit:depends("apptype", "go")
flac = s:option(Flag, "flac_enabled", translate("启用无损音质"))
flac.default = "1"
flac.rmempty = false
flac.description = translate("目前仅支持酷我、QQ、咪咕")
flac:depends("apptype", "nodejs")
flac:depends("apptype", "go")
force = s:option(Flag, "force_enabled", translate("强制替换为高音质歌曲"))
force.default = "1"
force.rmempty = false
force.description = translate("如果歌曲音质在 320Kbps 以内,则尝试强制替换为高音质版本")
force:depends("apptype", "nodejs")
o = s:option(Flag, "autoupdate")
o.title = translate("自动检查更新主程序")
o.default = "1"
o.rmempty = false
o.description = translate("每天自动检测并更新到最新版本")
o:depends("apptype", "nodejs")
download_certificate=s:option(DummyValue,"opennewwindow",translate("HTTPS 证书"))
download_certificate.description = translate("<input type=\"button\" class=\"btn cbi-button cbi-button-apply\" value=\"下载CA根证书\" onclick=\"window.open('https://raw.githubusercontent.com/1715173329/UnblockNeteaseMusic/enhanced/ca.crt')\" /><br />Mac/iOS客户端需要安装 CA根证书并信任<br />iOS系统需要在“设置 -> 通用 -> 关于本机 -> 证书信任设置”中,信任 UnblockNeteaseMusic Root CA <br />Linux 设备请在启用时加入 --ignore-certificate-errors 参数")
local ver = fs.readfile("/usr/share/UnblockNeteaseMusic/core_ver") or "0.00"
o = s:option(Button, "restart",translate("手动更新"))
o.inputtitle = translate("更新核心版本")
o.description = string.format(translate("NodeJS 解锁主程序版本") .. "<strong><font color=\"green\">: %s </font></strong>", ver)
o.inputstyle = "reload"
o.write = function()
luci.sys.exec("/usr/share/UnblockNeteaseMusic/update_core.sh luci_update 2>&1")
luci.http.redirect(luci.dispatcher.build_url("admin", "services", "unblockmusic"))
end
o:depends("apptype", "nodejs")
t=mp:section(TypedSection,"acl_rule",translate("例外客户端规则"),
translate("可以为局域网客户端分别设置不同的例外模式,默认无需设置"))
t.template="cbi/tblsection"
t.sortable=true
t.anonymous=true
t.addremove=true
e=t:option(Value,"ipaddr",translate("IP Address"))
e.width="40%"
e.datatype="ip4addr"
e.placeholder="0.0.0.0/0"
luci.ip.neighbors({ family = 4 }, function(entry)
if entry.reachable then
e:value(entry.dest:string())
end
end)
e=t:option(ListValue,"filter_mode",translate("例外协议"))
e.width="40%"
e.default="disable"
e.rmempty=false
e:value("disable",translate("不代理HTTP和HTTPS"))
e:value("http",translate("不代理HTTP"))
e:value("https",translate("不代理HTTPS"))
return mp
| gpl-2.0 |
Scavenge/darkstar | scripts/globals/items/bundle_of_shirataki.lua | 12 | 1186 | -----------------------------------------
-- ID: 5237
-- Item: Bundle of Shirataki
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Strength -3
-- Mind 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5237);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, -3);
target:addMod(MOD_MND, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, -3);
target:delMod(MOD_MND, 1);
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/QuBia_Arena/mobs/Vangknok_of_Clan_Death.lua | 23 | 2660 | -----------------------------------
-- Area: QuBia_Arena
-- Mission 9-2 SANDO
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
local mobs= {{17621017,17621018,17621019,17621020,17621021,17621022,17621023,17621024,17621025,17621026,17621027},{17621031,17621032,17621033,17621034,17621035,17621036,17621037,17621038,17621039,17621040,17621041},{17621031,17621046,17621047,17621048,17621049,17621050,17621051,17621052,17621053,17621054,17621055}};
local inst=player:getBattlefield():getBattlefieldNumber();
local victory = true
for i,v in ipairs(mobs[inst]) do
local action = GetMobAction(v);
printf("action %u",action);
if not(action == 0 or (action >=21 and action <=23)) then
victory = false
end
end
if victory == true then
player:startEvent(0x7d04,0,0,4);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
printf("finishCSID: %u",csid);
printf("RESULT: %u",option);
if (csid == 0x7d04) then
if (player:getBattlefield():getBattlefieldNumber() == 1) then
SpawnMob(17621014);
SpawnMob(17621015);
SpawnMob(17621016);
local trion = player:getBattlefield():insertAlly(14183)
trion:setSpawn(-403,-201,413,58);
trion:spawn();
player:setPos(-400,-201,419,61);
elseif (player:getBattlefield():getBattlefieldNumber() == 2) then
SpawnMob(17621028);
SpawnMob(17621029);
SpawnMob(17621030);
local trion = player:getBattlefield():insertAlly(14183)
trion:setSpawn(-3,-1,4,61);
trion:spawn();
player:setPos(0,-1,10,61);
elseif (player:getBattlefield():getBattlefieldNumber() == 3) then
SpawnMob(17621042);
SpawnMob(17621043);
SpawnMob(17621044);
local trion = player:getBattlefield():insertAlly(14183)
trion:setSpawn(397,198,-395,64);
trion:spawn();
player:setPos(399,198,-381,57);
end
end
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Throne_Room/bcnms/Where_two_paths_converge.lua | 25 | 1544 | -----------------------------------
-- Area: Throne Room
-- Name: Mission 9-2
-- @pos -111 -6 0 165
-----------------------------------
package.loaded["scripts/zones/Throne_Room/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Throne_Room/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function OnBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
print("leave code "..leavecode);
if (leavecode == 2) then
if (player:getCurrentMission(BASTOK) == WHERE_TWO_PATHS_CONVERGE) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
print("bc finish csid "..csid.." and option "..option);
player:setVar("BASTOK92",2);
end; | gpl-3.0 |
Scavenge/darkstar | scripts/zones/Sacrificial_Chamber/bcnms/jungle_boogymen.lua | 30 | 1759 | -----------------------------------
-- Area: Sacrificial Chamber
-- Name: jungle_boogymen
-- BCNM60
-----------------------------------
package.loaded["scripts/zones/Sacrificial_Chamber/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/Sacrificial_Chamber/TextIDs");
-----------------------------------
-- EXAMPLE SCRIPT
--
-- What should go here:
-- giving key items, playing ENDING cutscenes
--
-- What should NOT go here:
-- Handling of "battlefield" status, spawning of monsters,
-- putting loot into treasure pool,
-- enforcing ANY rules (SJ/number of people/etc), moving
-- chars around, playing entrance CSes (entrance CSes go in bcnm.lua)
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0);
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Eih_Lhogotan.lua | 14 | 1065 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Eih Lhogotan
-- Type: Standard NPC
-- @zone 94
-- @pos -29.887 -5.999 91.042
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0197);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/West_Ronfaure/npcs/Field_Manual.lua | 30 | 1055 | -----------------------------------
-- Area: West Ronfaure
-- NPC: Field Manual
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/fieldsofvalor");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startFov(FOV_EVENT_WEST_RONFAURE,player);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
updateFov(player,csid,menuchoice,1,2,3,4,56);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
finishFov(player,csid,option,1,2,3,4,56,FOV_MSG_WEST_RONFAURE);
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Horlais_Peak/bcnms/horns_of_war.lua | 30 | 1803 | -----------------------------------
-- Area: Horlias peak
-- Name: horns of war
-- KSNM99
-----------------------------------
package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Horlais_Peak/TextIDs");
-----------------------------------
-- EXAMPLE SCRIPT
--
-- What should go here:
-- giving key items, playing ENDING cutscenes
--
-- What should NOT go here:
-- Handling of "battlefield" status, spawning of monsters,
-- putting loot into treasure pool,
-- enforcing ANY rules (SJ/number of people/etc), moving
-- chars around, playing entrance CSes (entrance CSes go in bcnm.lua)
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0);
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
end;
| gpl-3.0 |
sleep/mal | lua/step2_eval.lua | 40 | 2090 | #!/usr/bin/env lua
local table = require('table')
local readline = require('readline')
local utils = require('utils')
local types = require('types')
local reader = require('reader')
local printer = require('printer')
local List, Vector, HashMap = types.List, types.Vector, types.HashMap
-- read
function READ(str)
return reader.read_str(str)
end
-- eval
function eval_ast(ast, env)
if types._symbol_Q(ast) then
if env[ast.val] == nil then
types.throw("'"..ast.val.."' not found")
end
return env[ast.val]
elseif types._list_Q(ast) then
return List:new(utils.map(function(x) return EVAL(x,env) end,ast))
elseif types._vector_Q(ast) then
return Vector:new(utils.map(function(x) return EVAL(x,env) end,ast))
elseif types._hash_map_Q(ast) then
local new_hm = {}
for k,v in pairs(ast) do
new_hm[EVAL(k, env)] = EVAL(v, env)
end
return HashMap:new(new_hm)
else
return ast
end
end
function EVAL(ast, env)
--print("EVAL: "..printer._pr_str(ast,true))
if not types._list_Q(ast) then return eval_ast(ast, env) end
local args = eval_ast(ast, env)
local f = table.remove(args, 1)
return f(unpack(args))
end
-- print
function PRINT(exp)
return printer._pr_str(exp, true)
end
-- repl
local repl_env = {['+'] = function(a,b) return a+b end,
['-'] = function(a,b) return a-b end,
['*'] = function(a,b) return a*b end,
['/'] = function(a,b) return math.floor(a/b) end}
function rep(str)
return PRINT(EVAL(READ(str),repl_env))
end
if #arg > 0 and arg[1] == "--raw" then
readline.raw = true
end
while true do
line = readline.readline("user> ")
if not line then break end
xpcall(function()
print(rep(line))
end, function(exc)
if exc then
if types._malexception_Q(exc) then
exc = printer._pr_str(exc.val, true)
end
print("Error: " .. exc)
print(debug.traceback())
end
end)
end
| mpl-2.0 |
mcvella/indexedRingBuffer | src/dictCache.lua | 1 | 1133 | local dictCache = {_TYPE='module', _NAME='dictCache' }
-- NOTE: nginx DICTs expire based on declared max size in memory (LRU), not total number of items.
function dictCache.new( dictName, secs )
local self = {
dictName = dictName,
maxSecs = secs or 0
}
local cache = ngx.shared[self.dictName];
function self:set( key, value )
cache:set( key, value, self.maxSecs )
end
function self:add( key, value )
cache:add( key, value, self.maxSecs )
end
function self:get( key )
return cache:get( key )
end
function self:delete( key )
return cache:delete( key )
end
function self:incr( key, by )
-- incr only works if already initialized, boo
local newval, err = cache:incr(key, by)
if newval == nil then
self.set( key, by )
newval = by
end
return newval
end
function self:flush_all()
cache:flush_all()
end
function self:flush_expired()
cache:flush_expired()
end
return self
end
return dictCache
| mit |
Zero-K-Experiments/Zero-K-Experiments | units/armartic.lua | 3 | 4967 | unitDef = {
unitname = [[armartic]],
name = [[Faraday]],
description = [[EMP Turret]],
buildCostEnergy = 200,
buildCostMetal = 200,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 4,
buildingGroundDecalSizeY = 4,
buildingGroundDecalType = [[armartic_aoplane.dds]],
buildPic = [[armartic.png]],
buildTime = 200,
canAttack = true,
category = [[SINK TURRET]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[32 75 32]],
collisionVolumeType = [[CylY]],
corpse = [[DEAD]],
customParams = {
description_de = [[EMP Waffe]],
description_fr = [[Tourelle EMP]],
helptext = [[The Faraday is a powerful EMP tower. It has high damage and area of effect. Greatly amplifies the effect of other towers, but virtually useless on its own. When closed damage received is reduced to a quarter. Be careful of its splash damage though, as it can paralyze your own units if they are too close to the enemy.]],
helptext_de = [[Faraday ist ein schlagkräftiger EMP Turm. Er hat einen großen Radius, sowie hohen Schaden. Er vervollständigt die Effekte anderer Türme, doch alleine ist er ziemlich nutzlos. Falls geschlossen, besitzt er mehr Lebenspunkte. Beachte dennoch seinen Flächenschaden, welcher auch nahegelegene eigene Einheiten paralysieren kann.]],
helptext_fr = [[le Faraday est une redoutable défense EMP à zone d'effêt paralysant les adversaires sans les endommager. Repliée son blindage réduit à un quart les dommages reçus. Attention cependant à ne pas paralyser ses propres unités dans la zone d'effêt EMP.]],
aimposoffset = [[0 10 0]],
modelradius = [[16]],
},
damageModifier = 0.25,
explodeAs = [[MEDIUM_BUILDINGEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[defensespecial]],
levelGround = false,
maxDamage = 1000,
maxSlope = 36,
maxWaterDepth = 0,
minCloakDistance = 150,
noChaseCategory = [[FIXEDWING LAND SHIP SWIM GUNSHIP SUB HOVER]],
objectName = [[ARMARTIC]],
script = [[armartic.lua]],
seismicSignature = 4,
selfDestructAs = [[MEDIUM_BUILDINGEX]],
sfxtypes = {
explosiongenerators = {
[[custom:YELLOW_LIGHTNING_MUZZLE]],
[[custom:YELLOW_LIGHTNING_GROUNDFLASH]],
},
},
sightDistance = 506,
useBuildingGroundDecal = true,
yardMap = [[oo oo]],
weapons = {
{
def = [[arm_det_weapon]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER FIXEDWING GUNSHIP]],
},
},
weaponDefs = {
arm_det_weapon = {
name = [[Electro-Stunner]],
areaOfEffect = 160,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
cylinderTargeting = 0,
customParams = {
light_color = [[0.75 0.75 0.56]],
light_radius = 220,
},
damage = {
default = 1000,
},
duration = 8,
edgeEffectiveness = 0.8,
explosionGenerator = [[custom:YELLOW_LIGHTNINGPLOSION]],
fireStarter = 0,
impulseBoost = 0,
impulseFactor = 0,
intensity = 12,
interceptedByShieldType = 1,
noSelfDamage = true,
paralyzer = true,
paralyzeTime = 2, -- was 2.5 but this can only be int
range = 460,
reloadtime = 2.8,
rgbColor = [[1 1 0.25]],
soundStart = [[weapon/lightning_fire]],
soundTrigger = true,
texture1 = [[lightning]],
thickness = 10,
turret = true,
weaponType = [[LightningCannon]],
weaponVelocity = 450,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[armartic_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris3x3b.s3o]],
},
},
}
return lowerkeys({ armartic = unitDef })
| gpl-2.0 |
kankaristo/premake-core | src/actions/vstudio/_vstudio.lua | 6 | 15259 | --
-- _vstudio.lua
-- Define the Visual Studio 200x actions.
-- Copyright (c) 2008-2013 Jason Perkins and the Premake project
--
premake.vstudio = {}
local vstudio = premake.vstudio
local p = premake
local project = p.project
local config = p.config
--
-- Mapping tables from Premake systems and architectures to Visual Studio
-- identifiers. Broken out as tables so new values can be pushed in by
-- add-ons.
--
vstudio.vs200x_architectures =
{
win32 = "x86",
x86 = "x86",
x86_64 = "x64",
xbox360 = "Xbox 360",
}
vstudio.vs2010_architectures =
{
win32 = "x86",
}
local function architecture(system, arch)
local result
if _ACTION >= "vs2010" then
result = vstudio.vs2010_architectures[arch] or vstudio.vs2010_architectures[system]
end
return result or vstudio.vs200x_architectures[arch] or vstudio.vs200x_architectures[system]
end
--
-- Mapping from ISO locales to MS culture identifiers.
-- http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.85%29.ASPX
--
vstudio._cultures = {
["af"] = 0x0036,
["af-ZA"] = 0x0436,
["sq"] = 0x001C,
["sq-AL"] = 0x041C,
["ar"] = 0x0001,
["ar-DZ"] = 0x1401,
["ar-BH"] = 0x3C01,
["ar-EG"] = 0x0C01,
["ar-IQ"] = 0x0801,
["ar-JO"] = 0x2C01,
["ar-KW"] = 0x3401,
["ar-LB"] = 0x3001,
["ar-LY"] = 0x1001,
["ar-MA"] = 0x1801,
["ar-OM"] = 0x2001,
["ar-QA"] = 0x4001,
["ar-SA"] = 0x0401,
["ar-SY"] = 0x2801,
["ar-TN"] = 0x1C01,
["ar-AE"] = 0x3801,
["ar-YE"] = 0x2401,
["hy"] = 0x002B,
["hy-AM"] = 0x042B,
["az"] = 0x002C,
["az-Cyrl-AZ"] = 0x082C,
["az-Latn-AZ"] = 0x042C,
["eu"] = 0x002D,
["eu-ES"] = 0x042D,
["be"] = 0x0023,
["be-BY"] = 0x0423,
["bg"] = 0x0002,
["bg-BG"] = 0x0402,
["ca"] = 0x0003,
["ca-ES"] = 0x0403,
["zh-HK"] = 0x0C04,
["zh-MO"] = 0x1404,
["zh-CN"] = 0x0804,
["zh-Hans"] = 0x0004,
["zh-SG"] = 0x1004,
["zh-TW"] = 0x0404,
["zh-Hant"] = 0x7C04,
["hr"] = 0x001A,
["hr-HR"] = 0x041A,
["cs"] = 0x0005,
["cs-CZ"] = 0x0405,
["da"] = 0x0006,
["da-DK"] = 0x0406,
["dv"] = 0x0065,
["dv-MV"] = 0x0465,
["nl"] = 0x0013,
["nl-BE"] = 0x0813,
["nl-NL"] = 0x0413,
["en"] = 0x0009,
["en-AU"] = 0x0C09,
["en-BZ"] = 0x2809,
["en-CA"] = 0x1009,
["en-029"] = 0x2409,
["en-IE"] = 0x1809,
["en-JM"] = 0x2009,
["en-NZ"] = 0x1409,
["en-PH"] = 0x3409,
["en-ZA"] = 0x1C09,
["en-TT"] = 0x2C09,
["en-GB"] = 0x0809,
["en-US"] = 0x0409,
["en-ZW"] = 0x3009,
["et"] = 0x0025,
["et-EE"] = 0x0425,
["fo"] = 0x0038,
["fo-FO"] = 0x0438,
["fa"] = 0x0029,
["fa-IR"] = 0x0429,
["fi"] = 0x000B,
["fi-FI"] = 0x040B,
["fr"] = 0x000C,
["fr-BE"] = 0x080C,
["fr-CA"] = 0x0C0C,
["fr-FR"] = 0x040C,
["fr-LU"] = 0x140C,
["fr-MC"] = 0x180C,
["fr-CH"] = 0x100C,
["gl"] = 0x0056,
["gl-ES"] = 0x0456,
["ka"] = 0x0037,
["ka-GE"] = 0x0437,
["de"] = 0x0007,
["de-AT"] = 0x0C07,
["de-DE"] = 0x0407,
["de-LI"] = 0x1407,
["de-LU"] = 0x1007,
["de-CH"] = 0x0807,
["el"] = 0x0008,
["el-GR"] = 0x0408,
["gu"] = 0x0047,
["gu-IN"] = 0x0447,
["he"] = 0x000D,
["he-IL"] = 0x040D,
["hi"] = 0x0039,
["hi-IN"] = 0x0439,
["hu"] = 0x000E,
["hu-HU"] = 0x040E,
["is"] = 0x000F,
["is-IS"] = 0x040F,
["id"] = 0x0021,
["id-ID"] = 0x0421,
["it"] = 0x0010,
["it-IT"] = 0x0410,
["it-CH"] = 0x0810,
["ja"] = 0x0011,
["ja-JP"] = 0x0411,
["kn"] = 0x004B,
["kn-IN"] = 0x044B,
["kk"] = 0x003F,
["kk-KZ"] = 0x043F,
["kok"] = 0x0057,
["kok-IN"] = 0x0457,
["ko"] = 0x0012,
["ko-KR"] = 0x0412,
["ky"] = 0x0040,
["ky-KG"] = 0x0440,
["lv"] = 0x0026,
["lv-LV"] = 0x0426,
["lt"] = 0x0027,
["lt-LT"] = 0x0427,
["mk"] = 0x002F,
["mk-MK"] = 0x042F,
["ms"] = 0x003E,
["ms-BN"] = 0x083E,
["ms-MY"] = 0x043E,
["mr"] = 0x004E,
["mr-IN"] = 0x044E,
["mn"] = 0x0050,
["mn-MN"] = 0x0450,
["no"] = 0x0014,
["nb-NO"] = 0x0414,
["nn-NO"] = 0x0814,
["pl"] = 0x0015,
["pl-PL"] = 0x0415,
["pt"] = 0x0016,
["pt-BR"] = 0x0416,
["pt-PT"] = 0x0816,
["pa"] = 0x0046,
["pa-IN"] = 0x0446,
["ro"] = 0x0018,
["ro-RO"] = 0x0418,
["ru"] = 0x0019,
["ru-RU"] = 0x0419,
["sa"] = 0x004F,
["sa-IN"] = 0x044F,
["sr-Cyrl-CS"] = 0x0C1A,
["sr-Latn-CS"] = 0x081A,
["sk"] = 0x001B,
["sk-SK"] = 0x041B,
["sl"] = 0x0024,
["sl-SI"] = 0x0424,
["es"] = 0x000A,
["es-AR"] = 0x2C0A,
["es-BO"] = 0x400A,
["es-CL"] = 0x340A,
["es-CO"] = 0x240A,
["es-CR"] = 0x140A,
["es-DO"] = 0x1C0A,
["es-EC"] = 0x300A,
["es-SV"] = 0x440A,
["es-GT"] = 0x100A,
["es-HN"] = 0x480A,
["es-MX"] = 0x080A,
["es-NI"] = 0x4C0A,
["es-PA"] = 0x180A,
["es-PY"] = 0x3C0A,
["es-PE"] = 0x280A,
["es-PR"] = 0x500A,
["es-ES"] = 0x0C0A,
["es-ES_tradnl"]= 0x040A,
["es-UY"] = 0x380A,
["es-VE"] = 0x200A,
["sw"] = 0x0041,
["sw-KE"] = 0x0441,
["sv"] = 0x001D,
["sv-FI"] = 0x081D,
["sv-SE"] = 0x041D,
["syr"] = 0x005A,
["syr-SY"] = 0x045A,
["ta"] = 0x0049,
["ta-IN"] = 0x0449,
["tt"] = 0x0044,
["tt-RU"] = 0x0444,
["te"] = 0x004A,
["te-IN"] = 0x044A,
["th"] = 0x001E,
["th-TH"] = 0x041E,
["tr"] = 0x001F,
["tr-TR"] = 0x041F,
["uk"] = 0x0022,
["uk-UA"] = 0x0422,
["ur"] = 0x0020,
["ur-PK"] = 0x0420,
["uz"] = 0x0043,
["uz-Cyrl-UZ"] = 0x0843,
["uz-Latn-UZ"] = 0x0443,
["vi"] = 0x002A,
["vi-VN"] = 0x042A,
}
--
-- Translate the system and architecture settings from a configuration
-- into a corresponding Visual Studio identifier. If no settings are
-- found in the configuration, a default value is returned, based on
-- the project settings.
--
-- @param cfg
-- The configuration to translate.
-- @param win32
-- If true, enables the "Win32" symbol. If false, uses "x86" instead.
-- @return
-- A Visual Studio architecture identifier.
--
function vstudio.archFromConfig(cfg, win32)
local isnative = project.isnative(cfg.project)
local arch = architecture(cfg.system, cfg.architecture)
if not arch then
arch = iif(isnative, "x86", "Any CPU")
end
if win32 and isnative and arch == "x86" then
arch = "Win32"
end
return arch
end
--
-- Attempt to translate a platform identifier into a corresponding
-- Visual Studio architecture identifier.
--
-- @param platform
-- The platform identifier to translate.
-- @return
-- A Visual Studio architecture identifier, or nil if no mapping
-- could be made.
--
function vstudio.archFromPlatform(platform)
local system = premake.api.checkValue(premake.fields.system, platform)
local arch = premake.api.checkValue(premake.fields.architecture, platform)
return architecture(system, arch or platform:lower())
end
---
-- Given an ISO locale identifier, return an MS culture code.
---
function vstudio.cultureForLocale(locale)
if locale then
local culture = vstudio._cultures[locale]
if not culture then
premake.warnOnce("Locale" .. locale, 'Unsupported locale "%s"', locale)
end
return culture
end
end
---
-- Assemble the list of links just the way Visual Studio likes them.
--
-- @param cfg
-- The active configuration.
-- @param explicit
-- True to explicitly include sibling project libraries; if false Visual
-- Studio's default implicit linking will be used.
-- @return
-- The list of linked libraries, ready to be used in Visual Studio's
-- AdditionalDependencies element.
---
function vstudio.getLinks(cfg, explicit)
local links = {}
-- If we need sibling projects to be listed explicitly, grab them first
if explicit then
links = config.getlinks(cfg, "siblings", "fullpath")
end
-- Then the system libraries, which come undecorated
local system = config.getlinks(cfg, "system", "fullpath")
for i = 1, #system do
-- Add extension if required
local link = system[i]
if not p.tools.msc.getLibraryExtensions()[link:match("[^.]+$")] then
link = path.appendextension(link, ".lib")
end
table.insert(links, link)
end
return links
end
--
-- Return true if the configuration kind is one of "Makefile" or "None". The
-- latter is generated like a Makefile project and excluded from the solution.
--
function vstudio.isMakefile(cfg)
return (cfg.kind == premake.MAKEFILE or cfg.kind == premake.NONE)
end
--
-- If a dependency of a project configuration is excluded from that particular
-- build configuration or platform, Visual Studio will still try to link it.
-- This function detects that case, so that the individual actions can work
-- around it by switching to external linking.
--
-- @param cfg
-- The configuration to test.
-- @return
-- True if the configuration excludes one or more dependencies.
--
function vstudio.needsExplicitLink(cfg)
if not cfg._needsExplicitLink then
local ex = cfg.flags.NoImplicitLink
if not ex then
local prjdeps = project.getdependencies(cfg.project, "linkOnly")
local cfgdeps = config.getlinks(cfg, "dependencies", "object")
ex = #prjdeps ~= #cfgdeps
end
cfg._needsExplicitLink = ex
end
return cfg._needsExplicitLink
end
---
-- Prepare a path value for output in a Visual Studio project or solution.
-- Converts path separators to backslashes, and makes relative to the project.
--
-- @param cfg
-- The project or configuration which contains the path.
-- @param value
-- The path to be prepared.
-- @return
-- The prepared path.
---
function vstudio.path(cfg, value)
cfg = cfg.project or cfg
local dirs = path.translate(project.getrelative(cfg, value))
if type(dirs) == 'table' then
dirs = table.filterempty(dirs)
end
return dirs
end
--
-- Returns the Visual Studio project configuration identifier corresponding
-- to the given Premake configuration.
--
-- @param cfg
-- The configuration to query.
-- @param arch
-- An optional architecture identifier, to override the configuration.
-- @return
-- A project configuration identifier of the form
-- <project platform name>|<architecture>.
--
function vstudio.projectConfig(cfg, arch)
local platform = vstudio.projectPlatform(cfg)
local architecture = arch or vstudio.archFromConfig(cfg, true)
return platform .. "|" .. architecture
end
---
-- Generates a Visual Studio project element for the current action.
---
function vstudio.projectElement()
p.push('<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">')
end
--
-- Returns the full, absolute path to the Visual Studio project file
-- corresponding to a particular project object.
--
-- @param prj
-- The project object.
-- @return
-- The absolute path to the corresponding Visual Studio project file.
--
function vstudio.projectfile(prj)
local extension
if project.isdotnet(prj) then
extension = ".csproj"
elseif project.iscpp(prj) then
extension = iif(_ACTION > "vs2008", ".vcxproj", ".vcproj")
end
return premake.filename(prj, extension)
end
--
-- Returns a project configuration name corresponding to the given
-- Premake configuration. This is just the solution build configuration
-- and platform identifiers concatenated.
--
function vstudio.projectPlatform(cfg)
local platform = cfg.platform
if platform then
local pltarch = vstudio.archFromPlatform(cfg.platform) or platform
local cfgarch = vstudio.archFromConfig(cfg)
if pltarch == cfgarch then
platform = nil
end
end
if platform then
return cfg.buildcfg .. " " .. platform
else
return cfg.buildcfg
end
end
--
-- Determine the appropriate Visual Studio platform identifier for a
-- solution-level configuration.
--
-- @param cfg
-- The configuration to be identified.
-- @return
-- A corresponding Visual Studio platform identifier.
--
function vstudio.solutionPlatform(cfg)
local platform = cfg.platform
-- if a platform is specified use it, translating to the corresponding
-- Visual Studio identifier if appropriate
local platarch
if platform then
platform = vstudio.archFromPlatform(platform) or platform
-- Value for 32-bit arch is different depending on whether this solution
-- contains C++ or C# projects or both
if platform ~= "x86" then
return platform
end
end
-- scan the contained projects to identify the platform
local hasnative = false
local hasnet = false
local slnarch
for prj in p.workspace.eachproject(cfg.workspace) do
if project.isnative(prj) then
hasnative = true
elseif project.isdotnet(prj) then
hasnet = true
end
-- get a VS architecture identifier for this project
local prjcfg = project.getconfig(prj, cfg.buildcfg, cfg.platform)
if prjcfg then
local prjarch = vstudio.archFromConfig(prjcfg)
if not slnarch then
slnarch = prjarch
elseif slnarch ~= prjarch then
slnarch = "Mixed Platforms"
end
end
end
if platform then
return iif(hasnet, "x86", "Win32")
elseif slnarch then
return iif(slnarch == "x86" and not hasnet, "Win32", slnarch)
elseif hasnet and hasnative then
return "Mixed Platforms"
elseif hasnet then
return "Any CPU"
else
return "Win32"
end
end
--
-- Attempt to determine an appropriate Visual Studio architecture identifier
-- for a solution configuration.
--
-- @param cfg
-- The configuration to query.
-- @return
-- A best guess at the corresponding Visual Studio architecture identifier.
--
function vstudio.solutionarch(cfg)
local hasnative = false
local hasdotnet = false
-- if the configuration has a platform identifier, use that as default
local arch = cfg.platform
-- if the platform identifier matches a known system or architecture,
--
for prj in p.workspace.eachproject(cfg.workspace) do
if project.isnative(prj) then
hasnative = true
elseif project.isdotnet(prj) then
hasdotnet = true
end
if hasnative and hasdotnet then
return "Mixed Platforms"
end
if not arch then
local prjcfg = project.getconfig(prj, cfg.buildcfg, cfg.platform)
if prjcfg then
if prjcfg.architecture then
arch = vstudio.archFromConfig(prjcfg)
end
end
end
end
-- use a default if no other architecture was specified
arch = arch or iif(hasnative, "Win32", "Any CPU")
return arch
end
--
-- Returns the Visual Studio solution configuration identifier corresponding
-- to the given Premake configuration.
--
-- @param cfg
-- The configuration to query.
-- @return
-- A solution configuration identifier of the format BuildCfg|Platform,
-- corresponding to the Premake values of the same names. If no platform
-- was specified by the script, the architecture is used instead.
--
function vstudio.solutionconfig(cfg)
local platform = cfg.platform
-- if no platform name was specified, use the architecture instead;
-- since architectures are defined in the projects and not at the
-- solution level, need to poke around to figure this out
if not platform then
platform = vstudio.solutionarch(cfg)
end
return string.format("%s|%s", cfg.buildcfg, platform)
end
--
-- Returns the Visual Studio tool ID for a given project type.
--
function vstudio.tool(prj)
if project.isdotnet(prj) then
return "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC"
elseif project.iscpp(prj) then
return "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942"
end
end
| bsd-3-clause |
PicoleDeLimao/Ninpou2 | game/dota_addons/ninpou2/scripts/vscripts/libraries/pathgraph.lua | 9 | 3962 | PATHGRAPH_VERSION = "0.80"
--[[
Path Graph Instantiation Library by BMD
Installation
-"require" this file inside your code in order to gain access to the PathGraph global and functions.
Usage
-PathGraph:Initialize() should be called sometime during your game mode's initialization.
-The Initialize function will find all of the connecting "path_corner" entities as placed on your map via hammer and connect them.
-Each "path_corner" entity after Initialize will have a "edges" property containing a full edge graph for that node to all other connected nodes.
-PathGraph:DrawPaths(pathCorner, duration, color) should be called for debugging purposes in order to show the path graph connections.
-pathCorner is the path_corner entity to display the connected graph for.
-duration is the duration to display the graph
-color is the color to use for the graph lines and nodes
Notes
-Currently only supports path_corner and not path_track
Examples:
--Initialize the graph
PathGraph:Initialize()
--Iterate through all connected edges starting from a path_corner node named "start_node"
local node = Entities:FindByName(nil, "start_node")
for _,edge in pairs(node.edges) do
print("'start_node' is connected to '" .. edge:GetName() .. "'")
end
]]
if not PathGraph then
PathGraph = class({})
end
local TableCount = function(t)
local n = 0
for _ in pairs( t ) do
n = n + 1
end
return n
end
function PathGraph:Initialize()
local corners = Entities:FindAllByClassname('path_corner')
local points = {}
for _,corner in ipairs(corners) do
points[corner:entindex()] = corner
end
local names = {}
for _,corner in ipairs(corners) do
local name = corner:GetName()
if names[name] ~= nil then
print("[PathGraph] Initialization error, duplicate path_corner named '" .. name .. "' found. Skipping...")
else
local parents = Entities:FindAllByTarget(corner:GetName())
corner.edges = corner.edges or {}
for _,parent in ipairs(parents) do
corner.edges[parent:entindex()] = parent
parent.edges = parent.edges or {}
parent.edges[corner:entindex()] = corner
end
end
end
end
function PathGraph:DrawPaths(pathCorner, duration, color)
duration = duration or 10
color = color or Vector(255,255,255)
if pathCorner ~= nil then
if pathCorner:GetClassname() ~= "path_corner" or pathCorner.edges == nil then
print("[PathGraph] An invalid path_corner was passed to PathGraph:DrawPaths.")
return
end
local seen = {}
local toDo = {pathCorner}
repeat
local corner = table.remove(toDo)
local edges = corner.edges
DebugDrawCircle(corner:GetAbsOrigin(), color, 50, 20, true, duration)
seen[corner:entindex()] = corner
for index,edge in pairs(edges) do
if seen[index] == nil then
DebugDrawLine_vCol(corner:GetAbsOrigin(), edge:GetAbsOrigin(), color, true, duration)
table.insert(toDo, edge)
end
end
until (#toDo == 0)
else
local corners = Entities:FindAllByClassname('path_corner')
local points = {}
for _,corner in ipairs(corners) do
points[corner:entindex()] = corner
end
repeat
local seen = {}
local k,v = next(points)
local toDo = {v}
repeat
local corner = table.remove(toDo)
points[corner:entindex()] = nil
local edges = corner.edges
DebugDrawCircle(corner:GetAbsOrigin(), color, 50, 20, true, duration)
seen[corner:entindex()] = corner
for index,edge in pairs(edges) do
if seen[index] == nil then
DebugDrawLine_vCol(corner:GetAbsOrigin(), edge:GetAbsOrigin(), color, true, duration)
table.insert(toDo, edge)
end
end
until (#toDo == 0)
until (TableCount(points) == 0)
end
end
--PathGraph:Initialize()
GameRules.PathGraph = PathGraph | apache-2.0 |
Zero-K-Experiments/Zero-K-Experiments | gamedata/modularcomms/staticcomms.lua | 4 | 9119 | local commsCampaign = {
-- singleplayer
comm_mission_tutorial1 = {
chassis = "cremcom3",
name = "Tutorial Commander",
modules = { "commweapon_beamlaser", "module_autorepair", "module_autorepair"},
},
comm_campaign_ada = {
chassis = "cremcom2",
name = "Ada's Commander",
-- comm module list should be empty/nil to avoid funny stuff when merging with misson's module table
--modules = { "commweapon_beamlaser", "module_ablative_armor", "module_autorepair", "module_high_power_servos"},
},
comm_campaign_promethean = {
chassis = "commrecon2",
name = "The Promethean",
--modules = { "commweapon_heatray", "module_ablative_armor", "module_ablative_armor", "weaponmod_plasma_containment", "module_autorepair" },
decorations = {"skin_recon_red"},
},
comm_campaign_freemachine = {
chassis = "commstrike2",
name = "Libertas Machina",
--modules = { "commweapon_riotcannon", "module_ablative_armor", "module_ablative_armor", "module_adv_targeting", "module_autorepair" },
},
comm_campaign_odin = {
chassis = "commrecon2",
name = "Odin",
--modules = { "commweapon_lparticlebeam", "module_ablative_armor", "module_ablative_armor", "module_high_power_servos", "module_autorepair", "module_companion_drone"},
},
comm_campaign_biovizier = {
chassis = "commsupport2",
name = "The Biovizier",
--modules = { "commweapon_gaussrifle", "module_ablative_armor", "weaponmod_railaccel", "module_autorepair", "module_autorepair" },
decorations = { "skin_support_green" },
},
comm_campaign_isonade = {
chassis = "benzcom2", -- TODO get a properly organic model
name = "Lord Isonade",
--modules = { "commweapon_sonicgun", "module_heavy_armor", "module_dmg_booster", "module_autorepair", "module_autorepair" },
decorations = { "skin_bombard_steel" },
},
comm_campaign_legion = {
chassis = "commstrike2",
name = "Legate Fidus",
--modules = { "commweapon_shotgun", "module_heavy_armor", "weaponmod_autoflechette", "module_adv_targeting", "module_autorepair"},
--decorations = { "skin_battle_tiger" },
},
comm_campaign_praetorian = {
chassis = "benzcom2",
name = "Scipio Astra",
--modules = { "commweapon_assaultcannon", "module_heavy_armor", "weaponmod_high_caliber_barrel", "module_adv_targeting", "module_autorepair"},
},
}
local comms = {
-- Not Hax
comm_riot_cai = {
chassis = "corcom1",
name = "Crowd Controller",
modules = { "commweapon_riotcannon", "module_adv_targeting",},
cost = 250,
},
comm_econ_cai = {
chassis = "commsupport1",
name = "Base Builder",
modules = { "commweapon_beamlaser", "module_econ",},
cost = 275,
},
comm_marksman_cai = {
chassis = "commsupport1",
name = "The Marksman",
modules = { "commweapon_gaussrifle", "module_adv_targeting",},
cost = 225,
},
comm_stun_cai = {
chassis = "armcom1",
name = "Exotic Assault",
modules = { "commweapon_lightninggun", "module_high_power_servos",},
cost = 250,
},
-- Hax
comm_strike_pea = {
chassis = "armcom1",
name = "Peashooter Commander",
modules = { "commweapon_peashooter"},
},
comm_strike_hmg = {
chassis = "armcom1",
name = "Heavy Machine Gun Commander",
modules = { "commweapon_heavymachinegun"},
},
comm_strike_lpb = {
chassis = "armcom1",
name = "Light Particle Beam Commander",
modules = { "commweapon_lparticlebeam"},
},
comm_battle_pea = {
chassis = "corcom1",
name = "Peashooter Commander",
modules = { "commweapon_peashooter"},
},
comm_support_pea = {
chassis = "commsupport1",
name = "Peashooter Commander",
modules = { "commweapon_peashooter"},
},
comm_recon_pea = {
chassis = "commrecon1",
name = "Peashooter Commander",
modules = { "commweapon_peashooter"},
},
comm_guardian = {
chassis = "armcom2",
name = "Star Guardian",
modules = { "commweapon_beamlaser", "module_ablative_armor", "module_high_power_servos", "weaponmod_high_frequency_beam"},
},
comm_thunder = {
chassis = "armcom2",
name = "Thunder Wizard",
modules = { "commweapon_lightninggun", "module_ablative_armor", "module_high_power_servos", "weaponmod_stun_booster", "module_energy_cell"},
},
comm_riot = {
chassis = "corcom2",
name = "Crowd Controller",
modules = { "commweapon_riotcannon", "commweapon_heatray"},
},
comm_flamer = {
chassis = "corcom2",
name = "The Fury",
modules = { "commweapon_flamethrower", "module_dmg_booster", "module_ablative_armor", "module_ablative_armor", "module_high_power_servos"},
},
comm_recon = {
chassis = "commrecon2",
name = "Ghost Recon",
modules = { "commweapon_lparticlebeam", "module_ablative_armor", "module_high_power_servos", "module_high_power_servos", "module_jammer" , "module_autorepair"},
},
comm_marine = {
chassis = "commrecon2",
name = "Space Marine",
modules = { "commweapon_heavymachinegun", "module_heavy_armor", "module_high_power_servos", "module_dmg_booster", "module_adv_targeting"},
},
comm_marksman = {
chassis = "commsupport2",
name = "The Marksman",
modules = { "commweapon_massdriver", "module_dmg_booster", "module_adv_targeting", "module_ablative_armor" , "module_high_power_servos"},
},
comm_hunter = {
chassis = "commsupport2",
name = "Bear Hunter",
modules = { "commweapon_shotgun", "module_dmg_booster", "module_adv_targeting", "module_high_power_servos", "module_fieldradar"},
},
comm_rocketeer = {
chassis = "benzcom2",
name = "Rocket Surgeon",
modules = { "commweapon_rocketlauncher", "module_dmg_booster", "module_adv_targeting", "module_ablative_armor"},
},
comm_hammer = {
chassis = "benzcom2",
name = "Hammer Slammer",
modules = { "commweapon_assaultcannon", "module_dmg_booster", "conversion_partillery"},
},
}
for name, data in pairs(commsCampaign) do
data.miscDefs = data.miscDefs or {}
data.miscDefs.customparams = data.miscDefs.customparams or {}
data.miscDefs.customparams.statsname = name;
data.miscDefs.reclaimable = false
data.miscDefs.canSelfDestruct = false
comms[name] = data
end
--------------------------------------------------------------------------------------
-- Dynamic Commander Clone Generation
--------------------------------------------------------------------------------------
local powerAtLevel = {2000, 3000, 4000, 5000, 6000}
local function MakeClones(levelLimits, moduleNames, fullChassisName, unitName, power, modules, moduleType)
if moduleType > #levelLimits then
comms[unitName] = {
chassis = fullChassisName,
name = fullChassisName,
modules = modules,
power = power,
}
return
end
for copies = 0, levelLimits[moduleType] do
local newModules = Spring.Utilities.CopyTable(modules)
for m = 1, copies do
newModules[#newModules + 1] = moduleNames[moduleType]
end
MakeClones(levelLimits, moduleNames, fullChassisName, unitName .. copies, power, newModules, moduleType + 1)
end
end
local function MakeCommanderChassisClones(chassis, levelLimits, moduleNames)
for level = 1, #levelLimits do
local fullChassisName = chassis .. level
local modules = {}
MakeClones(levelLimits[level], moduleNames, fullChassisName, fullChassisName .. "_", powerAtLevel[level], modules, 1)
end
end
--------------------------------------------------------------------------------------
-- Must match dynamic_comm_defs.lua around line 800 (top of the chassis defs)
--------------------------------------------------------------------------------------
MakeCommanderChassisClones("dynrecon",
{{0}, {1}, {1}, {1}, {1}},
{"module_personal_shield"}
)
MakeCommanderChassisClones("dynsupport",
{{0, 0, 0}, {1, 0, 1}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}},
{"module_personal_shield", "module_areashield", "module_resurrect"}
)
MakeCommanderChassisClones("dynassault",
{{0, 0}, {1, 0}, {1, 1}, {1, 1}, {1, 1}},
{"module_personal_shield", "module_areashield"}
)
MakeCommanderChassisClones("dynstrike",
{{0, 0}, {1, 0}, {1, 1}, {1, 1}, {1, 1}},
{"module_personal_shield", "module_areashield"}
)
--[[
for name,stats in pairs(comms) do
table.insert(stats.modules, "module_econ")
end
--]]
local costAtLevel = {[0] = 0, 0,200,600,300,400}
local morphableCommDefs = VFS.Include("gamedata/modularcomms/staticcomms_morphable.lua")
for templateName, data in pairs(morphableCommDefs) do
local modules = {}
local cost = 0
for i=0,#data.levels do
local levelInfo = data.levels[i] or {}
for moduleNum=1,#levelInfo do
modules[#modules+1] = levelInfo[moduleNum]
end
cost = cost + (levelInfo.cost or 0) + costAtLevel[i]
local name = templateName .. "_" .. i
local humanName = data.name .. " level " .. i
comms[name] = {
chassis = data.chassis .. i,
name = humanName,
cost = cost,
modules = Spring.Utilities.CopyTable(modules),
}
if i<5 then
comms[name].morphto = templateName .. "_" .. (i+1)
end
end
end
return comms
| gpl-2.0 |
Scavenge/darkstar | scripts/zones/Port_Jeuno/npcs/_6ua.lua | 14 | 1413 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Door: Departures Exit (for Bastok)
-- @zone 246
-- @pos -61 7 -54
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(AIRSHIP_PASS) == true and player:getGil() >= 200) then
player:startEvent(0x0024);
else
player:startEvent(0x002c);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0024) then
Z = player:getZPos();
if (Z >= -61 and Z <= -58) then
player:delGil(200);
end
end
end;
| gpl-3.0 |
Zero-K-Experiments/Zero-K-Experiments | LuaUI/Widgets/ignore.lua | 11 | 1751 | function widget:GetInfo()
return {
name = "In-game Ignore",
desc = "Adds ignore/unignore commands.",
author = "_Shaman",
date = "8-1-2016",
license = "Apply as needed",
layer = 0,
enabled = true,
}
end
local function ProcessString(str)
local strtbl = {}
for w in string.gmatch(str, "%S+") do
strtbl[#strtbl+1] = w
end
return strtbl
end
function widget:TextCommand(command)
local prcmd = ProcessString(command)
if string.lower(prcmd[1]) == "ignore" then
if prcmd[2] then
Spring.Echo("game_message: Ignoring " .. prcmd[2])
widgetHandler:Ignore(prcmd[2])
end
end
if string.lower(prcmd[1]) == "ignorelist" then
local IgnoreList,count = widgetHandler:GetIgnoreList()
if #IgnoreList ~= 1 then
ignorestring = "game_message: You are ignoring " .. count .. " users:"
else
ignorestring = "game_message: You are ignoring " .. count .. " user:"
end
for ignoree,_ in pairs(IgnoreList) do
ignorestring = ignorestring .. "\n- " .. ignoree
end
Spring.Echo(ignorestring)
end
if string.lower(prcmd[1]) == "unignore" then
local IgnoreList,_ = widgetHandler:GetIgnoreList()
if not IgnoreList[prcmd[2]] then
Spring.Echo("game_message: You were not ignoring " .. prcmd[2])
return
end
Spring.Echo("game_message: Unignoring " .. prcmd[2])
widgetHandler:Unignore(prcmd[2])
end
if string.lower(prcmd[1]) == "clearlist" then
local IgnoreList,_ = widgetHandler:GetIgnoreList()
for i=1,#IgnoreList do
widgetHandler:Unignore(IgnoreList[i])
end
end
end
function widget:GetConfigData()
local ignorelist,_ = widgetHandler:GetIgnoreList()
return ignorelist
end
function widget:SetConfigData(data)
data = data or {}
for ignoree,_ in pairs(data) do
widgetHandler:Ignore(ignoree)
end
end
| gpl-2.0 |
Scavenge/darkstar | scripts/zones/Western_Adoulin/npcs/Kongramm.lua | 14 | 2456 | -----------------------------------
-- Area: Western Adoulin
-- NPC: Kongramm
-- Type: Standard NPC, Mission NPC, and Quest NPC
-- Involved with Mission: 'A Curse From The Past'
-- Involved with Quests: 'A Certain Substitute Patrolman' and 'Transporting'
-- @zone 256
-- @pos 61 32 138
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local SOA_Mission = player:getCurrentMission(SOA);
local ACSP = player:getQuestStatus(ADOULIN, A_CERTAIN_SUBSTITUTE_PATROLMAN);
local Transporting = player:getQuestStatus(ADOULIN, TRANSPORTING);
if ((SOA_Mission == A_CURSE_FROM_THE_PAST) and (not player:hasKeyItem(PIECE_OF_A_STONE_WALL))) then
if (player:getVar("SOA_ACFTP_Kongramm") < 1) then
-- Gives hint for SOA Mission: 'A Curse From the Past'
player:startEvent(0x0094);
else
-- Reminds player of hint for SOA Mission: 'A Curse From the Past'
player:startEvent(0x0095);
end
elseif ((Transporting == QUEST_ACCEPTED) and (player:getVar("Transporting_Status") < 1)) then
-- Progresses Quest: 'Transporting'
player:startEvent(0x0A20);
elseif ((ACSP == QUEST_ACCEPTED) and (player:getVar("ACSP_NPCs_Visited") == 3)) then
-- Progresses Quest: 'A Certain Substitute Patrolman'
player:startEvent(0x09FB);
else
-- Standard dialogue
player:startEvent(0x022E);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x0094) then
-- Gave hint for SOA Mission: 'A Curse From the Past'
player:setVar("SOA_ACFTP_Kongramm", 1);
elseif (csid == 0x0A20) then
-- Progresses Quest: 'Transporting'
player:setVar("Transporting_Status", 1);
elseif (csid == 0x09FB) then
-- Progresses Quest: 'A Certain Substitute Patrolman'
player:setVar("ACSP_NPCs_Visited", 4);
end
end;
| gpl-3.0 |
Kyklas/luci-proto-hso | applications/luci-pbx/luasrc/model/cbi/pbx-voip.lua | 128 | 4540 | --[[
Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com>
This file is part of luci-pbx.
luci-pbx is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
luci-pbx is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luci-pbx. If not, see <http://www.gnu.org/licenses/>.
]]--
if nixio.fs.access("/etc/init.d/asterisk") then
server = "asterisk"
elseif nixio.fs.access("/etc/init.d/freeswitch") then
server = "freeswitch"
else
server = ""
end
modulename = "pbx-voip"
m = Map (modulename, translate("SIP Accounts"),
translate("This is where you set up your SIP (VoIP) accounts ts like Sipgate, SipSorcery, \
the popular Betamax providers, and any other providers with SIP settings in order to start \
using them for dialing and receiving calls (SIP uri and real phone calls). Click \"Add\" to \
add as many accounts as you wish."))
-- Recreate the config, and restart services after changes are commited to the configuration.
function m.on_after_commit(self)
commit = false
-- Create a field "name" for each account that identifies the account in the backend.
m.uci:foreach(modulename, "voip_provider",
function(s1)
if s1.defaultuser ~= nil and s1.host ~= nil then
name=string.gsub(s1.defaultuser.."_"..s1.host, "%W", "_")
if s1.name ~= name then
m.uci:set(modulename, s1['.name'], "name", name)
commit = true
end
end
end)
if commit == true then m.uci:commit(modulename) end
luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null")
luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null")
end
-----------------------------------------------------------------------------
s = m:section(TypedSection, "voip_provider", translate("SIP Provider Accounts"))
s.anonymous = true
s.addremove = true
s:option(Value, "defaultuser", translate("User Name"))
pwd = s:option(Value, "secret", translate("Password"),
translate("When your password is saved, it disappears from this field and is not displayed \
for your protection. The previously saved password will be changed only when you \
enter a value different from the saved one."))
pwd.password = true
pwd.rmempty = false
-- We skip reading off the saved value and return nothing.
function pwd.cfgvalue(self, section)
return ""
end
-- We check the entered value against the saved one, and only write if the entered value is
-- something other than the empty string, and it differes from the saved value.
function pwd.write(self, section, value)
local orig_pwd = m:get(section, self.option)
if value and #value > 0 and orig_pwd ~= value then
Value.write(self, section, value)
end
end
h = s:option(Value, "host", translate("SIP Server/Registrar"))
h.datatype = "host"
p = s:option(ListValue, "register", translate("Enable Incoming Calls (Register via SIP)"),
translate("This option should be set to \"Yes\" if you have a DID \(real telephone number\) \
associated with this SIP account or want to receive SIP uri calls through this \
provider."))
p:value("yes", translate("Yes"))
p:value("no", translate("No"))
p.default = "yes"
p = s:option(ListValue, "make_outgoing_calls", translate("Enable Outgoing Calls"),
translate("Use this account to make outgoing calls."))
p:value("yes", translate("Yes"))
p:value("no", translate("No"))
p.default = "yes"
from = s:option(Value, "fromdomain",
translate("SIP Realm (needed by some providers)"))
from.optional = true
from.datatype = "host"
port = s:option(Value, "port", translate("SIP Server/Registrar Port"))
port.optional = true
port.datatype = "port"
op = s:option(Value, "outboundproxy", translate("Outbound Proxy"))
op.optional = true
op.datatype = "host"
return m
| apache-2.0 |
Scavenge/darkstar | scripts/globals/spells/bluemagic/seedspray.lua | 31 | 2112 | -----------------------------------------
-- Spell: Seedspray
-- Delivers a threefold attack. Additional effect: Weakens defense. Chance of effect varies with TP
-- Spell cost: 61 MP
-- Monster Type: Plantoids
-- Spell Type: Physical (Slashing)
-- Blue Magic Points: 2
-- Stat Bonus: VIT+1
-- Level: 61
-- Casting Time: 4 seconds
-- Recast Time: 35 seconds
-- Skillchain Element(s): Ice (Primary) and Wind (Secondary) - (can open Impaction, Compression, Fragmentation, Scission or Gravitation; can close Induration or Detonation)
-- Combos: Beast Killer
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_CRITICAL;
params.dmgtype = DMGTYPE_SLASH;
params.scattr = SC_GRAVITATION;
params.numhits = 3;
params.multiplier = 1.925;
params.tp150 = 1.25;
params.tp300 = 1.25;
params.azuretp = 1.25;
params.duppercap = 61;
params.str_wsc = 0.0;
params.dex_wsc = 0.30;
params.vit_wsc = 0.0;
params.agi_wsc = 0.0;
params.int_wsc = 0.20;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
local chance = math.random();
if (damage > 0 and chance > 1) then
local typeEffect = EFFECT_DEFENSE_DOWN;
target:delStatusEffect(typeEffect);
target:addStatusEffect(typeEffect,4,0,getBlueEffectDuration(caster,resist,typeEffect));
end
return damage;
end; | gpl-3.0 |
Scavenge/darkstar | scripts/zones/Cape_Teriggan/Zone.lua | 11 | 2547 | -----------------------------------
--
-- Zone: Cape_Teriggan (113)
--
-----------------------------------
package.loaded[ "scripts/zones/Cape_Teriggan/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Cape_Teriggan/TextIDs");
require("scripts/globals/icanheararainbow");
require("scripts/globals/weather");
require("scripts/globals/zone");
require("scripts/globals/conquest");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
-- Kreutzet
SetRespawnTime(17240413, 900, 10800);
SetRegionalConquestOverseers(zone:getRegionID())
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn( player, prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( 315.644, -1.517, -60.633, 108);
end
if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow
cs = 0x0002;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter( player, region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0002) then
lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0002) then
lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow
end
end;
-----------------------------------
-- onZoneWeatherChange
-----------------------------------
function onZoneWeatherChange(weather)
if (GetMobAction(17240413) == 24 and (weather == WEATHER_WIND or weather == WEATHER_GALES)) then
SpawnMob(17240413); -- Kreutzet
elseif (GetMobAction(17240413) == 16 and (weather ~= WEATHER_WIND and weather ~= WEATHER_GALES)) then
DespawnMob(17240413);
end
end; | gpl-3.0 |
MOSAVI17/ABCD | plugins/autoleave.lua | 27 | 1849 | --[[
Kicking ourself (bot) from unmanaged groups.
When someone invited this bot to a group, the bot then will chek if the group
is in its moderations (moderation.json).
If not, the bot will exit immediately by kicking itself out of that group.
Enable plugin using !plugins plugin. And if your bot already invited into groups,
use following command to exit from those group;
!leave to leaving from current group.
!leaveall to exit from all unmanaged groups.
--]]
do
--Callbacks for get_dialog_list
local function cb_getdialog(extra, success, result)
local data = load_data(_config.moderation.data)
for k,v in pairs(result) do
if v.peer.id and v.peer.title then
if not data[tostring(v.peer.id)] then
chat_del_user("chat#id"..v.peer.id, 'user#id'..our_id, ok_cb, false)
end
end
end
end
local function run(msg, matches)
if is_admin(msg.from.id, msg.to.id) then
if matches[1] == 'leave' then
chat_del_user("chat#id"..msg.to.id, 'user#id'..our_id, ok_cb, false)
elseif matches[1] == 'leaveall' then
get_dialog_list(cb_getdialog, {chat_id=msg.to.id})
end
end
if msg.action and msg.action.type == 'chat_add_user' and not is_sudo(msg.from.id) then
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
print '>>> autoleave: This is not our group. Leaving...'
chat_del_user('chat#id'..msg.to.id, 'user#id'..our_id, ok_cb, false)
end
end
end
return {
description = 'Exit from unmanaged groups.',
usage = {
admin = {
' ^!leave : Exit from this group.',
' ^!leaveall : Exit from all unmanaged groups.'
},
},
patterns = {
'^!(leave)$',
'^!(leaveall)$',
'^!!tgservice (chat_add_user)$'
},
run = run
}
end
| gpl-2.0 |
Zero-K-Experiments/Zero-K-Experiments | scripts/shipassault.lua | 9 | 3498 | include "constants.lua"
local base, turret, sleeves = piece("base", "turret", "sleeves")
local wake1, wake2 = piece("wake1", "wake2")
local barrel1, barrel2, flare1, flare2 = piece("barrel1", "barrel2", "flare1", "flare2")
local gunPieces = {
[0] = {barrel = barrel1, flare = flare1},
[1] = {barrel = barrel2, flare = flare2},
}
local missiles = { piece("missile1", "missile2", "missile3", "missile4") }
local smokePiece = {base, turret}
----------------------------------------------------------
----------------------------------------------------------
local gun_1 = 0
local missileNum = 1
local SIG_MOVE = 1
local SIG_AIM = 2
local SIG_RESTORE = 4
----------------------------------------------------------
----------------------------------------------------------
local function Wake()
Signal(SIG_MOVE)
SetSignalMask(SIG_MOVE)
while true do
if not Spring.GetUnitIsCloaked(unitID) then
EmitSfx(wake1, 2)
EmitSfx(wake2, 2)
end
Sleep(200)
end
end
function script.StartMoving()
StartThread(Wake)
end
function script.StopMoving()
Signal(SIG_MOVE)
end
function script.Create()
StartThread(SmokeUnit, smokePiece)
for i=1,#missiles do
Turn(missiles[i], x_axis, -math.rad(90))
end
end
function script.QueryWeapon(num)
if num == 1 then return gunPieces[gun_1].flare
else return missiles[missileNum]
end
end
function script.AimFromWeapon(num)
if num == 1 then return sleeves end
return missiles[missileNum]
end
function script.BlockShot(num, targetID)
if num == 2 and GG.OverkillPrevention_CheckBlock(unitID, targetID, 400.1, 90, false, false, true) then
return true
end
return false
end
local function RestoreAfterDelay()
Signal(SIG_RESTORE)
SetSignalMask(SIG_RESTORE)
Sleep(6000)
Turn(turret, y_axis, 0, math.rad(120))
Turn(sleeves, x_axis, 0, math.rad(60))
end
function script.AimWeapon(num, heading, pitch)
if num == 1 then
Signal(SIG_AIM)
SetSignalMask(SIG_AIM)
Turn(turret, y_axis, heading, math.rad(270))
Turn(sleeves, x_axis, -pitch, math.rad(120))
WaitForTurn(turret, y_axis)
WaitForTurn(sleeves, x_axis)
StartThread(RestoreAfterDelay)
return true
elseif num == 2 then
return true
end
end
local function Recoil(piece)
Move(piece, z_axis, -8)
Sleep(400)
Move(piece, z_axis, 0, 6)
end
function script.Shot(num)
if num == 1 then
--EmitSfx(gunPieces[gun_1].flare, 1024)
gun_1 = 1 - gun_1
StartThread(Recoil, gunPieces[gun_1].barrel)
elseif num == 2 then
missileNum = missileNum + 1
if missileNum > 4 then missileNum = 1 end
EmitSfx(missiles[missileNum], 1025)
end
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage / maxHealth
if (severity <= .25) then
Explode(base, sfxNone)
Explode(turret, sfxNone)
Explode(sleeves, sfxNone)
Explode(barrel1, sfxFall)
Explode(barrel2, sfxFall)
return 1 -- corpsetype
elseif (severity <= .5) then
Explode(base, sfxNone)
Explode(turret, sfxNone)
Explode(sleeves, sfxShatter)
Explode(barrel1, sfxSmoke)
Explode(barrel2, sfxSmoke)
return 1 -- corpsetype
elseif (severity <= 1) then
Explode(base, sfxShatter)
Explode(turret, sfxShatter)
Explode(sleeves, sfxShatter)
Explode(barrel1, sfxSmoke + sfxFire)
Explode(barrel2, sfxSmoke + sfxFire)
return 2 -- corpsetype
else
Explode(base, sfxShatter)
Explode(turret, sfxShatter)
Explode(sleeves, sfxShatter)
Explode(barrel1, sfxSmoke + sfxFire + sfxExplode)
Explode(barrel2, sfxSmoke + sfxFire + sfxExplode)
return 2 -- corpsetype
end
end
| gpl-2.0 |
Brenin/PJ-3100 | Working Launchers/Games/Stepmania/StepMania 5/Docs/Themerdocs/Examples/OptionRowHandlerLua.lua | 1 | 6164 | -- This will discuss how to create an option row in lua for use on a normal options screen.
-- To try out this example, copy this file to Scripts/ and add the following
-- line to metrics.ini, on one of the options screens. Change the "1" to an
-- appropriate line name and make sure it's in the LineNames list for that
-- screen.
-- Line1="lua,FooMods()"
-- Make sure you test this with Player 2, Player 1 can't interact with this
-- option row as part of the example.
-- When on the screen testing the example, flush the log and read it when
-- interacting with the option row. This example doesn't actually apply any
-- modifiers to the player, it just prints messages to the log file so you can
-- see what functions are being called.
-- Comments explaining an element come before the element they explain.
-- The function "FooMods" returns a table containing all the information the
-- option row handler needs to build the option row.
function FooMods()
return {
-- A string with the name of the row. This name will be localized using
-- the entry in the "OptionTitles" section of the language file.
Name= "Foo",
-- A boolean that controls whether this row goes to the "next row"
-- element when NavigationMode for the screen is "toggle" and the
-- ArcadeOptionsNavigation preference is 1.
GoToFirstOnStart= false,
-- A boolean controlling whether the choice affects all players.
OneChoiceForAllPlayers= false,
-- A boolean controlling whether SaveSelections is called after every
-- change. If this is true, SaveSelections will be called every time
-- the player moves the cursor on the row.
ExportOnChange= false,
-- A LayoutType enum value. "ShowAllInRow" shows all items in the row,
-- "ShowOneInRow" shows only the choice with focus is shown.
-- "ShowOneInRow" is forced if there are enough choices that they would go
-- off screen.
LayoutType= "ShowAllInRow",
-- A SelectType enum value. "SelectOne" allows only one choice to be
-- selected. "SelectMultiple" allows multiple to be selected.
-- "SelectNone" allows none to be selected.
SelectType= "SelectMultiple",
-- Optional function. If non-nil, this function must return a table of
-- PlayerNumbers that are allowed to use the row.
-- A row that can't be used by one player can be confusing for the players
-- so consider carefully before using this.
-- This function will be called an extra time during loading to ensure
-- it returns a table.
EnabledForPlayers= function(self)
Trace("FooMods:EnabledForPlayers() called.")
-- Leave out PLAYER_1 just for example.
return {PLAYER_2}
end,
-- A table of strings that are the names of choices. Choice names are not
-- localized.
Choices= {"a", "b", "c", "d"},
-- Optional table. If non-nil, this table must contain a list of messages
-- this row should listen for. If one of the messages is recieved, the
-- row is reloaded (and the EnabledForPlayers function is called if it is
-- non-nil).
ReloadRowMessages= {"ReloadFooMods"},
-- LoadSelections should examine the player and figure out which options
-- on the row the player has selected.
-- self is the table returned by the original function used to create the
-- option row. (the table being created right now).
-- list is a table of bools, all initially false. Set them to true to
-- indicate which options are on.
-- pn is the PlayerNumber of the player the selections are for.
LoadSelections= function(self, list, pn)
Trace("FooMods:LoadSelections(" .. pn .. ")")
for i, choice in ipairs(self.Choices) do
-- Randomly set some to true just for an example.
if math.random(0, 1) == 1 then
Trace(choice .. " (" .. i .. ")" .. " set to true.")
list[i]= true
end
end
end,
-- SaveSelections should examine the list of what the player has selected
-- and apply the appropriate modifiers to the player.
-- Same args as LoadSelections.
SaveSelections= function(self, list, pn)
Trace("FooMods:SaveSelections(" .. pn .. ")")
for i, choice in ipairs(self.Choices) do
if list[i] then
Trace(choice .. " (" .. i .. ")" .. " set to true.")
end
end
end,
-- Optional function. If non-nil, this function must take 3 parameters
-- (self, pn, choice), and return a bool. It is called when a player
-- selects an item in the row by pressing start.
-- self is the same as for LoadSelections.
-- pn is the PlayerNumber of the player that made the selection.
-- choice is the choice the player's cursor is on.
-- The return value should be true if the Choices table is changed. If it
-- is true, then LoadSelections will be called to update which choices are
-- underlined for each player.
-- This function is meant to provide a way for a menu to change the text of
-- its choices. If it returns true, LoadSelections will be called for each
-- player. If OneChoiceForAllPlayers is true, this function will be called
-- for each player, which means LoadSelections will be called twice for
-- each player. Well written code shouldn't have a problem with this.
NotifyOfSelection= function(self, pn, choice)
Trace("FooMods:NotifyOfSelection(" .. pn .. ", " .. choice .. ")")
-- Randomly decide whether to change, as an example.
local change= math.random(0, 3)
-- No change half the time, lengthen or clip strings the other half.
if change < 2 then
Trace("Not changing choices.")
else
Trace("Changing choices.")
end
if change == 2 then
for i, choice in ipairs(self.Choices) do
self.Choices[i]= choice .. choice
end
elseif change == 3 then
for i, choice in ipairs(self.Choices) do
self.Choices[i]= choice:sub(1, 1)
end
end
-- Don't actually broadcast a reload message from here, do it from some
-- other place that actually has a reason to trigger a reload. This is
-- just here so that nothing needs to be added to a screen's lua files
-- for this example.
if math.random(0, 5) == 0 then
Trace("Broadcasting reload message.")
MESSAGEMAN:Broadcast("ReloadFooMods")
end
return change >= 2
end
}
end
| mit |
kasicass/gearx | bin/lua/operations.lua | 1 | 1480 | -- emacs: -*- mode: lua; coding: utf-8; -*-
--[[
Copyright (C) 2007 GearX Team
This source code is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This source code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
$Id: $
ChenZaichun@gmail.com
--]]
-------------------------------------------------------------------------------
-- operation of gearx
operations = {
-- client to server
MOVELEFT = 1,
MOVERIGHT = 2,
UPSCROLLIMG = 3,
DOWNSCROLLIMG = 4,
MOVEDOWN = 5,
EXIT = 6,
-- both server and client receive this message
START = 7,
-- server to client
UPDATE = 8,
OVER = 9,
}
-------------------------------------------------------------------------------
-- playing scene state
PLAYING_STATE = {
INIT = 1,
PLAYING = 2,
PAUSE = 3,
OVER = 4,
EXIT = 5, -- exit playing state
}
| lgpl-2.1 |
Brenin/PJ-3100 | Working Launchers/Games/Stepmania/StepMania 5/Themes/default/BGAnimations/ScreenGameplay overlay.lua | 1 | 1428 | local t = Def.ActorFrame {};
local function UpdateTime(self)
local c = self:GetChildren();
for pn in ivalues(PlayerNumber) do
local vStats = STATSMAN:GetCurStageStats():GetPlayerStageStats( pn );
local vTime;
local obj = self:GetChild( string.format("RemainingTime" .. PlayerNumberToString(pn) ) );
if vStats and obj then
vTime = vStats:GetLifeRemainingSeconds()
obj:settext( SecondsToMMSSMsMs( vTime ) );
end;
end;
end
if GAMESTATE:GetCurrentCourse() then
if GAMESTATE:GetCurrentCourse():GetCourseType() == "CourseType_Survival" then
-- RemainingTime
for pn in ivalues(PlayerNumber) do
local MetricsName = "RemainingTime" .. PlayerNumberToString(pn);
t[#t+1] = LoadActor( THEME:GetPathG( Var "LoadingScreen", "RemainingTime"), pn ) .. {
InitCommand=function(self)
self:player(pn);
self:name(MetricsName);
ActorUtil.LoadAllCommandsAndSetXY(self,Var "LoadingScreen");
end;
};
end
for pn in ivalues(PlayerNumber) do
local MetricsName = "DeltaSeconds" .. PlayerNumberToString(pn);
t[#t+1] = LoadActor( THEME:GetPathG( Var "LoadingScreen", "DeltaSeconds"), pn ) .. {
InitCommand=function(self)
self:player(pn);
self:name(MetricsName);
ActorUtil.LoadAllCommandsAndSetXY(self,Var "LoadingScreen");
end;
};
end
end;
end;
t.InitCommand=cmd(SetUpdateFunction,UpdateTime);
t[#t+1]= LoadActor(THEME:GetPathG("", "pause_menu"))
return t
| mit |
Tele-Fox/self | plugins/gpmanager.lua | 1 | 7551 | do
local function add_by_reply(extra, success, result)
result = backward_msg_format(result)
local msg = result
local chat = msg.to.id
local user = msg.from.id
if msg.to.type == 'chat' then
chat_add_user('chat#id'..chat, 'user#id'..user, ok_cb, false)
elseif msg.to.type == 'channel' then
channel_invite_user('channel#id'..chat, 'user#id'..user, ok_cb, false)
end
end
local function add_by_username(cb_extra, success, result)
local chat_type = cb_extra.chat_type
local chat_id = cb_extra.chat_id
local user_id = result.peer_id
local user_username = result.username
print(chat_id)
if chat_type == 'chat' then
chat_add_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false)
elseif chat_type == 'channel' then
channel_invite_user('channel#id'..chat_id, 'user#id'..user_id, ok_cb, false)
end
end
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
local channel = 'channel#id'..chat_id
if user_id == tostring(our_id) then
print("I won't kick myself!")
else
chat_del_user(chat, user, ok_cb, true)
channel_kick_user(channel, user, ok_cb, true)
end
end
local function chat_kick(extra, success, result)
result = backward_msg_format(result)
local msg = result
local chat = msg.to.id
local user = msg.from.id
local chat_type = msg.to.type
if chat_type == 'chat' then
chat_del_user('chat#id'..chat, 'user#id'..user, ok_cb, false)
elseif chat_type == 'channel' then
channel_kick_user('channel#id'..chat, 'user#id'..user, ok_cb, false)
end
end
local function kick_by_username(cb_extra, success, result)
chat_id = cb_extra.chat_id
user_id = result.peer_id
chat_type = cb_extra.chat_type
user_username = result.username
if chat_type == 'chat' then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false)
elseif chat_type == 'channel' then
channel_kick_user('channel#id'..chat_id, 'user#id'..user_id, ok_cb, false)
end
end
local function run(msg, matches)
if matches[1] == 'setname' then
if permissions(msg.from.id, msg.to.id, "settings") then
local hash = 'name:enabled:'..msg.to.id
if not redis:get(hash) then
if msg.to.type == 'chat' then
rename_chat(msg.to.peer_id, matches[2], ok_cb, false)
elseif msg.to.type == 'channel' then
rename_channel(msg.to.peer_id, matches[2], ok_cb, false)
end
end
return
end
elseif matches[1] == 'newlink' then
if permissions(msg.from.id, msg.to.id, "setlink") then
local receiver = get_receiver(msg)
local hash = 'link:'..msg.to.id
local function cb(extra, success, result)
if result then
redis:set(hash, result)
end
if success == 0 then
return send_large_msg(receiver, 'Error*\nnewlink not saved\nYou are not the group administrator', ok_cb, true)
end
end
if msg.to.type == 'chat' then
result = export_chat_link(receiver, cb, true)
elseif msg.to.type == 'channel' then
result = export_channel_link(receiver, cb, true)
end
if result then
if msg.to.type == 'chat' then
send_msg('chat#id'..msg.to.id, 'New link created', ok_cb, true)
elseif msg.to.type == 'channel' then
send_msg('channel#id'..msg.to.id, 'New link created', ok_cb, true)
end
end
return
else
return '?? '..lang_text(msg.to.id, 'require_admin')
end
elseif matches[1] == 'link' then
if permissions(msg.from.id, msg.to.id, "link") then
hash = 'link:'..msg.to.id
local linktext = redis:get(hash)
if linktext then
if msg.to.type == 'chat' then
send_msg('user#id'..msg.from.id, 'Group Link :'..linktext, ok_cb, true)
elseif msg.to.type == 'channel' then
send_msg('user#id'..msg.from.id, 'SuperGroup Link :'..linktext, ok_cb, true)
end
return 'Link was sent in your pv'
else
if msg.to.type == 'chat' then
send_msg('chat#id'..msg.to.id, 'Error*\nplease send #newlink', ok_cb, true)
elseif msg.to.type == 'channel' then
send_msg('channel#id'..msg.to.id, 'Error*\nplease send #newlink', ok_cb, true)
end
end
return
end
elseif matches[1] == 'tosuper' then
if msg.to.type == 'chat' then
if permissions(msg.from.id, msg.to.id, "tosupergroup") then
chat_upgrade('chat#id'..msg.to.id, ok_cb, false)
return 'Chat Upgraded Successfully.'
end
else
return 'Error !'
end
elseif matches[1] == 'rmv' then
if permissions(msg.from.id, msg.to.id, "kick") then
local chat_id = msg.to.id
local chat_type = msg.to.type
if msg.reply_id then
get_message(msg.reply_id, chat_kick, false)
return
end
if not is_id(matches[2]) then
local member = string.gsub(matches[2], '@', '')
resolve_username(member, kick_by_username, {chat_id=chat_id, member=member, chat_type=chat_type})
return
else
local user_id = matches[2]
if msg.to.type == 'chat' then
chat_del_user('chat#id'..msg.to.id, 'user#id'..matches[2], ok_cb, false)
elseif msg.to.type == 'channel' then
channel_kick_user('channel#id'..msg.to.id, 'user#id'..matches[2], ok_cb, false)
end
end
end
elseif matches[1] == 'add' then
if permissions(msg.from.id, msg.to.id, "add") then
local chat_id = msg.to.id
local chat_type = msg.to.type
if msg.reply_id then
get_message(msg.reply_id, add_by_reply, false)
return
end
if not is_id(matches[2]) then
local member = string.gsub(matches[2], '@', '')
print(chat_id)
resolve_username(member, add_by_username, {chat_id=chat_id, member=member, chat_type=chat_type})
return
else
local user_id = matches[2]
if chat_type == 'chat' then
chat_add_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false)
elseif chat_type == 'channel' then
channel_invite_user('channel#id'..chat_id, 'user#id'..user_id, ok_cb, false)
end
end
end
elseif matches[1] == 'setdes' then
if permissions(msg.from.id, msg.to.id, "description") then
local text = matches[2]
local chat = 'channel#id'..msg.to.id
if msg.to.type == 'channel' then
channel_set_about(chat, text, ok_cb, false)
return 'changed.'
end
end
end
end
return {
patterns = {
'^#(setname) (.*)$',
'^#(link)$',
'^#(newlink)$',
'^#(tosuper)$',
'^#(setdes) (.*)$',
"^#(rmv)$",
| gpl-2.0 |
seblindfors/ConsolePort | ConsolePort_Bar/Components/ActionbarPlacer.lua | 1 | 1817 | --[[
-- Idea abandoned for now, but this seems like it could be useful.
local _, env = ...
local acb = env.libs.acb
local HANDLE = CreateFrame('Frame', 'ConsolePortBarActionPlacer', UIParent, 'SecureHandlerStateTemplate')
RegisterStateDriver(HANDLE, 'cursor', '[cursor]true;nil')
RegisterStateDriver(HANDLE, 'combat', '[combat]true;nil')
HANDLE:SetAttribute('_onstate-combat', 'self:SetAttribute('incombat', newstate)')
HANDLE:SetAttribute('_onstate-cursor', "
if not self:GetAttribute('incombat') and newstate then
self:Show()
else
self:Hide()
end
")
function HANDLE:OnShow()
if not self.gridExists then
local noop = function () end
local xml = 'SecureHandlerBaseTemplate, SecureActionButtonTemplate, CPUISquareActionButtonTemplate'
local xoffset = NUM_ACTIONBAR_BUTTONS/2 * 42
self.FadeIn = noop
self.FadeOut = noop
for bar=1, 6 + GetNumShapeshiftForms() do
for slot=1, NUM_ACTIONBAR_BUTTONS do
local buttonID = ( ( bar - 1 ) * 12 ) + slot
local button = acb:CreateButton(buttonID, '$parentButton'..buttonID, self, nil, xml)
--lib:CreateButton(id, name, header, config, templates)
button.isMainButton = true
button:SetAttribute('type', 'action')
button:SetAttribute('action', buttonID)
button:SetAttribute('actionpage', bar)
button:FadeIn(1, 0.2)
button.FadeOut = noop
button.FadeIn = noop
button.forceShow = true
button:SetSize(40, 40)
button:SetPoint('TOPLEFT', ((slot-1)*42) - xoffset, -(bar-1)*42)
button:SetState('', 'action', buttonID)
button:Execute("self:RunAttribute('UpdateState', '') self:CallMethod('UpdateAction')")
end
end
ConsolePort:LoadHotKeyTextures()
self.gridExists = true
end
end
HANDLE:SetScript('OnShow', HANDLE.OnShow)
HANDLE:SetPoint('CENTER', 0, 0)
HANDLE:SetSize(1, 1)
HANDLE:Hide()
]] | artistic-2.0 |
lessthanoptimal/DeepBoof | modules/io/src/test/torch7/GenerateSpatialBatchNorm.lua | 1 | 1476 | ----------------------------------------------------------------------
-- Generates unit test data to test Torch to DeepBoof
--
-- Peter Abeles
----------------------------------------------------------------------
require 'torch'
require 'nn'
require 'boof'
local operation_name = "spatial_batch_normalization"
N = 2
C = 4
H = 8
W = 10
for k,data_type in pairs(boof.float_types) do
torch.setdefaulttensortype(boof.boof_to_tensor_name(data_type))
local output_dir = boof.create_output(operation_name,data_type,1)
local input = torch.randn(N,C,H,W)
-- Create batch normalization with parameters that are not learnable
local operation = nn.SpatialBatchNormalization(C, nil, nil, false)
operation.running_mean = torch.randn(C)
operation.running_var = torch.rand(C)
operation:evaluate()
local output = operation:forward(input)
boof.save(output_dir,input,operation,output)
------------------------------------------------------------------------
-- The same but with gamma+beta (a.k.a. weight and bias)
local output_dir = boof.create_output(operation_name,data_type,2)
local operation = nn.SpatialBatchNormalization(C, nil, nil, true)
operation.running_mean = torch.randn(C)
operation.running_var = torch.rand(C)
operation.weight = torch.randn(C)
operation.bias = torch.rand(C)
operation:evaluate()
output = operation:forward(input)
boof.save(output_dir,input,operation,output)
end | apache-2.0 |
Scavenge/darkstar | scripts/zones/Full_Moon_Fountain/Zone.lua | 30 | 2545 | -----------------------------------
--
-- Zone: Full_Moon_Fountain (170)
--
-----------------------------------
package.loaded["scripts/zones/Full_Moon_Fountain/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Full_Moon_Fountain/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/globals/titles");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-260.136,2.09,-325.702,188);
end
if (player:getCurrentMission(WINDURST) == FULL_MOON_FOUNTAIN and player:getVar("MissionStatus") == 3) then
cs = 0x0032;
elseif (player:getCurrentMission(WINDURST) == DOLL_OF_THE_DEAD and player:getVar("MissionStatus") == 7) then
cs = 0x003D;
end
return cs;
end;
-----------------------------------
-- afterZoneIn
-----------------------------------
function afterZoneIn(player)
player:entityVisualPacket("kilk");
player:entityVisualPacket("izum");
player:entityVisualPacket("hast");
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0032) then
finishMissionTimeline(player,3,csid,option);
elseif (csid == 0x003D) then
player:addTitle(GUIDING_STAR);
finishMissionTimeline(player,3,csid,option);
end
end;
| gpl-3.0 |
XingxingZhang/lstm-lm | layers/EMaskedClassNLLCriterion.lua | 3 | 1126 |
--[[
-- when y contains zeros
--]]
local EMaskedClassNLLCriterion, parent = torch.class('EMaskedClassNLLCriterion', 'nn.Module')
function EMaskedClassNLLCriterion:__init()
parent.__init(self)
end
function EMaskedClassNLLCriterion:updateOutput(input_)
local input, target, div = unpack(input_)
if input:dim() == 2 then
local nll = 0
local n = target:size(1)
for i = 1, n do
if target[i] ~= 0 then
nll = nll - input[i][target[i]]
end
end
self.output = nll / div
return self.output
else
error('input must be matrix! Note only batch mode is supported!')
end
end
function EMaskedClassNLLCriterion:updateGradInput(input_)
local input, target, div = unpack(input_)
-- print('self.gradInput', self.gradInput)
self.gradInput:resizeAs(input)
self.gradInput:zero()
local er = -1 / div
if input:dim() == 2 then
local n = target:size(1)
for i = 1, n do
if target[i] ~= 0 then
self.gradInput[i][target[i]] = er
end
end
return self.gradInput
else
error('input must be matrix! Note only batch mode is supported!')
end
end
| apache-2.0 |
Scavenge/darkstar | scripts/globals/items/plate_of_crab_sushi.lua | 12 | 1466 | -----------------------------------------
-- ID: 5721
-- Item: plate_of_crab_sushi
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Vitality 1
-- Defense 10
-- Accuracy % 13 (cap 64)
-- Resist Sleep +1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5721);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VIT, 1);
target:addMod(MOD_DEF, 10);
target:addMod(MOD_FOOD_ACCP, 13);
target:addMod(MOD_FOOD_ACC_CAP, 64);
target:addMod(MOD_SLEEPRES, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VIT, 1);
target:delMod(MOD_DEF, 10);
target:delMod(MOD_FOOD_ACCP, 13);
target:delMod(MOD_FOOD_ACC_CAP, 64);
target:delMod(MOD_SLEEPRES, 1);
end;
| gpl-3.0 |
Zero-K-Experiments/Zero-K-Experiments | LuaRules/Configs/cai/buildtasks.lua | 2 | 18719 | --[[
defenceQuota = how much of each level of defence the unit wants
defence demand in an area is additive
minFacCount = min other facs that must exist for factory to be built
minTime = not used yet
factory job indexes:
1 = con
2 = scout
3 = raider
4 = arty
5 = assault
6 = skirm
7 = riot
8 = AA
1 = con
2 = scout
3 = fighter
4 = bomber
5 = gunship
--]]
local reverseCompat = ((Spring.Utilities.GetEngineVersion():find('91.0') == 1))
factionBuildConfig = {
robots = {
airDefenceRange = {
[1] = 600,
[2] = 800,
[3] = 700,
},
factoryIds = {
count = 7,
[1] = {ID = UnitDefNames['factoryveh'].id},
[2] = {ID = UnitDefNames['factorytank'].id},
[3] = {ID = UnitDefNames['factoryhover'].id},
[4] = {ID = UnitDefNames['factorycloak'].id},
[5] = {ID = UnitDefNames['factoryshield'].id},
[6] = {ID = UnitDefNames['factoryspider'].id},
[7] = {ID = UnitDefNames['factoryjump'].id},
[8] = {ID = UnitDefNames['factoryamph'].id},
},
factoryByDefId = {
[UnitDefNames['factoryveh'].id] = {
defenceQuota = {2,0.6,0.3},
defenceRange = 400,
airDefenceQuota = {2,1,0.1},
importance = 1,
BPQuota = 70,
minFacCount = 0,
[1] = { -- con
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['corned'].id, chance = 1},
},
[2] = {-- scout
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['corfav'].id, chance = 1},
},
[3] = { -- raider
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['corgator'].id, chance = 1},
},
[4] = { -- arty
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames['corgarp'].id, chance = 0.9},
[2] = {ID = UnitDefNames['armmerl'].id, chance = 0.1},
},
[5] = { --assault
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['corraid'].id, chance = 1},
},
[6] = { -- skirm
importanceMult = 0.3,
count = 1,
[1] = {ID = UnitDefNames['cormist'].id, chance = 1},
},
[7] = { -- riot
importanceMult = 1.2,
count = 2,
[1] = {ID = UnitDefNames['cormist'].id, chance = 0.25},
[2] = {ID = UnitDefNames['corlevlr'].id, chance = 0.75},
},
[8] = { -- aa
importanceMult = 0.4,
count = 1,
[1] = {ID = UnitDefNames['cormist'].id, chance = 1},
},
},
[UnitDefNames['factoryjump'].id] = {
defenceQuota = {2,0.6,0.3},
defenceRange = 400,
airDefenceQuota = {2,1,0.1},
importance = 0.8,
BPQuota = 70,
minFacCount = 1,
[1] = { -- con
importanceMult = 0.8,
count = 1,
[1] = {ID = UnitDefNames['corfast'].id, chance = 1},
},
[2] = { -- scout
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['puppy'].id, chance = 1},
},
[3] = { -- raider
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames['puppy'].id, chance = 0.6},
[2] = {ID = UnitDefNames['corpyro'].id, chance = 0.4},
},
[4] = { -- arty
importanceMult = 0.3,
count = 1,
[1] = {ID = UnitDefNames['firewalker'].id, chance = 1},
},
[5] = { --assault
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames['corcan'].id, chance = 0.9},
[2] = {ID = UnitDefNames['corsumo'].id, chance = 0.1},
},
[6] = { -- skirm
importanceMult = 0.6,
count = 1,
[1] = {ID = UnitDefNames['slowmort'].id, chance = 1},
},
[7] = { -- riot
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames['corcan'].id, chance = 0.9},
[2] = {ID = UnitDefNames['corsumo'].id, chance = 0.1},
},
[8] = { -- aa
importanceMult = 0.8,
count = 1,
[1] = {ID = UnitDefNames['armaak'].id, chance = 1},
},
},
[UnitDefNames['factoryspider'].id] = {
defenceQuota = {2,0.6,0.3},
defenceRange = 400,
airDefenceQuota = {2,1,0.1},
importance = 1,
BPQuota = 70,
minFacCount = 0,
[1] = { -- con
importanceMult = 0.9,
count = 1,
[1] = {ID = UnitDefNames['arm_spider'].id, chance = 1},
},
[2] = { -- scout
importanceMult = 1.2,
count = 1,
[1] = {ID = UnitDefNames['armflea'].id, chance = 1},
--[2] = {ID = UnitDefNames['armspy'].id, chance = 0.05},
},
[3] = { -- raider
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['armflea'].id, chance = 1},
},
[4] = { -- arty
importanceMult = 0,
count = 0,
},
[5] = { -- assault
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames['spiderassault'].id, chance = 0.95},
[2] = {ID = UnitDefNames['armcrabe'].id, chance = 0.05},
},
[6] = { -- skirm
importanceMult = 1.5,
count = 1,
[1] = {ID = UnitDefNames['armsptk'].id, chance = 1},
},
[7] = { -- riot
importanceMult = 0.5,
count = 1,
[1] = {ID = UnitDefNames['arm_venom'].id, chance = 0.4},
[2] = {ID = UnitDefNames['spiderriot'].id, chance = 0.6},
},
[8] = { -- aa
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['spideraa'].id, chance = 1},
},
},
[UnitDefNames['factorycloak'].id] = {
defenceQuota = {2,0.6,0.3},
defenceRange = 400,
airDefenceQuota = {2,1,0.1},
importance = 1,
BPQuota = 70,
minFacCount = 0,
[1] = { -- con
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['armrectr'].id, chance = 1},
},
[2] = { -- scout
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['armpw'].id, chance = 1},
},
[3] = { -- raid
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames['armpw'].id, chance = 0.7},
[2] = {ID = UnitDefNames['spherepole'].id, chance = 0.3},
},
[4] = { -- arty
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames['armham'].id, chance = 0.9},
[2] = {ID = UnitDefNames['armsnipe'].id, chance = 0.1},
},
[5] = { --assault
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['armzeus'].id, chance = 1},
},
[6] = { -- skirm
importanceMult = 1.2,
count = 1,
[1] = {ID = UnitDefNames['armrock'].id, chance = 1},
},
[7] = { -- riot
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['armwar'].id, chance = 1},
},
[8] = { -- aa
importanceMult = 1.3,
count = 1,
[1] = {ID = UnitDefNames['armjeth'].id, chance = 1},
},
},
[UnitDefNames['factoryshield'].id] = {
defenceQuota = {2,0.6,0.3},
defenceRange = 400,
airDefenceQuota = {2,1,0.1},
importance = 1,
BPQuota = 70,
minFacCount = 0,
[1] = { -- con
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['cornecro'].id, chance = 1},
},
[2] = { -- scout
importanceMult = 2,
count = 2,
[1] = {ID = UnitDefNames['corclog'].id, chance = 0.4},
[2] = {ID = UnitDefNames['corak'].id, chance = 0.6},
},
[3] = { -- raid
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['corak'].id, chance = 1},
},
[4] = { -- arty
importanceMult = 0,
count = 0,
-- [1] = {ID = UnitDefNames['firewalker'].id, chance = 1},
},
[5] = { --assault
importanceMult = 1.2,
count = 1,
[1] = {ID = UnitDefNames['corthud'].id, chance = 1},
},
[6] = { -- skirm
importanceMult = 1.3,
count = 1,
[1] = {ID = UnitDefNames['corstorm'].id, chance = 1},
},
[7] = { -- riot
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['cormak'].id, chance = 1},
},
[8] = { -- aa
importanceMult = 1.3,
count = 1,
[1] = {ID = UnitDefNames['corcrash'].id, chance = 1},
},
},
[UnitDefNames['factoryhover'].id] = {
defenceQuota = {2,0.6,0.3},
defenceRange = 400,
airDefenceQuota = {2,1,0.1},
importance = 1,
BPQuota = 70,
minFacCount = 0,
[1] = { -- con
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['corch'].id, chance = 1},
},
[2] = { -- scout
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['corsh'].id, chance = 1},
},
[3] = { -- raider
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames['corsh'].id, chance = 0.5},
[2] = {ID = UnitDefNames['hoverassault'].id, chance = 0.5},
},
[4] = { -- arty
importanceMult = 0.5,
count = 1,
[1] = {ID = UnitDefNames['armmanni'].id, chance = 1},
},
[5] = { --assault
importanceMult = 1.2,
count = 2,
[1] = {ID = UnitDefNames['hoverassault'].id, chance = 0.65},
[2] = {ID = UnitDefNames['nsaclash'].id, chance = 0.35},
},
[6] = { -- skirm
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['nsaclash'].id, chance = 1},
},
[7] = { -- riot
importanceMult = 0.8,
count = 1,
[1] = {ID = UnitDefNames['hoverriot'].id, chance = 1},
},
[8] = { -- aa
importanceMult = 0.8,
count = 1,
[1] = {ID = UnitDefNames['hoveraa'].id, chance = 1},
},
},
[UnitDefNames['factorytank'].id] = {
defenceQuota = {2,0.6,0.3},
defenceRange = 400,
airDefenceQuota = {2,1,0.1},
importance = 1,
BPQuota = 100,
minFacCount = 1,
[1] = { -- con
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['coracv'].id, chance = 1},
},
[2] = { -- scout
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['logkoda'].id, chance = 1},
},
[3] = { -- raider
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames['logkoda'].id, chance = 0.3},
[2] = {ID = UnitDefNames['panther'].id, chance = 0.7},
},
[4] = { -- arty
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames['cormart'].id, chance = 0.7},
[2] = {ID = UnitDefNames['trem'].id, chance = 0.3},
},
[5] = { --assault
importanceMult = 1,
count = 3,
[1] = {ID = UnitDefNames['correap'].id, chance = 0.75},
[2] = {ID = UnitDefNames['tawf114'].id, chance = 0.15},
[3] = {ID = UnitDefNames['corgol'].id, chance = 0.1},
},
[6] = { -- skirm
importanceMult = 0.4,
count = 1,
[1] = {ID = UnitDefNames['cormart'].id, chance = 1},
},
[7] = { -- riot
importanceMult = 0.8,
count = 1,
[1] = {ID = UnitDefNames['tawf114'].id, chance = 1},
},
[8] = { -- aa
importanceMult = 0.8,
count = 1,
[1] = {ID = UnitDefNames['corsent'].id, chance = 1},
},
},
[UnitDefNames['factoryamph'].id] = {
defenceQuota = {2,0.6,0.3},
defenceRange = 400,
airDefenceQuota = {2,1,0.1},
importance = 0.8,
BPQuota = 70,
minFacCount = 0,
[1] = { -- con
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['amphcon'].id, chance = 1},
},
[2] = { -- scout
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['amphraider3'].id, chance = 1},
},
[3] = { -- raider
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames['amphraider3'].id, chance = 0.8},
[2] = {ID = UnitDefNames['amphraider2'].id, chance = 0.2},
},
[4] = { -- arty
importanceMult = 0.1,
count = 1,
[1] = {ID = UnitDefNames['amphassault'].id, chance = 0.7},
},
[5] = { --assault
importanceMult = 0.7,
count = 2,
[1] = {ID = UnitDefNames['amphriot'].id, chance = 0.3},
[2] = {ID = UnitDefNames['amphfloater'].id, chance = 0.7},
},
[6] = { -- skirm
importanceMult = 1.4,
count = 1,
[1] = {ID = UnitDefNames['amphfloater'].id, chance = 1},
},
[7] = { -- riot
importanceMult = 0.6,
count = 2,
[2] = {ID = UnitDefNames['amphraider2'].id, chance = 0.7},
[1] = {ID = UnitDefNames['amphriot'].id, chance = 0.3},
},
[8] = { -- aa
importanceMult = 1,
count = 1,
[1] = {ID = UnitDefNames['amphaa'].id, chance = 1},
},
},
[UnitDefNames['factoryplane'].id] = {
defenceQuota = {2,0.6,0.3},
defenceRange = 400,
airDefenceQuota = {2,1,0.1},
airFactory = true,
importance = 1,
BPQuota = 70,
minFacCount = 1,
[1] = { -- con
importanceMult = 0.8,
count = 1,
[1] = {ID = UnitDefNames['armca'].id, chance = 1},
},
[2] = { -- scout
importanceMult = 0.6,
count = 1,
[1] = {ID = UnitDefNames['corawac'].id, chance = 1},
},
[3] = { -- fighter
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames['fighter'].id, chance = 0.7},
[2] = {ID = UnitDefNames['corvamp'].id, chance = 0.3},
},
[4] = { -- bomber
importanceMult = 1,
count = 2,
[1] = {ID = UnitDefNames[reverseCompat and 'corshad' or 'bomberdive'].id, chance = 0.4},
[2] = {ID = UnitDefNames['corhurc2'].id, chance = 0.6},
},
[5] = { -- gunship
importanceMult = 0,
count = 0,
},
},
[UnitDefNames['factorygunship'].id] = {
defenceQuota = {2,0.6,0.3},
defenceRange = 400,
airDefenceQuota = {2,1,0.1},
airFactory = true,
importance = 1,
BPQuota = 70,
minFacCount = 1,
[1] = { -- con
importanceMult = 0.8,
count = 1,
[1] = {ID = UnitDefNames['gunshipcon'].id, chance = 1},
},
[2] = { -- scout
importanceMult = 0.6,
count = 1,
[1] = {ID = UnitDefNames['blastwing'].id, chance = 1},
},
[3] = { -- fighter
importanceMult = 0.6,
count = 2,
[1] = {ID = UnitDefNames['gunshipsupport'].id, chance = 1},
},
[4] = { -- bomber
importanceMult = 0,
count = 0,
},
[5] = { -- gunship
importanceMult = 1.4,
count = 4,
[1] = {ID = UnitDefNames['gunshipsupport'].id, chance = 0.30},
[2] = {ID = UnitDefNames['armkam'].id, chance = 0.35},
[3] = {ID = UnitDefNames['armbrawl'].id, chance = 0.175},
[4] = {ID = UnitDefNames['blackdawn'].id, chance = 0.175},
},
},
},
radarIds = {
count = 1,
[1] = {ID = UnitDefNames['corrad'].id, chance = 1},
},
mexIds = {
count = 1,
[1] = {ID = UnitDefNames['cormex'].id, chance = 1},
},
energyIds = {
count = 4,
[1] = {ID = UnitDefNames['cafus'].id},
[2] = {ID = UnitDefNames['armfus'].id},
[3] = {ID = UnitDefNames['armsolar'].id},
[4] = {ID = UnitDefNames['armwin'].id},
},
econByDefId = {
[UnitDefNames['armfus'].id] = {
energyGreaterThan = 30,
energySpacing = 100,
whileStall = false,
makeNearFactory = 1800,
chance = 0.8,
minEtoMratio = 1.5,
defenceQuota = {1,1,1},
defenceRange = 600,
airDefenceQuota = {2,1,0.1},
index = 2,
energy = true,
},
[UnitDefNames['geo'].id] = {
energyGreaterThan = 20,
energySpacing = 400,
whileStall = false,
makeNearFactory = 1800,
chance = 0.8,
minEtoMratio = 1.5,
defenceQuota = {0.8,0.6,0.4},
defenceRange = 600,
airDefenceQuota = {1.5,0.8,0.1},
index = 2,
energy = true,
},
[UnitDefNames['cafus'].id] = {
energyGreaterThan = 120,
energySpacing = 600,
whileStall = false,
makeNearFactory = 1800,
chance = 0.3,
minEtoMratio = 1.5,
defenceQuota = {3,2,2},
defenceRange = 800,
airDefenceQuota = {3,2,1},
index = 4,
energy = true,
},
[UnitDefNames['amgeo'].id] = {
energyGreaterThan = 120,
energySpacing = 900,
whileStall = false,
makeNearFactory = false,
chance = 0.3,
minEtoMratio = 1.5,
defenceQuota = {3,2,2},
defenceRange = 800,
airDefenceQuota = {3,2,1},
index = 4,
energy = true,
},
[UnitDefNames['armsolar'].id] = {
energyGreaterThan = 0,
whileStall = true,
makeNearFactory = false,
energySpacing = 0,
chance = 0.6,
minEtoMratio = 0,
defenceQuota = {0.5,0.3,0.07},
defenceRange = 200,
airDefenceQuota = {0,0.3,0.1},
index = 2,
energy = true,
},
[UnitDefNames['armwin'].id] = {
energyGreaterThan = 0,
whileStall = true,
makeNearFactory = false,
energySpacing = 60,
chance = 1,
minEtoMratio = 0,
defenceQuota = {0.3,0.15,0.03},
defenceRange = 200,
airDefenceQuota = {0,0.2,0},
index = 2,
energy = true,
},
[UnitDefNames['cormex'].id] = {
defenceQuota = {1,0.4,0.15},
defenceRange = 100,
airDefenceQuota = {0,0,0},
index = 1,
energy = false,
}
},
defenceIdCount = 3,
airDefenceIdCount = 3,
defenceIds = {
[1] = {
count = 2,
[1] = {ID = UnitDefNames['corllt'].id, chance = 0.4},
[2] = {ID = UnitDefNames['corrl'].id, chance = 0.6},
},
[2] = {
count = 3,
[1] = {ID = UnitDefNames['armdeva'].id, chance = 0.4},
[2] = {ID = UnitDefNames['armartic'].id, chance = 0.3},
[3] = {ID = UnitDefNames['corgrav'].id, chance = 0.3},
},
[3] = {
count = 1,
[1] = {ID = UnitDefNames['corhlt'].id, chance = 1},
},
},
defenceByDefId = {
[UnitDefNames['corllt'].id] = {
level = 1,
index = 1,
},
[UnitDefNames['corrl'].id] = {
level = 1,
index = 2,
},
[UnitDefNames['armdeva'].id] = {
level = 2,
index = 1,
},
[UnitDefNames['armartic'].id] = {
level = 2,
index = 2,
},
[UnitDefNames['corgrav'].id] = {
level = 2,
index = 3,
},
[UnitDefNames['corhlt'].id] = {
level = 3,
index = 1,
},
},
airDefenceIds = {
[1] = {
count = 1,
[1] = {ID = UnitDefNames['corrl'].id, chance = 1},
},
[2] = {
count = 2,
[1] = {ID = UnitDefNames['corrazor'].id, chance = 0.7},
[2] = {ID = UnitDefNames['missiletower'].id, chance = 0.3},
},
[3] = {
count = 2,
[1] = {ID = UnitDefNames['armcir'].id, chance = 0.7},
[2] = {ID = UnitDefNames['corflak'].id, chance = 0.3},
},
},
airDefenceByDefId = {
[UnitDefNames['corrl'].id] = {
level = 1,
index = 1,
},
[UnitDefNames['corrazor'].id] = {
level = 2,
index = 1,
},
[UnitDefNames['missiletower'].id] = {
level = 2,
index = 2,
},
[UnitDefNames['armcir'].id] = {
level = 3,
index = 1,
},
[UnitDefNames['corflak'].id] = {
level = 3,
index = 2,
},
},
airpadDefID = UnitDefNames['armasp'].id,
nanoDefID = UnitDefNames['armnanotc'].id,
metalStoreDefID = UnitDefNames['armmstor'].id,
}
}
| gpl-2.0 |
Scavenge/darkstar | scripts/zones/Halvung/npcs/Mining_Point.lua | 17 | 1062 | -----------------------------------
-- Area: Halvung
-- NPC: Mining Point
-----------------------------------
package.loaded["scripts/zones/Halvung/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/mining");
require("scripts/zones/Halvung/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startMining(player,player:getZoneID(),npc,trade,0x00D2);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(MINING_IS_POSSIBLE_HERE,605);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
Scavenge/darkstar | scripts/globals/items/plate_of_crab_sushi_+1.lua | 12 | 1469 | -----------------------------------------
-- ID: 5722
-- Item: plate_of_crab_sushi_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Vitality 2
-- Defense 15
-- Accuracy % 14 (cap 68)
-- Resist Sleep +2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5722);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VIT, 2);
target:addMod(MOD_DEF, 15);
target:addMod(MOD_FOOD_ACCP, 14);
target:addMod(MOD_FOOD_ACC_CAP, 68);
target:addMod(MOD_SLEEPRES, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VIT, 2);
target:delMod(MOD_DEF, 15);
target:delMod(MOD_FOOD_ACCP, 14);
target:delMod(MOD_FOOD_ACC_CAP, 68);
target:delMod(MOD_SLEEPRES, 2);
end;
| gpl-3.0 |
smanolache/kong | spec/plugins/acl/api_spec.lua | 1 | 3339 | local json = require "cjson"
local http_client = require "kong.tools.http_client"
local spec_helper = require "spec.spec_helpers"
describe("ACLs API", function()
local BASE_URL, acl, consumer
setup(function()
spec_helper.prepare_db()
spec_helper.start_kong()
end)
teardown(function()
spec_helper.stop_kong()
end)
describe("/consumers/:consumer/acls/", function()
setup(function()
local fixtures = spec_helper.insert_fixtures {
consumer = {{ username = "bob" }}
}
consumer = fixtures.consumer[1]
BASE_URL = spec_helper.API_URL.."/consumers/bob/acls/"
end)
describe("POST", function()
it("[FAILURE] should not create an ACL association without a group name", function()
local response, status = http_client.post(BASE_URL, { })
assert.equal(400, status)
assert.equal("group is required", json.decode(response).group)
end)
it("[SUCCESS] should create an ACL association", function()
local response, status = http_client.post(BASE_URL, { group = "admin" })
assert.equal(201, status)
acl = json.decode(response)
assert.equal(consumer.id, acl.consumer_id)
assert.equal("admin", acl.group)
end)
end)
describe("PUT", function()
it("[SUCCESS] should create and update", function()
local response, status = http_client.put(BASE_URL, { group = "pro" })
assert.equal(201, status)
acl = json.decode(response)
assert.equal(consumer.id, acl.consumer_id)
assert.equal("pro", acl.group)
end)
end)
describe("GET", function()
it("should retrieve all", function()
local response, status = http_client.get(BASE_URL)
assert.equal(200, status)
local body = json.decode(response)
assert.equal(2, #(body.data))
end)
end)
end)
describe("/consumers/:consumer/acl/:id", function()
describe("GET", function()
it("should retrieve by id", function()
local response, status = http_client.get(BASE_URL..acl.id)
assert.equal(200, status)
local body = json.decode(response)
assert.equals(acl.id, body.id)
end)
end)
describe("PATCH", function()
it("[SUCCESS] should update an ACL association", function()
local response, status = http_client.patch(BASE_URL..acl.id, { group = "basic" })
assert.equal(200, status)
acl = json.decode(response)
assert.equal("basic", acl.group)
end)
it("[FAILURE] should return proper errors", function()
local response, status = http_client.patch(BASE_URL..acl.id, { group = "" })
assert.equal(400, status)
assert.equal('{"group":"group is not a string"}\n', response)
end)
end)
describe("DELETE", function()
it("[FAILURE] should return proper errors", function()
local _, status = http_client.delete(BASE_URL.."blah")
assert.equal(400, status)
_, status = http_client.delete(BASE_URL.."00000000-0000-0000-0000-000000000000")
assert.equal(404, status)
end)
it("[SUCCESS] should delete an ACL association", function()
local _, status = http_client.delete(BASE_URL..acl.id)
assert.equal(204, status)
end)
end)
end)
end)
| apache-2.0 |
Zero-K-Experiments/Zero-K-Experiments | LuaUI/Widgets/chili_new/controls/colorbars.lua | 18 | 2724 | --//=============================================================================
--- Colorbars module
--- Colorbar fields.
-- Inherits from Control.
-- @see control.Control
-- @table Colorbars
-- @tparam {r,g,b,a} color color table, (default {1,1,1,1})
-- @tparam {func1,func2,...} OnChange listener functions for color changes, (default {})
Colorbars = Control:Inherit{
classname = "colorbars",
color = {1,1,1,1},
defaultWidth = 100,
defaultHeight = 20,
OnChange = {},
}
local this = Colorbars
local inherited = this.inherited
--//=============================================================================
--- Sets the new color
-- @tparam {r,g,b,a} c color table
function Colorbars:SetColor(c)
self:CallListeners(self.OnChange,c)
self.value = c
self:Invalidate()
end
--//=============================================================================
local GL_LINE_LOOP = GL.LINE_LOOP
local GL_LINES = GL.LINES
local glPushMatrix = gl.PushMatrix
local glPopMatrix = gl.PopMatrix
local glTranslate = gl.Translate
local glVertex = gl.Vertex
local glRect = gl.Rect
local glColor = gl.Color
local glBeginEnd = gl.BeginEnd
function Colorbars:DrawControl()
local barswidth = self.width - (self.height + 4)
local color = self.color
local step = self.height/7
--bars
local rX1,rY1,rX2,rY2 = 0,0*step,color[1]*barswidth,1*step
local gX1,gY1,gX2,gY2 = 0,2*step,color[2]*barswidth,3*step
local bX1,bY1,bX2,bY2 = 0,4*step,color[3]*barswidth,5*step
local aX1,aY1,aX2,aY2 = 0,6*step,(color[4] or 1)*barswidth,7*step
glColor(1,0,0,1)
glRect(rX1,rY1,rX2,rY2)
glColor(0,1,0,1)
glRect(gX1,gY1,gX2,gY2)
glColor(0,0,1,1)
glRect(bX1,bY1,bX2,bY2)
glColor(1,1,1,1)
glRect(aX1,aY1,aX2,aY2)
glColor(self.color)
glRect(barswidth + 2,self.height,self.width - 2,0)
gl.BeginEnd(GL.TRIANGLE_STRIP, theme.DrawBorder_, barswidth + 2,0,self.width - barswidth - 4,self.height, 1, self.borderColor, self.borderColor2)
end
--//=============================================================================
function Colorbars:HitTest()
return self
end
function Colorbars:MouseDown(x,y)
local step = self.height/7
local yp = y/step
local r = yp%2
local barswidth = self.width - (self.height + 4)
if (x<=barswidth)and(r<=1) then
local barIdx = (yp-r)/2 + 1
local newvalue = x/barswidth
if (newvalue>1) then newvalue=1 elseif (newvalue<0) then newvalue=0 end
self.color[barIdx] = newvalue
self:SetColor(self.color)
return self
end
end
function Colorbars:MouseMove(x,y,dx,dy,button)
if (button==1) then
return self:MouseDown(x,y)
end
end
--//=============================================================================
| gpl-2.0 |
ArchonTeam/Soft_TG | plugins/time.lua | 8 | 2812 | -- Implement a command !time [area] which uses
-- 2 Google APIs to get the desired result:
-- 1. Geocoding to get from area to a lat/long pair
-- 2. Timezone to get the local time in that lat/long location
-- Globals
-- If you have a google api key for the geocoding/timezone api
api_key = nil
base_api = "https://maps.googleapis.com/maps/api"
dateFormat = "%A %d %B - %H:%M:%S"
-- Need the utc time for the google api
function utctime()
return os.time(os.date("!*t"))
end
-- Use the geocoding api to get the lattitude and longitude with accuracy specifier
-- CHECKME: this seems to work without a key??
function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Get the data
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
-- Use timezone api to get the time in the lat,
-- Note: this needs an API key
function get_time(lat,lng)
local api = base_api .. "/timezone/json?"
-- Get a timestamp (server time is relevant here)
local timestamp = utctime()
local parameters = "location=" ..
URL.escape(lat) .. "," ..
URL.escape(lng) ..
"×tamp="..URL.escape(timestamp)
if api_key ~=nil then
parameters = parameters .. "&key="..api_key
end
local res,code = https.request(api..parameters)
if code ~= 200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Construct what we want
-- The local time in the location is:
-- timestamp + rawOffset + dstOffset
local localTime = timestamp + data.rawOffset + data.dstOffset
return localTime, data.timeZoneId
end
return localTime
end
function getformattedLocalTime(area)
if area == nil then
return "The time in nowhere is never"
end
lat,lng,acc = get_latlong(area)
if lat == nil and lng == nil then
return 'In "'..area..'" they dont have time'
end
local localTime, timeZoneId = get_time(lat,lng)
return "Local: "..timeZoneId.."\nTime: ".. os.date(dateFormat,localTime)
end
function run(msg, matches)
return getformattedLocalTime(matches[1])
end
return {
description = "Get Time Give by Local Name",
usage = "/time (local) : view local time",
patterns = {
"^[!/]time (.*)$"
},
run = run
| gpl-2.0 |
OpenPrograms/mpmxyz-Programs | home/bin/tar.lua | 1 | 26799 | -----------------------------------------------------
--name : bin/tar.lua
--description: creating, viewing and extracting tar archives on disk and tape
--author : mpmxyz
--github page: https://github.com/mpmxyz/ocprograms
--forum page : http://oc.cil.li/index.php?/topic/421-tar-for-opencomputers/
-----------------------------------------------------
--[[
tar archiver for OpenComputers
for further information check the usage text or man page
TODO: detect symbolic link cycles (-> remember already visited, resolved paths)
]]
local shell = require 'shell'
local fs = require 'filesystem'
local component = require 'component'
local BLOCK_SIZE = 512
local NULL_BLOCK = ("\0"):rep(BLOCK_SIZE)
local WORKING_DIRECTORY = fs.canonical(shell.getWorkingDirectory()):gsub("/$","")
--load auto_progress library if possible
local auto_progress
if true then
local ok
ok, auto_progress = pcall(require, "mpm.auto_progress")
if not ok then
auto_progress = {}
function auto_progress.new()
--library not available, create stub
return {
update = function() end,
finish = function() end,
}
end
end
end
--error information
local USAGE_TEXT = [[
Usage:
tar <function letter> [other options] FILES...
function letter description
-c --create creates a new archive
-r --append appends to existing archive
-t --list lists contents from archive
-x --extract --get extracts from archive
other options description
-f --file FILE first FILE is archive, else:
uses primary tape drive
--address=ADDRESS uses tape drive ADDRESS
-h --dereference follows symlinks
--exclude=FILE;... excludes FILE from archive
-v --verbose lists processed files, also
shows progress for large files
]]
local function addUsage(text)
return text .. "\n" .. USAGE_TEXT
end
local ERRORS = {
missingAction = addUsage("Error: Missing function letter!"),
multipleActions = addUsage("Error: Multiple function letters!"),
missingFiles = addUsage("Error: Missing file names!"),
invalidChecksum = "Error: Invalid checksum!",
noHeaderName = "Error: No file name in header!",
invalidTarget = "Error: Invalid target!",
}
--formats numbers and stringvalues to comply to the tar format
local function formatValue(text, length, maxDigits)
if type(text) == "number" then
maxDigits = maxDigits or (length - 1) --that is default
text = ("%0"..maxDigits.."o"):format(text):sub(-maxDigits, -1)
elseif text == nil then
text = ""
end
return (text .. ("\0"):rep(length - #text)):sub(-length, -1)
end
--a utility to make accessing the header easier
--Only one header is accessed at a time: no need to throw tables around.
local header = {}
--loads a header, uses table.concat on tables, strings are taken directly
function header:init(block)
if type(block) == "table" then
--combine tokens to form one 512 byte long header
block = table.concat(block, "")
elseif block == nil then
--make this header a null header
block = NULL_BLOCK
end
if #block < BLOCK_SIZE then
--add "\0"s to reach 512 bytes
block = block .. ("\0"):rep(BLOCK_SIZE - #block)
end
--remember the current block
self.block = block
end
--takes the given data and creates a header from it
--the resulting block can be retrieved via header:getBytes()
function header:assemble(data)
if #data.name > 100 then
local longName = data.name
--split at slash
local minPrefixLength = #longName - 101 --(100x suffix + 1x slash)
local splittingSlashIndex = longName:find("/", minPrefixLength + 1, true)
if splittingSlashIndex then
--can split path in 2 parts separated by a slash
data.filePrefix = longName:sub(1, splittingSlashIndex - 1)
data.name = longName:sub(splittingSlashIndex + 1, -1)
else
--unable to split path; try to put path to the file prefix
data.filePrefix = longName
data.name = ""
end
--checking for maximum file prefix length
assert(#data.filePrefix <= 155, "File name '"..longName.."' is too long; unable to apply ustar splitting!")
--force ustar format
data.ustarIndicator = "ustar"
data.ustarVersion = "00"
end
local tokens = {
formatValue(data.name, 100), --1
formatValue(data.mode, 8), --2
formatValue(data.owner, 8), --3
formatValue(data.group, 8), --4
formatValue(data.size, 12), --5
formatValue(data.lastModified, 12), --6
" ",--8 spaces --7
formatValue(data.typeFlag, 1), --8
formatValue(data.linkName, 100), --9
}
--ustar extension?
if data.ustarIndicator then
table.insert(tokens, formatValue(data.ustarindicator, 6))
table.insert(tokens, formatValue(data.ustarversion, 2))
table.insert(tokens, formatValue(data.ownerUser, 32))
table.insert(tokens, formatValue(data.ownerGroup, 32))
table.insert(tokens, formatValue(data.deviceMajor, 8))
table.insert(tokens, formatValue(data.deviceMinor, 8))
table.insert(tokens, formatValue(data.filePrefix, 155))
end
--temporarily assemble header for checksum calculation
header:init(tokens)
--calculating checksum
tokens[7] = ("%06o\0\0"):format(header:checksum(0, BLOCK_SIZE))
--assemble final header
header:init(tokens)
end
--extracts the information from the given header
function header:read()
local data = {}
data.name = self:extract (0 , 100)
data.mode = self:extract (100, 8)
data.owner = self:extractNumber(108, 8)
data.group = self:extractNumber(116, 8)
data.size = self:extractNumber(124, 12)
data.lastModified = self:extractNumber(136, 12)
data.checksum = self:extractNumber(148, 8)
data.typeFlag = self:extract (156, 1) or "0"
data.linkName = self:extract (157, 100)
data.ustarIndicator = self:extract (257, 6)
--There is an old format using "ustar \0" instead of "ustar\0".."00"?
if data.ustarIndicator and data.ustarIndicator:sub(1,5) == "ustar" then
data.ustarVersion = self:extractNumber(263, 2)
data.ownerUser = self:extract (265, 32)
data.ownerGroup = self:extract (297, 32)
data.deviceMajor = self:extractNumber(329, 8)
data.deviceMinor = self:extractNumber(337, 8)
data.filePrefix = self:extract (345, 155)
end
assert(self:verify(data.checksum), ERRORS.invalidChecksum)
--assemble raw file name, normally relative to working dir
if data.filePrefix then
data.name = data.filePrefix .. "/" .. data.name
data.filePrefix = nil
end
assert(data.name, ERRORS.noHeaderName)
return data
end
--returns the whole 512 bytes of the header
function header:getBytes()
return header.block
end
--returns if the header is a null header
function header:isNull()
return self.block == NULL_BLOCK
end
--extracts a 0 terminated string from the given area
function header:extract(offset, size)
--extract size bytes from the given offset, strips every NULL character
--returns a string
return self.block:sub(1 + offset, size + offset):match("[^\0]+")
end
--extracts an octal number from the given area
function header:extractNumber(offset, size)
--extract size bytes from the given offset
--returns the first series of octal digits converted to a number
return tonumber(self.block:sub(1 + offset, size + offset):match("[0-7]+") or "", 8)
end
--calculates the checksum for the given area
function header:checksum(offset, size, signed)
--calculates the checksum of a given range
local sum = 0
--summarize byte for byte
for index = 1 + offset, size + offset do
if signed then
--interpretation of a signed byte: compatibility for bugged implementations
sum = sum + (self.block:byte(index) + 128) % 256 - 128
else
sum = sum + self.block:byte(index)
end
end
--modulo to take care of negative sums
--The whole reason for the signed addition is that some implementations
--used signed bytes instead of unsigned ones and therefore computed 'wrong' checksums.
return sum % 0x40000
end
--checks if the given checksum is valid for the loaded header
function header:verify(checksum)
local checkedSums = {
[self:checksum(0, 148, false) + 256 + self:checksum(156, 356, false)] = true,
[self:checksum(0, 148, true ) + 256 + self:checksum(156, 356, true )] = true,
}
return checkedSums[checksum] or false
end
local function makeRelative(path, reference)
--The path and the reference directory must have a common reference. (e.g. root)
--The default reference is the current working directory.
reference = reference or WORKING_DIRECTORY
--1st: split paths into segments
local returnDirectory = path:sub(-1,-1) == "/" --?
path = fs.segments(path)
reference = fs.segments(reference)
--2nd: remove common directories
while path[1] and reference[1] and path[1] == reference[1] do
table.remove(path, 1)
table.remove(reference, 1)
end
--3rd: add ".."s to leave that what's left of the working directory
local path = ("../"):rep(#reference) .. table.concat(path, "/")
--4th: If there is nothing remaining, we are at the current directory.
if path == "" then
path = "."
end
return path
end
local function tarFiles(files, options, mode, ignoredObjects, isDirectoryContent)
--combines files[2], files[3], ... into files[1]
--prepare output stream
local target, closeAtExit
if type(files[1]) == "string" then
--mode = append -> overwrite trailing NULL headers
local targetFile = shell.resolve(files[1]):gsub("/$","")
ignoredObjects[targetFile] = ignoredObjects[targetFile] or true
target = assert(io.open(targetFile, mode))
closeAtExit = true
else
target = files[1]
closeAtExit = false
assert(target.write, ERRORS.invalidTarget)
end
if mode == "rb+" then --append: not working with files because io.read does not support mode "rb+"
--start from beginning of file
assert(target:seek("set", 0))
--loop over every block
--This loop implies that it is okay if there is nothing (!) after the last file block.
--It also ensures that trailing null blocks are overwritten.
for block in target:lines(BLOCK_SIZE) do
if #block < BLOCK_SIZE then
--reached end of file before block was finished
error("Missing "..(BLOCK_SIZE-#block).." bytes to finish block.")
end
--load header
header:init(block)
if header:isNull() then
--go back to the beginning of the block
assert(target:seek("cur", -BLOCK_SIZE))
--found null header -> finished with skipping
break
end
--extract size information from header
local data = header.read(header)
if data.size and data.size > 0 then
--skip file content
local skippedBytes = math.ceil(data.size / BLOCK_SIZE) * BLOCK_SIZE
assert(target:seek("cur", skippedBytes))
end
end
if options.verbose then
print("End of archive detected; appending...")
end
end
for i = 2, #files do
--prepare data
--remove trailing slashes that might come from fs.list
local file = shell.resolve(files[i]):gsub("/$","")
--determine object type, that determines how the object is handled
local isALink, linkTarget = fs.isLink(file)
local objectType
if isALink and not options.dereference then
objectType = "link" --It's a symbolic link.
else
if fs.isDirectory(file) then
objectType = "dir" --It's a directory.
else
objectType = "file" --It's a normal file.
end
end
--add directory contents before the directory
--(It makes sense if you consider that you could change the directories file permissions to be read only.)
if objectType == "dir" and ignoredObjects[file] ~= "strict" then
local list = {target}
local i = 2
for containedFile in fs.list(file) do
list[i] = fs.concat(file, containedFile)
i = i + 1
end
tarFiles(list, options, nil, ignoredObjects, true)
end
--Ignored objects are not added to the tar.
if not ignoredObjects[file] then
local data = {}
--get relative path to current directory
data.name = makeRelative(file)
--add object specific data
if objectType == "link" then
--It's a symbolic link.
data.typeFlag = "2"
data.linkName = makeRelative(linkTarget, fs.path(file)):gsub("/$","") --force relative links
else
data.lastModified = math.floor(fs.lastModified(file) / 1000) --Java returns milliseconds...
if objectType == "dir" then
--It's a directory.
data.typeFlag = "5"
data.mode = 448 --> 700 in octal -> rwx------
elseif objectType == "file" then
--It's a normal file.
data.typeFlag = "0"
data.size = fs.size(file)
data.mode = 384 --> 600 in octal -> rw-------
end
end
--tell user what is going on
if options.verbose then
print("Adding:", data.name)
end
--assemble header
header:assemble(data)
--write header
assert(target:write(header:getBytes()))
--copy file contents
if objectType == "file" then
--open source file
local source = assert(io.open(file, "rb"))
--keep track of what has to be copied
local bytesToCopy = data.size
--init progress bar
local progressBar = auto_progress.new(bytesToCopy)
--copy file contents
for block in source:lines(BLOCK_SIZE) do
assert(target:write(block))
bytesToCopy = bytesToCopy - #block
assert(bytesToCopy >= 0, "Error: File grew while copying! Is it the output file?")
if options.verbose then
--update progress bar
progressBar.update(#block)
end
if #block < BLOCK_SIZE then
assert(target:write(("\0"):rep(BLOCK_SIZE - #block)))
break
end
end
--close source file
source:close()
if options.verbose then
--draw full progress bar
progressBar.finish()
end
assert(bytesToCopy <= 0, "Error: Could not copy file!")
end
end
end
if not isDirectoryContent then
assert(target:write(NULL_BLOCK)) --Why wasting 0.5 KiB if you can waste a full KiB? xD
assert(target:write(NULL_BLOCK)) --(But that's the standard!)
end
if closeAtExit then
target:close()
end
end
local extractingExtractors = {
["0"] = function(data, options) --file
--creates a file at data.file and fills it with data.size bytes
--ensure that the directory is existing
local dir = fs.path(data.file)
if not fs.exists(dir) then
fs.makeDirectory(dir)
end
--don't overwrite the file if true
local skip = false
--check for existing file
if fs.exists(data.file) then
if options.verbose then
print("File already exists!")
end
--check for options specifying what to do now...
if options["keep-old-files"] then
error("Error: Attempting to overwrite: '"..data.file.."'!")
elseif options["skip-old-files"] then
--don't overwrite
skip = true
elseif options["keep-newer-files"] and data.lastModified then
--don't overwrite when file on storage is newer
local lastModifiedOnDrive = math.floor(fs.lastModified(data.file) / 1000)
if lastModifiedOnDrive > data.lastModified then
skip = true
end
else
--default: overwrite
end
if options.verbose and not skip then
--verbose: tell user that we are overwriting
print("Overwriting...")
end
end
if skip then
--go to next header
return data.size
end
--open target file
local target = assert(io.open(data.file, "wb"))
--set file length
local bytesToCopy = data.size
--init progress bar
local progressBar = auto_progress.new(bytesToCopy)
--create extractor function, writes min(bytesToCopy, #block) bytes to target
local function extractor(block)
--shortcut for abortion
if block == nil then
target:close()
return nil
end
--adjust block size to missing number of bytes
if #block > bytesToCopy then
block = block:sub(1, bytesToCopy)
end
--write up to BLOCK_SIZE bytes
assert(target:write(block))
--subtract copied amount of bytes from bytesToCopy
bytesToCopy = bytesToCopy - #block
if bytesToCopy <= 0 then
--close target stream when done
target:close()
if options.verbose then
--draw full progress bar
progressBar.finish()
end
--return nil to finish
return nil
else
if options.verbose then
--update progress bar
progressBar.update(#block)
end
--continue
return extractor
end
end
if bytesToCopy > 0 then
return extractor
else
target:close()
end
end,
["2"] = function(data, options) --symlink
--ensure that the directory is existing
local dir = fs.path(data.file)
if not fs.exists(dir) then
fs.makeDirectory(dir)
end
--check for existing file
if fs.exists(data.file) then
if options.verbose then
print("File already exists!")
end
if options["keep-old-files"] then
error("Error: Attempting to overwrite: '"..data.file.."'!")
elseif options["skip-old-files"] then
return
elseif options["keep-newer-files"] and data.lastModified then
--don't overwrite when file on storage is newer
local lastModifiedOnDrive = math.floor(fs.lastModified(data.file) / 1000)
if lastModifiedOnDrive > data.lastModified then
return
end
else
--default: overwrite file
end
--delete original file
if options.verbose then
print("Overwriting...")
end
assert(fs.remove(data.file))
end
assert(fs.link(data.linkName, data.file))
end,
["5"] = function(data, options) --directory
if not fs.isDirectory(data.file) then
assert(fs.makeDirectory(data.file))
end
end,
}
local listingExtractors = {
["0"] = function(data, options) --file
--output info
print("File:", data.name)
print("Size:", data.size)
--go to next header
return data.size
end,
["1"] = function(data, options) --hard link: unsupported, but reported
print("Hard link (unsupported):", data.name)
print("Target:", data.linkName)
end,
["2"] = function(data, options) --symlink
print("Symbolic link:", data.name)
print("Target:", data.linkName)
end,
["3"] = function(data, options) --device file: unsupported, but reported
print("Device File (unsupported):", data.name)
end,
["4"] = function(data, options) --device file: unsupported, but reported
print("Device File (unsupported):", data.name)
end,
["5"] = function(data, options) --directory
print("Directory:", data.name)
end,
}
local function untarFiles(files, options, extractorList)
--extracts the contents of every tar file given
for _,file in ipairs(files) do
--prepare input stream
local source, closeAtExit
if type(file) == "string" then
source = assert(io.open(shell.resolve(file), "rb"))
closeAtExit = true
else
source = file
closeAtExit = false
assert(source.lines, "Unknown source type.")
end
local extractor = nil
local hasDoubleNull = false
for block in source:lines(BLOCK_SIZE) do
if #block < BLOCK_SIZE then
error("Error: Unfinished Block; missing "..(BLOCK_SIZE-#block).." bytes!")
end
if extractor == nil then
--load header
header:init(block)
if header:isNull() then
--check for second null block
if source:read(BLOCK_SIZE) == NULL_BLOCK then
hasDoubleNull = true
end
--exit/close file when there is a NULL header
break
else
--read block as header
local data = header:read()
if options.verbose then
--tell user what is going on
print("Extracting:", data.name)
end
--enforcing relative paths
data.file = shell.resolve(WORKING_DIRECTORY.."/"..data.name)
--get extractor
local extractorInit = extractorList[data.typeFlag]
assert(extractorInit, "Unknown type flag \""..tostring(data.typeFlag).."\"")
extractor = extractorInit(data, options)
end
else
extractor = extractor(block)
end
if type(extractor) == "number" then
if extractor > 0 then
--adjust extractorInit to block size
local bytesToSkip = math.ceil(extractor / BLOCK_SIZE) * BLOCK_SIZE
--skip (extractorInit) bytes
assert(source:seek("cur", bytesToSkip))
end
--expect next header
extractor = nil
end
end
assert(extractor == nil, "Error: Reached end of file but expecting more data!")
if closeAtExit then
source:close()
end
if not hasDoubleNull then
print("Warning: Archive does not end with two Null blocks!")
end
end
end
--connect function parameters with actions
local actions = {
c = function(files, options, ignoredObjects) --create
tarFiles(files, options, "wb", ignoredObjects)
end,
r = function(files, options, ignoredObjects) --append
tarFiles(files, options, "rb+", ignoredObjects)
end,
x = function(files, options, ignoredObjects) --extract
untarFiles(files, options, extractingExtractors)
end,
t = function(files, options, ignoredObjects) --list
untarFiles(files, options, listingExtractors)
end,
}
--also add some aliases
actions["create"] = actions.c
actions["append"] = actions.r
actions["list"] = actions.t
actions["extract"] = actions.x
actions["get"] = actions.x
local debugEnabled = false
local function main(...)
--variables containing the processed arguments
local action, files
--prepare arguments
local params, options = shell.parse(...)
--add stacktrace to output
debugEnabled = options.debug
--quick help
if options.help then
print(USAGE_TEXT)
return
end
--determine executed function and options
for option, value in pairs(options) do
local isAction = actions[option]
if isAction then
assert(action == nil, ERRORS.multipleActions)
action = isAction
options[option] = nil
end
end
assert(action ~= nil, ERRORS.missingAction)
--prepare file names
files = params
--process options
if options.v then
options.verbose = true
end
if options.dir then
assert(options.dir ~= true and options.dir ~= "", "Error: Invalid --dir value!")
WORKING_DIRECTORY = shell.resolve(options.dir) or options.dir
assert(WORKING_DIRECTORY ~= nil and WORKING_DIRECTORY ~= "", "Error: Invalid --dir value!")
end
if options.f or options.file then
--use file for archiving
--keep file names as they are
else
--use tape
local tapeFile = {drive = component.tape_drive, pos = 0}
if type(options.address) == "string" then
tapeFile.drive = component.proxy(assert(component.get(options.address, "tape_drive")))
end
assert(tapeFile.drive, "Error: No tape drive found!")
assert(tapeFile.drive.type == "tape_drive", "Error: Address does not point to tape drive!")
do
--check for Computronics bug
local endInversionBug = false
--step 1: move to the end of the tape
local movedBy = assert(tapeFile.drive.seek(tapeFile.drive.getSize()))
--step 2: check output of isEnd
if tapeFile.drive.isEnd() ~= true then
endInversionBug = true
end
--step 3: restore previous position
assert(tapeFile.drive.seek(-movedBy) == -movedBy, "Error: Tape did not return to original position after checking for isEnd bug!")
if endInversionBug then
if options.verbose then
print("tape_drive.isEnd() bug detected; adjusting...")
end
function tapeFile:isEnd()
--This is a workaround for bugged versions of Computronics.
return (not self.drive.isEnd()) or (not self.drive.isReady())
end
else
function tapeFile:isEnd()
--This does not work in bugged versions of Computronics.
return self.drive.isEnd()
end
end
end
--create some kind of "tape stream" with limited buf sufficient functionality
function tapeFile:lines(byteCount)
return function()
return self:read(byteCount)
end
end
function tapeFile:read(byteCount)
if self:isEnd() then
return nil
end
local data = self.drive.read(byteCount)
self.pos = self.pos + #data
return data
end
function tapeFile:write(text)
self.drive.write(text)
self.pos = self.pos + #text
if self:isEnd() then
return nil, "Error: Reached end of tape!"
else
return self
end
end
function tapeFile:seek(typ, pos)
local toSeek
if typ == "set" then
toSeek = pos - self.pos
elseif typ == "cur" then
toSeek = pos
end
local movedBy = 0
if toSeek ~= 0 then
movedBy = self.drive.seek(toSeek)
self.pos = self.pos + movedBy
end
if movedBy == toSeek then
return self.pos
else
return nil, "Error: Unable to seek!"
end
end
--add tape before first file
table.insert(files, 1, tapeFile)
end
if options.h then
options.dereference = true
end
--prepare list of ignored objects, default is the current directory and the target file if applicable
local ignoredObjects = {}
ignoredObjects[WORKING_DIRECTORY] = true
if options.exclude then
--";" is used as a separator
for excluded in options.exclude:gmatch("[^%;]+") do
ignoredObjects[shell.resolve(excluded) or excluded] = "strict"
end
end
assert(#files > 0, ERRORS.missingFiles)
--And action!
action(files, options, ignoredObjects)
end
--adding stack trace when --debug is used
local function errorFormatter(msg)
msg = msg:gsub("^[^%:]+%:[^%:]+%: ","")
if debugEnabled then
--add traceback when debugging
return debug.traceback(msg, 3)
end
return msg
end
local ok, msg = xpcall(main, errorFormatter, ...)
if not ok then
io.stdout:write(msg)
end
| mit |
kasicass/gearx | bin/lua/scheduler.lua | 1 | 1336 | -- emacs: -*- mode: lua; coding: utf-8; -*-
--[[
Copyright (C) 2007 GearX Team
This source code is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This source code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
$Id$
ChenZaichun@gmail.com
--]]
-------------------------------------------------------------------------------
Scheduler = {}
function Scheduler:AddTask (name, task)
self._tasks[name] = coroutine.create(task)
end
function Scheduler:Loop ()
repeat
for name, co in pairs(self._tasks) do
coroutine.resume(co)
if (coroutine.status(co) == "dead") then
self._tasks[name] = nil
end
end
until not next(self.tasks)
end
| lgpl-2.1 |
Scavenge/darkstar | scripts/globals/abilities/no_foot_rise.lua | 30 | 2052 | -----------------------------------
-- Ability: No Foot Rise
-- Instantly grants additional Finishing Moves.
-- Obtained: Dancer Level 75 Merit Group 2
-- Recast Time: 3 minutes
-- Duration: Instant
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then
return 561,0;
else
return 0,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local moves = player:getMerit(MERIT_NO_FOOT_RISE);
if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then
if (moves > 4) then
moves = 4;
end
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_1);
player:addStatusEffect(EFFECT_FINISHING_MOVE_1 + moves,1,0,7200);
return moves+1;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then
if (moves > 3) then
moves = 3;
end
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_2);
player:addStatusEffect(EFFECT_FINISHING_MOVE_2 + moves,1,0,7200);
return moves + 2;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then
if (moves > 2) then
moves = 2;
end
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_3);
player:addStatusEffect(EFFECT_FINISHING_MOVE_3 + moves,1,0,7200);
return moves + 3;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then
if (moves > 1) then
moves = 1;
end
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_4);
player:addStatusEffect(EFFECT_FINISHING_MOVE_4 + moves,1,0,7200);
return moves + 4;
else
player:addStatusEffect(EFFECT_FINISHING_MOVE_1 + moves - 1,1,0,7200);
return moves;
end
end; | gpl-3.0 |
kankaristo/premake-core | tests/actions/vstudio/cs2005/projectsettings.lua | 4 | 5543 | --
-- tests/actions/vstudio/cs2005/projectsettings.lua
-- Validate generation of root <PropertyGroup/> in Visual Studio 2005+ .csproj
-- Copyright (c) 2009-2015 Jason Perkins and the Premake project
--
local suite = test.declare("vstudio_cs2005_projectsettings")
local cs2005 = premake.vstudio.cs2005
--
-- Setup
--
local wks, prj
function suite.setup()
_ACTION = "vs2005"
wks = test.createWorkspace()
language "C#"
uuid "AE61726D-187C-E440-BD07-2556188A6565"
end
local function prepare()
prj = test.getproject(wks, 1)
cs2005.projectProperties(prj)
end
--
-- Version Tests
--
function suite.OnVs2005()
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
</PropertyGroup>
]]
end
function suite.OnVs2008()
_ACTION = "vs2008"
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
</PropertyGroup>
]]
end
function suite.OnVs2010()
_ACTION = "vs2010"
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
]]
end
function suite.onVs2012()
_ACTION = "vs2012"
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
]]
end
--
-- Framework Tests
--
function suite.OnFrameworkVersion()
framework "3.0"
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
<TargetFrameworkVersion>v3.0</TargetFrameworkVersion>
</PropertyGroup>
]]
end
--
-- Make sure the root namespace can be overridden.
--
function suite.canOverrideRootNamespace()
namespace "MyCompany.%{prj.name}"
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyCompany.MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
</PropertyGroup>
]]
end
--
-- WPF adds an additional element.
--
function suite.projectTypeGuids_onWPF()
_ACTION = "vs2010"
flags { "WPF" }
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</PropertyGroup>
]]
end
| bsd-3-clause |
Scavenge/darkstar | scripts/zones/Hall_of_Transference/npcs/_0e7.lua | 14 | 1356 | -----------------------------------
-- Area: Hall of Transference
-- NPC: Large Apparatus (Left) - Mea
-- @pos 269 -81 -39 14
-----------------------------------
package.loaded["scripts/zones/Hall_of_Transference/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Hall_of_Transference/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 1) then
player:startEvent(0x00A0);
else
player:messageSpecial(NO_RESPONSE_OFFSET);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00A0) then
player:setPos(-93.268, 0, 170.749, 162, 20); -- To Promyvion Mea {R}
end
end; | gpl-3.0 |
Scavenge/darkstar | scripts/zones/AlTaieu/npcs/qm2.lua | 18 | 1499 | -----------------------------------
-- Area: Al'Taieu
-- NPC: ??? (Jailer of Justice Spawn)
-- Allows players to spawn the Jailer of Justice by trading the Second Virtue, Deed of Moderation, and HQ Xzomit Organ to a ???.
-- @pos , -278 0 -463
-----------------------------------
package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/AlTaieu/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--[[
-- Trade the Second Virtue, Deed of Moderation, and HQ Xzomit Organ
if (GetMobAction(16912839) == 0 and trade:hasItemQty(1853,1) and trade:hasItemQty(1854,1) and trade:hasItemQty(1785,1) and
trade:getItemCount() == 3) then
player:tradeComplete();
SpawnMob(16912839):updateClaim(player); -- Spawn Jailer of Justice
end
]]
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
end;
| gpl-3.0 |
Scavenge/darkstar | scripts/zones/Lower_Jeuno/npcs/Chimh_Dlesbah.lua | 14 | 1055 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Chimh Dlesbah
-- Type: Event Scene Replayer
-- @zone 245
-- @pos -71.995 -1 -115.882
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x2770);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.