content
stringlengths 5
1.05M
|
---|
---@class ContributionCollector
C_ContributionCollector = {}
function C_ContributionCollector:Close() end
---@param contributionID number
function C_ContributionCollector:Contribute(contributionID) end
---@return number contributionID
function C_ContributionCollector:GetActive() end
---@param contributionID number
---@return string atlasName
function C_ContributionCollector:GetAtlases(contributionID) end
---@param contributionID number
---@return number spellID
function C_ContributionCollector:GetBuffs(contributionID) end
---@param contributionID number
---@param contributionState ContributionState
---@return ContributionAppearance|nil appearance
function C_ContributionCollector:GetContributionAppearance(contributionID, contributionState) end
---@param uiMapID number
---@return ContributionMapInfo contributionCollectors
function C_ContributionCollector:GetContributionCollectorsForMap(uiMapID) end
---@param contributionID number
---@return ContributionResult result
function C_ContributionCollector:GetContributionResult(contributionID) end
---@param contributionID number
---@return string description
function C_ContributionCollector:GetDescription(contributionID) end
---@param creatureID number
---@return number contributionID
function C_ContributionCollector:GetManagedContributionsForCreatureID(creatureID) end
---@param contributionID number
---@return string name
function C_ContributionCollector:GetName(contributionID) end
---@param contributionID number
---@return number orderIndex
function C_ContributionCollector:GetOrderIndex(contributionID) end
---@param contributionID number
---@return number, number currencyID, currencyAmount
function C_ContributionCollector:GetRequiredContributionCurrency(contributionID) end
---@param contributionID number
---@return number, number itemID, itemCount
function C_ContributionCollector:GetRequiredContributionItem(contributionID) end
---@param contributionID number
---@return number questID
function C_ContributionCollector:GetRewardQuestID(contributionID) end
---@param contributionID number
---@return ContributionState, number, number|nil, number contributionState, contributionPercentageComplete, timeOfNextStateChange, startTime
function C_ContributionCollector:GetState(contributionID) end
---@param contributionID number
---@return bool hasPending
function C_ContributionCollector:HasPendingContribution(contributionID) end
---@param contributionID number
---@return bool awaitingData
function C_ContributionCollector:IsAwaitingRewardQuestData(contributionID) end
---@class ContributionState
local ContributionState = {}
ContributionState.None = 0
ContributionState.Building = 1
ContributionState.Active = 2
ContributionState.UnderAttack = 3
ContributionState.Destroyed = 4
---@class ContributionAppearanceFlags
local ContributionAppearanceFlags = {}
ContributionAppearanceFlags.TooltipUseTimeRemaining = 0
---@class ContributionResult
local ContributionResult = {}
ContributionResult.Success = 0
ContributionResult.MustBeNearNpc = 1
ContributionResult.IncorrectState = 2
ContributionResult.InvalidID = 3
ContributionResult.QuestDataMissing = 4
ContributionResult.FailedConditionCheck = 5
ContributionResult.UnableToCompleteTurnIn = 6
ContributionResult.InternalError = 7
---@class ContributionAppearance
---@field stateName string
---@field stateColor table
---@field tooltipLine string
---@field tooltipUseTimeRemaining bool
---@field statusBarAtlas string
---@field borderAtlas string
---@field bannerAtlas string
local ContributionAppearance = {}
---@class ContributionMapInfo
---@field areaPoiID number
---@field position table
---@field name string
---@field atlasName string
---@field collectorCreatureID number
local ContributionMapInfo = {}
|
local Obj = {}
Obj.__index = Obj
setmetatable(Obj, {__call = function (cls, ...) return cls.New(...) end })
function Obj.New(ttsObject)
print("hi")
local self = setmetatable({}, Obj)
if type(ttsObject) == "string" then ttsObject = getObjectFromGUID(ttsObject) end
self.ttsObj = ttsObject
return self
end
function Obj:PrintData()
print(self.ttsObj)
end
function Obj:DoStuff()
print("object does doStuff!!")
end
return Obj
|
require'nvim-treesitter.configs'.setup({})
|
require("__5dim_core__.lib.energy.generation-accumulator")
local speed = 5
local modules = 2
local energy = 300
local emisions = 10
local techCount = 450
-- Electric furnace 01
genAccumulators {
number = "01",
subgroup = "energy-accumulator",
craftingSpeed = speed,
moduleSlots = modules,
energyUsage = energy,
new = false,
order = "a",
ingredients = {
{"iron-plate", 2},
{"battery", 5}
},
pollution = emisions,
nextUpdate = "5d-accumulator-02",
tech = nil
}
speed = speed + 2.5
modules = modules + 1
energy = energy + 150
emisions = emisions + 5
-- Electric furnace 02
genAccumulators {
number = "02",
subgroup = "energy-accumulator",
craftingSpeed = speed,
moduleSlots = modules,
energyUsage = energy,
new = true,
order = "b",
ingredients = {
{"accumulator", 1},
{"electronic-circuit", 2},
{"iron-plate", 2},
{"battery", 5}
},
pollution = emisions,
nextUpdate = "5d-accumulator-03",
tech = {
number = 2,
count = techCount * 1,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1}
},
prerequisites = {
"electric-energy-accumulators"
}
}
}
speed = speed + 2.5
energy = energy + 150
emisions = emisions + 5
-- Electric furnace 03
genAccumulators {
number = "03",
subgroup = "energy-accumulator",
craftingSpeed = speed,
moduleSlots = modules + 1,
energyUsage = energy,
new = true,
order = "c",
ingredients = {
{"5d-accumulator-02", 1},
{"electronic-circuit", 7},
{"iron-plate", 4},
{"battery", 10}
},
pollution = emisions,
nextUpdate = "5d-accumulator-04",
tech = {
number = 3,
count = techCount * 2,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1}
},
prerequisites = {
"electric-energy-accumulators-2",
"chemical-science-pack"
}
}
}
speed = speed + 2.5
modules = modules + 1
energy = energy + 150
emisions = emisions + 5
-- Electric furnace 04
genAccumulators {
number = "04",
subgroup = "energy-accumulator",
craftingSpeed = speed,
moduleSlots = modules,
energyUsage = energy,
new = true,
order = "d",
ingredients = {
{"5d-accumulator-03", 1},
{"advanced-circuit", 7},
{"steel-plate", 7},
{"battery", 15}
},
pollution = emisions,
nextUpdate = "5d-accumulator-05",
tech = {
number = 4,
count = techCount * 3,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1}
},
prerequisites = {
"electric-energy-accumulators-3",
"production-science-pack"
}
}
}
speed = speed + 2.5
energy = energy + 150
emisions = emisions + 5
-- Electric furnace 05
genAccumulators {
number = "05",
subgroup = "energy-accumulator",
craftingSpeed = speed,
moduleSlots = modules + 1,
energyUsage = energy,
new = true,
order = "e",
ingredients = {
{"5d-accumulator-04", 1},
{"advanced-circuit", 2},
{"steel-plate", 2},
{"battery", 15},
{"effectivity-module", 1}
},
pollution = emisions,
nextUpdate = "5d-accumulator-06",
tech = {
number = 5,
count = techCount * 4,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1}
},
prerequisites = {
"electric-energy-accumulators-4",
"production-science-pack"
}
}
}
speed = speed + 2.5
modules = modules + 1
energy = energy + 150
emisions = emisions + 5
-- Electric furnace 06
genAccumulators {
number = "06",
subgroup = "energy-accumulator",
craftingSpeed = speed,
moduleSlots = modules,
energyUsage = energy,
new = true,
order = "f",
ingredients = {
{"5d-accumulator-05", 1},
{"advanced-circuit", 2},
{"steel-plate", 2},
{"battery", 15},
{"effectivity-module", 1}
},
pollution = emisions,
nextUpdate = "5d-accumulator-07",
tech = {
number = 6,
count = techCount * 5,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1}
},
prerequisites = {
"electric-energy-accumulators-5"
}
}
}
speed = speed + 2.5
energy = energy + 150
emisions = emisions + 5
-- Electric furnace 07
genAccumulators {
number = "07",
subgroup = "energy-accumulator",
craftingSpeed = speed,
moduleSlots = modules + 1,
energyUsage = energy,
new = true,
order = "g",
ingredients = {
{"5d-accumulator-06", 1},
{"advanced-circuit", 2},
{"steel-plate", 2},
{"battery", 15},
{"effectivity-module-2", 1}
},
pollution = emisions,
nextUpdate = "5d-accumulator-08",
tech = {
number = 7,
count = techCount * 6,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1}
},
prerequisites = {
"electric-energy-accumulators-6",
"utility-science-pack"
}
}
}
speed = speed + 2.5
modules = modules + 1
energy = energy + 150
emisions = emisions + 5
-- Electric furnace 08
genAccumulators {
number = "08",
subgroup = "energy-accumulator",
craftingSpeed = speed,
moduleSlots = modules,
energyUsage = energy,
new = true,
order = "h",
ingredients = {
{"5d-accumulator-07", 1},
{"processing-unit", 2},
{"steel-plate", 2},
{"battery", 15},
{"effectivity-module-2", 1}
},
pollution = emisions,
nextUpdate = "5d-accumulator-09",
tech = {
number = 8,
count = techCount * 7,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1}
},
prerequisites = {
"electric-energy-accumulators-7"
}
}
}
speed = speed + 2.5
energy = energy + 150
emisions = emisions + 5
-- Electric furnace 09
genAccumulators {
number = "09",
subgroup = "energy-accumulator",
craftingSpeed = speed,
moduleSlots = modules + 1,
energyUsage = energy,
new = true,
order = "i",
ingredients = {
{"5d-accumulator-08", 1},
{"processing-unit", 2},
{"low-density-structure", 1},
{"battery", 15},
{"effectivity-module-3", 1}
},
pollution = emisions,
nextUpdate = "5d-accumulator-10",
tech = {
number = 9,
count = techCount * 8,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1}
},
prerequisites = {
"electric-energy-accumulators-8"
}
}
}
speed = speed + 2.5
modules = modules + 1
energy = energy + 150
emisions = emisions + 5
-- Electric furnace 10
genAccumulators {
number = "10",
subgroup = "energy-accumulator",
craftingSpeed = speed,
moduleSlots = modules + 1,
energyUsage = energy,
new = true,
order = "j",
ingredients = {
{"5d-accumulator-09", 1},
{"processing-unit", 2},
{"low-density-structure", 1},
{"battery", 15},
{"effectivity-module-3", 1}
},
pollution = emisions,
tech = {
number = 10,
count = techCount * 9,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1}
},
prerequisites = {
"electric-energy-accumulators-9"
}
}
}
|
-----------------------------------
-- Area: Xarcabard
-- Mob: Lost Soul
-- Note: PH for Timeworn Warrior
-----------------------------------
local ID = require("scripts/zones/Xarcabard/IDs")
require("scripts/globals/regimes")
require("scripts/globals/mobs")
-----------------------------------
function onMobDeath(mob, player, isKiller)
tpz.regime.checkRegime(player, mob, 51, 1, tpz.regime.type.FIELDS)
tpz.regime.checkRegime(player, mob, 52, 1, tpz.regime.type.FIELDS)
tpz.regime.checkRegime(player, mob, 53, 2, tpz.regime.type.FIELDS)
tpz.regime.checkRegime(player, mob, 54, 3, tpz.regime.type.FIELDS)
end
function onMobDespawn(mob)
tpz.mob.phOnDespawn(mob, ID.mob.TIMEWORN_WARRIOR_PH, 5, 5400) -- 90 minutes
end
|
-- https://github.com/jgm/pandoc/issues/2106#issuecomment-371355862
function Span(el)
if el.classes:includes("todo") then
return {
pandoc.RawInline("latex", "\\textcolor{red}{\\textbf{TODO: }"),
el,
pandoc.RawInline("latex", "}")
}
end
end
|
function PS_EnemyAttack(toplayer, toptag, index, etype, elayer)
local atk, apatk, hpregainatk = game.GetEnemyATK(etype, elayer/CCZ_eLayer_01);
local hp, ap, sp = game.GetHPAPSP();
hp = hp - atk;
ap = ap - apatk;
if hp < 0 then
hp = 0;
end
if ap < 0 then
ap = 0;
end
game.SetHPAPSP(hp, ap, sp);
if hpregainatk > 0 then
-- Add Enemy HP
end
-- Animation
if atk > 0 then
LGlobal_PlayScene_RunShakeAction(toplayer, 0, 0);
end
end
function PS_EnemyAdvanceELayer(toplayer, toptag, index, etype, elayer)
local elayeradvance = game.GetEnemyELayerAdvance(etype);
if elayer == CCZ_eLayer_03 or elayeradvance == 0 then
return;
end
elayer = elayer + elayeradvance;
if elayer > CCZ_eLayer_03 then
elayer = CCZ_eLayer_03;
end
local itemtag, x, y, etype, life = game.GetActiveEnemyData(index, ENEMY_InScene);
local enemynode = game.GetNode({toplayer, itemtag});
local ttoptag, tsublayertag, tmenugrouptag, tmenuitemtag = game.GetSubTags(itemtag);
local menugroup = itemtag-tmenuitemtag;
game.SetZ(enemynode, menugroup+elayer);
game.SetActiveEnemyData(index, ENEMY_InScene, life, elayer);
local tx, ty, scale = game.GetEnemyXYScale(index);
local aemoveaction = game.ActionMove(CCAF_To, tx, ty, LConst_EnemySpriteFadeTime);
local aescaleaction = game.ActionScale(CCAF_To, scale, scale, LConst_EnemySpriteFadeTime, true);
local aeaction = game.ActionSpawn({aemoveaction, aescaleaction});
game.RunAction(enemynode, aeaction);
end
function PS_DoEnemyAction(toplayer, toptag, index, nowstage, nowmission, nowturn, bZeroLayerOnly)
local enemyinscenecount = game.GetActiveEnemyData();
if index >= enemyinscenecount then
return true;
end
local doaction = true;
local doadvance = true;
local layertag = toptag + CCPSTL_Enemy;
local itemtag, x, y, etype, life, elayer = game.GetActiveEnemyData(index, ENEMY_InScene);
game.SetActiveEnemyData(index, ENEMY_InScene, life, elayer, 0, 0, ENEMYSTATUS_Clear+ENEMYSTATUS_Blowed);
local atk, apatk, hpregainatk = game.GetEnemyATK(etype, 0);
if bZeroLayerOnly ~= nil and bZeroLayerOnly then
doadvance = false;
if atk == 0 and apatk == 0 and hpregainatk == 0 then
doaction = false;
end
else
if atk ~= 0 or apatk ~= 0 or hpregainatk ~= 0 then
doaction = false;
end
end
if doaction then
PS_EnemyAttack(toplayer, toptag, index, etype, elayer);
end
if doadvance then
PS_EnemyAdvanceELayer(toplayer, toptag, index, etype, elayer);
end
local enemynode = game.GetNode({toplayer, itemtag});
local delaytime = LConst_EnemyEnterDelayTime;
local state = STATE_EnemyAction;
if not doaction then
delaytime = 0;
end
if bZeroLayerOnly then
state = STATE_SpecialEnemyAction;
end
local dataindex = LGlobal_SaveData(state);
local callfuncaction = game.ActionCallFunc({toplayer, toptag}, delaytime, dataindex);
local callnodeitemtag = LGlobal_PlayScene_GetEnemyCallNodeItemtag(itemtag);
local callnode = game.AddNullChild({toplayer, itemtag}, {0, 0, 0, callnodeitemtag});
game.RunAction(callnode, callfuncaction);
return false;
end
function PS_EnemyAction(toplayer, toptag, index)
-- Check all enemy action done
local nowstage, nowmission, nowturn = game.GetNowStageMissionTurn();
if PS_DoEnemyAction(toplayer, toptag, index, nowstage, nowmission, nowturn) then
return true;
end
return false;
end |
------------
-- Classic Lua 5.1 module.
-- Description here
----
module 'two'
--- answer to everything.
function answer ()
return 42
end
|
local Native = require('lib.stdlib.native')
---@class Dialog : Agent
local Dialog = class('Dialog', require('lib.stdlib.oop.agent'))
---destructor
---@return void
function Dialog:destructor()
--@debug@
checkobject(self, Dialog, 'destructor', 'self')
--@end-debug@
return Native.DialogDestroy(getUd(self))
end
---<**_DEPRECATED_**> destroy
---@return void
function Dialog:destroy()
--@debug@
deprecated('Dialog.destroy', 'Dialog.delete')
--@end-debug@
return self:delete()
end
---<static> create
---@return Dialog
function Dialog:create()
return Dialog:fromUd(Native.DialogCreate())
end
---clear
---@return void
function Dialog:clear()
--@debug@
checkobject(self, Dialog, 'clear', 'self')
--@end-debug@
return Native.DialogClear(getUd(self))
end
---setMessage
---@param messageText string
---@return void
function Dialog:setMessage(messageText)
--@debug@
checkobject(self, Dialog, 'setMessage', 'self')
checktype(messageText, 'string', 'setMessage', 1)
--@end-debug@
return Native.DialogSetMessage(getUd(self), messageText)
end
---addButton
---@param buttonText string
---@param hotkey integer
---@return Button
function Dialog:addButton(buttonText, hotkey)
--@debug@
checkobject(self, Dialog, 'addButton', 'self')
checktype(buttonText, 'string', 'addButton', 1)
checktype(hotkey, 'integer', 'addButton', 2)
--@end-debug@
return require('lib.stdlib.oop.button'):fromUd(Native.DialogAddButton(getUd(self), buttonText, hotkey))
end
---addQuitButton
---@param doScoreScreen boolean
---@param buttonText string
---@param hotkey integer
---@return Button
function Dialog:addQuitButton(doScoreScreen, buttonText, hotkey)
--@debug@
checkobject(self, Dialog, 'addQuitButton', 'self')
checktype(doScoreScreen, 'boolean', 'addQuitButton', 1)
checktype(buttonText, 'string', 'addQuitButton', 2)
checktype(hotkey, 'integer', 'addQuitButton', 3)
--@end-debug@
return require('lib.stdlib.oop.button'):fromUd(Native.DialogAddQuitButton(getUd(self), doScoreScreen, buttonText, hotkey))
end
return Dialog
|
local inventory = require(script.inventory)
local equipped = require(script.equipped)
local stats = require(script.stats)
local toolbar = require(script.toolbar)
return function(state,action)
state = state or {}
-- server TODO: break this into two reducers?
if action.type == "PLAYER_ADD" then -- load save data
state = action.saveData
end
if action.type == "PLAYER_REMOVE" then -- bye bye
return nil
end
return {
inventory = inventory(state.inventory, action),
equipped = equipped(state.equipped, action),
stats = stats(state.stats, action),
toolbar = toolbar(state.toolbar, action),
}
end |
-- Persistent Data
local multiRefObjects = {
} -- multiRefObjects
local obj1 = {
["cartService"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop";
["extension"] = 8;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop/src/modules/CartService.lua";
};
["db.driver.mysql"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//orm";
["extension"] = 3;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//orm/src/db/driver/mysql.lua";
};
["utf8"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/utf8.lua";
};
["db.api.common"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//orm";
["extension"] = 3;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//orm/src/db/api/common.lua";
};
["DemoProductService"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/demo";
["extension"] = 9;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/demo/src/modules/DemoProductService.lua";
};
["property"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build";
["extension"] = 0;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build/src/property.lua";
};
["http"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/http.lua";
};
["http_headers"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/http_headers.lua";
};
["Editor"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/editor";
["extension"] = 5;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/editor/src/modules/Editor.lua";
};
["param"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/param.lua";
};
["builder"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/builder.lua";
};
["db.api.postgres"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//orm";
["extension"] = 3;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//orm/src/db/api/postgres.lua";
};
["Directory"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/editor";
["extension"] = 5;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/editor/src/modules/Directory.lua";
};
["db.api.mysql"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//orm";
["extension"] = 3;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//orm/src/db/api/mysql.lua";
};
["GIT"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/repository";
["extension"] = 6;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/repository/src/modules/GIT.lua";
};
["securityImport"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/security";
["extension"] = 4;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/security/src/import.lua";
};
["json"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/json.lua";
};
["persistence"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/persistence.lua";
};
["htmltemplates"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build";
["extension"] = 0;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build/src/htmltemplates.lua";
};
["eval"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/eval.lua";
};
["priceService"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop";
["extension"] = 8;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop/src/modules/PriceService.lua";
};
["crypto"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/crypto.lua";
};
["BaselineHtmlTemplate"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/baseline";
["extension"] = 2;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/baseline/src/BaselineHtmlTemplate.lua";
};
["utf8data"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/utf8data.lua";
};
["template"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/template.lua";
};
["fileutil"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/fileutil.lua";
};
["tests"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build";
["extension"] = 0;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build/src/tests.lua";
};
["countryService"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop";
["extension"] = 8;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop/src/modules/CountryService.lua";
};
["exceptionHandler"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop";
["extension"] = 8;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop/src/modules/ExceptionHandler.lua";
};
["exit"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/exit.lua";
};
["db.driver.postgres"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//orm";
["extension"] = 3;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//orm/src/db/driver/postgres.lua";
};
["localeService"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop";
["extension"] = 8;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop/src/modules/LocaleService.lua";
};
["userService"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/security";
["extension"] = 4;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/security/src/modules/UserService.lua";
};
["shopImport"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop";
["extension"] = 8;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop/src/import.lua";
};
["cookie"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/cookie.lua";
};
["testUser"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/security";
["extension"] = 4;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/security/src/testUser.lua";
};
["SVN"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/repository";
["extension"] = 6;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/repository/src/modules/SVN.lua";
};
["access"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build";
["extension"] = 0;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build/src/access.lua";
};
["types"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build";
["extension"] = 0;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build/src/types.lua";
};
["upload"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/upload.lua";
};
["exception"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/exception.lua";
};
["date"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/date.lua";
};
["database"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//orm";
["extension"] = 3;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//orm/src/database.lua";
};
["localization"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build";
["extension"] = 0;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build/src/localization.lua";
};
["modules"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build";
["extension"] = 0;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/build/src/modules.lua";
};
["parse"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/parse.lua";
};
["uuid"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/uuid.lua";
};
["util"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/util.lua";
};
["stacktrace"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core";
["extension"] = 1;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/../common//core/src/stacktrace.lua";
};
}
return obj1
|
PlazaRedPacketMainCcsView = class("PlazaRedPacketMainCcsView")
PlazaRedPacketMainCcsView.onCreationComplete = function (slot0)
ClassUtil.extends(slot0, ZoomPopUpChildView, true, slot0, slot0.bg, slot0.view)
slot0._spineErrorTime = 0.06666666666666667
end
PlazaRedPacketMainCcsView.show = function (slot0, slot1, slot2)
ZoomPopUpChildView.show(slot0, true, slot2)
slot0:addSignal()
end
PlazaRedPacketMainCcsView.onClickWhenCantTouchSignal = function (slot0)
tweenMsgMgr:showWhiteMsg("您还没有获得红包,请继续游戏哟!祝您好运!", nil, 680)
end
PlazaRedPacketMainCcsView.onZoomShowTweenComplete = function (slot0)
ZoomPopUpChildView.show(slot0)
slot0:addSpine()
slot0:onRedPacketDesInfoChanged()
slot0:onRedPacketInfoChanged()
slot0:playAnimate()
end
PlazaRedPacketMainCcsView.addSignal = function (slot0)
Hero.redPacketDesInfoChangedSignal:add(slot0.onRedPacketDesInfoChanged, slot0)
slot0.model.redPacketInfoChangedSignal:add(slot0.onRedPacketInfoChanged, slot0)
slot0.model.redPacketRewardScoreChangedSignal:add(slot0.onRedPacketRewardScoreChanged, slot0)
slot0.view.main.btnOpen:getClickWhenCantTouchSignal():add(slot0.onClickWhenCantTouchSignal, slot0)
slot0.view.main.btnYjlq:getClickWhenCantTouchSignal():add(slot0.onClickWhenCantTouchSignal, slot0)
end
PlazaRedPacketMainCcsView.addSpine = function (slot0)
if not slot0._bgSpine then
slot0._bgSpine = sp.SkeletonAnimation:create(slot1, ResConfig.getSpinePath("tjcs_hbhd_hld/tjcs_hbhd_hld.atlas"))
slot0.view.bgSpine:addChild(slot0._bgSpine)
end
if not slot0._openSpine then
slot0._openSpine = sp.SkeletonAnimation:create(slot1, slot2)
slot0._openSpine:setPosition(60, 60)
slot0._openSpine:setAnimation(0, "idle", true)
slot0.view.main.btnOpen:addChild(slot0._openSpine)
end
slot0._bgSpine:setAnimation(0, "start", false)
slot0._bgSpine:addAnimation(0, "idle", true)
end
PlazaRedPacketMainCcsView.hide = function (slot0, slot1, slot2)
ZoomPopUpChildView.hide(slot0, slot1, slot2)
slot0:removeSignal()
slot0:removeSpine()
end
PlazaRedPacketMainCcsView.playAnimate = function (slot0)
slot0.view.main:setOpacity(0)
slot0.view.main:setScale(0.6)
slot0.view.startDate:setOpacity(0)
slot0.view.endDate:setOpacity(0)
TweenLite.killTweensOf(slot0.view.main)
TweenLite.killTweensOf(slot0.view.startDate)
TweenLite.killTweensOf(slot0.view.endDate)
slot2 = TimelineLite.new()
TimelineLite.new().insert(slot1, TweenLite.to(slot0.view.main, 0.23333333333333334, {
autoAlpha = 1,
delay = 0.16666666666666666 - slot0._spineErrorTime
}))
slot2:append(TweenLite.to(slot0.view.main, 0.23333333333333334, {
scale = 1.05,
delay = 0.16666666666666666 - slot0._spineErrorTime
}))
slot2:append(TweenLite.to(slot0.view.main, 0.3, {
scale = 0.98
}))
slot2:append(TweenLite.to(slot0.view.main, 0.4, {
scale = 1
}))
slot3 = TimelineLite.new()
slot3:insert(TweenLite.to(slot0.view.startDate, 0.23333333333333334, {
delay = 0.4,
autoAlpha = 1
}))
slot3:insert(TweenLite.to(slot0.view.endDate, 0.23333333333333334, {
delay = 0.5333333333333333,
autoAlpha = 1
}))
slot0._spineErrorTime = 0
end
PlazaRedPacketMainCcsView.gotNumberTable = function (slot0, slot1)
slot3 = {}
for slot7 = 1, #tostring(slot1), 1 do
table.insert(slot3, string.sub(slot2, slot7, slot7))
end
if table.nums(slot3) == 1 then
table.insert(slot3, 1, 0)
end
return slot3
end
PlazaRedPacketMainCcsView.gotDateTable = function (slot0, slot1)
slot3 = {}
for slot7, slot8 in ipairs(slot2) do
table.insert(slot3, parseInt(string.split(slot8, ",")[1]))
table.insert(slot3, parseInt(string.split(slot8, ",")[2]))
end
return slot3
end
PlazaRedPacketMainCcsView.onRedPacketCountChanged = function (slot0, slot1)
slot0.view.main.packetCount2:setVisible(table.nums(slot0:gotNumberTable(slot1)) == 2)
slot0.view.main.packetCount3:setVisible(table.nums(slot2) == 3)
if table.nums(slot2) == 2 then
slot0.view.main.packetCount2.num1:setSpriteFrame("redpacket_panelcount_" .. slot2[1] .. ".png")
slot0.view.main.packetCount2.num2:setSpriteFrame("redpacket_panelcount_" .. slot2[2] .. ".png")
elseif table.nums(slot2) == 3 then
slot0.view.main.packetCount3.num1:setSpriteFrame("redpacket_panelcount_" .. slot2[1] .. ".png")
slot0.view.main.packetCount3.num2:setSpriteFrame("redpacket_panelcount_" .. slot2[2] .. ".png")
slot0.view.main.packetCount3.num3:setSpriteFrame("redpacket_panelcount_" .. slot2[3] .. ".png")
end
slot1 = parseInt(slot1)
if slot0._openSpine then
slot0._openSpine:setVisible(slot1 > 0)
end
slot0.view.main.btnOpen.lock:setVisible(slot1 == 0)
slot0.view.main.btnYjlq:setCanTouch(slot1 > 0)
slot0.view.main.btnOpen:setCanTouch(slot1 > 0)
end
PlazaRedPacketMainCcsView.onRedPacketDesInfoChanged = function (slot0)
if Hero:getRedPacketDesInfo() and slot1.date then
slot0.view.startDate.s1_tf:setHtmlText(HtmlUtil.createArtNum(slot0:gotDateTable(slot1.date)[1] or 0, "#redpacket_date_%d.png"))
slot0.view.startDate.s2_tf:setHtmlText(HtmlUtil.createArtNum(slot2[2] or 0, "#redpacket_date_%d.png"))
slot0.view.endDate.s1_tf:setHtmlText(HtmlUtil.createArtNum(slot2[3] or 0, "#redpacket_date_%d.png"))
slot0.view.endDate.s2_tf:setHtmlText(HtmlUtil.createArtNum(slot2[4] or 0, "#redpacket_date_%d.png"))
end
end
PlazaRedPacketMainCcsView.onRedPacketRewardScoreChanged = function (slot0)
slot1 = slot0.model:getRedPacketRewardScore()
slot0._openSpine:setAnimation(0, "start", false)
slot0._openSpine:addAnimation(0, "idle", true)
slot0.view.main.btnOpen:setTouchEnabled(false)
tickMgr:delayedCall(function ()
popupMgr.view.main.btnOpen:setTouchEnabled(true)
popupMgr:showRedPacketAwardPopup(tonumber(popupMgr.showRedPacketAwardPopup))._rootView.view.coinRain:removeAllChildren()
popupMgr:showMoneyEffect(popupMgr.showRedPacketAwardPopup(tonumber(popupMgr.showRedPacketAwardPopup))._rootView.view.coinRain)
end, 400)
end
PlazaRedPacketMainCcsView.onRedPacketInfoChanged = function (slot0)
if slot0.model:getRedPacketInfo() then
slot0:onRedPacketCountChanged(slot1.Quantity)
end
end
PlazaRedPacketMainCcsView.onBtnClick = function (slot0, slot1)
if slot1 == slot0.view.main.btnClose then
slot0.model:setIsShowingRedPacketMain(false)
elseif slot1 == slot0.view.main.btnHdxq then
slot0.model:setIsShowingRedPacketHdxq(true)
elseif slot1 == slot0.view.main.btnYjlq then
slot0.controller:requestOpenAllRedPacket()
elseif slot1 == slot0.view.main.btnOpen then
slot0.controller:requestOpenOneRedPacket()
end
end
PlazaRedPacketMainCcsView.removeSpine = function (slot0)
if slot0._bgSpine then
slot0._bgSpine:removeFromParent()
slot0._bgSpine = nil
end
if slot0._openSpine then
slot0._openSpine:removeFromParent()
slot0._openSpine = nil
end
end
PlazaRedPacketMainCcsView.removeSignal = function (slot0)
Hero.redPacketDesInfoChangedSignal:remove(slot0.onRedPacketDesInfoChanged, slot0)
slot0.model.redPacketInfoChangedSignal:remove(slot0.onRedPacketInfoChanged, slot0)
slot0.model.redPacketRewardScoreChangedSignal:remove(slot0.onRedPacketRewardScoreChanged, slot0)
slot0.view.main.btnOpen:getClickWhenCantTouchSignal():remove(slot0.onClickWhenCantTouchSignal, slot0)
slot0.view.main.btnYjlq:getClickWhenCantTouchSignal():remove(slot0.onClickWhenCantTouchSignal, slot0)
end
PlazaRedPacketMainCcsView.destroy = function (slot0)
slot0.view.main.btnClose:destroy(slot0)
slot0.view.main.btnHdxq:destroy(slot0)
slot0.view.main.btnYjlq:destroy(slot0)
slot0.view.main.btnOpen:destroy(slot0)
slot0:removeSpine()
slot0:removeSignal()
ZoomPopUpChildView.destroy(slot0)
end
return
|
local ObjBaseUnit = require "objects.ObjBaseUnit"
local ObjEnemy = Class.create("ObjEnemy", ObjBaseUnit)
function ObjEnemy:init( )
-- init other data
self.max_health = 100
self.health = 100
--initialize movement data
self.maxJumpTime = 300
self.currentJumpTime = 0
self.jumpSpeed = 490
self.maxAirJumps = 1
self.deceleration = -9
self.maxSpeed = 4 * 32
self.acceleration = 20 * 32
self.x = 0
self.y = 0
self.faction = "enemy"
end
function ObjEnemy:create()
ObjBaseUnit.create(self)
if math.random(1,2) == 1 then
self:addModule(require "modules.ModProjectileEnemy")
else
self:addModule(require "modules.ModMeleeEnemy")
end
self:setAttackRangeRate(1,1)
-- self:setMeleeHitbox({width = 60, height = 15,xOffset = 10, yOffset = -5, damage = 15, guardDamage = 12,
-- stun = 35, persistence = 0.15,xKnockBack = 4 * 32, yKnockBack = -3 * 32, element = "fire"})
-- self:setFrameData(8,10,10)
-- self:setAttackAnimation("slash")
self:addSpritePiece(require("assets.spr.scripts.SprLegBoots"))
self:addSpritePiece(require("assets.spr.scripts.SprBodyUniform"))
self:addSpritePiece(require("assets.spr.scripts.SprHeadGeneric"))
self:addSpritePiece(require("assets.spr.scripts.SprHatHelmet"))
self:createBody( "dynamic" ,true, true)
self.shape = love.physics.newRectangleShape(7, 16)
self.fixture = love.physics.newFixture(self.body, self.shape, 1)
self:setFixture(self.shape, 22.6)
self.fixture:setCategory(CL_NPC)
self:setEquipCreateItem("EqpHandgun")
end
return ObjEnemy
|
--[[ Netherstorm -- Phase Hunter.lua
This script was written and is protected
by the GPL v2. This script was released
by BlackHer0 of the BLUA Scripting
Project. Please give proper accredidations
when re-releasing or sharing this script
with others in the emulation community.
~~End of License Agreement
-- BlackHer0, September, 30th, 2008. ]]
function Hunter_OnEnterCombat(Unit,Event)
Unit:RegisterEvent("Hunter_DeMaterialize",8000,0)
Unit:RegisterEvent("Hunter_ManaBurn",3000,0)
end
function Hunter_DeMaterialize(Unit,Event)
Unit:CastSpell(34814)
Unit:RegisterEvent("Hunter_Materialize",3000,0)
end
function Hunter_ManaBurn(Unit,Event)
Unit:FullCastSpellOnTarget(13321,Unit:GetClosestPlayer())
end
function Hunter_Materialize(Unit,Event)
Unit:CastSpell(34804)
end
function Hunter_OnLeaveCombat(Unit,Event)
Unit:RemoveEvents()
end
function Hunter_OnDied(Unit,Event)
Unit:RemoveEvents()
end
RegisterUnitEvent (18879, 1, "Hunter_OnEnterCombat")
RegisterUnitEvent (18879, 2, "Hunter_OnLeaveCombat")
RegisterUnitEvent (18879, 4, "Hunter_OnDied") |
--[[ Element: Raid Role Icon
Handles visibility and updating of `self.RaidRole` based upon the units
party assignment.
Widget
RaidRole - A Texture representing the units party assignment. This is can be
main tank, main assist or blank.
Notes
This element updates by changing the texture.
Examples
-- Position and size
local RaidRole = self:CreateTexture(nil, 'OVERLAY')
RaidRole:SetSize(16, 16)
RaidRole:SetPoint('TOPLEFT')
-- Register it with oUF
self.RaidRole = RaidRole
Hooks
Override(self) - Used to completely override the internal update function.
Removing the table key entry will make the element fall-back
to its internal function again.
]]
local parent, ns = ...
local oUF = ns.oUF
local Update = function(self, event)
local unit = self.unit
if(not UnitInRaid(unit)) then return end
local raidrole = self.RaidRole
if(raidrole.PreUpdate) then
raidrole:PreUpdate()
end
local inVehicle = UnitHasVehicleUI(unit)
if(GetPartyAssignment('MAINTANK', unit) and not inVehicle) then
raidrole:Show()
raidrole:SetTexture[[Interface\GROUPFRAME\UI-GROUP-MAINTANKICON]]
elseif(GetPartyAssignment('MAINASSIST', unit) and not inVehicle) then
raidrole:Show()
raidrole:SetTexture[[Interface\GROUPFRAME\UI-GROUP-MAINASSISTICON]]
else
raidrole:Hide()
end
if(raidrole.PostUpdate) then
return raidrole:PostUpdate(rinfo)
end
end
local Path = function(self, ...)
return (self.RaidRole.Override or Update)(self, ...)
end
local ForceUpdate = function(element)
return Path(element.__owner, 'ForceUpdate')
end
local Enable = function(self)
local raidrole = self.RaidRole
if(raidrole) then
raidrole.__owner = self
raidrole.ForceUpdate = ForceUpdate
self:RegisterEvent('GROUP_ROSTER_UPDATE', Path, true)
return true
end
end
local Disable = function(self)
local raidrole = self.RaidRole
if(raidrole) then
self:UnregisterEvent('GROUP_ROSTER_UPDATE', Path)
end
end
oUF:AddElement('RaidRole', Path, Enable, Disable)
|
--[[
File: LuaNativeUIExampleLowLevel2.lua
Author: Mikael Kindborg
Description:
This is a slightly modified version of LuaNativeUIExampleLowLevel.lua.
The example shows how to attach event functions to widgets.
This is done by calling:
mosync.NativeUI:OnWidgetEvent(widgetHandle, eventFunction)
To disable an event function, call:
mosync.NativeUI:OnWidgetEvent(widgetHandle, nil)
This example uses global variables for the Widgets, to make
it possible to interactively experiment with the UI using
the LuaLive editor.
First press "Run program" in the editor to run all of the
code in this file. That will create the UI.
Then you can run code interactively. Here are some things
to try. Select a line of code, then press "Do selection".
mosync.maWidgetSetProperty(MessageLabel, mosync.MAW_LABEL_FONT_SIZE, "60")
mosync.maWidgetRemoveChild(MessageLabel)
mosync.maWidgetAddChild(MainLayout, MessageLabel)
mosync.maExit(0)
--]]
-- Widget size values as strings (the MAW_CONSTANT_* values
-- are integers and cannot be used with maWidgetSetProperty).
mosync.FILL_PARENT = ""..mosync.MAW_CONSTANT_FILL_AVAILABLE_SPACE
mosync.WRAP_CONTENT = ""..mosync.MAW_CONSTANT_WRAP_CONTENT
-- Create screen with widgets.
Screen = mosync.maWidgetCreate(mosync.MAW_SCREEN)
MainLayout = mosync.maWidgetCreate(mosync.MAW_VERTICAL_LAYOUT)
mosync.maWidgetSetProperty(MainLayout, mosync.MAW_WIDGET_WIDTH, mosync.FILL_PARENT)
mosync.maWidgetSetProperty(MainLayout, mosync.MAW_WIDGET_HEIGHT, mosync.FILL_PARENT)
mosync.maWidgetSetProperty(MainLayout, mosync.MAW_WIDGET_BACKGROUND_COLOR, "000000")
mosync.maWidgetAddChild(Screen, MainLayout)
MessageLabel = mosync.maWidgetCreate(mosync.MAW_LABEL)
mosync.maWidgetSetProperty(MessageLabel, mosync.MAW_WIDGET_WIDTH, mosync.FILL_PARENT)
mosync.maWidgetSetProperty(MessageLabel, mosync.MAW_WIDGET_HEIGHT, mosync.WRAP_CONTENT)
mosync.maWidgetSetProperty(MessageLabel, mosync.MAW_LABEL_FONT_SIZE, "36")
mosync.maWidgetSetProperty(MessageLabel, mosync.MAW_LABEL_FONT_COLOR, "AAAAAA")
mosync.maWidgetSetProperty(MessageLabel, mosync.MAW_LABEL_TEXT, "Demo of MoSync NativeUI")
mosync.maWidgetAddChild(MainLayout, MessageLabel)
ButtonSayHello = mosync.maWidgetCreate(mosync.MAW_BUTTON)
mosync.maWidgetSetProperty(ButtonSayHello, mosync.MAW_WIDGET_WIDTH, mosync.FILL_PARENT)
mosync.maWidgetSetProperty(ButtonSayHello, mosync.MAW_WIDGET_HEIGHT, mosync.WRAP_CONTENT)
mosync.maWidgetSetProperty(ButtonSayHello, mosync.MAW_BUTTON_TEXT_VERTICAL_ALIGNMENT, mosync.MAW_ALIGNMENT_CENTER)
mosync.maWidgetSetProperty(ButtonSayHello, mosync.MAW_BUTTON_TEXT_HORIZONTAL_ALIGNMENT, mosync.MAW_ALIGNMENT_CENTER)
mosync.maWidgetSetProperty(ButtonSayHello, mosync.MAW_BUTTON_FONT_SIZE, "24")
mosync.maWidgetSetProperty(ButtonSayHello, mosync.MAW_BUTTON_TEXT, "Say Hello")
mosync.maWidgetAddChild(MainLayout, ButtonSayHello)
mosync.NativeUI:OnWidgetEvent(ButtonSayHello, function(widgetEvent)
mosync.maWidgetSetProperty(MessageLabel, mosync.MAW_LABEL_TEXT, "Hello World!")
end)
ButtonSayHi = mosync.maWidgetCreate(mosync.MAW_BUTTON)
mosync.maWidgetSetProperty(ButtonSayHi, mosync.MAW_WIDGET_WIDTH, mosync.FILL_PARENT)
mosync.maWidgetSetProperty(ButtonSayHi, mosync.MAW_WIDGET_HEIGHT, mosync.WRAP_CONTENT)
mosync.maWidgetSetProperty(ButtonSayHi, mosync.MAW_BUTTON_TEXT_VERTICAL_ALIGNMENT, mosync.MAW_ALIGNMENT_CENTER)
mosync.maWidgetSetProperty(ButtonSayHi, mosync.MAW_BUTTON_TEXT_HORIZONTAL_ALIGNMENT, mosync.MAW_ALIGNMENT_CENTER)
mosync.maWidgetSetProperty(ButtonSayHi, mosync.MAW_BUTTON_FONT_SIZE, "24")
mosync.maWidgetSetProperty(ButtonSayHi, mosync.MAW_BUTTON_TEXT, "Say Hi")
mosync.maWidgetAddChild(MainLayout, ButtonSayHi)
mosync.NativeUI:OnWidgetEvent(ButtonSayHi, function(widgetEvent)
mosync.maWidgetSetProperty(MessageLabel, mosync.MAW_LABEL_TEXT, "Hi there!")
end)
-- Show screen.
mosync.maWidgetScreenShow(Screen)
|
AddCSLuaFile( )
DEFINE_BASECLASS("base_aperture_field")
local WireAddon = WireAddon or WIRE_CLIENT_INSTALLED
ENT.PrintName = "Material Emancipation Grill"
ENT.FieldColor = Color(120, 230, 255)
ENT.InUnFizzable = true
local FIELD_HEIGHT = 120
if WireAddon then
ENT.WireDebugName = ENT.PrintName
end
function ENT:Initialize()
self.BaseClass.Initialize(self)
if SERVER then
self:PhysicsInitStatic(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
if self:GetStartEnabled() then self:Enable(true) end
self.ProjectedWalls = {}
self:SetNWFloat("TA:FieldFlash", 0)
if not WireAddon then return end
self.Inputs = Wire_CreateInputs(self, {"Enable"})
end
if CLIENT then
end
end
function ENT:Think()
self.BaseClass.Think(self)
if CLIENT then
if self:GetNWFloat("TA:FieldFlash") > 0 then
local flash = (1 + self:GetNWFloat("TA:FieldFlash") / 15)
local color = Color(self.FieldColor.r * flash, self.FieldColor.g * flash, self.FieldColor.b * flash)
for k,v in pairs(self.FieldsEntities) do
v:SetColor(color)
end
end
return
end
self:NextThink(CurTime())
if self:GetNWFloat("TA:FieldFlash") > 0 then
self:SetNWFloat("TA:FieldFlash", self:GetNWFloat("TA:FieldFlash") - 1)
end
return true
end
function ENT:Draw()
self.BaseClass.Draw(self)
end
function ENT:Drawing()
local secondEmitter = self:GetSecondEmitter()
if not IsValid(secondEmitter) then return end
if not self:GetEnable() then return end
--Approach object field effect
local closesEntities = {}
local tracer = util.TraceHull({
start = self:LocalToWorld(Vector()),
endpos = secondEmitter:LocalToWorld(Vector()),
filter = function(ent)
if not ent.IsAperture
and ent != self
and ent != secondEmitter
and not ent:IsPlayer()
and not ent:IsNPC() then
table.insert(closesEntities, ent)
end
return false
end,
ignoreworld = true,
mins = -Vector(1, 1, 1) * FIELD_HEIGHT,
maxs = Vector(1, 1, 1) * FIELD_HEIGHT,
mask = MASK_SHOT_HULL
})
local clipNormalUp = -self:GetUp()
local clipPosUp = clipNormalUp:Dot(self:LocalToWorld(Vector( 0, 0, FIELD_HEIGHT / 2)))
local clipNormalDown = self:GetUp()
local clipPosDown = clipNormalDown:Dot(self:LocalToWorld(Vector(0, 0, -FIELD_HEIGHT / 2)))
render.SetMaterial(Material("models/aperture/effects/fizzler_approach"))
local oldEC = render.EnableClipping(true)
render.PushCustomClipPlane(clipNormalUp, clipPosUp)
render.PushCustomClipPlane(clipNormalDown, clipPosDown)
for _, ent in pairs(closesEntities) do
local localEntPos = self:WorldToLocal(ent:GetPos())
local distToField = math.abs(localEntPos.x)
localEntPos = Vector(0, localEntPos.y, localEntPos.z)
local rad = math.min(FIELD_HEIGHT, ent:GetModelRadius() * 6)
local alpha = math.max(0, math.min(1, (75 - distToField) / 50)) * 255
local dir = self:GetForward()
local flash = (1 + self:GetNWFloat("TA:FieldFlash") / 15)
local color = Color(math.min(self.FieldColor.r * flash, 255), math.min(self.FieldColor.g * flash, 255), math.min(self.FieldColor.b * flash, 255))
color.a = alpha
LIB_MATH_TA:NormalFlipZeros(dir)
render.DrawQuadEasy(self:LocalToWorld(localEntPos), dir, rad, rad, color, 0)
end
render.PopCustomClipPlane()
render.PopCustomClipPlane()
render.EnableClipping(oldEC)
end
-- no more client side
if CLIENT then return end
function ENT:HandleEntity(ent)
if not self:GetEnable() then return end
if ent.InUnFizzable then return end
if ent == self:GetSecondEmitter() then return end
-- if it portal gun projectile
if ent:GetClass() == "projectile_portal_ball" then
local ang = ent:GetAngles()
ang:RotateAroundAxis(ent:GetForward(), 90)
ang.y = self:GetAngles().y + 90
if GetConVarNumber("portal_beta_borders") >= 1 then
ParticleEffect("portal_"..ent:GetNWInt("Kind", 1).."_cleanser_", ent:GetPos(), ang)
else
ParticleEffect("portal_"..ent:GetNWInt("Kind", 1).."_cleanser", ent:GetPos(), ang)
end
ent:Remove()
self:SetNWFloat("TA:FieldFlash", 25)
return
end
-- if it player with portal gun
if ent:IsPlayer() and ent:Alive() then
local plyweap = ent:GetActiveWeapon()
if IsValid(plyweap) and plyweap:GetClass() == "weapon_portalgun" and plyweap.CleanPortals then
plyweap:CleanPortals()
end
return
end
if ent.UnFizzable then return end
if ent:IsPlayer() then return end
if ent:IsNPC() then return end
if ent:GetClass() == "prop_ragdoll" then return end
if ent:GetClass() == "prop_dynamic" then return end
if ent:GetClass() == "prop_dynamic_override" then return end
if ent:GetClass() == "portalrp_core" then return end
if not IsValid(ent:GetPhysicsObject()) then return end
if ent:GetModel() == "models/blackops/portal_sides.mdl" then return end
LIB_APERTURE:DissolveEnt(ent)
end
|
local function areTablesEqual(a, b)
local aKeys = Object.keys(a)
local bKeys = Object.keys(b)
if #aKeys ~= #bKeys then
return false
end
local allKeys = Array.concat(aKeys, bKeys)
for _, key in ipairs(allKeys) do
if a[key] ~= b[key] then
return false
end
end
return true
end
local function equals(a, b)
local typeA = type(a)
local typeB = type(b)
if typeA == 'table' and typeB == 'table' then
return areTablesEqual(a, b)
elseif typeA == 'boolean' and typeB == 'boolean' then
return a == b
else
-- TODO: Extend as required
print('Error: equals not implemented for given type.')
return false
end
end
local function expect(value)
return {
toEqual = function (expectedValue)
return equals(value, expectedValue)
end
}
end
Testing = {
expect = expect
}
|
local core = l2df or require((...):match("(.-)core.+$") or "" .. "core")
assert(type(core) == "table" and core.version >= 1.0, "Core.Entities.System works only with l2df v1.0 and higher")
local Object = core.import "core.object"
local System = Object:extend({ manager = { }, groups = { } })
return System |
function init()
self.signDirectiveStrings = config.getParameter("signData")
self.lightFrames = config.getParameter("lightData")
self.signLight = config.getParameter("signLight")
self.signBacking = config.getParameter("signBacking")
self.frameColors = config.getParameter("frameColors")
storage.storedDirectiveString = storage.storedDirectiveString or ""
animator.setAnimationState("displayedState", "idle")
self.isWired = config.getParameter("isWired")
self.isContainer = config.getParameter("isContainer")
if storage.isOn == nil then storage.isOn = true end
if self.isWired == true then
object.setInteractive(not object.isInputNodeConnected(0))
object.setAllOutputNodes(storage.isOn)
end
self.scanCooldown = config.getParameter("scanCooldown", 1)
self.scanTimer = math.random() * self.scanCooldown
self.drawCooldown = config.getParameter("drawCooldown", 0.5)
self.drawTimer = self.drawCooldown
storage.nearSpaces = {
{{-3,-1},"bl", nil, "01"},
{{-3,0},"ml",nil, "02"},
{{-3,1},"ul",nil, "03"},
{{-2,-1},"b1",nil, "0E"},
{{-1,-1},"b2",nil, "0D"},
{{0,-1},"b3",nil, "0C"},
{{1,-1},"b4", nil, "0B"},
{{2,-1},"br",nil, "0A"},
{{-2,1},"u1",nil, "04"},
{{-1,1},"u2",nil, "05"},
{{0,1},"u3",nil, "06"},
{{1,1},"u4",nil, "07"},
{{2,1},"ur",nil, "08"},
{{2,0},"mr", nil, "09"}
}
if self.signDirectiveStrings ~= nil and self.signDirectiveStrings[1] ~= nil then
if storage.isOn and self.isWired == true then
storage.frame = 2
else
storage.frame = 1
end
storage.storedDirectiveString = self.signDirectiveStrings[storage.frame]
applyDirectives()
end
end
function onNodeConnectionChange(args)
--want wired signs to stop functioning as switches when something's feeding them input
if self.isWired == true then
object.setInteractive(not object.isInputNodeConnected(0))
if object.isInputNodeConnected(0) then
onInputNodeChange({ level = object.getInputNodeLevel(0) })
else
onInputNodeChange({ level = false })
end
end
end
function onInputNodeChange(args)
if args.level then
storage.isOn = true
if self.isWired == true then storage.frame = 2 end
else
storage.isOn = false
if self.isWired == true then storage.frame = 1 end
end
object.setAllOutputNodes(storage.isOn)
storage.storedDirectiveString = self.signDirectiveStrings[storage.frame]
applyDirectives()
end
function onInteraction(args)
object.setLightColor({math.random(0,255), math.random(0,255), math.random(0,255), math.random(0,255)})
if self.isWired == true then
if storage.isOn then
storage.isOn = false
storage.frame = 1
object.setAllOutputNodes(false)
else
storage.isOn = true
storage.frame = 2
object.setAllOutputNodes(true)
end
storage.storedDirectiveString = self.signDirectiveStrings[storage.frame]
applyDirectives()
end
end
function update(dt)
--three behaviors: non-wired, wired and off, wired and on
if #self.signDirectiveStrings >=2 then
if self.drawTimer <= 0 then
if self.isWired == true then
if storage.isOn and #self.signDirectiveStrings > 2 then
if storage.frame < #self.signDirectiveStrings then
storage.frame = storage.frame + 1
else
storage.frame = 2
end
--need to handle the special cases for this string, blank frames and filler frames
if self.signDirectiveStrings[storage.frame] == "replace=" and storage.storedDirectiveString ~= self.signDirectiveStrings[storage.frame] then
storage.storedDirectiveString = ""
applyDirectives()
elseif self.signDirectiveStrings[storage.frame] ~= nil and storage.storedDirectiveString ~= self.signDirectiveStrings[storage.frame] then
storage.storedDirectiveString = self.signDirectiveStrings[storage.frame]
applyDirectives()
end
end
else
if storage.frame < #self.signDirectiveStrings then storage.frame = storage.frame + 1 else storage.frame = 1 end
if self.signDirectiveStrings[storage.frame] == "replace=" and storage.storedDirectiveString ~= self.signDirectiveStrings[storage.frame] then
storage.storedDirectiveString = ""
applyDirectives()
elseif self.signDirectiveStrings[storage.frame] ~= nil and storage.storedDirectiveString ~= self.signDirectiveStrings[storage.frame] then
storage.storedDirectiveString = self.signDirectiveStrings[storage.frame]
applyDirectives()
end
end
self.drawTimer = self.drawCooldown
else
self.drawTimer = self.drawTimer - dt
end
end
if self.scanTimer <= 0 then
updateFrameSegments()
self.scanTimer = self.scanCooldown
else
self.scanTimer = self.scanTimer - dt
end
end
function die()
storage = {}
end
function updateFrameSegments()
local needsRedraw = false
--sb.logInfo("//////////Checking frame//////////")
--sb.logInfo("%s %s at %s", object.name(), entity.id(), object.position())
--sb.logInfo("Old Spaces: %s", storage.nearSpaces)
for u,v in ipairs(storage.nearSpaces) do
local isOccupied = false
--no frame segement bordering an occupied spaces. used to ignore non-sign objects for this, but that was wonky
if world.tileIsOccupied({object.position()[1] + v[1][1], object.position()[2] + v[1][2]}) then
local nearObjects = world.entityQuery({object.position()[1] + v[1][1] + 0.5, object.position()[2] + v[1][2] + 0.5}, 0.2, { includedTypes = { "object" }, boundMode = "CollisionArea", withoutEntityId = entity.id() })
for _,objectId in pairs(nearObjects) do
if world.entityName(objectId) == "customsign" then
local signPos = world.distance(world.entityPosition(objectId) , object.position())
--sb.logInfo("%s, %s", v[1] ,signPos)
if signPos[2] == v[1][2] and signPos[1] <= v[1][1] + 2 and signPos[1] >= v[1][1] - 1 then
if v[3] ~= "tile" then
v[3] = "tile"
needsRedraw = true
end
isOccupied = true
break
end
end
end
end
if not isOccupied then
if v[3] == "tile" then
v[3] = nil
needsRedraw = true
end
end
end
--"bl" = "bl" or "ml" or "b1"
storage.nearSpaces[1][3] = storage.nearSpaces[1][3] or storage.nearSpaces[2][3] or storage.nearSpaces[4][3]
--"ul" = "ul" or "ml" or "u1"
storage.nearSpaces[3][3] = storage.nearSpaces[3][3] or storage.nearSpaces[2][3] or storage.nearSpaces[9][3]
--"br" = "br" or "mr" or "b4"
storage.nearSpaces[8][3] = storage.nearSpaces[8][3] or storage.nearSpaces[14][3] or storage.nearSpaces[7][3]
--"ur" = "ur" or "mr" or "u4"
storage.nearSpaces[13][3] = storage.nearSpaces[13][3] or storage.nearSpaces[14][3] or storage.nearSpaces[12][3]
--sb.logInfo("New Spaces: %s", storage.nearSpaces)
if needsRedraw then
applyDirectives()
end
--sb.logInfo("----------------------------------")
end
function applyDirectives()
-- Not using per frame lighting anymore
-- if self.lightFrames ~= nil and self.lightFrames["f"..tostring(storage.frame)] ~= nil then
-- local lightRGB = convertRGBAtoArray(self.lightFrames["f"..tostring(storage.frame)])
-- object.setLightColor({lightRGB[1], lightRGB[2], lightRGB[3], 255})
-- else
-- object.setLightColor({0, 0, 0, 0})
-- end
if storage.isOn and self.signLight then
object.setLightColor(convertRGBAtoArray(self.signLight))
else
object.setLightColor({0, 0, 0, 0})
end
storage.storedDirectiveString = storage.storedDirectiveString or ""
local frameDirectiveString = "replace="
local needsSemicolon = false
if storage.storedDirectiveString ~= "" then
frameDirectiveString = ""
needsSemicolon = true
end
for u,v in ipairs(storage.nearSpaces) do
if v[3] ~= "tile" then
if needsSemicolon == true then frameDirectiveString = frameDirectiveString .. ";" else needsSemicolon = true end
frameDirectiveString = frameDirectiveString .. "90" .. v[4] .. "0001" .. "=" .. self.frameColors[1] .. ";00" .. v[4] .. "9001=" .. self.frameColors[2]
end
end
object.setProcessingDirectives(storage.storedDirectiveString..frameDirectiveString)
end
function convertRGBAtoArray(rgba)
return {tonumber(string.sub(rgba,1,2),16),
tonumber(string.sub(rgba,3,4),16),
tonumber(string.sub(rgba,5,6),16),
tonumber(string.sub(rgba,7,8),16)}
end
|
local logger = require("scripts.logger")
local uid = {}
uid.chars = {"A", "a", "B", "b", "C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "g", "H", "h", "I", "i", "J", "j", "K", "k", "L", "l", "M", "m", "N", "n", "O", "o", "P", "p", "Q", "q", "R", "r", "S", "s", "T", "t", "U", "u", "V", "v", "W", "w", "X", "x", "Y", "y", "Z", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }
uid.max_length = 10
uid.generate = function()
local new_uid = {}
for i=1,uid.max_length do
table.insert(new_uid, uid.chars[math.random(#uid.chars)])
end
return table.concat(new_uid)
end
return uid |
if not modules then modules = { } end modules ['node-acc'] = {
version = 1.001,
comment = "companion to node-ini.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
local nodes, node = nodes, node
local nodecodes = nodes.nodecodes
local tasks = nodes.tasks
local nuts = nodes.nuts
local tonut = nodes.tonut
local tonode = nodes.tonode
local getid = nuts.getid
local getattr = nuts.getattr
local getlist = nuts.getlist
local getchar = nuts.getchar
local getnext = nuts.getnext
local setattr = nuts.setattr
local setlink = nuts.setlink
local setchar = nuts.setchar
local setsubtype = nuts.setsubtype
local getwidth = nuts.getwidth
local setwidth = nuts.setwidth
----- traverse_nodes = nuts.traverse
local traverse_id = nuts.traverse_id
----- copy_node = nuts.copy
local insert_after = nuts.insert_after
local copy_no_components = nuts.copy_no_components
local glue_code = nodecodes.glue
----- kern_code = nodecodes.kern
local glyph_code = nodecodes.glyph
local hlist_code = nodecodes.hlist
local vlist_code = nodecodes.vlist
local a_characters = attributes.private("characters")
local threshold = 65536 -- not used
local nofreplaced = 0
-- todo: nbsp etc
-- todo: collapse kerns (not needed, backend does this)
-- todo: maybe cache as we now create many nodes
-- todo: check for subtype related to spacing (13/14 but most seems to be user anyway)
local function injectspaces(head)
local p, p_id
local n = head
while n do
local id = getid(n)
if id == glue_code then
if p and getid(p) == glyph_code then
-- unless we don't care about the little bit of overhead
-- we can just: local g = copy_node(g)
local g = copy_no_components(p)
local a = getattr(n,a_characters)
setchar(g,32)
setlink(p,g,n)
setwidth(n,getwidth(n) - getwidth(g))
if a then
setattr(g,a_characters,a)
end
setattr(n,a_characters,0)
nofreplaced = nofreplaced + 1
end
elseif id == hlist_code or id == vlist_code then
injectspaces(getlist(n),attribute)
end
p_id = id
p = n
n = getnext(n)
end
return head, true -- always done anyway
end
nodes.handlers.accessibility = function(head)
local head, done = injectspaces(tonut(head))
return tonode(head), done
end
statistics.register("inserted spaces in output",function()
if nofreplaced > 0 then
return nofreplaced
end
end)
-- todo:
-- local a_hyphenated = attributes.private('hyphenated')
--
-- local hyphenated, codes = { }, { }
--
-- local function compact(n)
-- local t = { }
-- for n in traverse_id(glyph_code,n) do
-- t[#t+1] = utfchar(getchar(n)) -- check for unicode
-- end
-- return concat(t,"")
-- end
--
-- local function injectspans(head)
-- local done = false
-- for n in traverse_nodes(tonuts(head)) do
-- local id = getid(n)
-- if id == disc then
-- local r = getfield(n,"replace")
-- local p = getfield(n,"pre")
-- if r and p then
-- local str = compact(r)
-- local hsh = hyphenated[str]
-- if not hsh then
-- hsh = #codes + 1
-- hyphenated[str] = hsh
-- codes[hsh] = str
-- end
-- setattr(n,a_hyphenated,hsh)
-- done = true
-- end
-- elseif id == hlist_code or id == vlist_code then
-- injectspans(getlist(n))
-- end
-- end
-- return tonodes(head), done
-- end
--
-- nodes.injectspans = injectspans
--
-- tasks.appendaction("processors", "words", "nodes.injectspans")
--
-- local pdfpageliteral = nuts.pool.pdfpageliteral
--
-- local function injectspans(head)
-- local done = false
-- for n in traverse_nodes(tonut(head)) do
-- local id = getid(n)
-- if id == disc then
-- local a = getattr(n,a_hyphenated)
-- if a then
-- local str = codes[a]
-- local b = pdfpageliteral(format("/Span << /ActualText %s >> BDC", lpdf.tosixteen(str)))
-- local e = pdfpageliteral("EMC")
-- insert_before(head,n,b)
-- insert_after(head,n,e)
-- done = true
-- end
-- elseif id == hlist_code or id == vlist_code then
-- injectspans(getlist(n))
-- end
-- end
-- return tonodes(head), done
-- end
|
ArkRoyal = Class{}
function ArkRoyal:init()
self.x = -400
self.y = 100
self.graphic = love.graphics.newImage('graphics/arkroyal-old.png')
-- self.speed = 0.1
self.dx = 0
self.width = 500
self.height = 200
self.move = false
end
function ArkRoyal:update(dt)
-- self.dx = self.dx - self.speed * dt
-- self.x = self.x + self.dx
if self.move == true then
self.x = self.x - (self.dx * dt)
end
end
function ArkRoyal:render()
love.graphics.draw(self.graphic, self.x, self.y)
end |
--
-- tests/actions/vstudio/vc2010/test_excluded_configs.lua
-- Check handling of configurations which have been excluded from the build.
-- Copyright (c) 2012-2013 Jason Perkins and the Premake project
--
local suite = test.declare("vs2010_excluded_configs")
local vc2010 = premake.vstudio.vc2010
--
-- Setup/teardown
--
local sln, prj
function suite.setup()
_ACTION = "vs2010"
sln = solution("MySolution")
configurations { "Debug", "Release" }
platforms { "Zeus", "Ares" }
language "C++"
prj = project("MyProject")
kind "ConsoleApp"
links { "MyProject2", "MyProject3" }
project("MyProject2")
kind "StaticLib"
project("MyProject3")
kind "StaticLib"
removeplatforms { "Ares" }
end
local function prepare(platform)
local cfg = test.getconfig(prj, "Debug", platform)
vc2010.link(cfg)
end
--
-- If a sibling is included in one configuration and excluded from
-- another, the included configuration should link as normal.
--
function suite.normalLink_onIncludedConfig()
prepare("Zeus")
test.capture [[
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
</Link>
]]
end
function suite.normalLink_onIncludedConfig_externalTool()
solution("MySolution")
system "PS3"
prepare("Zeus")
test.capture [[
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
</Link>
]]
end
--
-- If a sibling is included in one configuration and excluded from
-- another, the excluded configuration should force explicit linking
-- and not list the excluded library.
--
function suite.explicitLink_onExcludedConfig()
prepare("Ares")
test.capture [[
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<AdditionalDependencies>MyProject2.lib;%(AdditionalDependencies)</AdditionalDependencies>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
</Link>
<ProjectReference>
<LinkLibraryDependencies>false</LinkLibraryDependencies>
</ProjectReference>
]]
end
function suite.explicitLink_onExcludedConfig_externalTool()
solution("MySolution")
system "PS3"
prepare("Ares")
test.capture [[
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<AdditionalDependencies>libMyProject2.a;%(AdditionalDependencies)</AdditionalDependencies>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
</Link>
<ProjectReference>
<LinkLibraryDependencies>false</LinkLibraryDependencies>
</ProjectReference>
]]
end
|
getglobal game
getfield -1 Workspace
getfield -1 resources
getfield -1 RemoteFunction
getfield -1 InvokeServer
pushvalue -2
pushstring requestTeam
pushstring police
pcall 3 0 0 |
module 'mock'
local defaultScript = [[
--Builtin Variable: self = Target Entity/Component; time = current Time;
]]
local scriptHeader = [[
local self = ...
]]
local scriptTail = [[
]]
local scriptMT = { __index = _G }
--------------------------------------------------------------------
CLASS: ScriptAnimatorKey ( AnimatorEventKey )
:MODEL{
Field 'script' :string() :widget('codebox');
Field 'desc' :string();
Field 'isCoroutine' :boolean();
}
function ScriptAnimatorKey:__init()
self.script = defaultScript
self.isCoroutine = false
self.compiledFunc = false
self.desc = 'Script'
end
function ScriptAnimatorKey:buildScript()
self.compiledFunc = false
local script = self.script
local finalScript = scriptHeader .. self.script .. scriptTail
local func, err = loadstring( finalScript, 'track-script' )
if not func then return _error( err ) end
local envTable = setmetatable( {}, scriptMT )
setfenv( func, envTable )
self.compiledFunc = func
end
function ScriptAnimatorKey:toString()
return self.desc
end
--------------------------------------------------------------------
CLASS: ScriptAnimatorTrack ( AnimatorEventTrack )
:MODEL{
}
function ScriptAnimatorTrack:getIcon()
return 'track_script'
end
function ScriptAnimatorTrack:toString()
local pathText = self.targetPath:toString()
return pathText..':(Script)'
end
function ScriptAnimatorTrack:isPreviewable()
return false
end
function ScriptAnimatorTrack:createKey( pos, context )
local key = ScriptAnimatorKey()
key:setPos( pos )
self:addKey( key )
return key
end
function ScriptAnimatorTrack:build( context )
self.idCurve = self:buildIdCurve()
context:updateLength( self:calcLength() )
for i, key in pairs( self.keys ) do
key:buildScript()
--TODO:error handling
end
end
function ScriptAnimatorTrack:onStateLoad( state )
local rootEntity, scene = state:getTargetRoot()
local target = self.targetPath:get( rootEntity, scene )
local playContext = { target, 0 }
state:addUpdateListenerTrack( self, playContext )
end
function ScriptAnimatorTrack:apply( state, playContext, t )
local target = playContext[1]
local keyId = playContext[2]
local newId = self.idCurve:getValueAtTime( t )
if keyId ~= newId then
local key = self.keys[ newId ]
playContext[2] = newId
if newId > 0 then
if key.isCoroutine then
--TODO
else
key.compiledFunc( target, t )
end
end
end
end
function ScriptAnimatorTrack:reset( state, playContext )
-- playContext[2] = 0
end
--------------------------------------------------------------------
registerCommonCustomAnimatorTrackType( 'Script', ScriptAnimatorTrack )
|
local rsp=[[{
"status": "OK",
"message": "",
"result": [
{
"date": "20210210",
"tradingDay": true
},
{
"date": "20210211",
"tradingDay": false
},
{
"date": "20210212",
"tradingDay": false
},
{
"date": "20210213",
"tradingDay": false
}
]
}]]
ngx.say(rsp)
|
local mod = get_mod("NeuterUltEffects")
local pl = require'pl.import_into'()
fassert(pl, "Neuter Ult Effects must be lower than Penlight Lua Libraries in your launcher's load order.")
--- Disable blood splatters.
mod:hook(World, "create_particles", function(func, world, particle_name, ...)
if mod:get(mod.SETTING_NAMES.BLOOD_SPLATTER)
and (
particle_name == "fx/screenspace_blood_drops"
or particle_name == "fx/screenspace_blood_drops_heavy"
)
then
return
end
if mod:get(mod.SETTING_NAMES.DISABLE_DAMAGE_TAKEN_FLASH)
and particle_name == "fx/screenspace_damage_indicator"
then
return
end
return func(world, particle_name, ...)
end)
local overcharge_events = {
["Play_weapon_staff_overcharge"] = true,
["Play_weapon_drakegun_overcharge"] = true,
["Play_weapon_life_staff_overcharge"] = true,
}
--- Mute wizard overcharge noise.
mod:hook(WwiseWorld, "trigger_event", function(func, wwise_world, sound_event, ...)
if overcharge_events[sound_event]
and mod:get(mod.SETTING_NAMES.MUTE_OVERCHARGE_NOISE) then
return
end
if sound_event == "hud_ping_enemy"
and mod:get(mod.SETTING_NAMES.MUTE_ENEMY_PING) then
return
end
if sound_event == "Play_wpn_steam_minigun_pump_damage"
and mod:get(mod.SETTING_NAMES.MUTE_CRANK_GUN_MAX_RELOAD) then
return
end
return func(wwise_world, sound_event, ...)
end)
--- Skip huntsman fov malarkey.
mod:hook(BuffFunctionTemplates.functions, "apply_huntsman_activated_ability", function(func, ...)
if mod:get(mod.SETTING_NAMES["HUNTSMAN_VISUAL"]) then
return
end
return func(...)
end)
--- Stop moods from getting activated.
local name_to_mood = {
SLAYER = "skill_slayer",
ZEALOT = "skill_zealot",
RANGER = "skill_ranger",
SHADE = "skill_shade",
}
mod:hook(StateInGameRunning, "update_mood", function (func, ...)
for name, mood in pairs( name_to_mood ) do
if mod:get(mod.SETTING_NAMES[name.."_VISUAL"]) then
MOOD_BLACKBOARD[mood] = false
end
end
if mod:get(mod.SETTING_NAMES["HUNTSMAN_VISUAL"]) then
MOOD_BLACKBOARD["skill_huntsman_surge"] = false
MOOD_BLACKBOARD["skill_huntsman_stealth"] = false
end
if mod:get(mod.SETTING_NAMES.WOUNDED) then
MOOD_BLACKBOARD["wounded"] = false
end
if mod:get(mod.SETTING_NAMES.KNOCKED_DOWN) then
MOOD_BLACKBOARD["knocked_down"] = false
end
if mod:get(mod.SETTING_NAMES.HEALING) then
MOOD_BLACKBOARD["heal_medikit"] = false
end
return func(...)
end)
--- Skip ult audio distortions.
--- Skip potions audio.
mod.name_to_event = {
SLAYER_AUDIO = { "Play_career_ability_bardin_slayer_loop", "Stop_career_ability_bardin_slayer_loop" },
HUNTSMAN_AUDIO = { "Play_career_ability_markus_huntsman_loop", "Stop_career_ability_markus_huntsman_loop" },
SHADE_AUDIO = { "Play_career_ability_kerillian_shade_loop", "Stop_career_ability_kerillian_shade_loop" },
RANGER_AUDIO = { "Play_career_ability_bardin_ranger_loop", "Stop_career_ability_bardin_ranger_loop" },
ZEALOT_AUDIO = { "Play_career_ability_victor_zealot_loop", "Stop_career_ability_victor_zealot_loop" },
}
mod.pot_to_event = {
STR_POT_AUDIO = "hud_gameplay_stance_smiter_activate",
SPEED_POT_AUDIO = "hud_gameplay_stance_ninjafencer_activate",
CDR_POT_AUDIO = "hud_gameplay_stance_ninjafencer_activate",
}
mod.crank_gun_firing_sound_events = {
["Play_player_engineer_shooting_burst"] = true,
["Play_player_engineer_shooting_armor_piercing"] = true,
}
mod:hook(PlayerUnitFirstPerson, "play_hud_sound_event", function (func, self, event_name, ...)
-- ults
for name, event_names in pairs( mod.name_to_event ) do
if mod:get(mod.SETTING_NAMES[name]) then
for _, ult_event_name in ipairs( event_names ) do
if ult_event_name == event_name then
return
end
end
end
end
-- potions
for name, pot_event in pairs( mod.pot_to_event ) do
if mod:get(mod.SETTING_NAMES[name]) and event_name == pot_event then
return
end
end
if mod.crank_gun_firing_sound_events[event_name] and mod:get(mod.SETTING_NAMES.MUTE_CRANK_GUN_SHOOTING) then
return
end
return func(self, event_name, ...)
end)
--- Skip huntsman, ranger, shade ult swirly screen effect.
--- Skip potions visuals.
mod.ult_name_to_fx = {
HUNTSMAN_VISUAL = { "fx/screenspace_huntsman_skill_01", "fx/screenspace_huntsman_skill_02" },
SHADE_VISUAL = { "fx/screenspace_shade_skill_01", "fx/screenspace_shade_skill_02" },
RANGER_VISUAL = { "fx/screenspace_ranger_skill_01", "fx/screenspace_ranger_skill_02" },
IRONBREAKER_VISUAL = { "fx/screenspace_potion_03" },
}
mod.pot_name_to_fx = {
STR_POT_VISUAL = "fx/screenspace_potion_01",
SPEED_POT_VISUAL = "fx/screenspace_potion_02",
CDR_POT_VISUAL = "fx/screenspace_potion_02",
}
mod:hook(BuffExtension, "_play_screen_effect", function (func, self, effect)
-- ults
for name, fxs in pairs( mod.ult_name_to_fx ) do
if mod:get(mod.SETTING_NAMES[name]) then
for _, fx in ipairs( fxs ) do
if fx == effect then
return
end
end
end
end
if effect == "fx/thornsister_avatar_screenspace" and mod:get(mod.SETTING_NAMES.HIDE_SIS_RADIANCE_ENTER) then
return
end
if effect == "fx/thornsister_avatar_screenspace_loop" and mod:get(mod.SETTING_NAMES.HIDE_SIS_RADIANCE_LOOP) then
return
end
-- potions
for name, pot_fx in pairs( mod.pot_name_to_fx ) do
if mod:get(mod.SETTING_NAMES[name]) and effect == pot_fx then
return
end
end
return func(self, effect)
end)
mod:dofile("scripts/mods/"..mod:get_name().."/no_potion_glow")
mod:dofile("scripts/mods/"..mod:get_name().."/no_ult_vo")
mod:dofile("scripts/mods/"..mod:get_name().."/overcharge")
|
#!/usr/bin/env tarantool
test = require("sqltester")
test:plan(1)
-- Check that OP_NextIdEphemeral generates unique ids.
--
test:execsql [[
CREATE TABLE T1(A INT PRIMARY KEY);
CREATE TABLE T2(A INT PRIMARY KEY, B INT);
INSERT INTO T1 VALUES(12);
INSERT INTO T2 VALUES(1, 5);
INSERT INTO T2 VALUES(2, 2);
INSERT INTO T2 VALUES(3, 2);
INSERT INTO T2 VALUES(4, 2);
]]
test:do_execsql_test(
"gh-3297-1",
[[
SELECT * FROM ( SELECT A FROM T1 LIMIT 1), (SELECT B FROM T2 LIMIT 10);
]],
{
12, 2,
12, 2,
12, 2,
12, 5
}
)
test:finish_test()
|
local component = require("component")
local net = {} --library table
--[[Layer 1 implementation]]
local drivers = {} --driver cache
local devices = { --network devices
["by_address"] = {},
["by_type"] = {}
}
net.drivers = drivers
net.devices = devices
function net.registerDevice(address, c_type, driver_path)
if drivers[c_type] == nil then
drivers[c_type] = loadfile(driver_path)()
end
local device = {
["address"] = address,
["type"] = c_type,
["driver"] = drivers[c_type]
}
--create proxy to driver for device methods
device = setmetatable(device, {
__index = function(self, method)
--device object should only access driver component methods
if self.driver.methods(self.address)[method] ~= nil then
return function(...)
return self.driver[method](self.address, ...)
end
else
return nil
end
end
})
--instert device into devices table
devices.by_address[address] = device
if not devices.by_type[c_type] then
devices.by_type[c_type] = {n = 0}
end
devices.by_type[c_type][address] = device
devices.by_type[c_type].n = devices.by_type[c_type].n + 1
end
function net.removeDevice(address)
local device = devices.by_address[address]
local c_type = device.type
local n = devices.by_type[c_type].n - 1
if n == 0 then --if last device of c_type
net.removeDriver(c_type)
else
devices.by_type[c_type][address] = nil
devices.by_type[c_type].n = n
devices.by_address[address] = nil
end
end
function net.removeDriver(c_type)
drivers[c_type].deactivate() --call deactivation function to clean up listeners
drivers[c_type] = nil
--remove any devices relating to the driver
--remove device count for iteration (no longer neccesary anyway)
devices.by_type[c_type].n = nil
for address, device in pairs(devices.by_type[c_type]) do
devices.by_address[address] = nil
devices.by_type[c_type][address] = nil
end
devices.by_type[c_type] = nil
end
return net
|
require("data/recycle-gases")
|
local tl = require("tl")
local util = require("spec.util")
describe("require", function()
it("reports module not found", util.check_type_error([[
local notfound = require "modulenotfound"
]], {
{ y = 1, msg = "module not found: 'modulenotfound'" }
}))
it("for .tl files, complain if required module has no type information", function ()
-- ok
util.mock_io(finally, {
["box.lua"] = [[
local box = {}
function box.foo(n)
return "hello number " .. tostring(n)
end
return box
]],
["foo.tl"] = [[
local Box = require "box"
Box.foo(123)
]],
})
local result, err = tl.process("foo.tl")
assert.same(0, #result.syntax_errors)
assert.same({
{ filename = "foo.tl", y = 1, x = 33, msg = "no type information for required module: 'box'" },
}, result.type_errors)
end)
it("exports functions", function ()
-- ok
util.mock_io(finally, {
["box.tl"] = [[
local box = {}
function box.foo(n: number): string
return "hello number " .. tostring(n)
end
return box
]],
["foo.tl"] = [[
local Box = require "box"
Box.foo(123)
]],
})
local result, err = tl.process("foo.tl")
assert.same(0, #result.syntax_errors)
assert.same(0, #result.type_errors)
end)
it("exports types", function ()
-- ok
util.mock_io(finally, {
["point.tl"] = [[
local type Point = record
x: number
y: number
end
local point = {
Point = Point,
}
function Point:move(x: number, y: number)
self.x = self.x + x
self.y = self.y + y
end
return point
]],
["foo.tl"] = [[
local point = require "point"
function bla(p: point.Point)
print(p.x, p.y)
end
]],
})
local result, err = tl.process("foo.tl")
assert.same({}, result.syntax_errors)
assert.same({}, result.type_errors)
end)
it("local types can be exported indirectly, but not their names", function ()
util.mock_io(finally, {
["box.tl"] = [[
local box = {}
local type Box = record
x: number
y: number
w: number
h: number
end
function box.foo(self: Box): Box
return self
end
return box
]],
["foo.tl"] = [[
local box = require "box"
-- passing a table that matches the local type works
local b = box.foo({ x = 10, y = 10, w = 123, h = 120 })
-- you can declare a variable based on another value's type
local anotherbox = b
anotherbox = { x = 10, y = 10, w = 123, h = 120 }
]],
})
local result, err = tl.process("foo.tl")
assert.same({}, result.syntax_errors)
assert.same({}, result.type_errors)
end)
it("exported types resolve regardless of module name", function ()
-- ok
util.mock_io(finally, {
["point.tl"] = [[
local type Point = record
x: number
y: number
end
local point = {
Point = Point,
}
function Point:move(x: number, y: number)
self.x = self.x + x
self.y = self.y + y
end
return point
]],
["bar.tl"] = [[
local bar = {}
local mypoint = require "point"
function bar.get_point(): mypoint.Point
return { x = 100, y = 100 }
end
return bar
]],
["bla.tl"] = [[
local type bla = record
record subtype
xx: number
end
end
function bla.func(): bla.subtype
return { xx = 2 }
end
return bla
]],
["foo.tl"] = [[
local pnt = require "point"
local bar = require "bar"
local bla1 = require "bla"
function use_point(p: pnt.Point)
print(p.x, p.y)
print(bla1.func().xx)
end
use_point(bar.get_point():move(5, 5))
]],
})
local result, err = tl.process("foo.tl")
assert.same({}, result.syntax_errors)
assert.same({}, result.type_errors)
end)
it("local types can get exported", function ()
-- ok
util.mock_io(finally, {
["point.tl"] = [[
local type Point = record
x: number
y: number
end
local point = {
Point = Point,
}
function Point:move(x: number, y: number)
self.x = self.x + x
self.y = self.y + y
end
return point
]],
["bar.tl"] = [[
local mypoint = require "point"
local type rec = record
xx: number
yy: number
end
local function get_point(): mypoint.Point
return { x = 100, y = 100 }
end
return {
get_point = get_point,
rec = rec,
}
]],
["foo.tl"] = [[
local pnt = require "point"
local bar = require "bar"
function use_point(p: pnt.Point)
print(p.x, p.y)
end
use_point(bar.get_point():move(5, 5))
local r: bar.rec = {
xx = 10,
yy = 20,
}
]],
})
local result, err = tl.process("foo.tl")
assert.same({}, result.syntax_errors)
assert.same({}, result.type_errors)
end)
it("equality of nominal types does not depend on module names", function ()
-- ok
util.mock_io(finally, {
["point.tl"] = [[
local type Point = record
x: number
y: number
end
local point = {
Point = Point,
}
return point
]],
["foo.tl"] = [[
local point1 = require "point"
local point2 = require "point"
local a: point1.Point = { x = 1, y = 2 }
local b: point2.Point = a
]],
})
local result, err = tl.process("foo.tl")
assert.same({}, result.syntax_errors)
assert.same({}, result.type_errors)
end)
it("does not get confused by similar names", function ()
-- ok
util.mock_io(finally, {
["point.tl"] = [[
local type Point = record
x: number
y: number
end
local point = {
Point = Point,
}
function point.f(p: Point): number
return p.x + p.y
end
return point
]],
["foo.tl"] = [[
local point1 = require "point"
local type Point = record
foo: string
end
local a: point1.Point = { x = 1, y = 2 }
local myp: Point = { foo = "hello" }
point1.f(myp)
]],
})
local result, err = tl.process("foo.tl")
assert.same({}, result.syntax_errors)
assert.same(1, #result.type_errors)
assert.match("Point (defined in foo.tl:3) is not a Point (defined in ./point.tl:1)", result.type_errors[1].msg, 1, true)
end)
it("catches errors in exported functions", function ()
util.mock_io(finally, {
["box.tl"] = [[
local box = {}
function box.foo(n: number): string
return "hello number " .. box.foo
end
return box
]],
["foo.tl"] = [[
local Box = require "box"
Box.foo(123)
]],
})
local result, err = tl.process("foo.tl")
assert.same(0, #result.syntax_errors)
assert.same(1, #result.env.loaded["./box.tl"].type_errors)
assert.match("cannot use operator ..", result.env.loaded["./box.tl"].type_errors[1].msg)
end)
it("exports global types", function ()
-- ok
util.mock_io(finally, {
["box.tl"] = [[
local box = {}
-- global type
global type Box = record
x: number
y: number
w: number
h: number
end
function box.foo(self: Box): string
return "hello " .. tostring(self.w)
end
return box
]],
["foo.tl"] = [[
local box = require "box"
box.foo({ x = 10, y = 10, w = 123, h = 120 })
]],
})
local result, err = tl.process("foo.tl")
assert.same(0, #result.syntax_errors)
assert.same(0, #result.type_errors)
end)
it("exports scoped types", function ()
-- ok
util.mock_io(finally, {
["box.tl"] = [[
local record box
record Box
x: number
y: number
w: number
h: number
end
end
function box.foo(self: box.Box): string
return "hello " .. tostring(self.w)
end
return box
]],
["foo.tl"] = [[
local Box = require "box"
Box.foo({ x = 10, y = 10, w = 123, h = 120 })
]],
})
local result, err = tl.process("foo.tl")
assert.same(0, #result.syntax_errors)
assert.same(0, #result.type_errors)
end)
it("nested types resolve in definition files", function ()
-- ok
util.mock_io(finally, {
["someds.d.tl"] = [[
local type someds = record
type Event = record
end
type Callback = function(Event)
subscribe: function(callback: Callback)
end
return someds
]],
["main.tl"] = [[
local someds = require("someds")
function main()
local b:someds.Callback = function(event: someds.Event)
end
someds.subscribe(b)
end
]],
})
local result, err = tl.process("main.tl")
assert.same(0, #result.syntax_errors)
assert.same(0, #result.type_errors)
end)
it("nested types resolve in definition files required with different name", function ()
-- ok
util.mock_io(finally, {
["someds.d.tl"] = [[
local type someds = record
type Event = record
end
type Callback = function(Event)
subscribe: function(callback: Callback)
end
return someds
]],
["main.tl"] = [[
local som = require("someds")
function main()
local b:som.Callback = function(event: som.Event)
end
som.subscribe(b)
end
]],
})
local result, err = tl.process("main.tl")
assert.same(0, #result.syntax_errors)
assert.same(0, #result.type_errors)
end)
it("nested types with metamethods resolve in definition files required with different names (#326)", function ()
-- ok
util.mock_io(finally, {
["my_huge_lib_name.d.tl"] = [[
local record my_huge_lib_name
record nested_type
f: function(my_huge_lib_name.nested_type, my_huge_lib_name.nested_type)
metamethod __add: function(my_huge_lib_name.nested_type, number)
end
new: function(): my_huge_lib_name.nested_type
end
return my_huge_lib_name
]],
["main.tl"] = [[
local lib = require 'my_huge_lib_name'
local v = lib.new()
v:f(v) -- this works fine
print(v + 2)
]],
})
local result, err = tl.process("main.tl")
assert.same({}, result.syntax_errors)
assert.same({}, result.type_errors)
end)
it("generic nested types resolve in definition files", function ()
-- ok
util.mock_io(finally, {
["someds.d.tl"] = [[
local type someds = record
type Event = record<T>
x: T
end
type Callback = function(Event<string>)
subscribe: function(callback: Callback)
end
return someds
]],
["main.tl"] = [[
local someds = require("someds")
function main()
local b:someds.Callback = function(event: someds.Event<string>)
end
someds.subscribe(b)
end
]],
})
local result, err = tl.process("main.tl")
assert.same({}, result.syntax_errors)
assert.same({}, result.type_errors)
end)
it("cannot extend a record object with unknown types outside of scope", function ()
util.mock_io(finally, {
["love.d.tl"] = [[
global type LoveGraphics = record
print: function(text: string)
end
global type Love = record
draw: function()
graphics: LoveGraphics
end
global love: Love
]],
["foo.tl"] = [[
function love.draw()
love.graphics.print("<3")
end
function love.draws()
love.graphics.print("</3")
end
]],
})
local result, err = tl.process("foo.tl", assert(tl.init_env(false, nil, nil, {"love"})))
assert.same(nil, err)
assert.same({}, result.syntax_errors)
assert.match("cannot add undeclared function 'draws' outside of the scope where 'love' was originally declared", result.type_errors[1].msg)
end)
it("cannot extend a record type with unknown types outside of scope", function ()
util.mock_io(finally, {
["love.d.tl"] = [[
global type love_graphics = record
print: function(text: string)
end
global type love = record
draw: function()
graphics: love_graphics
end
]],
["foo.tl"] = [[
function love.draw()
love.graphics.print("<3")
end
function love.draws()
love.graphics.print("</3")
end
]],
})
local result, err = tl.process("foo.tl", assert(tl.init_env(false, nil, nil, {"love"})))
assert.same(nil, err)
assert.same({}, result.syntax_errors)
assert.same(1, #result.type_errors)
assert.match("cannot add undeclared function 'draws' outside of the scope where 'love' was originally declared", result.type_errors[1].msg)
end)
it("cannot extend a record type outside of scope", function ()
util.mock_io(finally, {
["widget.tl"] = [[
local type Widget = record
draw: function(self: Widget)
end
return Widget
]],
["foo.tl"] = [[
local Widget = require("widget")
function Widget:totally_unrelated_function()
print("heyo")
end
]],
})
local result, err = tl.process("foo.tl")
assert.same(nil, err)
assert.same({}, result.syntax_errors)
assert.same(1, #result.type_errors)
assert.match("cannot add undeclared function 'totally_unrelated_function' outside of the scope where 'Widget' was originally declared", result.type_errors[1].msg)
end)
it("can redeclare a function that was previously declared outside of scope", function ()
util.mock_io(finally, {
["widget.tl"] = [[
local type Widget = record
draw: function(self: Widget)
end
return Widget
]],
["foo.tl"] = [[
local Widget = require("widget")
function Widget:draw()
print("heyo")
end
]],
})
local result, err = tl.process("foo.tl")
assert.same(nil, err)
assert.same({}, result.syntax_errors)
assert.same(0, #result.type_errors)
end)
it("can extend a global defined in scope", function ()
util.mock_io(finally, {
["luaunit.d.tl"] = [[
global type luaunit_runner_t = record
setOutputType: function(luaunit_runner_t, string)
runSuite: function(luaunit_runner_t, any): number
end
global type luaunit_t = record
new: function(): luaunit_runner_t
end
local type luaunit = record
LuaUnit: luaunit_t
assertIsTrue: function(any)
end
return luaunit
]],
["tests.tl"] = [[
local lu = require("luaunit")
local os = require("os")
-- it must be global to use luaunit
global TestSuite = {}
function TestSuite:test_count()
lu.assertIsTrue(100 == 200)
end
function main(args: any)
local runner = lu.LuaUnit.new()
runner:setOutputType("tap")
local code = runner:runSuite(args)
os.exit(code)
end
]],
})
local result, err = tl.process("tests.tl")
assert.same(nil, err)
assert.same({}, result.syntax_errors)
assert.same({}, result.type_errors)
end)
it("can use type definitions to do dynamic dispatch on module returns (#334)", function()
util.mock_io(finally, {
["minimal/type/Front.d.tl"] = [[
local record Front
bool: boolean
end
return Front
]],
["minimal/back.tl"] = [[
local Front = require "minimal.type.Front"
return function(bool: boolean): Front return {bool = bool} end
]],
["minimal/middle-true.tl"] = [[
return (require "minimal.back")(true)
]],
["minimal/middle-false.tl"] = [[
return (require "minimal.back")(false)
]],
["minimal/front.tl"] = [[
if true then return require "minimal.middle-true" else return require "minimal.middle-false" end
]],
["minimal/proof.tl"] = [[
local front = require "minimal.front"
print(front.bool)
]],
})
local result, err = tl.process("minimal/proof.tl")
assert.same(nil, err)
assert.same({}, result.syntax_errors)
assert.same({}, result.type_errors)
end)
end)
|
-- AI Variables (These must be set here) --
_ready = false;
targetAI = nil;
mCharacter = nil;
isAngry = nil; --IO (these are grabbed and sent to game after Execute)
isAlerted = nil; --IO
aiTarget = nil; --I (these are input only)
aiTargetTable = nil; --I
-- Inputs
atkFeedbackTable = nil;
atkRangeTable = nil;
--only new function is _npc_ai_PerformAttack
-- Local variables
m_isSearching = false;
m_searchState = 0;
m_searchTimer = 0;
m_attackState = 0;
m_attackStatePrev = 0;
--m_circlingTime = 0;
m_fleeDirection = nil;
m_stateTime = 0;
m_circleDistance = 0;
m_circleDirection = 0;
--m_nextCirclingTime = 0;
m_seekPosition = nil;
m_searchOffset = nil;
m_isMoving = false;
m_AtkfeedbackWaitingState = 0;
-- States for attack mode
local AI_SETUP = 0;
local AI_STANDING = 1;
local AI_RUN_AROUND = 2;
local AI_RUN_UP = 3;
local AI_RUN_AWAY = 4;
local AI_HIDE = 5;
local AI_ATTACK = 6;
function Initialize ( )
--print( "======================" );
--print( " AI ANGRY INIT" );
--print( "======================" );
m_attackState = AI_SETUP;
end
function Execute ( deltaTime )
if ( aiTarget == -1 or aiTarget == nil ) then
return 0;
end
local aggroTarget = aiTargetTable;
local character = ZonedCharacter.new(mCharacter);
-- Create seek position, and check if looking for the target again now
local vSeekPosition = {};
if ( aggroTarget.timeSinceSeen <= aggroTarget.timeSinceHeard ) then
vSeekPosition = Vector3d.fromTable(aggroTarget.lastSeenPosition);
if ( aggroTarget.timeSinceSeen < 3 ) then
m_isSearching = false;
else
m_isSearching = true;
end
else
vSeekPosition = Vector3d.fromTable(aggroTarget.lastHeardPosition);
m_isSearching = true;
end
if ( m_isSearching ) then
-- Search mode, search for the target
m_attackState = 0; -- Reset attack mode
if ( m_searchState == 0 ) then
-- Move to the seek position
if ( _npc_ai_MoveTo( targetAI, vSeekPosition.x,vSeekPosition.y,vSeekPosition.z ) ) then
m_searchState = 1; -- If at target position, then go to waiting for a moment state
m_searchTimer = 0;
m_searchOffset = nil; -- Reset searching offset
end
elseif ( m_searchState == 1 ) then
-- Wait at the seek position
m_searchTimer = m_searchTimer + deltaTime;
if ( m_searchTimer > 2 ) then --Wait for 2 seconds, then start drifting randomly
m_searchState = 2;
-- Create an offset to look at
if ( m_searchOffset == nil ) then
m_searchOffset = Vector3d.new( math.random(-10,10), math.random(-10,10), math.random(-2,2) );
else
m_searchOffset = m_searchOffset+Vector3d.new( math.random(-10,10), math.random(-10,10), math.random(-2,2) );
end
end
elseif ( m_searchState == 2 ) then
-- Go to the new offset
m_seekPosition = vSeekPosition + m_searchOffset;
-- Search to that random position
if ( _npc_ai_MoveTo( targetAI, m_seekPosition.x,m_seekPosition.y,m_seekPosition.z ) ) then
m_searchState = 1; -- If at target position, then go to waiting for a moment state
m_searchTimer = 0;
end
end
else
-- Attack mode, move up to target and attack
m_searchState = 0; -- Reset search mode
local t_previousState = m_attackState;
if ( m_attackState == AI_SETUP ) then
-- Setup state
m_circlingTime = 0;
m_stateTime = 0;
m_nextCirclingTime = math.random( 25,45 ) * 0.1;
m_attackState = AI_STANDING;
m_isMoving = false;
elseif ( m_attackState == AI_STANDING ) then
-- Face the target, don't move
_npc_ai_FaceAt( targetAI, vSeekPosition.x,vSeekPosition.y,vSeekPosition.z );
m_isMoving = false;
-- If change in state, reset timer
if ( m_attackStatePrev ~= m_attackState ) then
m_stateTime = 0;
end
-- After 2 seconds of standing, go run
m_stateTime = m_stateTime + deltaTime;
if ( m_stateTime > 2 ) then
-- Go to running away state
m_attackState = AI_RUN_AWAY;
end
-- TODO: Check for incoming damage
elseif ( m_attackState == AI_RUN_AWAY ) then
-- If change in state, reset timer
if ( m_attackStatePrev ~= m_attackState ) then
m_stateTime = 0;
m_fleeDirection = Vector3d.new( math.random(-1,1), math.random(-1,1), 0);
end
-- Fuck facing the target, run away
local vDeltaPos = character:GetPosition() - vSeekPosition;
local t_fleeResult = nil;
--
vDeltaPos.z = 0;
--t_fleeResult = vDeltaPos:normal();
t_fleeResult = m_fleeDirection + (vDeltaPos:normal() * 1.2);
t_fleeResult = t_fleeResult:normal();
local vTargetPosition = character:GetPosition() + (t_fleeResult * 17); -- Run away
--print( "Flee: " .. t_fleeResult.x .. " " .. t_fleeResult.y .. " " .. t_fleeResult.z );
-- Run away
--_npc_ai_FaceAt( targetAI, vTargetPosition.x,vTargetPosition.y,vTargetPosition.z );
_npc_ai_MoveTo( targetAI, vTargetPosition.x,vTargetPosition.y,vTargetPosition.z, true );
m_circleDistance = vDeltaPos:length();
--print( "Current circle dist: " .. m_circleDistance );
if ( m_circleDistance > 43 ) then
m_stateTime = m_stateTime + 50 * deltaTime;
end
-- After 3 seconds of running, either stand, hide, or run around
m_stateTime = m_stateTime + deltaTime;
if ( m_stateTime > 3 ) then
local chancer = math.random();
if ( chancer < 0.25 ) then
m_attackState = AI_HIDE;
elseif ( chancer < 0.75 ) then
m_attackState = AI_RUN_AROUND;
else
m_attackState = AI_STANDING;
end
end
elseif ( m_attackState == AI_RUN_AROUND ) then
-- If change in state, reset values
if ( m_attackStatePrev ~= m_attackState ) then
m_stateTime = math.random( 25,85 ) * 0.1;
if ( math.random() < 0.5 ) then
m_circleDirection = 1;
else
m_circleDirection = -1;
end
end
-- Circle around the target. (Generate a target position that curves around)
local vDeltaPos = character:GetPosition() - vSeekPosition;
vDeltaPos.z = 0;
vDeltaPos = (character:GetPosition() + vDeltaPos:normal() * m_circleDistance * 0.9);
vDeltaPos = vDeltaPos + (vDeltaPos:normal():cross( Vector3d.new(0,0,1) ) * 18 * m_circleDirection);
-- Go to the circling distance
m_seekPosition = vSeekPosition + vDeltaPos;
--_npc_ai_FaceAt( targetAI, m_seekPosition.x,m_seekPosition.y,m_seekPosition.z );
_npc_ai_MoveTo( targetAI, m_seekPosition.x,m_seekPosition.y,m_seekPosition.z, true );
-- Attack after amount of time
m_stateTime = m_stateTime - deltaTime;
if ( m_stateTime < 0 ) then
m_attackState = AI_RUN_UP;
end
-- TODO: check for incoming damage
elseif ( m_attackState == AI_HIDE ) then
-- Face the target, don't move
_npc_ai_FaceAt( targetAI, vSeekPosition.x,vSeekPosition.y,vSeekPosition.z );
m_isMoving = false;
-- Go to reduced damage mode
_npc_ai_PerformDefend( targetAI );
-- If change in state, reset timer
if ( m_attackStatePrev ~= m_attackState ) then
m_stateTime = 0;
end
-- After 1 seconds of standing, go attack
m_stateTime = m_stateTime + deltaTime;
if ( m_stateTime > 1 ) then
-- Go to running away state
m_attackState = AI_RUN_UP;
end
elseif ( m_attackState == AI_RUN_UP ) then
-- Need to go up and perform attack
local vDeltaPos = character:GetPosition() - vSeekPosition;
-- Get into melee range
m_seekPosition = vSeekPosition + (vDeltaPos:normal() * atkRangeTable.meleeRange * 0.8);
-- Face target
--_npc_ai_FaceAt( targetAI, vSeekPosition.x,vSeekPosition.y,vSeekPosition.z );
if ( _npc_ai_MoveTo( targetAI, m_seekPosition.x,m_seekPosition.y,m_seekPosition.z, true ) ) then
-- Go to attack state
m_attackState = AI_ATTACK;
end
elseif ( m_attackState == AI_ATTACK ) then
-- If change in state, reset timer
if ( m_attackStatePrev ~= m_attackState ) then
m_stateTime = 0;
m_AtkfeedbackWaitingState = 0;
end
-- Attacking. Go to target, attack. Keep attacking.
if ( m_AtkfeedbackWaitingState == 0 ) then
-- Need to go up and perform attack
local vDeltaPos = character:GetPosition() - vSeekPosition;
m_seekPosition = vSeekPosition + (vDeltaPos:normal() * atkRangeTable.meleeRange * 0.8);
_npc_ai_FaceAt( targetAI, vSeekPosition.x,vSeekPosition.y,vSeekPosition.z );
if ( _npc_ai_MoveTo( targetAI, m_seekPosition.x,m_seekPosition.y,m_seekPosition.z, true ) ) then
-- request attack
_npc_ai_PerformAttack( targetAI );
-- go to attack request check
m_AtkfeedbackWaitingState = 1;
end
elseif ( m_AtkfeedbackWaitingState == 1 ) then
-- check if attack request when through
if ( atkFeedbackTable.atk_waitForResult == true ) then
-- request went through. go to attack result check.
m_AtkfeedbackWaitingState = 2;
else
-- didn't go through, go back to request
m_AtkfeedbackWaitingState = 0;
m_stateTime = m_stateTime + 1;
end
else
if ( atkFeedbackTable.atk_waitForResult == false or atkFeedbackTable.atk_hit == true ) then
if ( aiAttackHit == true ) then
-- attack hit. who cares. keep attacking
--m_AtkfeedbackWaitingState = 0;
m_attackState = AI_RUN_AWAY;
else
-- keep attacking
--m_AtkfeedbackWaitingState = 0;
-- Missed, run away
m_attackState = AI_RUN_AWAY;
end
end
end
-- This counts the misses here. If there's 2 or more failures, run away
if ( m_stateTime >= 2 ) then
m_attackState = AI_RUN_AWAY;
end
end -- attacking state machine
m_attackStatePrev = t_previousState;
end -- attacking state
-- if ( m_attackState == AI_SETUP ) then
-- print( "Current attack state: AI_SETUP" );
-- elseif ( m_attackState == AI_STANDING ) then
-- print( "Current attack state: AI_STANDING" );
-- elseif ( m_attackState == AI_RUN_AROUND ) then
-- print( "Current attack state: AI_RUN_AROUND" );
-- elseif ( m_attackState == AI_RUN_UP ) then
-- print( "Current attack state: AI_RUN_UP" );
-- elseif ( m_attackState == AI_RUN_AWAY ) then
-- print( "Current attack state: AI_RUN_AWAY" );
-- elseif ( m_attackState == AI_HIDE ) then
-- print( "Current attack state: AI_HIDE" );
-- elseif ( m_attackState == AI_ATTACK ) then
-- print( "Current attack state: AI_ATTACK" );
-- else
-- print( "Current attack state: UNKNOWN" );
-- end
return 0;
end
print( "human_melee_angry.lua loaded" ); |
local Output = require('luatest.output.generic'):new_class()
Output.BOLD_CODE = '\x1B[1m'
Output.ERROR_COLOR_CODE = Output.BOLD_CODE .. '\x1B[31m' -- red
Output.SUCCESS_COLOR_CODE = Output.BOLD_CODE .. '\x1B[32m' -- green
Output.RESET_TERM = '\x1B[0m'
function Output.mt:start_suite()
if self.runner.seed then
print('Running with --shuffle ' .. self.runner.shuffle .. ':' .. self.runner.seed)
end
if self.verbosity >= self.class.VERBOSITY.VERBOSE then
print('Started on '.. os.date(nil, self.result.start_time))
end
end
function Output.mt:start_test(test) -- luacheck: no unused
if self.verbosity >= self.class.VERBOSITY.VERBOSE then
io.stdout:write(" ", test.name, " ... ")
end
end
function Output.mt:end_test(node)
if node:is('success') then
if self.verbosity >= self.class.VERBOSITY.VERBOSE then
io.stdout:write("Ok\n")
else
io.stdout:write(".")
io.stdout:flush()
end
else
if self.verbosity >= self.class.VERBOSITY.VERBOSE then
print(node.status)
print(node.message)
else
-- write only the first character of status E, F or S
io.stdout:write(string.sub(node.status, 1, 1):upper())
io.stdout:flush()
end
end
end
function Output.mt:display_one_failed_test(index, fail) -- luacheck: no unused
print(index..") " .. fail.name .. self.class.ERROR_COLOR_CODE)
print(fail.message .. self.class.RESET_TERM)
print(fail.trace)
print()
end
function Output.mt:display_errored_tests()
if #self.result.tests.error > 0 then
print(self.class.BOLD_CODE)
print("Tests with errors:")
print("------------------")
print(self.class.RESET_TERM)
for i, v in ipairs(self.result.tests.error) do
self:display_one_failed_test(i, v)
end
end
end
function Output.mt:display_failed_tests()
if #self.result.tests.fail > 0 then
print(self.class.BOLD_CODE)
print("Failed tests:")
print("-------------")
print(self.class.RESET_TERM)
for i, v in ipairs(self.result.tests.fail) do
self:display_one_failed_test(i, v)
end
end
end
function Output.mt:end_suite()
if self.verbosity >= self.class.VERBOSITY.VERBOSE then
print("=========================================================")
else
print()
end
self:display_errored_tests()
self:display_failed_tests()
print(self:status_line({
success = self.class.SUCCESS_COLOR_CODE,
failure = self.class.ERROR_COLOR_CODE,
reset = self.class.RESET_TERM,
}))
if self.result.notSuccessCount == 0 then
print('OK')
end
local list = table.copy(self.result.tests.fail)
for _, x in pairs(self.result.tests.error) do
table.insert(list, x)
end
if #list > 0 then
table.sort(list, function(a, b) return a.name < b.name end)
if self.verbosity >= self.class.VERBOSITY.VERBOSE then
print("\n=========================================================")
else
print()
end
print(self.class.BOLD_CODE .. 'Failed tests:\n' .. self.class.ERROR_COLOR_CODE)
for _, x in pairs(list) do
print(x.name)
end
io.stdout:write(self.class.RESET_TERM)
end
end
return Output
|
GM.Version = "0.1.0"
GM.Name = "Space Explorers"
GM.Author = "The HellBox"
DeriveGamemode("base")
include("base/client/ship_state_update.lua")
include("base/client/race_choose_menu.lua")
include("base/client/draw_space_body.lua")
include("base/client/ship_uis.lua")
include("base/client/hud.lua")
include("lib/draw.lua")
include("lib/support.lua")
hook.Add( "CreateClientsideRagdoll", "se_fade_out_corpses", function( entity, ragdoll )
timer.Simple(10, function()
if IsValid(ragdoll) then
ragdoll:SetSaveValue( "m_bFadingOut", true )
end
end)
end )
|
--[[
License : GLPv3, see LICENCE in root of repository
Authors : Nikolay Fiykov, v1
--]]
local nodemcu = require("nodemcu-module")
enduser_setup = {}
enduser_setup.__index = enduser_setup
--- enduser_setup.manual is stock nodemcu API
enduser_setup.manual = function(on_off)
nodemcu.eus_manual = on_off
end
--- enduser_setup.start is stock nodemcu API
-- @param onConnected()
-- @param onError(err_num, string)
-- @param onDebug(string)
enduser_setup.start = function(onConnected, onError, onDebug)
end
--- enduser_setup.stop is stock nodemcu API
enduser_setup.stop = function()
end
return enduser_setup
|
local luadev = require('lua-dev').setup({
plugins = true,
lspconfig = {
settings = {
Lua = {
diagnostics = {
globals = { 'vim', 'bufnr' },
},
},
},
},
})
return luadev
|
dofilepath("data:ui/newui/Styles/HWRM_Style/HWRMDefines.lua")
dofilepath("data:ui/newui/Styles/HWRM_Style/ControlConstructors.lua")
LAYOUT_MENU_CONNECTION_BUTTONS =
{
min_WH = { w = MAINMENU_BUTTON_WIDTH, h = STD_BUTTON_HEIGHT, wr = "scr", hr = "scr" },
}
ConnectionType = {
stylesheet = "HW2StyleSheet",
Layout = {
pos_XY = { x=0.0, y=0.0, xr="px", yr="px",},
size_WH = {w = 1, h = 1, wr = "scr", hr = "scr",},
},
pixelUVCoords = 1,
-- the message that will be displayed in a player joins and their name is already in use.
nameInUseFormatID = 3549,
ErrorMessages =
{
[ LM_AuthCD ] = "$3542",--"Authenticating CD key",
[ LM_UnableToConnect ] = "$3543",--"Unable to connect to server",
[ LM_InvalidNickname ] = "$3544",--"You need to set a proper chat name",
[ LM_Connecting ] = "$3545",--"Connecting to Server",
[ LM_AuthCDFailed ] = "$3546",--"CD Key authentication failed",
[ LM_Disconnected ] = "$3547",--"Disconnected from server",
[ LM_InvalidCDKey ] = "$3548",--"Your CD Key is invalid",
},
previousScreen = "NewMainMenu",
;
-- ERSB Warning label
{
type = "TextLabel",
Layout = {
pivot_XY = { 0, 1 },
pos_XY = { x=0, y=1, xr="par", yr="par",},
},
autosize = 1,
Text = {
font = "ChatFont",
color = {255,255,255,255},
text = "$1220", --* Game Experience May Change During Online Play
hAlign = "Left",
vAlign = "Middle",
},
},
------------------------------------------------------------------------------------
-- SCREEN HEADER
------------------------------------------------------------------------------------
{
type = "RmWindow",
WindowTemplate = SCREENHEADER_WINDOWSTYLE,
TitleText = "$2614", -- MULTIPLAYER
SubTitleText = "$3530", -- MANAGE PLAYER PROFILES
Extra1Text = "$2622", -- BETA
Layout = {
size_WH = { w = 1.0, h = 180.0/540, wr = "par", hr = "scr" },
},
--autosize=1,
;
},
------------------------------------------------------------------------------------
-- MAIN WINDOW FRAME (Window and Navigation Panel)
------------------------------------------------------------------------------------
{
type = "Frame",
name = "frmRootbottombigfrm",
Layout = {
pivot_XY = { 0.5, 0.5 },
pos_XY = { x=0.5, y=0.5, xr="par", yr="par",},
},
autosize=1,
arrangetype = "vert",
--arrangeSep = { x=0, y=PANEL_SPACING_VERT, xr="scr", yr="scr",},
;
------------------------------------------------------------------------------------
-- WINDOW FRAME
------------------------------------------------------------------------------------
{
type = "RmWindow",
WindowTemplate = PANEL_WINDOWSTYLE,
TitleText = "$3530",
-- SubtitleText = "$3531",
autosize=1,
;
{
type = "Frame",
autosize = 1,
autoarrange = 1,
arrangetype = "vert",
autoarrangeWidth = MAINMENU_BUTTON_WIDTH,
arrangeSep = { x=0, y= 6/540, xr="scr", yr="scr"},
autoarrangeSpace = 6,
Layout = {
pad_LT = { l = BUTTON_TEXT_PAD_HORIZ, t = BUTTON_TEXT_PAD_VERT, lr = "scr", tr = "scr" },
pad_RB = { r = BUTTON_TEXT_PAD_HORIZ, b = 0, rr = "scr", br = "scr" },
},
;
-- Buttons:
NewMenuButton("m_itemLAN", "$3533", "$3532", 0, LAYOUT_MENU_CONNECTION_BUTTONS, "FEButtonStyle1", nil),
NewMenuButton("m_itemSteam", "$3537", "$3536", 0, LAYOUT_MENU_CONNECTION_BUTTONS, "FEButtonStyle1", nil),
NewMenuButton("m_itemTCP", "$3535", "$3534", 0, LAYOUT_MENU_CONNECTION_BUTTONS, "FEButtonStyle1", "UI_ShowScreen('DirectConnection', eTransition)"),
},
},
------------------------------------------------------------------------------------
-- BOTTOM NAVIGATION FRAME
------------------------------------------------------------------------------------
{
type = "RmWindow",
name = "frmRootbottombigfrm",
WindowTemplate = PANEL_NAVIGATIONFRAME,
;
-- Back Button
NewMenuButton("m_btnCancel", "$3539", "$3043", 0, BTN_FOOTER_STD_SMALL_LAYOUT, "FEButtonStyle1_Outlined_Chipped", "UI_PreviousScreen(eTransition);"),
},
},
} |
function clamp(x,l,u)
return max(l,min(x,u))
end
function sign(x)
if(x >= 0) then return 1
else return -1 end
end
function nsin(x)
return sin(-x)
end
function atan3(x,y)
return atan2(x,-y)
end |
appname="QQ闪照查看器"
appver="1.0"
appcode="1"
appsdk="15"
packagename="com.sz"
debugmode=true
user_permission={
"WRITE_EXTERNAL_STORAGE",
} |
-- led_sweep = coroutine.wrap( function()
-- for i=1,255 do
-- for j=1,255 do
-- for k=1,255 do
-- out = string.char(31, i, j, k)
-- apa102.write(7,6,out)
-- coroutine.yield()
-- end
-- end
-- end
-- end)
max_bright = 255
function mod(a ,b)
m=a-(a/b)*b
return m
end
function normal(a)
if a < 0 then
return 0
elseif a > max_bright then
return mod(a, max_bright)
else
return a
end
end
function make_sweep()
inc_channel = 1
channel = 2
dec_channel =3
channels = { max_bright; max_bright; max_bright }
return function()
channels[inc_channel] = normal(channels[inc_channel] + 1)
channels[dec_channel] = normal(channels[dec_channel] - 1)
if channels[dec_channel] == 1 then
inc_channel = mod(inc_channel+1,3)+1
channel = mod(channel+1,3)+1
dec_channel = mod(dec_channel+1,3)+1
end
out = string.rep(string.char(10, channels[1], channels[2], channels[3]), 6)
apa102.write(7,6,out)
end
end
tmr.alarm(0, 10, tmr.ALARM_AUTO, make_sweep())
|
local file_path = "sample.json"
local file = io.open(file_path, "r")
if not file then print("File '".. file_path .. "' not found!") return end
local file_content = file:read "*all"
io.close(file)
local json = require("json")
local obj = json:decode(file_content)
local function join_strs(arr)
local strs = {}
for _, str in ipairs(arr) do strs[#strs+1] = "\"" .. str .. "\"" end
return "[" .. table.concat(strs, ", ") .. "]"
end
print("\b Displaying file content:\n" .. file_content .. "\n")
print("\a obj[\"name\"] -> " .. obj["name"] .. "\n")
print("\a obj[\"callback\"][\"method\"] -> " .. obj["callback"]["method"] .. "\n")
print("\a obj[\"callback\"][\"params\"] -> " .. join_strs(obj["callback"]["params"]) .. "\n")
print("\a obj[\"lua_script\"] -> " .. obj["lua_script"] .. "\n")
local obj_method = obj["callback"]["method"]
local obj_params = obj["callback"]["params"]
local obj_script = obj["lua_script"]
print(obj_params)
function abc(args)
local a = args[1]
local b = args[2]
local c = args[3]
print("A -> " .. a)
print("B -> " .. b)
print("C -> " .. tostring(c))
print("C + 5 -> " .. tostring(c + 5))
end
_G[obj_method](obj_params)
if not obj_script ~= nil then
local script = load(obj_script)
script()
end |
ENT.Type = "point"
ENT.Base = "base_point"
ENT.Items = { "ph_luckyball", "ph_devilball", "ph_ultpointball" }
function ENT:Initialize() end
function ENT:SetupDataTables()
self:NetworkVar( "Int", 0, "SpawnEntity" )
self:NetworkVar( "Int", 1, "Amount" )
self:NetworkVar( "String", 0, "EntityName" )
end
function ENT:KeyValue( key, value )
if key == "spawnent" then
self:SetSpawnEntity( value )
elseif key == "amount" then
self:SetAmount( value )
elseif key == "spawnontarget" then
self:SetEntityName( value )
else
self:SetNetworkKeyValue(key, value)
end
end
function ENT:CreateBall( entToSpawn, pos, ang )
if SERVER then
local e = ents.Create( entToSpawn )
e:SetPos(pos)
e:SetAngles(ang)
e:Spawn()
e:Activate()
end
end
function ENT:makeEntity()
local entToSpawn = self.Items[ self:GetSpawnEntity() ]
local amount = self:GetAmount()
local SpawnOn = self:GetEntityName()
local pos = self:GetPos()
local ang = angle_zero
if SpawnOn and SpawnOn ~= nil then
local ent = ents.FindByName(SpawnOn)
local on = ent[math.random(1, #ent)]
pos = on:GetPos()
ang = on:GetAngles()
end
self:CreateBall( entToSpawn, pos, ang )
if amount > 0 then
for i=1,amount do
self:CreateBall( entToSpawn, pos, ang )
end
end
end
function ENT:AcceptInput(name, act, cal, data)
if name == "Spawn" then
self:makeEntity()
return true
elseif name == "SetAmount" then
self:SetAmount(tonumber(data))
return true
elseif name == "ChangeTarget" then
self:SetEntityName(tostring(data))
return true
elseif name == "SetType" then
self:SetSpawnEntity(tonumber(data))
return true
end
end |
local combat = Combat()
combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_ENERGYDAMAGE)
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_ENERGYHIT)
combat:setParameter(COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_ENERGY)
local condition = Condition(CONDITION_ENERGY)
condition:setParameter(CONDITION_PARAM_DELAYED, 1)
condition:addDamage(25, 3000, -45)
combat:setCondition(condition)
function onCastSpell(creature, var)
return combat:execute(creature, var)
end
|
local cfg = {}
-- PCs positions
cfg.pcs = {
{1853.21, 3689.51, 34.2671},
{442.030609130859, -978.72705078125, 30.6896057128906},
{-448.97076416016,6012.4208984375,31.71639251709}
}
-- vehicle tracking configuration
cfg.trackveh = {
min_time = 150, -- min time in seconds
max_time = 300, -- max time in seconds
service = "police" -- service to alert when the tracking is successful
}
-- wanted display
cfg.wanted = {
blipid = 458,
blipcolor = 38,
service = "police"
}
-- illegal items (seize)
cfg.seizable_items = {
"dirty_money",
"cannabis",
"metanfetamina",
"crystalmelamine",
"toclonecards",
"clonedcards",
"rede",
"lsd",
"lsdpro",
"cocaina",
"ecstasy",
"clonedcards",
"folhadecoca",
"Tartaruga",
"driver",
"weed"
}
-- jails {x,y,z,radius}
cfg.jails = {
{459.485870361328,-1001.61560058594,24.914867401123,2.1},
{459.305603027344,-997.873718261719,24.914867401123,2.1},
{459.999938964844,-994.331298828125,24.9148578643799,1.6}
}
-- fines
-- map of name -> money
cfg.fines = {
["Desacato."] = 0,
}--]]
return cfg
|
local parser = require("moocscript.parser")
local compile = require("moocscript.compile")
describe("test success #continue", function()
local mnstr=[[
i = 1
for i=1, 20, 1 {
if i < 15 {
continue
}
if i > 18 {
continue
}
}
while true {
i += 1
if i < 15 {
continue
}
if i < 18 {
continue
}
if i >= 20 {
break
}
}
repeat {
i += 1
if i < 15 {
continue
}
if i < 18 {
continue
}
if i >= 20 {
break
}
} until i >= 20
]]
local ret, ast = parser.parse(mnstr)
it("should get ast", function()
assert.is_true(ret)
assert.is_true(type(ast) == "table")
end)
local ret, content = compile.compile({}, ast)
it("should get compiled lua", function()
assert.is_true(ret)
assert.is_true(type(content) == "string")
end)
local f = load(content, "test", "t")
it("should get function", function()
assert(type(f) == "function")
local ClsA, ClsB = f()
end)
end)
describe("test success #continue", function()
local mnstr=[[
fn testContinue(a) {
for i=1, 20 {
if i < a {
continue
}
for j=20, 1, -1 {
if j > a {
continue
}
do {
return i + j + a
}
}
};
return 0
}
return testContinue
]]
local ret, ast = parser.parse(mnstr)
it("should get ast", function()
assert.is_true(ret)
assert.is_true(type(ast) == "table")
end)
local ret, content = compile.compile({}, ast)
it("should get compiled lua", function()
assert.is_true(ret)
assert.is_true(type(content) == "string")
end)
local f = load(content, "test", "t")
it("should get function", function()
assert(type(f) == "function")
local f = f()
assert.is_equal(f(8), 24)
assert.is_equal(f(16), 48)
end)
end)
describe("test failed 1 #continue", function()
local mnstr=[[
fn failedContinue(a) {
if a < 2 {
continue
}
}
]]
local ret, ast = parser.parse(mnstr)
it("should get ast", function()
assert.is_true(ret)
assert.is_true(type(ast) == "table")
end)
it("has error", function()
local ret, content = compile.compile({}, ast)
assert.is_false(ret)
assert.is_equal(content, "_:3: continue <not in loop 'continue'>")
end)
end)
describe("test failed return #continue", function()
local mnstr=[[
fn failedContinue(a) {
for i=1, 2 {
if a < 2 {
continue
}
return a
}
}
]]
local ret, ast = parser.parse(mnstr)
it("should get ast", function()
assert.is_true(ret)
assert.is_true(type(ast) == "table")
end)
it("has error", function()
local ret, content = compile.compile({}, ast)
assert.is_false(ret)
assert.is_equal(content, "_:6: return a <try do { return } for continue will insert label after 'return'>")
end)
end)
describe("test failed break #continue", function()
local mnstr=[[
fn failedContinue(a) {
for i=1, 2 {
if a < 2 {
continue
}
break
}
}
]]
local ret, ast = parser.parse(mnstr)
it("should get ast", function()
assert.is_true(ret)
assert.is_true(type(ast) == "table")
end)
it("has error", function()
local ret, content = compile.compile({}, ast)
assert.is_false(ret)
assert.is_equal(content, "_:6: break <try do { break } for continue will insert label after 'break'>")
end)
end) |
-- FUNCTIONAL
require 'Q/UTILS/lua/strict'
local Q = require 'Q'
local sum_prod = require( 'Q/ML/LOGREG/lua/sum_prod' )
local test = {}
test.t1 = function ()
local c1 = Q.mk_col ( {1, 2, 0, 2} , "I4")
local c2 = Q.mk_col ( {3, 2, 1, 3} , "I4")
local c3 = Q.mk_col ( {4, 1, 1, 1} , "I4")
local X = {c1, c2, c3}
local w = Q.mk_col ( { 2, 0, 1, 4} , "I4")
local A = sum_prod(X, w)
for i = 1, #A do
for j = 1, #A do
print(i, j, A[i][j])
end
print("================")
end
print("SUCCESS")
os.exit()
end
return test
|
local hexagon = {}
local function distanceBetween(x1, y1, x2, y2)
return math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1))
end
local function drawHexagon(x, y, hexagonSize, pointyTopped)
local vertices = {}
if pointyTopped then
table.insert(vertices, x)
table.insert(vertices, y + hexagonSize)
for i = 1, 5 do
table.insert(vertices, x + hexagonSize * math.sin(i * math.pi / 3))
table.insert(vertices, y + hexagonSize * math.cos(i * math.pi / 3))
end
else
table.insert(vertices, x + hexagonSize)
table.insert(vertices, y)
for i = 1, 5 do
table.insert(vertices, x + hexagonSize * math.cos(i * math.pi / 3))
table.insert(vertices, y + hexagonSize * math.sin(i * math.pi / 3))
end
end
love.graphics.polygon("line", vertices)
end
local function toHexagonCoordinatesHorizontal(x, y, grid)
local hexagonSize = grid.hexagonSize
local shifted = grid.shifted
local tileX = 0
local tileY = 0
local tileThirdWidth = hexagonSize * math.cos(math.pi / 3)
local tileWidth = 3 * tileThirdWidth
local tileHalfHeight = hexagonSize * math.cos(math.pi / 6)
local tileHeight = 2 * tileHalfHeight
-- We use math.ceil because we start the coordinates at 1 and not 0
tileX = math.ceil(x / tileWidth)
local offset
local hexagonA
local hexagonB
local hexagonC
local resultX
local resultY
if math.fmod(x, tileWidth) < tileThirdWidth then
if (not shifted and tileX % 2 == 0) or (shifted and tileX % 2 == 1) then
tileY = math.ceil(y / tileHeight)
offset = 0
else
tileY = math.ceil((y - tileHalfHeight) / tileHeight)
offset = tileHalfHeight
end
-- Uncertain, so we check which hexagon is the nearest
local xA = (tileX - 1) * tileWidth + hexagonSize
local xB = (tileX - 1) * tileWidth + tileThirdWidth - hexagonSize
local xC = xA
local yA = (tileY - 1) * tileHeight + offset
local yB = yA + tileHeight / 2
local yC = yB + tileHeight / 2
local distanceToA = distanceBetween(x, y, xA, yA)
local distanceToB = distanceBetween(x, y, xB, yB)
local distanceToC = distanceBetween(x, y, xC, yC)
if (not shifted and tileX % 2 == 0) or (shifted and tileX % 2 == 1) then
hexagonA = {X = tileX, Y = tileY - 1}
hexagonC = {X = tileX, Y = tileY}
else
hexagonA = {X = tileX, Y = tileY}
hexagonC = {X = tileX, Y = tileY + 1}
end
hexagonB = {X = tileX - 1, Y = tileY}
local possibleHexagons = {[distanceToA] = hexagonA, [distanceToB] = hexagonB, [distanceToC] = hexagonC}
local distances = {}
for k in pairs(possibleHexagons) do
table.insert(distances, k)
end
table.sort(distances)
local closerHexagon = possibleHexagons[distances[1]]
resultX = closerHexagon.X
resultY = closerHexagon.Y
else
if (not shifted and tileX % 2 == 0) or (shifted and tileX % 2 == 1) then
tileY = math.ceil((y - tileHalfHeight) / tileHeight)
else
tileY = math.ceil(y / tileHeight)
end
resultX = tileX
resultY = tileY
end
return resultX, resultY
end
local function toHexagonCoordinatesVertical(x, y, grid)
local hexagonSize = grid.hexagonSize
local shifted = grid.shifted
local tileX = 0
local tileY = 0
local tileThirdHeight = hexagonSize * math.cos(math.pi / 3)
local tileHeight = 3 * tileThirdHeight
local tileHalfWidth = hexagonSize * math.cos(math.pi / 6)
local tileWidth = 2 * tileHalfWidth
-- We use math.ceil because we start the coordinates at 1 and not 0
tileY = math.ceil(y / tileHeight)
local offset
local hexagonA
local hexagonB
local hexagonC
local resultX
local resultY
if math.fmod(y, tileHeight) < tileThirdHeight then
if (not shifted and tileY % 2 == 0) or (shifted and tileY % 2 == 1) then
tileX = math.ceil(x / tileWidth)
offset = 0
else
tileX = math.ceil((x - tileHalfWidth) / tileWidth)
offset = tileHalfWidth
end
-- Uncertain, so we check which hexagon is the nearest
local yA = (tileY - 1) * tileHeight + hexagonSize
local yB = (tileY - 1) * tileHeight + tileThirdHeight - hexagonSize
local yC = yA
local xA = (tileX - 1) * tileWidth + offset
local xB = xA + tileWidth / 2
local xC = xB + tileWidth / 2
local distanceToA = distanceBetween(x, y, xA, yA)
local distanceToB = distanceBetween(x, y, xB, yB)
local distanceToC = distanceBetween(x, y, xC, yC)
if (not shifted and tileY % 2 == 0) or (shifted and tileY % 2 == 1) then
hexagonA = {Y = tileY, X = tileX - 1}
hexagonC = {Y = tileY, X = tileX}
else
hexagonA = {Y = tileY, X = tileX}
hexagonC = {Y = tileY, X = tileX + 1}
end
hexagonB = {Y = tileY - 1, X = tileX}
local possibleHexagons = {[distanceToA] = hexagonA, [distanceToB] = hexagonB, [distanceToC] = hexagonC}
local distances = {}
for k in pairs(possibleHexagons) do
table.insert(distances, k)
end
table.sort(distances)
local closerHexagon = possibleHexagons[distances[1]]
resultX = closerHexagon.X
resultY = closerHexagon.Y
else
if (not shifted and tileY % 2 == 0) or (shifted and tileY % 2 == 1) then
tileX = math.ceil((x - tileHalfWidth) / tileWidth)
else
tileX = math.ceil(x / tileWidth)
end
resultX = tileX
resultY = tileY
end
return resultX, resultY
end
function hexagon.grid(width, height, hexagonSize, pointyTopped, shifted)
local grid = {}
assert(type(width) == "number", "width expects a number")
grid.width = width
assert(type(height) == "number", "height expects a number")
grid.height = height
assert(type(hexagonSize) == "number", "hexagonSize expects a number")
grid.hexagonSize = hexagonSize
assert(type(pointyTopped) == "boolean", "pointyTopped expects a boolean")
grid.pointyTopped = pointyTopped
assert(type(shifted) == "boolean", "shifted expects a boolean")
grid.shifted = shifted
return grid
end
function hexagon.drawGrid(grid, canvas)
love.graphics.setCanvas(canvas)
for i = 1, grid.width do
for j = 1, grid.height do
local hx, hy = hexagon.toPlanCoordinates(i, j, grid)
drawHexagon(hx, hy, grid.hexagonSize, grid.pointyTopped)
end
end
love.graphics.setCanvas()
end
-- Given the coordinates of an hexagon in the grid, return the coordinates of its center in the plan
function hexagon.toPlanCoordinates(x, y, grid)
local hexagonSize = grid.hexagonSize
local shifted = grid.shifted
local hx
local hy
if grid.pointyTopped then
hx = x * 2 * hexagonSize * (math.sin(math.pi / 3))
hy = hexagonSize + (y - 1) * hexagonSize * (math.cos(math.pi / 3) + 1)
if (shifted and y % 2 == 0) or (not shifted and y % 2 == 1) then
hx = hx - hexagonSize * (math.sin(math.pi / 3))
end
else
hx = hexagonSize + (x - 1) * hexagonSize * (math.cos(math.pi / 3) + 1)
hy = y * 2 * hexagonSize * (math.sin(math.pi / 3))
if (shifted and x % 2 == 0) or (not shifted and x % 2 == 1) then
hy = hy - hexagonSize * (math.sin(math.pi / 3))
end
end
return hx , hy
end
-- Given the coordinates of a point in the plan, return the coordinates of the hexagon under that point in the grid
function hexagon.toHexagonCoordinates(x, y, grid)
local resultX = 0
local resultY = 0
if grid.pointyTopped then
resultX, resultY = toHexagonCoordinatesVertical(x, y, grid)
else
resultX, resultY = toHexagonCoordinatesHorizontal(x, y, grid)
end
-- Out of the grid
if resultX < 1 or resultX > grid.width or resultY < 1 or resultY > grid.height then
resultX = -1
resultY = -1
end
return resultX, resultY
end
return hexagon
|
local spec = {}
local cp = ...
function spec.isCompatible(address)
return cp.proxy(address).type == "openprinter"
end
function spec.getName()
return "OpenPrinter Fuchas Driver"
end
function spec.getRank()
return 1
end
function spec.new(address)
local out = nil
local outbuf = ""
printer = cp.proxy(address)
function drv.getStatistics()
return {
blackInkLevel = printer.getBlackInkLevel(),
colorInkLevel = printer.getColorInkLevel(),
inkLevel = printer.getBlackInkLevel() + printer.getColorInkLevel(),
maxBlackInkLevel = 4000,
maxColorInkLevel = 4000,
maxInkLevel = 8000,
paperLevel = printer.getPaperLevel(),
maxPaperLevel = 256
}
end
function drv.out()
if out == nil then
out = {
write = function(self, str)
local ln = table.pack(string.find(str, "\n", 1, true))
local last = 1
for k, v in ipairs(ln) do
if outbuf ~= nil then
printer.writeln(outbuf)
outbuf = nil
end
printer.writeln(string.sub(last, v))
last = v+1
end
if last < str:len() then
outbuf = str:sub(last, str:len())
end
end,
flush = function(self)
if outbuf ~= nil then
printer.writeln(outbuf)
end
end,
print = function(self)
self.flush()
return printer.print()
end
}
end
return out
end
end
return spec |
local utils = {}
utils.readFile = function (fileName, base)
if not base then base = system.ResourceDirectory; end
local path = system.pathForFile(fileName, base)
local file = io.open(path, "r")
if not file then return nil; end
local contents = file:read("*a")
io.close(file)
return contents
end
function tablePrint (tt, indent, done)
done = done or {}
indent = indent or 0
if type(tt) == "table" then
local sb = {}
for key, value in pairs (tt) do
table.insert(sb, string.rep (" ", indent)) -- indent it
if type (value) == "table" and not done [value] then
done [value] = true
table.insert(sb, "{\n");
table.insert(sb, tablePrint (value, indent + 2, done))
table.insert(sb, string.rep (" ", indent)) -- indent it
table.insert(sb, "}\n");
elseif "number" == type(key) then
table.insert(sb, string.format("\"%s\"\n", tostring(value)))
else
table.insert(sb, string.format(
"%s = \"%s\"\n", tostring (key), tostring(value)))
end
end
return table.concat(sb)
else
return tt .. "\n"
end
end
function utils.print (value)
if "nil" == type(value) then
print(tostring(nil))
elseif "table" == type(value) then
print(tablePrint(value))
elseif "string" == type(value) then
print(value)
else
print(tostring(value))
end
end
function utils.indexOf (haystack, needle)
for i,value in ipairs(haystack) do
if value == needle then return i end
end
return nil
end
return utils
|
---------------------------------------------------------------------------------------------------
-- User story: Smoke
-- Use case: GetPolicyConfigurationData
-- Item: Happy path
--
-- Requirement summary:
-- [GetPolicyConfigurationData] SUCCESS: getting SUCCESS:SDL.GetPolicyConfigurationData()
--
-- Description:
-- Processing GetPolicyConfigurationData request from HMI
-- Pre-conditions:
-- a. HMI and SDL are started
-- Steps:
-- HMI requests GetPolicyConfigurationData with valid parameters
-- Expected:
-- SDL responds with value for requested parameter
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local commonSmoke = require('test_scripts/Smoke/commonSmoke')
--[[ Local Variables ]]
local preloadedPT = commonSmoke:read_parameter_from_smart_device_link_ini("PreloadedPT")
local preloadedFile = commonSmoke:GetPathToSDL() .. preloadedPT
local pt = commonSmoke.jsonFileToTable(preloadedFile)
--[[ Local Functions ]]
local function GetPolicyConfigurationData(self)
local requestId = self.hmiConnection:SendRequest("SDL.GetPolicyConfigurationData",
{ policyType = "module_config", property = "endpoints" })
EXPECT_HMIRESPONSE(requestId, { result = { code = 0 } })
:ValidIf(function(_, data)
if true ~= commonSmoke:is_table_equal(commonSmoke.decode(data.result.value[1]),
pt.policy_table.module_config.endpoints) then
return false, "GetPolicyConfigurationData contains unexpected parameters.\n" ..
"Expected table: " .. commonSmoke.tableToString(pt.policy_table.module_config.endpoints) .. "\n" ..
"Actual table: " .. commonSmoke.tableToString(commonSmoke.decode(data.result.value[1])) .. "\n"
end
return true
end)
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", commonSmoke.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", commonSmoke.start)
runner.Title("Test")
runner.Step("GetPolicyConfigurationData from HMI", GetPolicyConfigurationData)
runner.Title("Postconditions")
runner.Step("Stop SDL", commonSmoke.postconditions)
|
--[[
Upbit Open API
## REST API for Upbit Exchange - Base URL: [https://api.upbit.com] - Official Upbit API Documents: [https://docs.upbit.com] - Official Support email: [[email protected]]
OpenAPI spec version: 1.0.0
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
]]
-- withdraw class
local withdraw = {}
local withdraw_mt = {
__name = "withdraw";
__index = withdraw;
}
local function cast_withdraw(t)
return setmetatable(t, withdraw_mt)
end
local function new_withdraw(type, uuid, currency, txid, state, created_at, done_at, amount, fee, transaction_type)
return cast_withdraw({
["type"] = type;
["uuid"] = uuid;
["currency"] = currency;
["txid"] = txid;
["state"] = state;
["created_at"] = created_at;
["done_at"] = done_at;
["amount"] = amount;
["fee"] = fee;
["transaction_type"] = transaction_type;
})
end
return {
cast = cast_withdraw;
new = new_withdraw;
}
|
---------------------------------------------------------------------------------------------------
-- Issue: https://github.com/SmartDeviceLink/sdl_core/issues/1915
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local common = require('test_scripts/MobileProjection/Phase2/common')
local runner = require('user_modules/script_runner')
local hmi_values = require('user_modules/hmi_values')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Variables ]]
local appHMIType = {
[1] = "MEDIA",
[2] = "NAVIGATION"
}
local isMixingAudioSupported = true
--[[ General configuration parameters ]]
config.application1.registerAppInterfaceParams.appHMIType = { appHMIType[1] }
config.application2.registerAppInterfaceParams.appHMIType = { appHMIType[2] }
--[[ Local Functions ]]
local function getHMIParams(pIsMixingSupported)
local hmiParams = hmi_values.getDefaultHMITable()
hmiParams.BasicCommunication.MixingAudioSupported.params.attenuatedSupported = pIsMixingSupported
return hmiParams
end
local function activateApp(pAppId, pTC, pAudioSS, pAppName)
local requestId = common.getHMIConnection():SendRequest("SDL.ActivateApp", { appID = common.getHMIAppId(pAppId) })
common.getHMIConnection():ExpectResponse(requestId)
common.getMobileSession(pAppId):ExpectNotification("OnHMIStatus")
:ValidIf(function(_, data)
return common.checkAudioSS(pTC, pAppName, pAudioSS, data.payload.audioStreamingState)
end)
end
local function appStartAudioStreaming(pApp1Id, pApp2Id)
common.getMobileSession(pApp2Id):StartService(10)
:Do(function()
common.getHMIConnection():ExpectRequest("Navigation.StartAudioStream")
:Do(function(_, data)
common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
common.getMobileSession(pApp2Id):StartStreaming(10,"files/MP3_1140kb.mp3")
common.getHMIConnection():ExpectNotification("Navigation.OnAudioDataStreaming", { available = true })
end)
end)
common.getMobileSession(pApp1Id):ExpectNotification("OnHMIStatus", {
hmiLevel = "FULL",
audioStreamingState = "ATTENUATED"
})
:Times(1)
end
local function appStopStreaming()
common.getMobileSession(2):StopStreaming("files/MP3_1140kb.mp3")
common.getMobileSession():ExpectNotification("OnHMIStatus", { hmiLevel = "FULL", audioStreamingState = "AUDIBLE" })
common.getMobileSession(2):ExpectNotification("OnHMIStatus")
:Times(0)
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session, isMixingSupported:" .. tostring(isMixingAudioSupported),
common.start, { getHMIParams(isMixingAudioSupported) })
runner.Step("Set App Config", common.setAppConfig, { 2, "NAVIGATION", true })
runner.Step("Register App", common.registerApp, { 2 })
runner.Step("Activate App2, audioState:" .. "AUDIBLE", activateApp, { 2, 001, "AUDIBLE", "App2" })
runner.Step("Set App Config", common.setAppConfig, { 1, "MEDIA", true })
runner.Step("Register " .. appHMIType[1] .. " App", common.registerApp, { 1 })
runner.Step("Activate App1, audioState:" .. "AUDIBLE", activateApp, { 1, 001, "AUDIBLE", "App1" })
runner.Step("App starts Audio streaming", appStartAudioStreaming, { 1, 2 })
runner.Step("App stops streaming", appStopStreaming)
runner.Step("Clean sessions", common.cleanSessions)
runner.Step("Stop SDL", common.postconditions)
|
--lost desert-- mewmew made this --
local simplex_noise = require 'utils.simplex_noise'
simplex_noise = simplex_noise.d2
local event = require 'utils.event'
local map_functions = require "tools.map_functions"
local math_random = math.random
local function shipwreck(position, surface)
local wrecks = {"big-ship-wreck-1", "big-ship-wreck-2", "big-ship-wreck-3"}
local wreck = wrecks[math.random(1,#wrecks)]
local wreck_raffle_table = {}
local wreck_loot_weights = {}
table.insert(wreck_loot_weights, {{name = "firearm-magazine", count = math.random(64,128)},8})
table.insert(wreck_loot_weights, {{name = 'grenade', count = math.random(16,32)},5})
table.insert(wreck_loot_weights, {{name = 'land-mine', count = math.random(16,32)},5})
table.insert(wreck_loot_weights, {{name = 'heavy-armor', count = 1},2})
table.insert(wreck_loot_weights, {{name = 'assembling-machine-1', count = math.random(1,4)},2})
table.insert(wreck_loot_weights, {{name = 'assembling-machine-2', count = math.random(1,3)},2})
table.insert(wreck_loot_weights, {{name = 'assembling-machine-3', count = math.random(1,2)},1})
table.insert(wreck_loot_weights, {{name = 'combat-shotgun', count = 1},3})
table.insert(wreck_loot_weights, {{name = 'piercing-shotgun-shell', count = math.random(16,48)},5})
table.insert(wreck_loot_weights, {{name = 'flamethrower', count = 1},3})
table.insert(wreck_loot_weights, {{name = 'rocket-launcher', count = 1},4})
table.insert(wreck_loot_weights, {{name = 'flamethrower-ammo', count = math.random(16,48)},5})
table.insert(wreck_loot_weights, {{name = 'rocket', count = math.random(16,48)},5})
table.insert(wreck_loot_weights, {{name = 'explosive-rocket', count = math.random(16,48)},5})
table.insert(wreck_loot_weights, {{name = 'modular-armor', count = 1},3})
table.insert(wreck_loot_weights, {{name = 'power-armor', count = 1},1})
table.insert(wreck_loot_weights, {{name = 'uranium-rounds-magazine', count = math.random(16,32)},3})
table.insert(wreck_loot_weights, {{name = 'piercing-rounds-magazine', count = math.random(64,128)},5})
table.insert(wreck_loot_weights, {{name = 'railgun', count = 1},3})
table.insert(wreck_loot_weights, {{name = 'railgun-dart', count = math.random(16,48)},4})
table.insert(wreck_loot_weights, {{name = 'exoskeleton-equipment', count = 1},1})
table.insert(wreck_loot_weights, {{name = 'defender-capsule', count = math.random(8,16)},5})
table.insert(wreck_loot_weights, {{name = 'distractor-capsule', count = math.random(4,8)},4})
table.insert(wreck_loot_weights, {{name = 'destroyer-capsule', count = math.random(4,8)},3})
table.insert(wreck_loot_weights, {{name = 'atomic-bomb', count = 1},1})
for _, t in pairs (wreck_loot_weights) do
for x = 1, t[2], 1 do
table.insert(wreck_raffle_table, t[1])
end
end
local e = surface.create_entity {name=wreck, position=position, force="player"}
e.minable = false
local i = e.get_inventory(defines.inventory.chest)
for x = 1, math.random(2,3), 1 do
local loot = wreck_raffle_table[math.random(1,#wreck_raffle_table)]
i.insert(loot)
end
end
local function shuffle(tbl)
local size = #tbl
for i = size, 1, -1 do
local rand = math.random(size)
tbl[i], tbl[rand] = tbl[rand], tbl[i]
end
return tbl
end
local function get_noise(name, pos)
local seed = game.surfaces[1].map_gen_settings.seed
local noise = {}
local noise_seed_add = 25000
seed = seed + noise_seed_add
if name == 1 then
local m = 2
noise[1] = simplex_noise(pos.x * 0.001 * m, pos.y * 0.001 * m, seed)
seed = seed + noise_seed_add
noise[2] = simplex_noise(pos.x * 0.01 * m, pos.y * 0.01 * m, seed)
seed = seed + noise_seed_add
noise[3] = simplex_noise(pos.x * 0.05 * m, pos.y * 0.05 * m, seed)
seed = seed + noise_seed_add
noise[4] = simplex_noise(pos.x * 0.1 * m, pos.y * 0.1 * m, seed)
local noise = noise[1] + noise[2] * 0.05 + noise[3] * 0.02 + noise[4] * 0.001
return noise
end
seed = seed + noise_seed_add
seed = seed + noise_seed_add
seed = seed + noise_seed_add
seed = seed + noise_seed_add
if name == "rocks_1" then
noise[1] = simplex_noise(pos.x * 0.005, pos.y * 0.005, seed)
seed = seed + noise_seed_add
noise[2] = simplex_noise(pos.x * 0.01, pos.y * 0.01, seed)
seed = seed + noise_seed_add
noise[3] = simplex_noise(pos.x * 0.1, pos.y * 0.1, seed)
local noise = noise[1] + noise[2] * 0.005 + noise[3] * 0.0002
return noise
end
seed = seed + noise_seed_add
seed = seed + noise_seed_add
seed = seed + noise_seed_add
if name == "deco_1" then
noise[1] = simplex_noise(pos.x * 0.01, pos.y * 0.01, seed)
local noise = noise[1]
return noise
end
seed = seed + noise_seed_add
if name == "deco_2" then
noise[1] = simplex_noise(pos.x * 0.01, pos.y * 0.01, seed)
local noise = noise[1]
return noise
end
seed = seed + noise_seed_add
if name == "dead_trees" then
noise[1] = simplex_noise(pos.x * 0.005, pos.y * 0.005, seed)
local noise = noise[1]
return noise
end
seed = seed + noise_seed_add
end
local worm_raffle = {"small-worm-turret", "small-worm-turret", "small-worm-turret", "medium-worm-turret", "medium-worm-turret", "big-worm-turret"}
local rock_raffle = {"sand-rock-big","sand-rock-big","rock-big","rock-big","rock-big","rock-big","rock-huge"}
local ore_spawn_raffle = {"iron-ore","iron-ore","iron-ore","copper-ore","copper-ore","copper-ore","coal","coal","stone","stone","uranium-ore","crude-oil"}
local function on_chunk_generated(event)
local surface = game.surfaces["lost_desert"]
if event.surface.name ~= surface.name then return end
local chunk_pos_x = event.area.left_top.x
local chunk_pos_y = event.area.left_top.y
local area = {
left_top = {x = chunk_pos_x, y = chunk_pos_y},
right_bottom = {x = chunk_pos_x + 31, y = chunk_pos_y + 31}
}
local tiles = {}
local entities_to_place = {
rocks = {},
worms = {},
enemy_buildings = {},
trees = {},
fish = {},
shipwrecks = {}
}
surface.destroy_decoratives(area)
local decoratives = {}
local entities = surface.find_entities(area)
for _, e in pairs(entities) do
if e.type == "tree" or e.force.name == "enemy" then
e.destroy()
end
end
local sands = {"sand-1", "sand-2", "sand-3"}
local tile_to_insert = false
for x = 0, 31, 1 do
for y = 0, 31, 1 do
local pos_x = chunk_pos_x + x
local pos_y = chunk_pos_y + y
local pos = {x = pos_x, y = pos_y}
local tile_distance_to_center = pos_x^2 + pos_y^2
tile_to_insert = false
local noise_1 = get_noise(1, pos)
if tile_distance_to_center > 10000 then
if noise_1 <= -0.80 then
if math_random(1,250) == 1 then table.insert(entities_to_place.shipwrecks, pos) end
end
if noise_1 <= -0.75 then
if math_random(1,16) == 1 then table.insert(entities_to_place.worms, pos) end
if math_random(1,16) == 1 then table.insert(entities_to_place.enemy_buildings, pos) end
end
end
if noise_1 <= -0.4 then tile_to_insert = "sand-2" end
if noise_1 > -0.4 then tile_to_insert = "sand-1" end
if noise_1 > 0.4 then tile_to_insert = "sand-3" end
if noise_1 > 0.72 and noise_1 < 0.8 then if math_random(1,3) == 1 then table.insert(decoratives, {name = "garballo", position = pos, amount = math_random(1,3)}) end end
if noise_1 > 0.75 then
if math_random(1,5) == 1 then table.insert(entities_to_place.trees, {"tree-05", pos}) end
if math_random(1,400) == 1 then
if surface.count_entities_filtered({name = "market", area = {{pos.x - 50, pos.y - 50}, {pos.x + 50, pos.y + 50}}, limit = 1}) < 1 then
if surface.can_place_entity {name = "market", position = pos} then
local market = surface.create_entity {name = "market", position = pos}
market.destructible = false
market.add_market_item({price = {{"wood", math.random(2,10)}}, offer = {type = 'give-item', item = 'raw-fish'}})
end
end
end
end
if noise_1 > 0.8 then
tile_to_insert = "water"
if math_random(1,32) == 1 then table.insert(entities_to_place.fish, pos) end
end
if noise_1 > 0.9 then tile_to_insert = "deepwater" end
if tile_to_insert ~= "deepwater" and tile_to_insert ~= "water" and noise_1 < 0.7 then
if math_random(1, 15000) == 1 and noise_1 < 0.65 then
local ore = ore_spawn_raffle[math_random(1,#ore_spawn_raffle)]
if ore == "crude-oil" then
amount = 100000 + math_random(tile_distance_to_center,tile_distance_to_center*2)
map_functions.draw_oil_circle(pos, ore, surface, math_random(4,12), amount)
else
map_functions.draw_crazy_smoothed_out_ore_circle(pos, ore, surface, math_random(10,70), math_random(300,400) + math.sqrt(tile_distance_to_center))
end
end
local noise_dead_trees = get_noise("dead_trees", pos)
local noise_rocks_1 = get_noise("rocks_1", pos)
local noise_deco_1 = get_noise("deco_1", pos)
local noise_deco_2 = get_noise("deco_2", pos)
while true do
if noise_dead_trees > 0.5 then
if math_random(1,55) == 1 then table.insert(entities_to_place.trees, {"tree-06", pos}) end
break
end
if noise_rocks_1 > 0.5 and noise_dead_trees < -0.4 then
if noise_rocks_1 > 0.55 then
if math_random(1,6) == 1 then table.insert(entities_to_place.rocks, pos) end
end
--tile_to_insert = "dirt-1"
end
if noise_deco_1 > 0.75 then
if math_random(1,7) == 1 then table.insert(decoratives, {name = "brown-fluff-dry", position = pos, amount = math_random(1,3)}) end
break
end
if noise_deco_1 < -0.75 then
if math_random(1,7) == 1 then table.insert(decoratives, {name = "red-desert-bush", position = pos, amount = math_random(1,3)}) end
break
end
if noise_deco_2 > 0.75 then
if math_random(1,7) == 1 then table.insert(decoratives, {name = "white-desert-bush", position = pos, amount = math_random(1,3)}) end
break
end
if noise_deco_2 < -0.75 then
if math_random(1,7) == 1 then table.insert(decoratives, {name = "brown-asterisk", position = pos, amount = math_random(1,3)}) end
break
end
if tile_to_insert == "sand-1" then
if math_random(1,50) == 1 then table.insert(decoratives, {name = "sand-dune-decal", position = pos, amount = 1}) end
end
break
end
end
if tile_to_insert == false then
--table.insert(tiles, {name = "sand-4", position = {pos_x,pos_y}}) tree-06
else
table.insert(tiles, {name = tile_to_insert, position = pos})
end
end
end
surface.set_tiles(tiles,true)
surface.create_decoratives{check_collision=false, decoratives=decoratives}
for _, p in pairs(entities_to_place.shipwrecks) do
shipwreck(p, surface)
end
for _, p in pairs(entities_to_place.enemy_buildings) do
if math_random(1,3) == 1 then
if surface.can_place_entity({name="spitter-spawner", position=p}) then surface.create_entity {name="spitter-spawner", position=p} end
else
if surface.can_place_entity({name="biter-spawner", position=p}) then surface.create_entity {name="biter-spawner", position=p} end
end
end
for _, p in pairs(entities_to_place.worms) do
local e = worm_raffle[math.random(1,#worm_raffle)]
if surface.can_place_entity({name=e, position=p}) then surface.create_entity {name=e, position=p} end
end
for _, p in pairs(entities_to_place.rocks) do
local e = rock_raffle[math.random(1,#rock_raffle)]
surface.create_entity {name=e, position=p}
end
for _, p in pairs(entities_to_place.trees) do
if surface.can_place_entity({name=p[1], position=p[2]}) then surface.create_entity {name=p[1], position=p[2]} end
end
for _, p in pairs(entities_to_place.fish) do
surface.create_entity {name="fish",position=p}
end
if not global.lost_desert_spawn_ores then
if chunk_pos_x > 96 then
map_functions.draw_smoothed_out_ore_circle({x=0, y=20}, "stone", surface , 14, 500)
map_functions.draw_smoothed_out_ore_circle({x=0, y=-20}, "coal", surface , 14, 500)
map_functions.draw_smoothed_out_ore_circle({x=-20, y=0}, "iron-ore", surface , 14, 500)
map_functions.draw_smoothed_out_ore_circle({x=20, y=0}, "copper-ore", surface , 14, 500)
global.lost_desert_spawn_ores = true
end
end
end
local function on_player_joined_game(event)
local player = game.players[event.player_index]
if not global.map_init_done then
local map_gen_settings = {}
map_gen_settings.water = "none"
map_gen_settings.cliff_settings = {cliff_elevation_interval = 20, cliff_elevation_0 = 20}
map_gen_settings.autoplace_controls = {
["coal"] = {frequency = "none", size = "none", richness = "none"},
["stone"] = {frequency = "none", size = "none", richness = "none"},
["copper-ore"] = {frequency = "none", size = "none", richness = "none"},
["uranium-ore"] = {frequency = "none", size = "none", richness = "none"},
["iron-ore"] = {frequency = "none", size = "none", richness = "none"},
["crude-oil"] = {frequency = "none", size = "none", richness = "none"},
["trees"] = {frequency = "none", size = "none", richness = "none"},
["enemy-base"] = {frequency = "none", size = "none", richness = "none"}
}
game.map_settings.pollution.pollution_restored_per_tree_damage = 0
game.create_surface("lost_desert", map_gen_settings)
game.forces["player"].set_spawn_position({0,0},game.surfaces["lost_desert"])
local surface = game.surfaces["lost_desert"]
--create_cluster("crude-oil", {x=0,y=0}, 5, surface, 10, math.random(300000,400000))
global.map_init_done = true
end
local surface = game.surfaces["lost_desert"]
if player.online_time < 5 and surface.is_chunk_generated({0,0}) then
player.teleport(surface.find_non_colliding_position("character", {0,0}, 2, 1), "lost_desert")
else
if player.online_time < 5 then
player.teleport({0,0}, "lost_desert")
end
end
if player.online_time < 10 then
player.insert {name = 'raw-fish', count = 3}
player.insert {name = 'light-armor', count = 1}
end
end
event.add(defines.events.on_chunk_generated, on_chunk_generated)
--event.add(defines.events.on_marked_for_deconstruction, on_marked_for_deconstruction)
event.add(defines.events.on_player_joined_game, on_player_joined_game) |
vim.api.nvim_set_keymap("n", "<leader>fn", "<cmd>DashboardNewFile<CR>", { noremap = true, silent = true })
vim.api.nvim_set_keymap("n", "<leader>db", "<cmd>Dashboard<CR>", { noremap = true, silent = true })
vim.api.nvim_set_keymap("n", "<leader>sl", "<cmd>SessionLoad<CR>", { noremap = true, silent = true })
vim.api.nvim_set_keymap("n", "<leader>ss", "<cmd>SessionSave<CR>", { noremap = true, silent = true })
|
-----------------------------------
-- Area: Wajaom Woodlands
-- NPC: Watisa
-- Type: Chocobo Renter
-- !pos -201 -11 93 51
-----------------------------------
require("scripts/globals/chocobo")
-----------------------------------
local eventSucceed = 9
local eventFail = 10
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
tpz.chocobo.renterOnTrigger(player, eventSucceed, eventFail)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
tpz.chocobo.renterOnEventFinish(player, csid, option, eventSucceed)
end
|
local ls = require "lovesnow"
local harbor = require "lovesnow.harbor"
require "lovesnow.manager" -- import ls.launch, ...
local memory = require "lovesnow.memory"
ls.start(function()
local sharestring = tonumber(ls.getenv "sharestring" or 4096)
memory.ssexpand(sharestring)
local standalone = ls.getenv "standalone"
local launcher = assert(ls.launch("ls_load_script","launcher"))
ls.name(".launcher", launcher)
local harbor_id = tonumber(ls.getenv "harbor" or 0)
if harbor_id == 0 then
assert(standalone == nil)
standalone = true
ls.setenv("standalone", "true")
local ok, slave = pcall(ls.newservice, "cdummy")
if not ok then
ls.abort()
end
ls.name(".cslave", slave)
else
if standalone then
if not pcall(ls.newservice,"cmaster") then
ls.abort()
end
end
local ok, slave = pcall(ls.newservice, "cslave")
if not ok then
ls.abort()
end
ls.name(".cslave", slave)
end
if standalone then
local datacenter = ls.newservice "datacenterd"
ls.name("DATACENTER", datacenter)
end
ls.newservice "service_mgr"
pcall(ls.newservice,ls.getenv "start" or "main")
ls.exit()
end)
|
lvl1_table = {}
lvl1_table["nothing"] = 1000
lvl1_table["item_flask"] = 200
lvl1_table["item_enchanted_mango"] = 200
lvl1_table["item_branches"] = 10
lvl1_table["item_tango"] = 10
lvl1_table["item_ward_observer"] = 1
lvl1_table["item_mantle"] = 1
lvl1_table["item_slippers"] = 1
lvl1_table["item_gauntlets"] = 1
lvl1_table["item_ring_of_protection"] = 1
lvl1_table["item_clarity"] = 1
lvl1_table["item_tango_single"] = 1
lvl1_table["item_quelling_blade"] = 1
lvl1_table["item_tpscroll"] = 10
lvl1_table["item_courier"] = 1
lvl1_table["item_ring_of_regen"] = 5
lvl1_table["item_sobi_mask"] = 5
lvl1_table["item_boots"] = 5
lvl1_table["item_creep_whistle"] = 1
lvl1_table["item_strange_mushroom"] = 5
lvl2_table = {}
lvl2_table["nothing"] = 800
lvl2_table["item_flask"] = 140
lvl2_table["item_enchanted_mango"] = 140
lvl2_table["item_branches"] = 10
lvl2_table["item_tango"] = 10
lvl2_table["item_mantle"] = 10
lvl2_table["item_slippers"] = 10
lvl2_table["item_gauntlets"] = 10
lvl2_table["item_ring_of_protection"] = 10
lvl2_table["item_circlet"] = 10
lvl2_table["item_tango_single"] = 1
lvl2_table["item_quelling_blade"] = 1
lvl2_table["item_tpscroll"] = 10
lvl2_table["item_ring_of_regen"] = 10
lvl2_table["item_sobi_mask"] = 10
lvl2_table["item_boots"] = 5
lvl2_table["item_tpscroll"] = 10
lvl2_table["item_creep_whistle"] = 2
lvl2_table["item_strange_mushroom"] = 3
lvl3_table = {}
lvl3_table["nothing"] = 700
lvl3_table["item_flask"] = 140
lvl3_table["item_enchanted_mango"] = 140
lvl3_table["item_branches"] = 10
lvl3_table["item_tango"] = 10
lvl3_table["item_mantle"] = 30
lvl3_table["item_slippers"] = 30
lvl3_table["item_gauntlets"] = 30
lvl3_table["item_ring_of_protection"] = 30
lvl3_table["item_tango_single"] = 1
lvl3_table["item_quelling_blade"] = 1
lvl3_table["item_broadsword"] = 1
lvl3_table["item_tpscroll"] = 10
lvl3_table["item_ring_of_regen"] = 10
lvl3_table["item_sobi_mask"] = 10
lvl3_table["item_boots"] = 5
lvl3_table["item_recipe_vladmir"] = 4
lvl3_table["item_recipe_headdress"] = 4
lvl3_table["item_recipe_medallion_of_courage"] = 4
lvl3_table["item_creep_whistle"] = 5
lvl3_table["item_strange_mushroom"] = 5
lvl3_table["item_recipe_soul_ring"] = 3
lvl4_table = {}
lvl4_table["nothing"] = 600
lvl4_table["item_greater_flask"] = 10
lvl4_table["item_flask"] = 100
lvl4_table["item_enchanted_mango"] = 80
lvl4_table["item_branches"] = 1
lvl4_table["item_tango"] = 1
lvl4_table["item_robe"] = 10
lvl4_table["item_boots"] = 10
lvl4_table["item_boots_of_elves"] = 10
lvl4_table["item_belt_of_strength"] = 10
lvl4_table["item_ring_of_protection"] = 10
lvl4_table["item_tango_single"] = 1
lvl4_table["item_quelling_blade"] = 1
lvl4_table["item_broadsword"] = 10
lvl4_table["item_claymore"] = 5
lvl4_table["item_recipe_vladmir"] = 2
lvl4_table["item_recipe_pipe"] = 2
lvl4_table["item_recipe_headdress"] = 2
lvl4_table["item_recipe_cyclone"] = 2
lvl4_table["item_recipe_lesser_crit"] = 2
lvl4_table["item_recipe_armlet"] = 2
lvl4_table["item_tpscroll"] = 10
lvl4_table["item_creep_whistle"] = 5
lvl5_table = {}
lvl5_table["nothing"] = 00
lvl5_table["item_gloves"] = 10
lvl5_table["item_chainmail"] = 10
lvl5_table["item_branches"] = 10
lvl5_table["item_tango"] = 5
lvl5_table["item_cloak"] = 10
lvl5_table["item_bottle"] = 10
lvl5_table["item_blades_of_attack"] = 10
lvl5_table["item_clarity"] = 1
lvl5_table["item_tango_single"] = 1
lvl5_table["item_quelling_blade"] = 1
lvl5_table["item_tpscroll"] = 10
lvl5_table["item_flask"] = 1
lvl5_table["item_enchanted_mango"] = 100
lvl5_table["item_branches"] = 10
lvl5_table["item_robe"] = 10
lvl5_table["item_boots_of_elves"] = 10
lvl5_table["item_belt_of_strength"] = 10
lvl5_table["item_ring_of_protection"] = 1
lvl5_table["item_tango_single"] = 1
lvl5_table["item_greater_flask"] = 100
lvl5_table["item_recipe_mekansm"] = 10
lvl5_table["item_broadsword"] = 10
lvl5_table["item_claymore"] = 10
lvl5_table["item_recipe_vladmir"] = 2
lvl5_table["item_recipe_pipe"] = 2
lvl5_table["item_recipe_cyclone"] = 2
lvl5_table["item_recipe_lotus_orb"] = 2
lvl5_table["item_creep_whistle"] = 3
lvl6_table = {}
lvl6_table["nothing"] = 00
lvl6_table["item_helm_of_iron_will"] = 20
lvl6_table["item_recipe_force_staff"] = 10
lvl6_table["item_chainmail"] = 30
lvl6_table["item_tango"] = 30
lvl6_table["item_bottle"] = 30
lvl6_table["item_void_stone"] = 30
lvl6_table["item_blink"] = 5
lvl6_table["item_quarterstaff"] = 30
lvl6_table["item_ring_of_health"] = 30
lvl6_table["item_tango_single"] = 1
lvl6_table["item_quelling_blade"] = 1
lvl6_table["item_tpscroll"] = 1
lvl6_table["item_greater_flask"] = 130
lvl6_table["item_skill_book"] = 10
lvl6_table["item_recipe_travel_boots"] = 4
lvl6_table["item_talisman_of_evasion"] = 10
lvl6_table["item_claymore"] = 20
lvl6_table["item_ghost"] = 10
lvl6_table["item_recipe_hand_of_midas"] = 4
lvl6_table["item_hyperstone"] = 3
lvl6_table["item_recipe_assault"] = 2
lvl6_table["item_recipe_greater_crit"] = 2
lvl6_table["item_recipe_diffusal_blade"] = 2
lvl6_table["item_recipe_mask_of_madness"] = 2
lvl6_table["item_recipe_guardian_greaves"] = 2
lvl6_table["item_recipe_maelstrom"] = 2
drop_meta_lvltable = {
lvl1_table,
lvl2_table,
lvl3_table,
lvl4_table,
lvl5_table,
lvl6_table
}
weakancient_table = {}
weakancient_table["item_greater_flask"] = 100
weakancient_table["item_enchanted_mango"] = 100
weakancient_table["item_tango"] = 1
weakancient_table["item_branches"] = 1
weakancient_table["item_skill_book"] = 10
weakancient_table["item_energy_booster"] = 10
weakancient_table["item_point_booster"] = 10
weakancient_table["item_vitality_booster"] = 10
strongancient_table = {}
strongancient_table["item_skill_book"] = 80
strongancient_table["item_greater_flask"] = 180
strongancient_table["item_void_stone"] = 20
strongancient_table["item_ogre_axe"] = 20
strongancient_table["item_blade_of_alacrity"] = 20
strongancient_table["item_staff_of_wizardry"] =20
strongancient_table["item_lifesteal"] = 20
strongancient_table["item_mithril_hammer"] = 10
strongancient_table["item_javelin"] = 10
strongancient_table["item_platemail"] = 10
strongancient_table["item_cheese"] = 2
strongancient_table["item_demon_edge"] = 20
strongancient_table["item_recipe_dagon"] = 10
strongancient_table["item_recipe_travel_boots"] = 10
strongancient_table["item_relic"] = 20
strongancient_table["item_talisman_of_evasion"] = 20
strongancient_table["item_ghost"] = 20
strongancient_table["item_eagle"] = 10
strongancient_table["item_reaver"] = 10
strongancient_table["item_hyperstone"] = 20
strongancient_table["item_mystic_staff"] = 20
strongancient_table["item_recipe_heart"] = 20
strongancient_table["item_relic"] = 20
|
return function(_write)
function write(...)
local args = {}
for k,v in pairs({...}) do
args[k] = tostring(v)
end
_write(unpack(args))
end
function write_esc(...)
write(tostring(...):gsub("[\">/<'&]", {
["&"] = "&",
["<"] = "<",
[">"] = ">",
['"'] = """,
["'"] = "'",
["/"] = "/"
}))
end
write[====[]====]
local current = {}
local archived = {}
local extra = {}
local motds = {
"Now with 3% more burgers!",
"There is a realistic chance of a random burger encounter on this site!",
"May contain burger!",
"Most cerntainly contains burger!",
"A vegetarian's nightmare!",
"Also try other fastfood!",
"4 times a day to keep the doctor away!",
"Doctor's hate it!",
"8/8 gr8, m8(no h8)!",
"made by me!",
"come have a look around",
"have a hamburger!"
}
for i,coupon in pairs(coupons) do
if tonumber(coupon.plu) then
if tonumber(coupon.to) or 0 > os.time() then
table.insert(current, coupon)
else
table.insert(archived, coupon)
end
else
table.insert(extra, coupon)
end
end
local sort_f = function(a,b)
local a = tonumber(a.plu) or math.huge
local b = tonumber(b.plu) or math.huge
return a<b
end
table.sort(current, sort_f)
table.sort(archived, sort_f)
table.sort(extra, sort_f)
write[====[
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Slurger - Free burgerking coupons!</title>
<style>
body {
padding: 0 0;
margin: 0 0;
color: #333;
font-family: sans-serif;
}
.modal {
max-width: 700px;
background-color: #EEE;
margin: 20px auto;
padding: 20px 30px;
border-radius: 6px;
}
.motd {
font-size: 125%;
font-style: italic;
}
.modal img {
align: center;
}
.clear {
clear: both;
}
.coupons {
padding-top: 30px;
}
.coupon {
border-top: 1px solid #ccc;
padding-top: 10px;
text-align:center;
}
.coupon h3 {
font-size: 3em;
font-weight: normal;
}
@media only screen and (max-width: 500px) {
.coupon img {
width: 100%;
}
}
@media only screen and (min-width: 500px) {
.coupon h3 {
float: left;
margin: 0;
line-height:296px;
}
.coupon img {
float: right;
height: 286px;
}
}
</style>
</head>
<body>
<div class="modal">
<h1>Slurger2</h1>
<p class="motd" title="MOTD (motto of the day)">]====]write_esc( motds[math.random(1, #motds)])write[====[</p>
<p>
This site has a list of burgerking coupons.<br>
To use them, tell the cashier PLU of the coupon.
</p>
<p>The source and some documentation is available on <a href="https://github.com/max1220/slurger">github</a>.</p>
<div class="coupons clear">
<h2>Current coupons:</h2>
]====] for i, coupon in pairs(current) do write[====[
<div class="coupon clear">
<h3>]====]write_esc( coupon.plu )write[====[</h3>
<img src="]====]write_esc( coupon.local_image_286 )write[====[" alt="]====]write_esc( tostring(coupon.plu) )write[====[">
</div>
]====] end write[====[
</div>
]====] if #archived > 0 then write[====[
<div class="coupons clear">
<h2>Archived coupons:</h2>
<p>These coupons are expired, but should work anyway:</p>
<div class="coupons">
]====] for i, coupon in pairs(archived) do write[====[
<img src="]====]write_esc( coupon.local_image_286 )write[====[" alt="]====]write_esc( tostring(coupon.plu) )write[====[">
]====] end write[====[
</div>
</div>
]====] end write[====[
]====] if #extra > 0 then write[====[
<div class="coupons clear">
<h2>Extra coupons:</h2>
<p>These coupons don't have a numerical PLU.</p>
<div class="coupons clear">
]====] for i, coupon in pairs(extra) do write[====[
<div class="coupon clear">
<h3>]====]write_esc( coupon.plu )write[====[</h3>
<img src="]====]write_esc( coupon.local_image_286 )write[====[" alt="]====]write_esc( tostring(coupon.plu) )write[====[">
</div>
]====] end write[====[
</div>
</div>
]====] end write[====[
<div class="clear"></div>
</div>
</body>
</html>
]====] end |
setfenv(1, setmetatable({}, {__index=getfenv()}))
local modules = require("tweaks").modules
local ffi = modules.ffi
local C = ffi.C
local function jitable_unpack(t, i, j, ...)
if j - i >= 5 then return jitable_unpack(t, i, j - 5, t[j], t[j-1], t[j-2], t[j-3], t[j-4], ...) end
--if j - i >= 3 then return jitable_unpack(t, i, j - 3, t[j], t[j-1], t[j-2], ...) end
if i == j then return t[j], ... end
return jitable_unpack(t, i, j - 1, t[j], ...)
end
local function jitable_pack(...)
return select("#", ...), {...}
end
--[[
local function vswap(...)
local n = select("#", ...)
if n == 1 then
return ...
end
return select(n, ...), vswap(unpack({ ... }, 1, n - 1))
end
--]]
local function swap_impl(n, ...)
if n == 1 then return (...) end
return select(n, ...), swap_impl(n-1, ...)
end
-- swap("a", "b", "c") -> "c", "b", "a"
-- swap(1, 2, 3, 4, 5) -> 5, 4, 3, 2, 1
local function swap(...)
return swap_impl(select("#", ...), ...)
end
return
{
pack = jitable_pack,
unpack = function(t, i, j) return jitable_unpack(t, i or 1, j or #t) end,
swap = swap,
} |
local AddOn_Name, ns = ...
local friendlyName = GetAddOnMetadata(AddOn_Name,"Title")
local L = LibStub("AceLocale-3.0"):GetLocale(AddOn_Name,true)
local defaultOptions = {
global = {
hideHelm = true,
hideShoulders = false,
hideBack = false,
hideBelt = false,
expandVariants = true
},
char = {
useCharSettings = false
}
}
local optionsTable = {
name = friendlyName,
handler = ASHH,
type = 'group',
args = {
enable = {
name = "Enable",
desc = "Enables/Disables the addon",
type = 'toggle',
order = 0,
hidden = true,
set = function(self, val) end,
get = function(self) return end
},
reloadDialogue = {
type = "description",
name = L["ReloadMsg"],
order = 1
},
globalHeader = {
name = L["Global Defaults"],
type = "header",
order = 2
},
helmDefault_G = {
name = L["Hide Helm"],
type = "toggle",
order = 3,
set = function(_, val)
ASHH.db.global.hideHelm = val
if not ASHH.db.char.useCharSettings then
ASHH.db.char.hideHelm = val
end
end,
get = function() return ASHH.db.global.hideHelm end
},
shoulderDefault_G = {
name = L["Hide Shoulders"],
type = "toggle",
order = 4,
set = function(_,val)
ASHH.db.global.hideShoulders = val
if not ASHH.db.char.useCharSettings then
ASHH.db.char.hideShoulders = val
end
end,
get = function() return ASHH.db.global.hideShoulders end
},
backDefault_G = {
name = L["Hide Back"],
type = "toggle",
order = 5,
set = function(_,val)
ASHH.db.global.hideBack = val
if not ASHH.db.char.useCharSettings then
ASHH.db.char.hideBack = val
end
end,
get = function() return ASHH.db.global.hideBack end
},
beltDefault_G = {
name = L["Hide Belt"],
type = "toggle",
order = 5,
set = function(_,val)
ASHH.db.global.hideBelt = val
if not ASHH.db.char.useCharSettings then
ASHH.db.char.hideBelt = val
end
end,
get = function() return ASHH.db.global.hideBelt end
},
expandVariants_G = {
name = L["Expand Variants"],
type = "toggle",
order = 6,
desc = L["Coming soon!"],
descStyle = "inline",
disabled = true,
set = function(_,val) ASHH.db.global.expandVariants = val end,
get = function() return ASHH.db.global.expandVariants end
},
charHeader = {
name = L["Character Defaults"],
type = "header",
order = 7,
},
helmDefault_C = {
name = L["Hide Helm"],
type = "toggle",
order = 8,
set = function(_,val)
ASHH.db.char.hideHelm = val
ASHH.db.char.useCharSettings = true
end,
get = function() return ASHH.db.char.hideHelm end
},
shoulderDefault_C = {
name = L["Hide Shoulders"],
type = "toggle",
order = 9,
set = function(_,val)
ASHH.db.char.hideShoulders = val
ASHH.db.char.useCharSettings = true
end,
get = function() return ASHH.db.char.hideShoulders end
},
backDefault_C = {
name = L["Hide Back"],
type = "toggle",
order = 10,
set = function(_,val)
ASHH.db.char.hideBack = val
ASHH.db.char.useCharSettings = true
end,
get = function() return ASHH.db.char.hideBack end
},
beltDefault_C = {
name = L["Hide Belt"],
type = "toggle",
order = 10,
set = function(_,val)
ASHH.db.char.hideBelt = val
ASHH.db.char.useCharSettings = true
end,
get = function() return ASHH.db.char.hideBelt end
},
resetToDefault = {
name = L["Use Global"],
type = "execute",
order = 11,
disabled = function() return not ASHH.db.char.useCharSettings end,
func = "ResetCharOptions" -- Hope this works!
}
-- TODO: Way in the future, just add this as a setting to the dressing room to remove any helms tried on "anywhere"
}
}
function ASHH:InitOps()
self.db = LibStub("AceDB-3.0"):New("ASHHDB",defaultOptions,true)
self:SetupOptions()
LibStub("AceConfig-3.0"):RegisterOptionsTable(AddOn_Name,optionsTable,nil)
self.optionsFrame = LibStub("AceConfigDialog-3.0"):AddToBlizOptions(AddOn_Name,friendlyName,nil)
end
function ASHH:SetupOptions()
-- if usecharsettings false, then use global settings
if self.db.char.useCharSettings ~= true then
self.db.char.hideHelm = self.db.global.hideHelm
self.db.char.hideShoulders = self.db.global.hideShoulders
self.db.char.hideBack = self.db.global.hideBack
self.db.char.hideBelt = self.db.global.hideBelt
end
end
function ASHH:ResetOptions()
self.db:ResetDB(defaultOptions)
end
function ASHH:ResetCharOptions()
self.db.char.hideHelm = self.db.global.hideHelm
self.db.char.hideShoulders = self.db.global.hideShoulders
self.db.char.hideBack = self.db.global.hideBack
self.db.char.hideBelt = self.db.global.hideBelt
self.db.char.useCharSettings = false
end |
-- Copyright (c) 2020 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local quest = require "game.entities.quest"
return quest:new{
title = "Deliver the Stuff",
description = "You can take it over there!",
image = "assets/images/gold-coins.png",
prerequisites = quest.prerequisites.turn_counter(2),
goals = {
turns = 5
},
rewards = {
xp = 250,
money = 500
}
} |
require('plugins.lsp-status').activate()
local lsp_status = require 'plugins.lsp-status'
local home = os.getenv 'HOME'
-- The nvim-cmp almost supports LSP's capabilities so You should advertise it to LSP servers..
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities)
-- LUA:
local sumneko_lua_root_path = home .. '/Repositories/language-servers/lua-language-server'
require('lspconfig').sumneko_lua.setup {
cmd = {
sumneko_lua_root_path .. '/bin/macOS/lua-language-server',
'-E',
sumneko_lua_root_path .. '/main.lua',
},
commands = {
Format = {
function()
require('stylua-nvim').format_file()
end,
},
},
settings = {
Lua = {
diagnostics = {
globals = {
'vim',
'map',
'filter',
'range',
'reduce',
'head',
'tail',
'nth',
'describe',
'it',
'use',
},
disable = { 'redefined-local' },
},
runtime = { version = 'LuaJIT' },
workspace = {
library = {
[vim.fn.expand '$VIMRUNTIME/lua'] = true,
[vim.fn.expand '$VIMRUNTIME/lua/vim/lsp'] = true,
-- ['usr/local/bin/busted'] = true,
--[require 'busted'(busted)] = true,
-- [require 'busted.runner'({standalone = false})] = true,
--[require "nvim-treesitter.utils".get_package_path() .. "/lua"] = true,
},
},
},
},
on_attach = lsp_status.on_attach,
-- capabilities = lsp_status.capabilities
capabilities = capabilities,
}
|
local utils = require "kong.tools.utils"
local Errors = require "kong.dao.errors"
local schemas_validation = require "kong.dao.schemas_validation"
local validate = schemas_validation.validate_entity
return setmetatable({}, {
__call = function(_, schema)
local Model_mt = {}
Model_mt.__meta = {
__schema = schema,
__name = schema.name,
__table = schema.table
}
function Model_mt.__index(self, key)
if key and string.find(key, "__") == 1 then
local meta_field = Model_mt.__meta[key]
if meta_field then
return meta_field
end
end
return Model_mt[key]
end
function Model_mt:validate(opts)
local ok, errors, self_check_err = validate(self, self.__schema, opts)
if errors ~= nil then
return nil, Errors.schema(errors)
elseif self_check_err ~= nil then
-- TODO: merge errors and self_check_err now that our errors handle this
return nil, Errors.schema(self_check_err)
end
return ok
end
function Model_mt:extract_keys()
local schema = self.__schema
local primary_keys_idx = {}
local primary_keys, values, nils = {}, {}, {}
for _, key in pairs(schema.primary_key) do
-- check for uuid here. not all dbs might have ids of type uuid however
if schema.fields[key].type == "id" and not utils.is_valid_uuid(self[key]) then
return nil, nil, nil, self[key] .. " is not a valid uuid"
end
primary_keys[key] = self[key]
primary_keys_idx[key] = true
end
for col in pairs(schema.fields) do
if not primary_keys_idx[col] then
if self[col] ~= nil then
values[col] = self[col]
else
nils[col] = true
end
end
end
return primary_keys, values, nils
end
function Model_mt:has_primary_keys()
local schema = self.__schema
for _, key in pairs(schema.primary_key) do
if self[key] == nil then
return false
end
end
return true
end
return setmetatable({}, {
__call = function(_, tbl)
local m = {}
for k,v in pairs(tbl) do
m[k] = v
end
return setmetatable(m, Model_mt)
end
})
end
})
|
local TroopFunctions = import('/mods/DilliDalli/lua/AI/DilliDalli/TroopFunctions.lua')
local Translation = import('/mods/DilliDalli/lua/AI/DilliDalli/FactionCompatibility.lua').translate
local CreatePriorityQueue = import('/mods/DilliDalli/lua/AI/DilliDalli/PriorityQueue.lua').CreatePriorityQueue
local PROFILER = import('/mods/DilliDalli/lua/AI/DilliDalli/Profiler.lua').GetProfiler()
local MAP = import('/mods/DilliDalli/lua/AI/DilliDalli/Mapping.lua').GetMap()
BaseController = Class({
Initialise = function(self,brain)
self.brain = brain
self.jobID = 1
self.mobileJobs = {}
self.factoryJobs = {}
self.upgradeJobs = {}
self.pendingStructures = { }
self.isBOComplete = false
self.tID = 1
self.assistRadius = 40
end,
GetThreadID = function(self)
self.tID = self.tID + 1
return self.tID
end,
CreateGenericJob = function(self,config)
local job = {
-- The thing to build
work = nil,
-- How important is it?
priority = 0,
-- Do we have a target location?
location = nil,
-- If we have a location, within what distance does the thing need building in?
distance = 0,
-- How much mass do we want to spend on this (through assistance only)?
targetSpend = 0,
-- Is this part of the initial build order?
buildOrder = false,
-- How many of these things to make? -1 => Inf
count = 1,
-- How many duplicates of this job to allow. -1 => Inf
duplicates = 1,
-- Keep while count == 0? (e.g. long standing tasks that the brain may want to update)
keep = false,
-- If we have to disable this job for some reason, then let the creator know (priority will get reset in this case)
failed = false,
-- Feedback to the job creator on how much is being spent on this job.
actualSpend = 0,
-- Should other units assist this job?
assist = true,
}
if config then
for k, v in config do
job[k] = v
end
end
return job
end,
AddMobileJob = function(self,job)
if not Translation[job.work] then
WARN("Unable to translate, ignoring: "..tostring(job.work))
return nil
end
local meta = { assigned = {}, assisting = {}, spend = 0, id = self.jobID, activeCount = 0, failures = 0, type="mobile" }
self.jobID = self.jobID + 1
table.insert(self.mobileJobs, { job = job, meta=meta })
return meta
end,
AddFactoryJob = function(self,job)
if not Translation[job.work] then
WARN("Unable to translate, ignoring: "..tostring(job.work))
return nil
end
local meta = { assigned = {}, assisting = {}, spend = 0, id = self.jobID, activeCount = 0, failures = 0, type="factory" }
self.jobID = self.jobID + 1
table.insert(self.factoryJobs, { job = job, meta=meta })
return meta
end,
AddUpgradeJob = function(self,job)
if not Translation[job.work] then
WARN("Unable to translate, ignoring: "..tostring(job.work))
return nil
end
local meta = { assigned = {}, assisting = {}, spend = 0, id = self.jobID, activeCount = 0, failures = 0, type="upgrade" }
self.jobID = self.jobID + 1
table.insert(self.upgradeJobs, { job = job, meta=meta })
return meta
end,
OnCompleteAssist = function(self,jobID,buildRate,thread)
for _, job in self.mobileJobs do
if job.meta.id == jobID then
local index = 0
for k, v in job.meta.assisting do
if v.myThread == thread then
job.meta.spend = job.meta.spend - buildRate*v.bp.Economy.BuildCostMass/v.bp.Economy.BuildTime
index = k
end
end
if index ~= 0 then
table.remove(job.meta.assisting,index)
else
WARN("BaseController: Unable to complete assist! (mobile) "..tostring(thread)..", "..tostring(jobID))
self:LogJobs()
end
return nil
end
end
for _, job in self.factoryJobs do
if job.meta.id == jobID then
local index
for k, v in job.meta.assisting do
if v.myThread == thread then
job.meta.spend = job.meta.spend - buildRate*v.bp.Economy.BuildCostMass/v.bp.Economy.BuildTime
index = k
end
end
if index then
table.remove(job.meta.assisting,index)
else
WARN("BaseController: Unable to complete assist! (factory) "..tostring(thread)..", "..tostring(jobID))
self:LogJobs()
end
return nil
end
end
-- Arriving here may be fine, the job could already have been deleted (in which case maintaining state isn't necessary)
return nil
end,
OnCompleteJob = function(self,unit,jobID,failed,buildRate,threadID,jobs)
-- Delete a job
-- TODO: end reliance on unit pointer for faction category (may be nil?)
local index = 0
for i, job in jobs do
if job.meta.id == jobID then
-- Keep this index
index = i
-- Keep track of job failures
if failed then
job.meta.failures =job.meta.failures+1
else
job.meta.failures = math.max(job.meta.failures-10,0)
end
-- Tidy up state
job.job.count = job.job.count - 1
local tBP = GetUnitBlueprintByName(Translation[job.job.work][unit.factionCategory])
job.meta.spend = job.meta.spend - buildRate*tBP.Economy.BuildCostMass/tBP.Economy.BuildTime
job.meta.activeCount = job.meta.activeCount - 1
-- Remove from assigned workers
local assignedIndex = 0
for k, v in job.meta.assigned do
if v.thread == threadID then
assignedIndex = k
end
end
if assignedIndex == 0 then
WARN("Unable to unassign job! "..tostring(jobID)..", "..tostring(threadID))
else
table.remove(job.meta.assigned,assignedIndex)
end
-- Complete assisting engies
for k, v in job.meta.assisting do
if v.thread == threadID then
if v.unit and (not v.unit.Dead) then
v.unit.CustomData.assistComplete = true
end
end
end
end
end
if index ~= 0 and (not jobs[index].job.keep) and jobs[index].meta.activeCount <= 0 and jobs[index].job.count <= 0 then
table.remove(jobs,index)
elseif index and jobs[index].meta.failures >= 10 then
-- Some kind of issue with this job, so stop assigning it.
if jobs[index].job.keep then
WARN("BaseController: Repeated Job failure, de-prioritising: "..tostring(jobs[index].job.work))
jobs[index].job.priority = -1
jobs[index].job.failed = true
else
WARN("BaseController: Repeated Job failure, removing: "..tostring(jobs[index].job.work))
table.remove(jobs,index)
end
elseif (not index) then
WARN("BaseController: Unable to complete job!")
end
end,
DoMobileAssist = function(self,engie,job,assist,thread)
-- Update job metadata to reflect this engie assisting the given job+target
local buildRate = engie:GetBuildRate()
for _, v in job.meta.assigned do
if v.thread == assist.thread then
job.meta.spend = job.meta.spend + buildRate*v.bp.Economy.BuildCostMass/v.bp.Economy.BuildTime
-- Set a flag to tell everyone this engie is busy
if (not engie.CustomData) then
engie.CustomData = {}
end
engie.CustomData.isAssigned = true
table.insert(job.meta.assisting,{ unit = engie, thread = assist.thread, myThread = thread, bp = v.bp })
return buildRate
end
end
WARN("BaseController: Unable to find assist target!")
return nil
end,
DoJobAssignment = function(self,unit,job,threadID)
-- Update job metadata to reflect this unit being assigned to the given job
local tBP = GetUnitBlueprintByName(Translation[job.job.work][unit.factionCategory])
local buildRate = unit:GetBuildRate()
job.meta.spend = job.meta.spend + buildRate*tBP.Economy.BuildCostMass/tBP.Economy.BuildTime
job.meta.activeCount = job.meta.activeCount + 1
-- Set a flag to tell everyone this unit is busy
if (not unit.CustomData) then
unit.CustomData = {}
end
unit.CustomData.isAssigned = true
--LOG("Assigning: "..tostring(unit.Dead)..", "..tostring(job.meta.id)..", "..tostring(threadID))
table.insert(job.meta.assigned,{ unit = unit, thread = threadID, bp = tBP })
return buildRate
end,
RunMobileJobThread = function(self,job,engie,assist,buildRate,threadID)
-- TODO: Support assistance
local start = PROFILER:Now()
local activeJob = job
local assistData = assist
local success = false
while activeJob do
if assistData then
PROFILER:Add("RunMobileJobThread",PROFILER:Now()-start)
TroopFunctions.EngineerAssist(engie,assistData.unit)
start = PROFILER:Now()
self:OnCompleteAssist(activeJob.meta.id,buildRate,threadID)
success = true
else
local unitID = Translation[activeJob.job.work][engie.factionCategory]
-- Build the thing
PROFILER:Add("RunMobileJobThread",PROFILER:Now()-start)
if activeJob.job.work == "MexT1" or activeJob.job.work == "MexT2" or activeJob.job.work == "MexT3" then
success = TroopFunctions.EngineerBuildMarkedStructure(self.brain,engie,unitID,"Mass")
elseif activeJob.job.work == "Hydro" then
success = TroopFunctions.EngineerBuildMarkedStructure(self.brain,engie,unitID,"Hydrocarbon")
else
success = TroopFunctions.EngineerBuildStructure(self.brain,engie,unitID)
end
start = PROFILER:Now()
-- Return engie back to the pool
self:OnCompleteJob(engie,activeJob.meta.id,not success,buildRate,threadID,self.mobileJobs)
end
if success and engie and (not engie.Dead) and (not engie.CustomData.excludeAssignment) then
activeJob = self:IdentifyJob(engie,self.mobileJobs)
if activeJob then
assistData = self:FindAssistInRadius(engie,activeJob,self.assistRadius)
if assistData then
self:DoMobileAssist(engie,activeJob,assistData,threadID)
else
self:DoJobAssignment(engie,activeJob,threadID)
end
end
else
activeJob = nil
end
end
if engie and (not engie.Dead) then
engie.CustomData.isAssigned = false
end
PROFILER:Add("RunMobileJobThread",PROFILER:Now()-start)
end,
RunFactoryJobThread = function(self,job,fac,buildRate,threadID)
-- TODO: Support assistance
local start = PROFILER:Now()
local activeJob = job
while activeJob do
local unitID = Translation[activeJob.job.work][fac.factionCategory]
-- Build the thing
PROFILER:Add("RunFactoryJobThread",PROFILER:Now()-start)
TroopFunctions.FactoryBuildUnit(fac,unitID)
start = PROFILER:Now()
-- Return fac back to the pool
self:OnCompleteJob(fac,activeJob.meta.id,false,buildRate,threadID,self.factoryJobs)
if fac and (not fac.Dead) and (not fac.CustomData.excludeAssignment) then
activeJob = self:IdentifyJob(fac,self.factoryJobs)
if activeJob then
self:DoJobAssignment(fac,activeJob,threadID)
end
else
activeJob = nil
end
end
if fac and (not fac.Dead) then
fac.CustomData.isAssigned = false
end
PROFILER:Add("RunFactoryJobThread",PROFILER:Now()-start)
end,
RunUpgradeJobThread = function(self,job,unit,buildRate,threadID)
local start = PROFILER:Now()
-- while assigned wait
while unit and (not unit.Dead) and unit.CustomData.isAssigned do
-- Probs fine, number of upgrades at any one time will be "smallish". Will profile this to be sure
PROFILER:Add("RunUpgradeJobThread",PROFILER:Now()-start)
WaitTicks(1)
start = PROFILER:Now()
end
if unit and (not unit.Dead) then
-- Issue upgrade
--LOG("Issuing upgrade")
IssueClearCommands({unit})
IssueUpgrade({unit},Translation[job.job.work][unit.factionCategory])
end
PROFILER:Add("RunUpgradeJobThread",PROFILER:Now()-start)
WaitTicks(2)
start = PROFILER:Now()
while unit and (not unit.Dead) and (not unit:IsIdleState()) do
-- Still probably fine
PROFILER:Add("RunUpgradeJobThread",PROFILER:Now()-start)
WaitTicks(2)
start = PROFILER:Now()
end
-- reset exclusion flag, to release the unit for jobs
if unit and (not unit.Dead) then
unit.CustomData.excludeAssignment = nil
end
self:OnCompleteJob(unit,job.meta.id,false,buildRate,threadID,self.upgradeJobs)
PROFILER:Add("RunUpgradeJobThread",PROFILER:Now()-start)
end,
AssignJobMobile = function(self,engie,job)
local threadID = self:GetThreadID()
-- TODO: check for unfinished buildings/exps in the same category that could be continued
-- This must be done before we fork, or we risk over-assigning units to this job
local assist = self:FindAssistInRadius(engie,job,self.assistRadius)
local buildRate = 0
if assist then
buildRate = self:DoMobileAssist(engie,job,assist,threadID)
else
buildRate = self:DoJobAssignment(engie,job,threadID)
end
self:ForkThread(self.RunMobileJobThread,job,engie,assist,buildRate,threadID)
end,
AssignJobFactory = function(self,fac,job)
local threadID = self:GetThreadID()
-- This must be done before we fork, or we risk over-assigning units to this job
local buildRate = self:DoJobAssignment(fac,job,threadID)
self:ForkThread(self.RunFactoryJobThread,job,fac,buildRate,threadID)
end,
AssignUpgradeJob = function(self,unit,job)
local threadID = self:GetThreadID()
-- I can't use the regular job assignment, since units are passed in here that may already be on jobs.
local tBP = GetUnitBlueprintByName(Translation[job.job.work][unit.factionCategory])
local buildRate = unit:GetBuildRate()
job.meta.spend = job.meta.spend + buildRate*tBP.Economy.BuildCostMass/tBP.Economy.BuildTime
job.meta.activeCount = job.meta.activeCount + 1
-- Exclude this unit from additional jobs, so we can reserve it for an upgrade. Pertinent for factories.
if (not unit.CustomData) then
unit.CustomData = {}
end
unit.CustomData.excludeAssignment = true
table.insert(job.meta.assigned,{ unit = unit, thread = threadID, bp = tBP })
self:ForkThread(self.RunUpgradeJobThread,job,unit,buildRate,threadID)
end,
FindAssistInRadius = function(self,engie,job,radius)
if (not job.job.assist) or (not job.meta.assigned) then
return nil
end
local best
local myPos = engie:GetPosition()
for _, v in job.meta.assigned do
local theirPos = v.unit:GetPosition()
if MAP:CanPathTo(myPos,theirPos,"surf") and (VDist3(myPos,theirPos) < self.assistRadius) and (not v.unit:IsBeingBuilt()) then
return { unit = v.unit, thread = v.thread }
end
end
return nil
end,
CanDoJob = function(self,unit,job)
-- Used for both Engineers and Factories
-- Check if there is an available and pathable resource marker for restrictive thingies
if (job.job.work == "MexT1" or job.job.work == "MexT2" or job.job.work == "MexT3") then
if (not self.brain.intel:EmptyMassMarkerExists(unit:GetPosition())) then
return false
elseif (not EntityCategoryContains(categories.TECH1,unit)) and self.isBOComplete then
return false
end
elseif job.job.work == "Hydro" then
if (not self.brain.intel:FindNearestEmptyMarker(unit:GetPosition(),"Hydrocarbon")) then
return false
elseif (not EntityCategoryContains(categories.TECH1,unit)) and self.isBOComplete then
return false
end
-- TODO
return false
end
if job.job.priority <= 0 or job.job.count <= 0 or job.job.targetSpend < 0 then
return false
end
if job.job.com and (not EntityCategoryContains(categories.COMMAND,unit)) then
-- We're still allowed to assist, just not start it
return job.meta.spend < job.job.targetSpend and job.job.assist and self:FindAssistInRadius(unit,job,self.assistRadius)
end
-- TODO: Add location checks in here
-- TODO: check for unfinished buildings/exps in the same category that could be continued
return (
job.meta.spend < job.job.targetSpend and (
(
(job.meta.activeCount < job.job.duplicates)
and (job.meta.activeCount < job.job.count)
and unit:CanBuild(Translation[job.job.work][unit.factionCategory])
) or (
job.job.assist and self:FindAssistInRadius(unit,job,self.assistRadius)
)
)
)
end,
CheckPriority = function(self, currentJob, newJob)
-- Return true if the new job should be higher priority than the old job.
-- Check the old one is actually set yet
if (not currentJob) then
return newJob.job.priority > 0
end
-- Check if one is a build order, in which case prioritise it.
if currentJob.job.buildOrder and (not newJob.job.buildOrder) then
return false
elseif newJob.job.buildOrder and (not currentJob.job.buildOrder) then
return true
end
-- Check if one has a higher priority field
if currentJob.job.priority > newJob.job.priority then
return false
elseif currentJob.job.priority < newJob.job.priority then
return true
end
-- Get most limiting marginal utility between each of the three restrictions on jobs: duplicates vs active, count vs active, targetSpend vs spend
-- Division is ok because we check in CanDoJob that each denominator is strictly positive
local oldMarginalUtility = math.max(currentJob.meta.activeCount/currentJob.job.duplicates,
currentJob.meta.activeCount/currentJob.job.count,
currentJob.meta.spend/currentJob.job.targetSpend)
local newMarginalUtility = math.max(newJob.meta.activeCount/newJob.job.duplicates,
newJob.meta.activeCount/newJob.job.count,
newJob.meta.spend/newJob.job.targetSpend)
return oldMarginalUtility > newMarginalUtility
end,
IdentifyJob = function(self,unit,jobs)
-- TODO: Add factory assistance support
local bestJob
for _, job in jobs do
-- TODO: Support assitance
-- TODO: Support location constraints
if self:CanDoJob(unit,job) and self:CheckPriority(bestJob,job) then
bestJob = job
end
end
return bestJob
end,
AssignEngineers = function(self,allEngies)
-- TODO: implement full stable matching algorithm
-- TODO: implement job queues (take eta into account when considering location specific jobs)
local idle = 0
for i=1,table.getn(allEngies) do
local job = self:IdentifyJob(allEngies[i],self.mobileJobs)
if job then
self:AssignJobMobile(allEngies[i],job)
else
idle = idle + 1
end
end
return idle
end,
AssignFactories = function(self,allFacs)
-- TODO: implement full stable matching algorithm
for i=1,table.getn(allFacs) do
local job = self:IdentifyJob(allFacs[i],self.factoryJobs)
if job then
self:AssignJobFactory(allFacs[i],job)
end
end
end,
AssignUpgrades = function(self)
-- TODO: fix location thingy
local myPos = self.brain.intel.allies[1]
for _, job in self.upgradeJobs do
local units
-- Get the right kind of units for upgrading
if job.job.targetSpend <= 0 or job.job.count <= 0 or job.job.duplicates <= 0 then
continue
elseif job.job.work == "MexT2" or job.job.work == "MexT3" then
units = self.brain.aiBrain:GetListOfUnits(categories.MASSEXTRACTION*categories.STRUCTURE,false,true)
elseif job.job.work == "LandHQT2" or job.job.work == "LandHQT3" or job.job.work == "LandSupportT2" or job.job.work == "LandSupportT3" then
units = self.brain.aiBrain:GetListOfUnits(categories.LAND*categories.FACTORY*categories.STRUCTURE,false,true)
elseif job.job.work == "AirHQT2" or job.job.work == "AirHQT3" or job.job.work == "AirSupportT2" or job.job.work == "AirSupportT3" then
units = self.brain.aiBrain:GetListOfUnits(categories.AIR*categories.FACTORY*categories.STRUCTURE,false,true)
end
local prioritisedUnits = CreatePriorityQueue()
for _, unit in units do
if (not unit) or unit.Dead or (not unit:CanBuild(Translation[job.job.work][unit.factionCategory])) or unit.CustomData.excludeAssignment or unit:IsBeingBuilt() then
-- Can't upgrade to the relevant unit
continue
else
prioritisedUnits:Queue({ unit = unit, priority = VDist3(unit:GetPosition(),myPos) })
end
end
while job.meta.spend < job.job.targetSpend and job.meta.activeCount < job.job.duplicates and job.meta.activeCount < job.job.count and prioritisedUnits:Size() > 0 do
self:AssignUpgradeJob(prioritisedUnits:Dequeue().unit,job)
end
end
end,
GetEngineers = function(self)
local units = self.brain.aiBrain:GetListOfUnits(categories.MOBILE*categories.ENGINEER,false,true)
local n = 0
local engies = {}
for _, v in units do
if (not v.CustomData or ((not v.CustomData.excludeAssignment) and (not v.CustomData.isAssigned))) and (not v:IsBeingBuilt()) and (not v.Dead) then
table.insert(engies,v)
end
end
return engies
end,
GetFactories = function(self)
local units = self.brain.aiBrain:GetListOfUnits(categories.STRUCTURE*categories.FACTORY,false,true)
local n = 0
local facs = {}
for _, v in units do
if ((not v.CustomData) or ((not v.CustomData.excludeAssignment) and (not v.CustomData.isAssigned))) and (not v.Dead) then
n = n+1
facs[n] = v
end
end
return facs
end,
EngineerManagementThread = function(self)
local i = 0
while self.brain:IsAlive() do
i = i+1
local start = PROFILER:Now()
local idle = self:AssignEngineers(self:GetEngineers())
PROFILER:Add("EngineerManagementThread",PROFILER:Now()-start)
if math.mod(i,10) == 0 then
--self:LogJobs()
end
WaitTicks(math.min(math.max(10,idle),100))
end
end,
FactoryManagementThread = function(self)
while self.brain:IsAlive() do
local start = PROFILER:Now()
self:AssignFactories(self:GetFactories())
PROFILER:Add("FactoryManagementThread",PROFILER:Now()-start)
WaitSeconds(1)
end
end,
UpgradeManagementThread = function(self)
while self.brain:IsAlive() do
local start = PROFILER:Now()
self:AssignUpgrades()
PROFILER:Add("UpgradeManagementThread",PROFILER:Now()-start)
WaitSeconds(3)
end
end,
MonitorBOCompletion = function(self)
local isComplete = false
while self.brain:IsAlive() and (not isComplete) do
isComplete = true
for _, v in self.mobileJobs do
if v.job.buildOrder then
isComplete = false
end
end
WaitTicks(2)
end
LOG("Build Order Completed")
self.isBOComplete = true
end,
JobMonitoring = function(self)
while self.brain:IsAlive() do
local numAssigned = 0
local numAssisting = 0
for _, v in self.mobileJobs do
numAssigned = numAssigned + table.getn(v.meta.assigned)
numAssisting = numAssisting + table.getn(v.meta.assisting)
end
for _, v in self.factoryJobs do
numAssigned = numAssigned + table.getn(v.meta.assigned)
numAssisting = numAssisting + table.getn(v.meta.assisting)
end
for _, v in self.upgradeJobs do
numAssigned = numAssigned + table.getn(v.meta.assigned)
numAssisting = numAssisting + table.getn(v.meta.assisting)
end
LOG("Assigned builders: "..tostring(numAssigned))
LOG("Assisting builders: "..tostring(numAssisting))
LOG("Total Jobs: "..tostring(table.getn(self.mobileJobs)+table.getn(self.factoryJobs)+table.getn(self.upgradeJobs)))
LOG("Pending Structures: "..tostring(table.getn(self.pendingStructures)))
WaitTicks(50)
end
end,
Run = function(self)
self:ForkThread(self.EngineerManagementThread)
self:ForkThread(self.FactoryManagementThread)
self:ForkThread(self.UpgradeManagementThread)
self:ForkThread(self.MonitorBOCompletion)
--self:ForkThread(self.JobMonitoring)
end,
LogAssisters = function(self,id)
for k, v in self.mobileJobs do
if v.meta.id == id then
s = ""
for _, v1 in v.meta.assisting do
s = s.."("..tostring(v1.thread)..","..tostring(v1.myThread)..") "
end
LOG(tostring(k)..") { "..s.."}")
end
end
end,
LogMobileJobs = function(self)
LOG("===== LOGGING MOBILE JOBS =====")
for k, v in self.mobileJobs do
LOG(tostring(k).." {")
LOG("\tjob:")
for k1, v1 in v.job do
LOG("\t\t"..tostring(k1)..":\t"..tostring(v1))
if type(v1) == "table" then
for k2, v2 in v1 do
LOG("\t\t\t"..tostring(k2)..":\t"..tostring(v2))
end
end
end
LOG("\tmeta:")
for k1, v1 in v.meta do
LOG("\t\t"..tostring(k1)..":\t"..tostring(v1))
if type(v1) == "table" then
for k2, v2 in v1 do
LOG("\t\t\t"..tostring(k2)..":\t"..tostring(v2))
if type(v2) == "table" then
for k3, v3 in v2 do
LOG("\t\t\t\t"..tostring(k3)..":\t"..tostring(v3))
end
end
end
end
end
end
end,
LogJobs = function(self)
LOG("===== LOGGING BASECONTROLLER JOBS =====")
LOG("MOBILE:")
for k, v in self.mobileJobs do
LOG("\t"..tostring(k)..":\t"..tostring(v.job.work)..", "..tostring(v.meta.id)..", "..tostring(v.job.targetSpend)..", "..tostring(v.job.actualSpend)..", "..tostring(v.meta.spend)..", "..tostring(v.job.count))
end
LOG("FACTORY:")
for k, v in self.factoryJobs do
LOG("\t"..tostring(k)..":\t"..tostring(v.job.work)..", "..tostring(v.meta.id)..", "..tostring(v.job.targetSpend)..", "..tostring(v.job.actualSpend)..", "..tostring(v.meta.spend)..", "..tostring(v.job.count))
end
LOG("===== END LOG =====")
end,
BaseIssueBuildMobile = function(self, units, pos, bp, id)
table.insert(self.pendingStructures, { pos=table.copy(pos), bp=bp, id=id })
-- TODO: check this later
IssueBuildMobile(units,pos,bp.BlueprintId,{})
end,
BaseCompleteBuildMobile = function(self, id)
local index = 0
for k, v in self.pendingStructures do
if v.id == id then
index = k
end
end
if index ~= 0 then
table.remove(self.pendingStructures,index)
else
WARN("BaseController: No pending structure found! ("..tostring(id)..")")
end
end,
LocationIsClear = function(self, location, bp)
-- TODO: Fix this, noticed it's not working quite right
-- Checks if any planned buildings overlap with this building. Return true if they do not.
local cornerX0 = location[1]+bp.SizeX/2
local cornerZ0 = location[3]+bp.SizeZ/2
local cornerX1 = location[1]-bp.SizeX/2
local cornerZ1 = location[3]-bp.SizeZ/2
for k, v in self.pendingStructures do
-- If overlap, return false
if location[1] == v.pos[1] and location[3] == v.pos[3] then
-- Location is the same, return false
return false
elseif cornerX0 >= v.pos[1]-v.bp.SizeX/2 and cornerX0 <= v.pos[1]+v.bp.SizeX/2 and cornerZ0 >= v.pos[3]-v.bp.SizeZ/2 and cornerZ0 <= v.pos[3]+v.bp.SizeZ/2 then
-- Bottom right corner
return false
elseif cornerX1 >= v.pos[1]-v.bp.SizeX/2 and cornerX1 <= v.pos[1]+v.bp.SizeX/2 and cornerZ0 >= v.pos[3]-v.bp.SizeZ/2 and cornerZ0 <= v.pos[3]+v.bp.SizeZ/2 then
-- Bottom left corner
return false
elseif cornerX0 >= v.pos[1]-v.bp.SizeX/2 and cornerX0 <= v.pos[1]+v.bp.SizeX/2 and cornerZ1 >= v.pos[3]-v.bp.SizeZ/2 and cornerZ1 <= v.pos[3]+v.bp.SizeZ/2 then
-- Top right corner
return false
elseif cornerX1 >= v.pos[1]-v.bp.SizeX/2 and cornerX1 <= v.pos[1]+v.bp.SizeX/2 and cornerZ1 >= v.pos[3]-v.bp.SizeZ/2 and cornerZ1 <= v.pos[3]+v.bp.SizeZ/2 then
-- Top left corner
return false
end
end
return true
end,
ForkThread = function(self, fn, ...)
if fn then
local thread = ForkThread(fn, self, unpack(arg))
self.brain.Trash:Add(thread)
return thread
else
return nil
end
end,
})
function CreateBaseController(brain)
local bc = BaseController()
bc:Initialise(brain)
return bc
end |
-------------------------------------------------------------------------------
-- PhysObj functions.
-------------------------------------------------------------------------------
SF.PhysObjs = {}
--- PhysObj Type
-- @shared
local physobj_methods, physobj_metatable = SF.RegisterType("PhysObj")
local wrap, unwrap = SF.CreateWrapper(physobj_metatable, true, false)
local checktype = SF.CheckType
local checkluatype = SF.CheckLuaType
local checkpermission = SF.Permissions.check
SF.PhysObjs.Methods = physobj_methods
SF.PhysObjs.Metatable = physobj_metamethods
SF.PhysObjs.Wrap = wrap
SF.PhysObjs.Unwrap = unwrap
local ewrap, eunwrap
local owrap, ounwrap = SF.WrapObject, SF.UnwrapObject
local ang_meta, vec_meta
local vwrap, vunwrap, awrap, aunwrap, mwrap
SF.AddHook("postload", function()
ang_meta = SF.Angles.Metatable
vec_meta = SF.Vectors.Metatable
ewrap = SF.Entities.Wrap
eunwrap = SF.Entities.Unwrap
vwrap = SF.Vectors.Wrap
vunwrap = SF.Vectors.Unwrap
awrap = SF.Angles.Wrap
aunwrap = SF.Angles.Unwrap
mwrap = SF.VMatrix.Wrap
-- @name SF.DefaultEnvironment.FVPHYSICS
-- @class table
SF.DefaultEnvironment.FVPHYSICS = {
["CONSTRAINT_STATIC"] = FVPHYSICS_CONSTRAINT_STATIC,
["DMG_DISSOLVE"] = FVPHYSICS_DMG_DISSOLVE,
["DMG_SLICE"] = FVPHYSICS_DMG_SLICE,
["HEAVY_OBJECT"] = FVPHYSICS_HEAVY_OBJECT,
["MULTIOBJECT_ENTITY"] = FVPHYSICS_MULTIOBJECT_ENTITY,
["NO_IMPACT_DMG"] = FVPHYSICS_NO_IMPACT_DMG,
["NO_NPC_IMPACT_DMG"] = FVPHYSICS_NO_NPC_IMPACT_DMG,
["NO_PLAYER_PICKUP"] = FVPHYSICS_NO_PLAYER_PICKUP,
["NO_SELF_COLLISIONS"] = FVPHYSICS_NO_SELF_COLLISIONS,
["PART_OF_RAGDOLL"] = FVPHYSICS_PART_OF_RAGDOLL,
["PENETRATING"] = FVPHYSICS_PENETRATING,
["PLAYER_HELD"] = FVPHYSICS_PLAYER_HELD,
["WAS_THROWN"] = FVPHYSICS_WAS_THROWN,
}
end)
local function checkvector(v)
if v[1]<-1e12 or v[1]>1e12 or v[1]~=v[1] or
v[2]<-1e12 or v[2]>1e12 or v[2]~=v[2] or
v[3]<-1e12 or v[3]>1e12 or v[3]~=v[3] then
SF.Throw("Input vector too large or NAN", 3)
end
end
--- Checks if the physics object is valid
-- @shared
-- @return boolean if the physics object is valid
function physobj_methods:isValid()
return unwrap(self):IsValid()
end
--- Gets the entity attached to the physics object
-- @shared
-- @return The entity attached to the physics object
function physobj_methods:getEntity()
return ewrap(unwrap(self):GetEntity())
end
--- Gets the position of the physics object
-- @shared
-- @return Vector position of the physics object
function physobj_methods:getPos()
return vwrap(unwrap(self):GetPos())
end
--- Returns the world transform matrix of the physobj
-- @shared
-- @return The matrix
function physobj_methods:getMatrix()
return mwrap(unwrap(self):GetPositionMatrix())
end
--- Gets the angles of the physics object
-- @shared
-- @return Angle angles of the physics object
function physobj_methods:getAngles()
return awrap(unwrap(self):GetAngles())
end
--- Gets the velocity of the physics object
-- @shared
-- @return Vector velocity of the physics object
function physobj_methods:getVelocity()
return vwrap(unwrap(self):GetVelocity())
end
--- Gets the axis aligned bounding box of the physics object
-- @shared
-- @return The mins of the AABB
-- @return The maxs of the AABB
function physobj_methods:getAABB()
local a, b = unwrap(self):GetAABB()
return vwrap(a), vwrap(b)
end
--- Gets the velocity of the physics object at an arbitrary point in its local reference frame
--- This includes velocity at the point induced by rotational velocity
-- @shared
-- @param vec The point to get velocity of in local reference frame
-- @return Vector Local velocity of the physics object at the point
function physobj_methods:getVelocityAtPoint(vec)
checktype(vec, vec_meta)
return vwrap(unwrap(self):GetVelocityAtPoint(vunwrap(vec)))
end
--- Gets the angular velocity of the physics object
-- @shared
-- @return Vector angular velocity of the physics object
function physobj_methods:getAngleVelocity()
return vwrap(unwrap(self):GetAngleVelocity())
end
--- Gets the mass of the physics object
-- @shared
-- @return mass of the physics object
function physobj_methods:getMass()
return unwrap(self):GetMass()
end
--- Gets the center of mass of the physics object in the local reference frame.
-- @shared
-- @return Center of mass vector in the physobject's local reference frame.
function physobj_methods:getMassCenter()
return vwrap(unwrap(self):GetMassCenter())
end
--- Gets the inertia of the physics object
-- @shared
-- @return Vector Inertia of the physics object
function physobj_methods:getInertia()
return vwrap(unwrap(self):GetInertia())
end
--- Gets the material of the physics object
-- @shared
-- @return The physics material of the physics object
function physobj_methods:getMaterial()
return unwrap(self):GetMaterial()
end
--- Returns a vector in the local reference frame of the physicsobject from the world frame
-- @param vec The vector to transform
-- @return The transformed vector
function physobj_methods:worldToLocal(vec)
checktype(vec, vec_meta)
return vwrap(unwrap(self):WorldToLocal(vunwrap(vec)))
end
--- Returns a vector in the reference frame of the world from the local frame of the physicsobject
-- @param vec The vector to transform
-- @return The transformed vector
function physobj_methods:localToWorld(vec)
checktype(vec, vec_meta)
return vwrap(unwrap(self):LocalToWorld(vunwrap(vec)))
end
--- Returns a normal vector in the local reference frame of the physicsobject from the world frame
-- @param vec The normal vector to transform
-- @return The transformed vector
function physobj_methods:worldToLocalVector(vec)
checktype(vec, vec_meta)
return vwrap(unwrap(self):WorldToLocalVector(vunwrap(vec)))
end
--- Returns a normal vector in the reference frame of the world from the local frame of the physicsobject
-- @param vec The normal vector to transform
-- @return The transformed vector
function physobj_methods:localToWorldVector(vec)
checktype(vec, vec_meta)
return vwrap(unwrap(self):LocalToWorldVector(vunwrap(vec)))
end
--- Returns a table of MeshVertex structures where each 3 vertices represent a triangle. See: http://wiki.garrysmod.com/page/Structures/MeshVertex
-- @return table of MeshVertex structures
function physobj_methods:getMesh ()
local mesh = unwrap(self):GetMesh()
return SF.Sanitize(mesh)
end
--- Returns a structured table, the physics mesh of the physics object. See: http://wiki.garrysmod.com/page/Structures/MeshVertex
-- @return table of MeshVertex structures
function physobj_methods:getMeshConvexes ()
local mesh = unwrap(self):GetMeshConvexes()
return SF.Sanitize(mesh)
end
--- Sets the physical material of a physics object
-- @param material The physical material to set it to
function physobj_methods:setMaterial(material)
checkluatype (material, TYPE_STRING)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.setRenderProperty")
phys:SetMaterial(material)
if not phys:IsMoveable() then
phys:EnableMotion(true)
phys:EnableMotion(false)
end
end
if SERVER then
--- Sets the position of the physics object. Will cause interpolation of the entity in clientside, use entity.setPos to avoid this.
-- @server
-- @param pos The position vector to set it to
function physobj_methods:setPos(pos)
checktype(pos, vec_meta)
pos = vunwrap(pos)
checkvector(pos)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.setPos")
phys:SetPos(pos)
end
--- Sets the angles of the physics object. Will cause interpolation of the entity in clientside, use entity.setAngles to avoid this.
-- @server
-- @param ang The angle to set it to
function physobj_methods:setAngles(ang)
checktype(ang, ang_meta)
ang = aunwrap(ang)
checkvector(ang)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.setAngles")
phys:SetAngles(ang)
end
--- Sets the velocity of the physics object
-- @server
-- @param vel The velocity vector to set it to
function physobj_methods:setVelocity(vel)
checktype(vel, vec_meta)
vel = vunwrap(vel)
checkvector(vel)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.setVelocity")
phys:SetVelocity(vel)
end
--- Sets the buoyancy ratio of a physobject
-- @server
-- @param ratio The buoyancy ratio to use
function physobj_methods:setBuoyancyRatio(ratio)
checkluatype(ratio, TYPE_NUMBER)
if ratio<-1e12 or ratio>1e12 or ratio~=ratio then
SF.Throw("Input number too large or NAN", 2)
end
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.setMass")
phys:SetBuoyancyRatio(ratio)
end
--- Applys a force to the center of the physics object
-- @server
-- @param force The force vector to apply
function physobj_methods:applyForceCenter(force)
checktype(force, vec_meta)
force = vunwrap(force)
checkvector(force)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.applyForce")
phys:ApplyForceCenter(force)
end
--- Applys an offset force to a physics object
-- @server
-- @param force The force vector to apply
-- @param position The position in world coordinates
function physobj_methods:applyForceOffset(force, position)
checktype(force, vec_meta)
checktype(position, vec_meta)
force = vunwrap(force)
checkvector(force)
position = vunwrap(position)
checkvector(position)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.applyForce")
phys:ApplyForceOffset(force, position)
end
--- Sets the angular velocity of an object
-- @server
-- @param angvel The local angvel vector to set
function physobj_methods:setAngleVelocity(angvel)
checktype(angvel, vec_meta)
angvel = vunwrap(angvel)
checkvector(angvel)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.applyForce")
phys:AddAngleVelocity(angvel - phys:GetAngleVelocity())
end
--- Applys a angular velocity to an object
-- @server
-- @param angvel The local angvel vector to apply
function physobj_methods:addAngleVelocity(angvel)
checktype(angvel, vec_meta)
angvel = vunwrap(angvel)
checkvector(angvel)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.applyForce")
phys:AddAngleVelocity(angvel)
end
--- Applys a torque to a physics object
-- @server
-- @param torque The world torque vector to apply
function physobj_methods:applyTorque(torque)
checktype(torque, vec_meta)
torque = vunwrap(torque)
checkvector(torque)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.applyForce")
phys:ApplyTorqueCenter(torque)
end
--- Sets the mass of a physics object
-- @server
-- @param mass The mass to set it to
function physobj_methods:setMass(mass)
checkluatype(mass, TYPE_NUMBER)
local phys = unwrap(self)
local ent = phys:GetEntity()
checkpermission(SF.instance, ent, "entities.setMass")
local m = math.Clamp(mass, 1, 50000)
phys:SetMass(m)
duplicator.StoreEntityModifier(ent, "mass", { Mass = m })
end
--- Sets the inertia of a physics object
-- @server
-- @param inertia The inertia vector to set it to
function physobj_methods:setInertia(inertia)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.setInertia")
local vec = vunwrap(inertia)
checkvector(vec)
vec[1] = math.Clamp(vec[1], 1, 100000)
vec[2] = math.Clamp(vec[2], 1, 100000)
vec[3] = math.Clamp(vec[3], 1, 100000)
phys:SetInertia(vec)
end
local validGameFlags = FVPHYSICS_DMG_DISSOLVE + FVPHYSICS_DMG_SLICE + FVPHYSICS_HEAVY_OBJECT + FVPHYSICS_NO_IMPACT_DMG +
FVPHYSICS_NO_NPC_IMPACT_DMG + FVPHYSICS_NO_PLAYER_PICKUP
--- Adds game flags to the physics object. Some flags cannot be modified
-- @param flags The flags to add. FVPHYSICS enum. Can be:<br>
-- FVPHYSICS.DMG_DISSOLVE<br>
-- FVPHYSICS.DMG_SLICE<br>
-- FVPHYSICS.HEAVY_OBJECT<br>
-- FVPHYSICS.NO_IMPACT_DMG<br>
-- FVPHYSICS.NO_NPC_IMPACT_DMG<br>
-- FVPHYSICS.NO_PLAYER_PICKUP<br>
function physobj_methods:addGameFlags(flags)
checkluatype(flags, TYPE_NUMBER)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.canTool")
local invalidFlags = bit.band(bit.bnot(validGameFlags), flags)
if invalidFlags == 0 then
phys:AddGameFlag(flags)
else
SF.Throw("Invalid flags " .. invalidFlags, 2)
end
end
--- Clears game flags from the physics object. Some flags cannot be modified
-- @param flags The flags to add. FVPHYSICS enum. Can be:<br>
-- FVPHYSICS.DMG_DISSOLVE<br>
-- FVPHYSICS.DMG_SLICE<br>
-- FVPHYSICS.HEAVY_OBJECT<br>
-- FVPHYSICS.NO_IMPACT_DMG<br>
-- FVPHYSICS.NO_NPC_IMPACT_DMG<br>
-- FVPHYSICS.NO_PLAYER_PICKUP<br>
function physobj_methods:clearGameFlags(flags)
checkluatype(flags, TYPE_NUMBER)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.canTool")
local invalidFlags = bit.band(bit.bnot(validGameFlags), flags)
if invalidFlags == 0 then
phys:ClearGameFlag(flags)
else
SF.Throw("Invalid flags " .. invalidFlags, 2)
end
end
--- Returns whether the game flags of the physics object are set.
-- @param flags The flags to test. FVPHYSICS enum.
-- @return boolean If the flags are set
function physobj_methods:hasGameFlags(flags)
checkluatype(flags, TYPE_NUMBER)
local phys = unwrap(self)
return phys:HasGameFlag(flags)
end
--- Sets bone gravity
-- @param grav Bool should the bone respect gravity?
function physobj_methods:enableGravity(grav)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.enableGravity")
phys:EnableGravity(grav and true or false)
phys:Wake()
end
--- Sets the bone drag state
-- @param drag Bool should the bone have air resistence?
function physobj_methods:enableDrag(drag)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.enableDrag")
phys:EnableDrag(drag and true or false)
end
--- Check if bone is affected by air resistance
-- @return boolean If bone is affected by drag
function physobj_methods:isDragEnabled()
local phys = unwrap(self)
return phys:IsDragEnabled()
end
--- Sets coefficient of air resistance affecting the bone. Air resistance depends on the cross-section of the object.
-- @param coeff Number how much drag affects the bone
function physobj_methods:setDragCoefficient(coeff)
checkluatype(coeff, TYPE_NUMBER)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.enableDrag")
phys:SetDragCoefficient(coeff)
end
--- Sets coefficient of air resistance affecting the bone when rotating. Air resistance depends on the cross-section of the object.
-- @param coeff Number how much drag affects the bone when rotating
function physobj_methods:setAngleDragCoefficient(coeff)
checkluatype(coeff, TYPE_NUMBER)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.enableDrag")
phys:SetAngleDragCoefficient(coeff)
end
--- Returns Movement damping of the bone.
-- @return Linear damping
-- @return Angular damping
function physobj_methods:getDamping()
local phys = unwrap(self)
return phys:GetDamping()
end
--- Sets the movement damping of the bone. Unlike air drag, it doesn't take into account the cross-section of the object.
-- @param linear Number of the linear damping
-- @param angular Number of the angular damping
function physobj_methods:setDamping(linear, angular)
checkluatype(linear, TYPE_NUMBER)
checkluatype(angular, TYPE_NUMBER)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.setDamping")
return phys:SetDamping(linear, angular)
end
--- Sets the bone movement state
-- @param move Bool should the bone move?
function physobj_methods:enableMotion(move)
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.enableMotion")
phys:EnableMotion(move and true or false)
phys:Wake()
end
--- Returns whether the physobj is asleep
-- @server
-- @return boolean if the physobj is asleep
function physobj_methods:isAsleep()
local phys = unwrap(self)
return phys:IsAsleep()
end
--- Makes a physobj go to sleep. (like it's frozen but interacting wakes it back up)
-- @server
function physobj_methods:sleep()
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.applyForce")
phys:Sleep()
end
--- Makes a sleeping physobj wakeup
-- @server
function physobj_methods:wake()
local phys = unwrap(self)
checkpermission(SF.instance, phys:GetEntity(), "entities.applyForce")
phys:Wake()
end
end
|
local screens = require "lib.screens"
local fuiorc = require "fuior.compiler"
local fui = require "fuior.runtime"
local function game()
fuiorc.compile("/fuior/src/test.fui")(fui.new())
local wait_for_transition = screens.replace("game")
print("Screen loaded")
wait_for_transition()
print("Screen transition finished")
end
return game
|
----------------------------------------------------------------
-- Copyright (c) 2013 Klei Entertainment Inc.
-- All Rights Reserved.
-- SPY SOCIETY.
----------------------------------------------------------------
local PITCH_SHIFT_FFT = 256
local array = include( "modules/array" )
----------------------------------------------------------------
--
local Mix = class()
function Mix:init( name, fadetime, priority, categoryVolumes, pitchShifts )
self._name = name
self._fadetime = fadetime or 1
self._priority = priority or 0
self._categoryVolumes = categoryVolumes or {}
self._pitchShifts = pitchShifts or {}
end
function Mix:destroy()
end
function Mix:applyBlend( from, t )
t = math.min( 1.0, t )
for category,volume in pairs( from._categoryVolumes ) do
local target_volume = self:getCategoryVolume( category )
local eased_volume = volume * (1 - t) + target_volume * t
MOAIFmodDesigner.setCategoryVolume( category, eased_volume )
end
-- Blend dsp effects from source.
for category, sourcePitch in pairs( from._pitchShifts ) do
local targetPitch = self._pitchShifts[ category ] or 1.0
local pitchShift = sourcePitch * (1 - t) + targetPitch * t
if pitchShift == 1.0 then
MOAIFmodDesigner.clearDSP( category )
else
MOAIFmodDesigner.setPitchShift( category, pitchShift, PITCH_SHIFT_FFT )
end
end
-- Blend remaining dsp effects in self. (only ones taht werne't already blended)
for category, targetPitch in pairs( self._pitchShifts ) do
if from._pitchShifts[ category ] == nil then
local sourcePitch = 1.0
local pitchShift = sourcePitch * (1 - t) + targetPitch * t
if pitchShift == 1.0 then
MOAIFmodDesigner.clearDSP( category )
else
MOAIFmodDesigner.setPitchShift( category, pitchShift, PITCH_SHIFT_FFT )
end
end
end
end
function Mix:setCategoryVolume( category, volume )
self._categoryVolumes[ category ] = volume
end
function Mix:getCategoryVolume( category )
return self._categoryVolumes[ category ] or 0
end
function Mix:setPitchShift( category, pitchShift )
self._pitchShifts[ category ] = pitchShift
end
----------------------------------------------------------------
local Mixer = class()
function Mixer:init()
self._mixes = {}
self._stack = {}
self._autoMixes = {}
self._updateThread = MOAICoroutine.new()
self._updateThread:run( function() while true do self:update() coroutine.yield() end end )
end
function Mixer:destroy()
self._updateThread:stop()
end
function Mixer:addMix( name, ... )
self._mixes[ name ] = Mix( name, ... )
end
function Mixer:getMixes()
return self._stack
end
function Mixer:pushMix( name )
local mix = self._mixes[ name ]
if mix then
local top = self._stack[1]
table.insert( self._stack, mix )
table.sort( self._stack, function(l,r) return l._priority > r._priority end )
if top and top ~= self._stack[1] then
self:startBlend( self._snapshot or top )
end
end
end
function Mixer:popMix( name )
local top = self._stack[1]
for i,mix in ipairs( self._stack ) do
if name == mix._name then
table.remove( self._stack, i )
if top ~= self._stack[1] then
self:startBlend( self._snapshot or top )
end
break;
end
end
end
function Mixer:startBlend( fromMix )
self._snapshot = self:createSnapshot( fromMix )
self._fadetimer = 0
end
function Mixer:createSnapshot( top )
if top then
local snapshot = Mix()
for category,volume in pairs( top._categoryVolumes ) do
snapshot:setCategoryVolume( category, MOAIFmodDesigner.getCategoryVolume( category ) )
end
for category, pitchShift in pairs( top._pitchShifts ) do
snapshot:setPitchShift( category, MOAIFmodDesigner.getPitchShift( category ))
end
return snapshot
end
end
function Mixer:update()
local top = self._stack[1]
if self._snapshot and top then
self._fadetimer = self._fadetimer + 1/60
local lerp = self._fadetimer / top._fadetime
top:applyBlend( self._snapshot, lerp )
if lerp >= 1 then
self._snapshot = nil
end
end
for i, autoMix in ipairs( self._autoMixes ) do
if autoMix.enabled ~= MOAIFmodDesigner.isPlaying( autoMix.alias ) then
if autoMix.enabled then
self:popMix( autoMix.mixName )
else
self:pushMix( autoMix.mixName )
end
autoMix.enabled = not autoMix.enabled
end
end
end
function Mixer:addAutoMix( alias, mixName )
table.insert( self._autoMixes, { alias = alias, mixName = mixName, enabled = false } )
end
function Mixer:removeAutoMix( alias )
for i = #self._autoMixes, 1, -1 do
local autoMix = self._autoMixes[i]
if autoMix.alias == alias then
if autoMix.enabled then
self:popMix( autoMix.mixName )
end
table.remove( self._autoMixes, i )
end
end
end
return Mixer |
local currentVault
RegisterCommand("vault",function(source,args)
local ped = PlayerPedId()
local cds = GetEntityCoords(ped)
for k,v in pairs(cfg.homesChests) do
local distance = Vdist(cds,v.coords)
if distance <= 2.0 then
chestTimer = 3
if vrpServer.checkIntPermissionsVault(k) then
currentVault = k
openVault(k)
end
end
end
end)
function openVault()
local weight,data,_,max = vrpServer.getInv(gridZone)
local data2,weight2 = vrpServer.loadVault(currentVault)
if data2 then
isInInventory = true
SendNUIMessage({ action = "display", type = "vault" })
SetNuiFocus(true, true)
SendNUIMessage({ action = "setText", text = 'ply-' .. GetPlayerServerId(PlayerId()), weight = weight, max = max })
SendNUIMessage({ action = "setItems", itemList = data })
SendNUIMessage({ action = "setSecondText", text = 'vault-' .. currentVault, weight = weight2, max = cfg.homesChests[currentVault].max })
SendNUIMessage({ action = "setSecondItems", itemSList = data2 })
end
end
function updateVault()
local data2,weight2 = vrpServer.loadVault(currentVault)
local weight,data,_,max = vrpServer.getInv(gridZone)
SendNUIMessage({ action = "display", type = "vault" })
SendNUIMessage({ action = "setText", text = 'ply-' .. GetPlayerServerId(PlayerId()), weight = weight, max = max })
SendNUIMessage({ action = "setItems", itemList = data })
SendNUIMessage({ action = "setSecondText", text = 'vault-' .. currentVault, weight = weight2, max = cfg.homesChests[currentVault].max })
SendNUIMessage({ action = "setSecondItems", itemSList = data2 })
end
RegisterNUICallback("PutIntoVault", function(data, cb)
if IsPedSittingInAnyVehicle(playerPed) then
return
end
if type(data.number) == "number" and math.floor(data.number) == data.number then
TriggerServerEvent("b15798xx:pd-inventory:putItem", data.data.item, data.number)
end
Wait(500)
updateInventory()
updateVault()
end)
RegisterNUICallback("TakeFromVault", function(data, cb)
if IsPedSittingInAnyVehicle(playerPed) then
return
end
if type(data.number) == "number" and math.floor(data.number) == data.number then
TriggerServerEvent("b15798xx:pd-inventory:getItem", data.data.item, data.number)
end
Wait(500)
updateInventory()
updateVault()
end)
|
local monsters = {}
local fishfrogmanthing = {
name = "fishfrogmanthing",
description = "Half fish, half frog, half man-thing, this proud warrior race of amphibious extraterrestrials fled their homeworld and tries to eke out a meager existence on ours.",
symbol = "F",
types={"animal","intelligent","swimmer"},
level = 4,
strength = 13,
critical_chance=3,
melee = 27,
dodging = 22,
possession_chance = 50,
max_hp = 125,
perception = 9,
aggression = 50,
notice_chance = 70,
bravery=90,
stealth=-5,
ranged_chance=20,
color={r=150,g=150,b=100,a=255},
animated=true,
spritesheet=true,
animation_time=0.1,
image_max=3
}
monsters['fishfrogmanthing'] = fishfrogmanthing
local sharkman = {
name = "sharkman",
description = "He's not here to deliver candygrams.",
symbol = "S",
types={"animal","intelligent","swimmer"},
pathType="swimmer",
ai_flags={"bully"},
faction="chaos",
gender="male",
hit_conditions={{condition="bleeding",minTurns=2,maxTurns=5,chance=25}},
crit_conditions={{condition="bleeding",turns=5,chance=100}},
level = 4,
strength = 13,
critical_chance=3,
melee = 27,
dodging = 22,
possession_chance = 50,
max_hp = 125,
perception = 9,
aggression = 50,
notice_chance = 70,
stealth=-5,
color={r=150,g=150,b=150,a=255},
animated=true,
spritesheet=true,
animation_time=0.1,
image_max=3,
reverseAnimation=true
}
function sharkman:nameGen()
local names = {"blood","bone","crush","death","fang","fear","fin","fish","flesh","kill","jaw","maw","meat","mouth","murder","rage","rip","snap","swim","tear","teeth","tooth"}
return ucfirst(names[random(#names)] .. names[random(#names)])
end
monsters['sharkman'] = sharkman
local merfolkhunter = {
name = "merfolk hunter",
description = "Don't be confused, this isn't someone who hunts merfolk, they're a merfolk who hunts whatever prey it is that merfolk hunt. Which is pretty much everything, so look out.",
symbol = "m",
types={"intelligent","swimmer"},
pathType="swimmer",
nameType="merfolk",
specialOnly=true,
level = 4,
strength = 13,
critical_chance=3,
melee = 27,
dodging = 22,
possession_chance = 50,
max_hp = 125,
perception = 9,
aggression = 50,
notice_chance = 70,
bravery=90,
stealth=-5,
spells={'thrownet','waterdweller'},
faction="merfolk",
gender="either",
specialOnly=true,
ranged_chance=20,
color={r=150,g=150,b=100,a=255},
animated=true,
spritesheet=true,
animation_time=0.3,
image_max=4,
image_varieties=3,
image_name = "mermaid3",
new = function(self)
local base = ""
if self.gender == "male" then
base = "merman"
else
base = "mermaid"
end
self.image_name = base .. self.image_variety
self.soundgroup = base
self.name = base .. " hunter"
end
}
monsters['merfolkhunter'] = merfolkhunter
local electriceel = {
name = "electric eel",
description = "A snakelike fish with the capability of generating an electric current in its body. Don't touch it or you'll get an electric feel.",
symbol = "e",
types={"animal","swimmer"},
pathType="swimmer",
specialOnly=true,
level = 4,
strength = 13,
critical_chance=3,
melee = 27,
dodging = 22,
possession_chance = 50,
max_hp = 125,
perception = 9,
aggression = 50,
notice_chance = 70,
bravery=50,
resistances={electricity=100},
spells={'electricbolt','electricskin','waterdweller'},
ranged_chance=50,
color={r=50,g=42,b=31,a=255},
animated=true,
spritesheet=true,
animation_time=0.15,
image_max=4
}
monsters['electriceel'] = electriceel
local squid = {
name = "fairly large but not giant squid",
description = "It may not be a giant squid, but it's still pretty big.",
symbol = "s",
types={"animal","intelligent","swimmer"},
pathType="swimmer",
specialOnly=true,
level = 4,
strength = 13,
critical_chance=3,
melee = 27,
dodging = 22,
possession_chance = 50,
max_hp = 125,
perception = 9,
aggression = 50,
notice_chance = 70,
bravery=50,
spells={'ink','waterdweller'},
ranged_chance=50,
color={r=150,g=150,b=100,a=255},
animated=true,
spritesheet=true,
animation_time=0.15,
image_max=4,
image_name = "squid1",
image_varieties=3,
}
monsters['squid'] = squid
local hydromancer = {
name="hydromancer",
description = "The art of hydromancy was thought lost, but apparently there are still some practitioners.",
symbol = "h",
types={"intelligent","human"},
nameType = "wizard",
level = 2,
strength = 5,
possession_chance=55,
max_hp=65,
melee = 15,
dodging = 18,
perception = 8,
aggression = 85,
min_distance = 3,
run_chance = 25,
ranged_chance = 70,
bravery=40,
stealth=15,
gender = 'either',
spells = {'waterelemental','bubble'},
color={r=0,g=87,b=132,a=255},
animated=true,
spritesheet=true,
image_max=6,
animation_time = 0.2,
image_varieties=3
}
possibleMonsters['hydromancer'] = hydromancer
local waterelemental = {
name = "water elemental",
description = "A humanoid blob of water, given limited sentience through magical means.",
symbol ="G",
types={"swimmer","mindless","bloodless"},
pathType="swimmer",
ai_flags={"stubborn"},
color={r=255,g=255,b=255},
melee = 20,
dodging = 0,
perception=3,
max_hp = 125,
strength = 10,
level = 3,
speed=75,
possession_chance = 1000,
spells = {'sleepless'},
neverSpawn = true,
weaknesses={electricity=100,ice=25},
resistances={fire=50,poison=100},
animated=true,
spritesheet=true,
randomAnimation=true,
animation_time=0.5,
image_max=5,
ignoreMasterPossession=true
}
possibleMonsters['waterelemental'] = waterelemental
local seamonster = {
name = "leviathan",
description = "A giant creature from the depths of the sea!",
bossText = "As you begin to go up the stairs, you hear a roar behind you. A horrific sea monster rises from the depths!",
symbol = "L",
types={"swimmer"},
ai_flags={"playerstalker"},
pathType="swimmer",
specialOnly=true,
corpse=false,
level = 4,
strength = 18,
melee = 40,
dodging = 30,
possession_chance=-1000,
max_hp = 210,
perception = 6,
notice_chance = 60,
aggression = 80,
color={r=150,g=150,b=150},
ranged_chance = 50,
specialOnly = true,
terrainLimit={'shallowwater','deepwater'},
isBoss = true,
animated=true,
image_max=3,
spritesheet=true,
reverseAnimation=true,
animation_time = 0.33
}
monsters['seamonster'] = seamonster
return monsters |
--[[
The contents of this file are subject to the Common Public Attribution
License Version 1.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://ultimate-empire-at-war.com/cpal. The License is based on the Mozilla
Public License Version 1.1 but Sections 14 and 15 have been added to cover
use of software over a computer network and provide for limited attribution
for the Original Developer. In addition, Exhibit A has been modified to be
consistent with Exhibit B.
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is Ultimate Empire at War.
The Original Developer is the Initial Developer. The Initial Developer of the
Original Code is the Ultimate Empire at War team. All portions of the code
written by the Ultimate Empire at War team are Copyright (c) 2012.
All Rights Reserved. ]]
--//////////////////////////////////////////////////////////////////////////////////////
-- UU UU EEEEEEEE AAAA WW WW WW
-- UU UU EE AA AA WW WW WW
-- UU UU EEEEE AAAAAAAA WW WW WW
-- UU UU EE AA AA WW WWWW WW
-- UUUUUU EEEEEEEE AA AA WW WW
-- Controls Starbase Check, because marker always spawns the first specific marker object with the player's affiliation
-- For OR Starbase Level 3
--//////////////////////////////////////////////////////////////////////////////////////
require ("PGStateMachine")
require("PGStoryMode")
function Definitions ()
Define_State("State_Init", State_Init)
end
function State_Init(message) --initialise
if Get_Game_Mode() ~= "Space" then --end script if in any mode but space
ScriptExit()
end
if message == OnEnter then
--Find each possible enemy unit
--Singleplayer
--Sith
S_SITH_FIGHTER_LIST = Find_All_Objects_Of_Type("S_SITH_FIGHTER_SQUADRON")
S_SITH_BOMBER_LIST = Find_All_Objects_Of_Type("S_SITH_BOMBER_SQUADRON")
S_SITH_GUNBOAT_LIST = Find_All_Objects_Of_Type("S_SITH_GUNBOAT_SQUADRON")
S_HEAVY_CRUISER_LIST = Find_All_Objects_Of_Type("S_HEAVY_CRUISER")
S_HEAVY_CRUISER_ADV_LIST = Find_All_Objects_Of_Type("S_HEAVY_CRUISER_ADV")
S_INTERDICTOR_CRUISER_LIST = Find_All_Objects_Of_Type("S_INTERDICTOR_CRUISER")
S_INTERDICTOR_CRUISER_ADV_LIST = Find_All_Objects_Of_Type("S_INTERDICTOR_CRUISER_ADV")
S_CENTURION_LIST = Find_All_Objects_Of_Type("S_CENTURION")
S_SITH_STAR_DESTROYER_LIST = Find_All_Objects_Of_Type("S_SITH_DESTROYER")
S_RAVAGER_LIST = Find_All_Objects_Of_Type("S_RAVAGER")
--CIS
C_VULTURE_DROID_IAI_LIST = Find_All_Objects_Of_Type("C_VULTURE_DROID_IAI_SQUADRON")
C_DROID_BOMBER_IAI_LIST = Find_All_Objects_Of_Type("C_DROID_BOMBER_IAI_SQUADRON")
C_TRI_FIGHTER_LIST = Find_All_Objects_Of_Type("C_TRI_FIGHTER_SQUADRON")
C_MISSILE_FRIGATE_LIST = Find_All_Objects_Of_Type("C_MISSILE_FRIGATE")
C_RECUSANT_LIST = Find_All_Objects_Of_Type("C_RECUSANT")
C_MUNIFICENT_LIST = Find_All_Objects_Of_Type("C_MUNIFICENT")
C_RECUSANT_CARRIER_LIST = Find_All_Objects_Of_Type("C_RECUSANT_CARRIER")
C_LUCREHULK_LIST = Find_All_Objects_Of_Type("C_LUCREHULK")
C_LUCREHULK_CARRIER_LIST = Find_All_Objects_Of_Type("C_LUCREHULK_CARRIER")
INVISIBLE_HAND_LIST = Find_All_Objects_Of_Type("INVISIBLE_HAND")
--Empire
E_TIE_SCOUT_LIST = Find_All_Objects_Of_Type("E_TIE_SCOUT_SQUADRON")
E_TIE_DEFENDER_LIST = Find_All_Objects_Of_Type("E_TIE_DEFENDER_SQUADRON")
E_XG_STAR_WING_LIST = Find_All_Objects_Of_Type("E_XG_STAR_WING_SQUADRON")
E_TARTAN_CRUISER = Find_All_Objects_Of_Type("E_TARTAN_CRUISER")
E_IPV_PATROL_CRAFT_LIST = Find_All_Objects_Of_Type("E_IPV_PATROL_CRAFT")
E_BROADSIDE_LIST = Find_All_Objects_Of_Type("E_BROADSIDE")
E_ACCLAMATOR_ASSAULT_FRIGATE_I_LIST = Find_All_Objects_Of_Type("E_ACCLAMATOR_ASSAULT_FRIGATE_I")
E_ACCLAMATOR_ASSAULT_FRIGATE_II_LIST = Find_All_Objects_Of_Type("E_ACCLAMATOR_ASSAULT_FRIGATE_II")
E_INTERDICTOR_CRUISER = Find_All_Objects_Of_Type("E_INTERDICTOR_CRUISER")
E_DREADNAUGHT_LIST = Find_All_Objects_Of_Type("E_DREADNAUGHT")
E_DREADNAUGHT_REFIT_LIST = Find_All_Objects_Of_Type("E_DREADNAUGHT_REFIT")
E_VICTORY_I_LIST = Find_All_Objects_Of_Type("E_VICTORY_I")
E_VICTORY_II_LIST = Find_All_Objects_Of_Type("E_VICTORY_II")
E_ISDI_LIST = Find_All_Objects_Of_Type("E_ISDI")
E_ISDII_LIST = Find_All_Objects_Of_Type("E_ISDII")
UEAW_ACCUSER_LIST = Find_All_Objects_Of_Type("UEAW_Accuser")
ARC_HAMMER_LIST = Find_All_Objects_Of_Type("Arc_Hammer")
VADER_LIST = Find_All_Objects_Of_Type("Darth_Team_Space_MP")
SLAVE_I_LIST = Find_All_Objects_Of_Type("Slave_I")
--Imperial Remnant
IR_TIE_SCOUT_LIST = Find_All_Objects_Of_Type("IR_TIE_SCOUT_SQUADRON")
IR_TIE_DEFENDER_LIST = Find_All_Objects_Of_Type("IR_TIE_DEFENDER_SQUADRON")
IR_TIE_PHANTOM_SQUADRON = Find_All_Objects_Of_Type("IR_TIE_DEFENDER_SQUADRON")
IR_TIE_DROID_SQUADRON_LIST = Find_All_Objects_Of_Type("IR_TIE_DROID_SQUADRON")
IR_XG_STAR_WING_LIST = Find_All_Objects_Of_Type("IR_XG_STAR_WING_SQUADRON")
IR_TARTAN_CRUISER = Find_All_Objects_Of_Type("IR_TARTAN_CRUISER")
IR_IPV_PATROL_CRAFT_LIST = Find_All_Objects_Of_Type("IR_IPV_PATROL_CRAFT")
IR_LANCER_FRIGATE_LIST = Find_All_Objects_Of_Type("IR_LANCER_FRIGATE")
IR_BROADSIDE_LIST = Find_All_Objects_Of_Type("IR_BROADSIDE")
IR_ACCLAMATOR_ASSAULT_FRIGATE_I_LIST = Find_All_Objects_Of_Type("IR_ACCLAMATOR_ASSAULT_FRIGATE_I")
IR_ACCLAMATOR_ASSAULT_FRIGATE_II_LIST = Find_All_Objects_Of_Type("IR_ACCLAMATOR_ASSAULT_FRIGATE_II")
IR_INTERDICTOR_CRUISER = Find_All_Objects_Of_Type("IR_INTERDICTOR_CRUISER")
IR_STRIKE_CLASS_CRUISER = Find_All_Objects_Of_Type("IR_STRIKE_CLASS_CRUISER")
IR_DREADNAUGHT_REFIT_LIST = Find_All_Objects_Of_Type("IR_DREADNAUGHT_REFIT")
IR_VICTORY_I_LIST = Find_All_Objects_Of_Type("IR_VICTORY_I")
IR_VICTORY_II_LIST = Find_All_Objects_Of_Type("IR_VICTORY_II")
IR_ISDI_LIST = Find_All_Objects_Of_Type("IR_ISDI")
IR_ISDII_LIST = Find_All_Objects_Of_Type("IR_ISDII")
IR_ECLIPSE_LIST = Find_All_Objects_Of_Type("IR_ECLIPSE")
PELLAEON_LIST = Find_All_Objects_Of_Type("Chimaera_Star_Destroyer")
THRAWN_LIST = Find_All_Objects_Of_Type("Admonitor_Star_Destroyer")
EXECUTOR_LIST = Find_All_Objects_Of_Type("Executor_Super_Star_Destroyer")
--Multiplayer
E_TIE_SCOUT_MP_LIST = Find_All_Objects_Of_Type("E_TIE_SCOUT_MP_SQUADRON")
E_TIE_DEFENDER_MP_LIST = Find_All_Objects_Of_Type("E_TIE_DEFENDER_MP_SQUADRON")
E_XG_STAR_WING_MP_LIST = Find_All_Objects_Of_Type("E_XG_STAR_WING_MP_SQUADRON")
E_TARTAN_CRUISER_MP = Find_All_Objects_Of_Type("E_TARTAN_CRUISER_MP")
E_IPV_PATROL_CRAFT_MP_LIST = Find_All_Objects_Of_Type("E_IPV_PATROL_CRAFT_MP")
E_BROADSIDE_MP_LIST = Find_All_Objects_Of_Type("E_BROADSIDE_MP")
E_ACCLAMATOR_ASSAULT_FRIGATE_I_MP_LIST = Find_All_Objects_Of_Type("E_ACCLAMATOR_ASSAULT_FRIGATE_I_MP")
E_ACCLAMATOR_ASSAULT_FRIGATE_II_MP_LIST = Find_All_Objects_Of_Type("E_ACCLAMATOR_ASSAULT_FRIGATE_II_MP")
E_INTERDICTOR_CRUISER_MP = Find_All_Objects_Of_Type("E_INTERDICTOR_CRUISER_MP")
E_DREADNAUGHT_MP_LIST = Find_All_Objects_Of_Type("E_DREADNAUGHT_MP")
E_DREADNAUGHT_REFIT_MP_LIST = Find_All_Objects_Of_Type("E_DREADNAUGHT_REFIT_MP")
E_VICTORY_I_MP_LIST = Find_All_Objects_Of_Type("E_VICTORY_I_MP")
E_VICTORY_II_MP_LIST = Find_All_Objects_Of_Type("E_VICTORY_II_MP")
E_ISDI_MP_LIST = Find_All_Objects_Of_Type("E_ISDI_MP")
E_ISDII_MP_LIST = Find_All_Objects_Of_Type("E_ISDII_MP")
Rebel = Find_Player("Rebel")
starbase_marker = Object.Get_Bone_Position("ROOT")
--Check for CIS Units
if table.getn(C_VULTURE_DROID_IAI_LIST) > 0 or table.getn(C_DROID_BOMBER_IAI_LIST) > 0 or table.getn(C_TRI_FIGHTER_LIST) > 0 or table.getn(C_MISSILE_FRIGATE_LIST) > 0 then
starbase = { "R_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(C_RECUSANT_LIST) > 0 or table.getn(C_MUNIFICENT_LIST) > 0 or table.getn(C_RECUSANT_CARRIER_LIST) > 0 or table.getn(C_LUCREHULK_LIST) > 0 then
starbase = { "R_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(C_LUCREHULK_CARRIER_LIST) > 0 or table.getn(INVISIBLE_HAND_LIST) > 0 then
starbase = { "R_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
--Check for Empire Units
if table.getn(E_TIE_SCOUT_LIST) > 0 or table.getn(E_TIE_DEFENDER_LIST) > 0 or table.getn(E_XG_STAR_WING_LIST) > 0 or table.getn(E_TARTAN_CRUISER) > 0 then
starbase = { "RA_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(E_IPV_PATROL_CRAFT_LIST) > 0 or table.getn(E_BROADSIDE_LIST) > 0 or table.getn(E_ACCLAMATOR_ASSAULT_FRIGATE_I_LIST) > 0 or table.getn(E_ACCLAMATOR_ASSAULT_FRIGATE_II_LIST) > 0 then
starbase = { "RA_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(E_INTERDICTOR_CRUISER) > 0 or table.getn(E_DREADNAUGHT_LIST) > 0 or table.getn(E_DREADNAUGHT_REFIT_LIST) > 0 or table.getn(E_VICTORY_I_LIST) > 0 then
starbase = { "RA_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(E_VICTORY_II_LIST) > 0 or table.getn(E_ISDI_LIST) > 0 or table.getn(E_ISDII_LIST) > 0 or table.getn(UEAW_ACCUSER_LIST) > 0 then
starbase = { "RA_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(ARC_HAMMER_LIST) > 0 or table.getn(VADER_LIST) > 0 or table.getn(SLAVE_I_LIST) > 0 then
starbase = { "RA_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
--Check for Imperial Remnant Units
if table.getn(IR_TIE_SCOUT_LIST) > 0 or table.getn(IR_TIE_DEFENDER_LIST) > 0 or table.getn(IR_XG_STAR_WING_LIST) > 0 or table.getn(IR_TARTAN_CRUISER) > 0 then
starbase = { "NR_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(IR_IPV_PATROL_CRAFT_LIST) > 0 or table.getn(IR_BROADSIDE_LIST) > 0 or table.getn(IR_ACCLAMATOR_ASSAULT_FRIGATE_I_LIST) > 0 or table.getn(IR_ACCLAMATOR_ASSAULT_FRIGATE_II_LIST) > 0 then
starbase = { "NR_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(IR_INTERDICTOR_CRUISER) > 0 or table.getn(IR_DREADNAUGHT_REFIT_LIST) > 0 or table.getn(IR_VICTORY_I_LIST) > 0 then
starbase = { "NR_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(IR_VICTORY_II_LIST) > 0 or table.getn(IR_ISDI_LIST) > 0 or table.getn(IR_ISDII_LIST) > 0 or table.getn(IR_ECLIPSE_LIST) > 0 then
starbase = { "NR_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(IR_TIE_PHANTOM_SQUADRON) > 0 or table.getn(IR_TIE_DROID_SQUADRON_LIST) > 0 or table.getn(IR_LANCER_FRIGATE_LIST) > 0 or table.getn(IR_STRIKE_CLASS_CRUISER) > 0 then
starbase = { "NR_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(PELLAEON_LIST) > 0 or table.getn(THRAWN_LIST) > 0 or table.getn(EXECUTOR_LIST) > 0 then
starbase = { "NR_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
--Check for Empire Multiplayer Units
if table.getn(E_TIE_SCOUT_MP_LIST) > 0 or table.getn(E_TIE_DEFENDER_MP_LIST) > 0 or table.getn(E_XG_STAR_WING_MP_LIST) > 0 or table.getn(E_TARTAN_CRUISER_MP) > 0 then
starbase = { "RA_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(E_IPV_PATROL_CRAFT_MP_LIST) > 0 or table.getn(E_BROADSIDE_MP_LIST) > 0 or table.getn(E_ACCLAMATOR_ASSAULT_FRIGATE_I_MP_LIST) > 0 or table.getn(E_ACCLAMATOR_ASSAULT_FRIGATE_II_MP_LIST) > 0 then
starbase = { "RA_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(E_INTERDICTOR_CRUISER_MP) > 0 or table.getn(E_DREADNAUGHT_MP_LIST) > 0 or table.getn(E_DREADNAUGHT_REFIT_MP_LIST) > 0 or table.getn(E_VICTORY_I_MP_LIST) > 0 then
starbase = { "RA_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
if table.getn(E_VICTORY_II_MP_LIST) > 0 or table.getn(E_ISDI_MP_LIST) > 0 or table.getn(E_ISDII_MP_LIST) > 0 then
starbase = { "RA_STARBASE_3" }
SpawnList(starbase, starbase_marker, Rebel, true, true)
Object.Despawn()
ScriptExit()
end
end
end |
--- The environment file.
-- @module crit.env
-- @todo
local sys_config = require "crit.sys_config"
local function load_from_resource()
local file = sys.load_resource(sys.get_config("crit.env_file", "/_env/env.lua"))
if not file then return {} end
local chunk, error = loadstring(file or "")
if not chunk then
print(error)
return {}
end
return chunk() or {}
end
local function load_from_parameters(env)
local luastring
if html5 then
luastring = html5.run([[
decodeURIComponent(window.location.hash.substring(1))
]])
else
if not defos then return end
local args = defos.get_parameters()
for i, arg in ipairs(args) do
if args == '--env' then
luastring = args[i + 1]
break
end
end
end
if not luastring or luastring == "" then return end
local chunk, error = loadstring(luastring)
if not chunk then
print(error)
return
end
local new_env = chunk()
for k, v in pairs(new_env) do
env[k] = v
end
end
local function load_from_save(env)
local game_name = sys.get_config("project.title")
local save_path = sys.get_save_file(game_name, "env.lua")
local f = io.open(save_path)
if not f then return end
print("Found env.lua save file overrides")
local luastring = f:read("*all")
f:close()
if not luastring or luastring == "" then return end
local chunk, error = loadstring(luastring)
if not chunk then
print(error)
return
end
local new_env = chunk()
for k, v in pairs(new_env) do
env[k] = v
end
end
local debug = sys_config.debug
local function config_enabled(config_key)
local value = sys.get_config(config_key .. (debug and "_debug" or "_release"), debug and "1" or "0")
return value == "1" or value == "true"
end
local env
env = config_enabled("crit.env_from_resource") and load_from_resource() or {}
if config_enabled("crit.env_from_save") then
load_from_save(env)
end
if config_enabled("crit.env_from_parameters") then
load_from_parameters(env)
end
return env
|
function AddVulkan()
defines { "MODULE_VULKAN" }
includedirs { "$(VULKAN_SDK)/include" }
postbuildcommands
{
}
links
{
"$(VULKAN_SDK)/lib/vulkan-1.lib"
}
end
function AddGLM()
defines { "MODULE_GLM" }
includedirs "$(SolutionDir)/ThirdParty/glm/"
filter {}
end
function AddGLFW()
defines { "MODULE_GLFW" }
includedirs "$(SolutionDir)/ThirdParty/glfw/include/"
libdirs "$(SolutionDir)/ThirdParty/glfw/lib-vc2019/"
postbuildcommands
{
"{COPY} \"$(SolutionDir)ThirdParty\\glfw\\lib-vc2019\\glfw3.dll\" \"$(OutDir)\""
}
links
{
"glfw3.lib"
}
filter {}
end
function AddSTB(isTarget)
defines { "MODULE_STB", "STB_IMAGE_IMPLEMENTATION" }
includedirs {
"$(SolutionDir)/ThirdParty/stb/include/",
}
filter {}
end
function AddTinyObjLoader(isTarget)
defines { "MODULE_TINYOBJLOADER", "TINYOBJLOADER_IMPLEMENTATION" }
includedirs {
"$(SolutionDir)/ThirdParty/tinyobjloader/include/",
}
filter {}
end
|
allianceGUI = { tabs = {} }
function centerWindow(window)
local screenW,screenH=guiGetScreenSize()
local windowW,windowH=guiGetSize(window,false)
local x,y = (screenW-windowW)/2,(screenH-windowH)/2
guiSetPosition(window,x,y,false)
end
function table.copy(tab)
local ret = {}
for key, value in pairs(tab) do
if (type(value) == "table") then ret[key] = table.copy(value)
else ret[key] = value end
end
return ret
end
function createAllianceGUI()
allianceGUI.window = guiCreateWindow(408, 183, 550, 402, "New Gaming Community ~ Alliance Management", false)
guiWindowSetSizable( allianceGUI.window, false)
centerWindow(allianceGUI.window)
allianceGUI.tabpanel = guiCreateTabPanel(9, 25, 532, 368, false, allianceGUI.window)
allianceGUI.tabs.main = { guiCreateTab("Main", allianceGUI.tabpanel) }
allianceGUI.tabs.main.createNewAlliance = guiCreateButton(7, 12, 151, 29, "Create new alliance", false, allianceGUI.tabs.main[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.main.createNewAlliance,createNewAlliance,false)
allianceGUI.tabs.main.createNewAllianceEdit = guiCreateEdit(162, 11, 363, 30, "", false, allianceGUI.tabs.main[1])
guiLabelSetColor(guiCreateLabel(9, 44, 519, 11, string.rep("-",128), false, allianceGUI.tabs.main[1]), 230, 86, 8)
-- info labels
guiSetFont(guiCreateLabel(9, 64, 130, 16, "Your current alliance:", false, allianceGUI.tabs.main[1]),"default-bold-small")
allianceGUI.tabs.main.currentAlliance = guiCreateLabel(137, 64, 382, 16, "N.A", false, allianceGUI.tabs.main[1])
guiSetFont(guiCreateLabel(9, 91, 130, 16, "Alliance members:", false, allianceGUI.tabs.main[1]), "default-bold-small")
allianceGUI.tabs.main.currentAllianceMembers = guiCreateLabel(137, 90, 385, 16, "N.A", false, allianceGUI.tabs.main[1])
guiSetFont(guiCreateLabel(9, 119, 130, 16, "Alliance founder:", false, allianceGUI.tabs.main[1]), "default-bold-small")
allianceGUI.tabs.main.currentAllianceFounder = guiCreateLabel(137, 118, 381, 16, "N.A", false, allianceGUI.tabs.main[1])
guiSetFont(guiCreateLabel(9, 148, 130, 16, "Date created:", false, allianceGUI.tabs.main[1]), "default-bold-small")
allianceGUI.tabs.main.currentAllianceCreated = guiCreateLabel(137, 147, 382, 16, "N.A", false, allianceGUI.tabs.main[1])
guiSetFont(guiCreateLabel(9, 177, 130, 16, "Last group joined at:", false, allianceGUI.tabs.main[1]), "default-bold-small")
allianceGUI.tabs.main.currentAllianceLastJoinDate = guiCreateLabel(137, 176, 377, 16, "N.A", false, allianceGUI.tabs.main[1])
guiSetFont(guiCreateLabel(9, 207, 130, 16, "Alliance bank balance:", false, allianceGUI.tabs.main[1]),"default-bold-small")
allianceGUI.tabs.main.currentAllianceBankBalance = guiCreateLabel(137, 207, 384, 16, "N.A", false, allianceGUI.tabs.main[1])
guiSetFont(guiCreateLabel(9, 236, 130, 16, "Your group:", false, allianceGUI.tabs.main[1]), "default-bold-small")
allianceGUI.tabs.main.currentAllianceMyGroup = guiCreateLabel(137, 236, 383, 16, "Group Leader", false, allianceGUI.tabs.main[1])
allianceGUI.tabs.main.backToGroups = guiCreateButton(450, 236, 70, 30, "Groups", false, allianceGUI.tabs.main[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.main.backToGroups,backToGroups,false)
guiSetFont(guiCreateLabel(9, 268, 130, 16, "Alliance groups: ", false, allianceGUI.tabs.main[1]), "default-bold-small")
allianceGUI.tabs.main.currentAllianceGroups = guiCreateLabel(137, 269, 382, 16, "N.A", false, allianceGUI.tabs.main[1])
guiLabelSetColor(guiCreateLabel(9, 283, 519, 11, string.rep("-",128), false, allianceGUI.tabs.main[1]), 230, 86, 8)
-- options
allianceGUI.tabs.main.leaveAlliance = guiCreateButton(7, 304, 151, 29, "Leave alliance", false, allianceGUI.tabs.main[1])
guiSetProperty(allianceGUI.tabs.main.leaveAlliance, "NormalTextColour", "FFE10000")
addEventHandler("onClientGUIClick",allianceGUI.tabs.main.leaveAlliance,leaveAlliance,false)
allianceGUI.tabs.main.enableAllianceBlips = guiCreateCheckBox(167, 304, 213, 29, "Enable alliance members blips", true, false, allianceGUI.tabs.main[1])
guiSetFont(allianceGUI.tabs.main.enableAllianceBlips, "default-bold-small")
addEventHandler("onClientGUIClick",allianceGUI.tabs.main.enableAllianceBlips,onPlayerAllianceSettingChanged,false)
exports.DENsettings:addPlayerSetting("allianceblips","true")
allianceGUI.tabs.groups = { guiCreateTab("Groups", allianceGUI.tabpanel) }
guiSetFont(guiCreateLabel(6, 6, 517, 15, "Alliance groups:", false, allianceGUI.tabs.groups[1]), "default-bold-small")
allianceGUI.tabs.groups.groupGrid = guiCreateGridList(6, 26, 519, 311, false, allianceGUI.tabs.groups[1])
guiGridListAddColumn(allianceGUI.tabs.groups.groupGrid,"Name",0.65)
guiGridListAddColumn(allianceGUI.tabs.groups.groupGrid,"Founder",0.25)
allianceGUI.tabs.info = { guiCreateTab("Information", allianceGUI.tabpanel) }
guiSetFont(guiCreateLabel(6, 6, 115, 16, "Alliance information:", false, allianceGUI.tabs.info[1]),"default-bold-small")
allianceGUI.tabs.info.memo = guiCreateMemo(3, 22, 526, 293, "", false, allianceGUI.tabs.info[1])
allianceGUI.tabs.info.update = guiCreateButton(3, 317, 526, 22, "Update alliance information", false, allianceGUI.tabs.info[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.info.update,updateInformation,false)
allianceGUI.tabs.maintenance = { guiCreateTab("Maintenance", allianceGUI.tabpanel) }
guiSetFont(guiCreateLabel(6, 6, 185, 14, "Group and member maintenance:", false, allianceGUI.tabs.maintenance[1]), "default-bold-small")
allianceGUI.tabs.maintenance.gridlist = guiCreateGridList(5, 20, 345, 285, false, allianceGUI.tabs.maintenance[1])
guiGridListAddColumn(allianceGUI.tabs.maintenance.gridlist, "Name", 0.55)
guiGridListAddColumn(allianceGUI.tabs.maintenance.gridlist, "Leader", 0.35)
-- right
allianceGUI.tabs.maintenance.noteAllMembers = guiCreateButton(366, 9, 155, 36, "Note to all groups", false, allianceGUI.tabs.maintenance[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.maintenance.noteAllMembers,function () getNoteText(noteAllMembers,"all groups.") end,false )
allianceGUI.tabs.maintenance.noteGroup = guiCreateButton(366, 51, 155, 36, "Note to selected group", false, allianceGUI.tabs.maintenance[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.maintenance.noteGroup,function () getNoteText(noteGroup, "selected group.") end,false )
allianceGUI.tabs.maintenance.inviteGroup = guiCreateButton(366, 90, 155, 36, "Invite groups", false, allianceGUI.tabs.maintenance[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.maintenance.inviteGroup,inviteGroups,false )
allianceGUI.tabs.maintenance.kickGroup = guiCreateButton(366, 130, 155, 36, "Kick group", false, allianceGUI.tabs.maintenance[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.maintenance.kickGroup,kickGroup,false )
allianceGUI.tabs.maintenance.pickColor = guiCreateButton(366, 170, 155, 36, "Pick Turf Color", false, allianceGUI.tabs.maintenance[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.maintenance.pickColor,pickColor,false )
allianceGUI.tabs.maintenance.shareGates = guiCreateCheckBox(5,295,90,40,"Share gates.",true,false,allianceGUI.tabs.maintenance[1])
allianceGUI.tabs.maintenance.shareSpawners = guiCreateCheckBox(125,295,145,40,"Share spawners.",true,false,allianceGUI.tabs.maintenance[1])
allianceGUI.tabs.maintenance.shareArmor = guiCreateCheckBox(265,295,125,40,"Share armor.",true,false,allianceGUI.tabs.maintenance[1])
allianceGUI.tabs.maintenance.forceBlips = guiCreateCheckBox(405,295,125,40,"Force alliance blips.",true,false,allianceGUI.tabs.maintenance[1])
allianceGUI.tabs.maintenance.canDefend = guiCreateCheckBox(5,310,145,40,"Can defend turfs.",true,false,allianceGUI.tabs.maintenance[1])
allianceGUI.tabs.maintenance.splitMoney = guiCreateCheckBox(125,310,145,40,"Split defend money.",true,false,allianceGUI.tabs.maintenance[1])
allianceGUI.tabs.maintenance.ignore = guiCreateCheckBox(265,310,125,40,"FuturePur",true,false,allianceGUI.tabs.maintenance[1])
allianceGUI.tabs.maintenance.turfAsAlliance = guiCreateCheckBox(405,310,125,40,"Turf as Alliance.",true,false,allianceGUI.tabs.maintenance[1])
allianceGUI.tabs.maintenance.setAllianceFounder = guiCreateButton(366, 216, 155, 36, "Set new alliance founder", false, allianceGUI.tabs.maintenance[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.maintenance.setAllianceFounder,
function ()
local selected = getSelectedGroupInMaintenanceTab()
if selected then
alliance_confirmActionGUI(setAllianceFounder,"","Set new founder?", true)
end
end
, false) allianceGUI.tabs.maintenance.deleteAlliance = guiCreateButton(366, 258, 155, 36, "Delete alliance", false, allianceGUI.tabs.maintenance[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.maintenance.deleteAlliance,
function ()
alliance_confirmActionGUI(deleteAlliance,"","Delete alliance?", true)
end
, false)
guiSetProperty(allianceGUI.tabs.maintenance.deleteAlliance, "NormalTextColour", "FFC50000")
allianceGUI.tabs.bank = { guiCreateTab("Banking", allianceGUI.tabpanel) }
allianceGUI.tabs.bank.balance = guiCreateLabel(7, 8, 377, 18, "Last bank transactions: (Current balance: $0)", false, allianceGUI.tabs.bank[1])
guiSetFont(allianceGUI.tabs.bank.balance, "default-bold-small")
allianceGUI.tabs.bank.gridlist = guiCreateGridList(4, 25, 525, 282, false, allianceGUI.tabs.bank[1])
guiGridListAddColumn(allianceGUI.tabs.bank.gridlist, "Group", 0.435)
guiGridListAddColumn(allianceGUI.tabs.bank.gridlist, "Action", 0.18)
guiGridListAddColumn(allianceGUI.tabs.bank.gridlist, "", 0.01)
guiGridListAddColumn(allianceGUI.tabs.bank.gridlist, "Amount", 0.31)
allianceGUI.tabs.bank.withdraw = guiCreateButton(383, 309, 145, 30, "Withdraw", false, allianceGUI.tabs.bank[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.bank.withdraw,alliance_withdrawFromBank,false)
allianceGUI.tabs.bank.deposit = guiCreateButton(232, 309, 147, 30, "Deposit", false, allianceGUI.tabs.bank[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.bank.deposit,alliance_depositToBank,false)
allianceGUI.tabs.bank.amount = guiCreateEdit(4, 310, 226, 29, "", false, allianceGUI.tabs.bank[1])
allianceGUI.tabs.invites = { guiCreateTab("Alliance invites", allianceGUI.tabpanel) }
allianceGUI.tabs.invites.headerLabel = guiCreateLabel(7, 7, 394, 16, "Alliance invites:", false, allianceGUI.tabs.invites[1])
guiSetFont(allianceGUI.tabs.invites.headerLabel, "default-bold-small")
allianceGUI.tabs.invites.gridlist = guiCreateGridList(4, 24, 523, 278, false, allianceGUI.tabs.invites[1])
allianceGUI.tabs.invites.acceptInvite = guiCreateButton(4, 305, 260, 34, "Accept alliance invitation", false, allianceGUI.tabs.invites[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.invites.acceptInvite,alliance_acceptInvitation,false)
allianceGUI.tabs.invites.rejectInvite = guiCreateButton(267, 305, 260, 34, "Reject alliance invitation", false, allianceGUI.tabs.invites[1])
addEventHandler("onClientGUIClick",allianceGUI.tabs.invites.rejectInvite,alliance_rejectInvitation,false)
allianceGUI.tabs.alliances = { guiCreateTab("Alliance(s)", allianceGUI.tabpanel) }
guiSetFont(guiCreateLabel(8, 6, 351, 19, "All alliances:", false, allianceGUI.tabs.alliances[1]), "default-bold-small")
allianceGUI.tabs.alliances.gridlist = guiCreateGridList(8, 29, 513, 309, false, allianceGUI.tabs.alliances[1])
guiGridListAddColumn(allianceGUI.tabs.alliances.gridlist, "Name", 0.4)
guiGridListAddColumn(allianceGUI.tabs.alliances.gridlist, "Founder", 0.35)
guiGridListAddColumn(allianceGUI.tabs.alliances.gridlist, "Number of groups", 0.2)
end
function onPlayerAllianceSettingChanged()
if source == allianceGUI.tabs.main.enableAllianceBlips then
exports.DENsettings:setPlayerSetting( "allianceblips", tostring( guiCheckBoxGetSelected( source ) ) )
else
--
end
end
local allianceSettings = {}
local configuredSettings = {}
function onAllianceSettingChanged()
if myAlliance then
alliances[myAlliance].shareGates = guiCheckBoxGetSelected(allianceGUI.tabs.maintenance.shareGates)
alliances[myAlliance].shareSpawners = guiCheckBoxGetSelected(allianceGUI.tabs.maintenance.shareSpawners)
alliances[myAlliance].shareArmor = guiCheckBoxGetSelected(allianceGUI.tabs.maintenance.shareArmor)
alliances[myAlliance].forceBlips = guiCheckBoxGetSelected(allianceGUI.tabs.maintenance.forceBlips)
alliances[myAlliance].canDefend = guiCheckBoxGetSelected(allianceGUI.tabs.maintenance.canDefend)
alliances[myAlliance].splitMoney = guiCheckBoxGetSelected(allianceGUI.tabs.maintenance.splitMoney)
alliances[myAlliance].ignore = guiCheckBoxGetSelected(allianceGUI.tabs.maintenance.ignore)
alliances[myAlliance].turfAsAlliance = guiCheckBoxGetSelected(allianceGUI.tabs.maintenance.turfAsAlliance)
end
end
groupInfoByID = {}
function pickColor()
req()
end
function req()
exports.cpicker:openPicker("alliance",false,"NGC ~ Pick a Alliance Turf Color")
end
function cpick(id,hex,r,g,b)
if id == "alliance" then
triggerServerEvent("CSGalliance.newcolor",localPlayer,myAlliance,r,g,b)
end
end
addEvent("onColorPickerOK",true)
addEventHandler("onColorPickerOK",root,cpick)
function getGroupInfoByID(groupID)
if groupID then
if groupInfoByID[groupID] then
return groupInfoByID[groupID]
end
end
end
addEvent("alliances_client_updateAllianceInfo",true)
function updateAllianceInfo(allianceToEditID,index,newValue,newPlayerAlliance)
if ( not index ) then
alliances[allianceToEditID] = newValue
if allianceToEditID == myAlliance and newValue == nil then
guiSetSelectedTab(allianceGUI.tabpanel,allianceGUI.tabs.main[1])
end
elseif ( type(index) == "string" ) and newValue then
alliances[allianceToEditID][index] = newValue
end
if newPlayerAlliance then
myAlliance = newPlayerAlliance
elseif allianceToEditID == myAlliance and not alliances[allianceToEditID] then
myAlliance = nil
end
updateAllianceGUI(alliances,myAlliance)
end
addEventHandler("alliances_client_updateAllianceInfo",root,updateAllianceInfo)
function updateAllianceGUI(alliances,myAllianceID,settingsAvailable)
local aclList = getAliancesACL ()
local originalAlliances = table.copy(alliances)
originalAlliances["empty"] = nil
local myLevel = 0
if exports.server:getPlayerGroupID(localPlayer) and getElementData(localPlayer,"GroupRank") == "Group Leader" then
myLevel = 1
end
if myAllianceID then
myLevel = 2
end
if myAllianceID and getElementData(localPlayer,"GroupRank") == "Group Leader" then
myLevel = 3
end
if myAllianceID and getElementData(localPlayer,"GroupRank") == "Group Leader" and alliances[myAllianceID].founderGroup == exports.server:getPlayerGroupID(localPlayer) then
myLevel = 4
end
for i=1,#aclList do
local element,startLevel,endLevel = unpack(aclList[i])
if element and startLevel then
if myLevel >= startLevel and ( ( endLevel and myLevel <= endLevel ) or not endLevel ) then
guiSetEnabled(element,true)
else
guiSetEnabled(element,false)
end
end
end
configuredSettings = {}
for setting,_ in pairs(allianceSettings) do
configuredSettings[setting] = (alliances[myAllianceID] or {})[setting]
guiCheckBoxSetSelected(allianceGUI.tabs.maintenance[setting],configuredSettings[setting] == true)
end
guiCheckBoxSetSelected(allianceGUI.tabs.main.enableAllianceBlips,(exports.DENsettings:getPlayerSetting("allianceblips")) )
if not myAllianceID then myAllianceID = "empty" alliances[myAllianceID] = { groups = {} } end -- make empty table
local founderGroupInfo = getGroupInfoByID(alliances[myAllianceID].founderGroup) or { }
guiSetText(allianceGUI.tabs.main.createNewAllianceEdit,alliances[myAllianceID].name or "")
guiSetText(allianceGUI.tabs.main.currentAlliance,alliances[myAllianceID].name or "None")
if alliances[myAllianceID].rgb then
local t = fromJSON(alliances[myAllianceID].rgb)
if type(t) ~= "table" then t = {255,0,0} end
local r,g,b = unpack(t)
guiLabelSetColor(allianceGUI.tabs.main.currentAlliance,r,g,b)
guiSetText(allianceGUI.tabs.main.currentAllianceMembers,alliances[myAllianceID].memberCount or "")
guiSetText(allianceGUI.tabs.main.currentAllianceFounder,founderGroupInfo.groupname or "")
guiSetText(allianceGUI.tabs.main.currentAllianceCreated,alliances[myAllianceID].dateCreated or "")
guiSetText(allianceGUI.tabs.main.currentAllianceLastJoinDate,alliances[myAllianceID].dateLastJoin or "")
end
if #alliances[myAllianceID].groups <= 1 then
guiSetText(allianceGUI.tabs.main.leaveAlliance,"Delete\leave alliance")
guiSetText(allianceGUI.tabs.main.currentAllianceMembers,"N.A")
guiSetText(allianceGUI.tabs.main.currentAllianceFounder,"N.A")
guiSetText(allianceGUI.tabs.main.currentAllianceCreated,"N.A")
guiSetText(allianceGUI.tabs.main.currentAllianceLastJoinDate,"N.A")
else
guiSetText(allianceGUI.tabs.main.leaveAlliance,"Leave alliance")
end
local balance = ""
if alliances[myAllianceID].balance then balance = "$"..alliances[myAllianceID].balance end
guiSetText(allianceGUI.tabs.main.currentAllianceBankBalance,balance)
local myGroup = exports.server:getPlayerGroupID( localPlayer )
local myGroupName = exports.server:getPlayerGroupName( localPlayer )
guiSetText(allianceGUI.tabs.main.currentAllianceMyGroup,myGroupName or "")
local groupNames = {}
if alliances[myAllianceID].groups then
for i=1,#alliances[myAllianceID].groups do
table.insert(groupNames,getGroupInfoByID(alliances[myAllianceID].groups[i]).groupname)
end
end
guiSetText(allianceGUI.tabs.main.currentAllianceGroups,table.concat(groupNames,", "))
if myLevel >= 4 then
guiSetEnabled(allianceGUI.tabs.maintenance.pickColor,true)
else
guiSetEnabled(allianceGUI.tabs.maintenance.pickColor,false)
guiSetEnabled(allianceGUI.tabs.maintenance.kickGroup,false)
end
if myLevel >= 3 then
guiSetEnabled(allianceGUI.tabs.maintenance.shareGates,true)
guiSetEnabled(allianceGUI.tabs.maintenance.shareSpawners,true)
guiSetEnabled(allianceGUI.tabs.maintenance.shareArmor,true)
guiSetEnabled(allianceGUI.tabs.maintenance.forceBlips,true)
guiSetEnabled(allianceGUI.tabs.maintenance.canDefend,true)
guiSetEnabled(allianceGUI.tabs.maintenance.splitMoney,true)
guiSetEnabled(allianceGUI.tabs.maintenance.ignore,true)
guiSetEnabled(allianceGUI.tabs.maintenance.turfAsAlliance,true)
guiSetEnabled(allianceGUI.tabs.bank.withdraw,true)
else
guiSetEnabled(allianceGUI.tabs.bank.withdraw,false)
guiSetEnabled(allianceGUI.tabs.maintenance.shareGates,false)
guiSetEnabled(allianceGUI.tabs.maintenance.shareSpawners,false)
guiSetEnabled(allianceGUI.tabs.maintenance.shareArmor,false)
guiSetEnabled(allianceGUI.tabs.maintenance.forceBlips,false)
guiSetEnabled(allianceGUI.tabs.maintenance.canDefend,false)
guiSetEnabled(allianceGUI.tabs.maintenance.splitMoney,false)
guiSetEnabled(allianceGUI.tabs.maintenance.ignore,false)
guiSetEnabled(allianceGUI.tabs.maintenance.turfAsAlliance,false)
end
-- groups tab
guiGridListClear(allianceGUI.tabs.groups.groupGrid)
for i=1,#alliances[myAllianceID].groups do
local row = guiGridListAddRow(allianceGUI.tabs.groups.groupGrid)
guiGridListSetItemText(allianceGUI.tabs.groups.groupGrid,row,1,getGroupInfoByID(alliances[myAllianceID].groups[i]).groupname,false,false)
guiGridListSetItemText(allianceGUI.tabs.groups.groupGrid,row,2,getGroupInfoByID(alliances[myAllianceID].groups[i]).groupleader,false,false)
end
-- information tab
guiSetText(allianceGUI.tabs.info.memo,alliances[myAllianceID].info or "")
-- maintenance tab
local allianceGroups = alliances[myAllianceID].groups or {}
guiGridListClear(allianceGUI.tabs.maintenance.gridlist)
for i=1,#allianceGroups do
local row = guiGridListAddRow(allianceGUI.tabs.maintenance.gridlist)
guiGridListSetItemText(allianceGUI.tabs.maintenance.gridlist,row,1,getGroupInfoByID(allianceGroups[i]).groupname,false,false)
guiGridListSetItemData(allianceGUI.tabs.maintenance.gridlist,row,1,getGroupInfoByID(allianceGroups[i]).groupid)
guiGridListSetItemText(allianceGUI.tabs.maintenance.gridlist,row,2,getGroupInfoByID(allianceGroups[i]).groupleader,false,false)
end
-- banking tab
local balance = alliances[myAllianceID].balance or 0
guiSetText(allianceGUI.tabs.bank.balance,"Last bank transactions: ( Current balance: $"..balance.." )")
local transactions = alliances[myAllianceID].transactions or {}
guiGridListClear(allianceGUI.tabs.bank.gridlist)
for i=1,#transactions do
local group = transactions[i][1]
local groupInfo = getGroupInfoByID(group) or {groupname = tostring(group)}
local amount = transactions[i][2]
local transactionType = transactions[i][3]
local transaction = guiGridListAddRow(allianceGUI.tabs.bank.gridlist)
guiGridListSetItemText(allianceGUI.tabs.bank.gridlist,transaction,1,groupInfo.groupname,false,false)
guiGridListSetItemText(allianceGUI.tabs.bank.gridlist,transaction,2,transactionType,false,false)
guiGridListSetItemText(allianceGUI.tabs.bank.gridlist,transaction,3,"$",false,false)
guiGridListSetItemText(allianceGUI.tabs.bank.gridlist,transaction,4,amount,false,true)
end
-- invites + alliances tab
local invites = {}
local inAlliance
guiGridListRemoveColumn(allianceGUI.tabs.invites.gridlist,2)
guiGridListRemoveColumn(allianceGUI.tabs.invites.gridlist,1)
if alliances[myAllianceID].invites then
invites = alliances[myAllianceID].invites
inAlliance = true
guiSetText(allianceGUI.tabs.invites.headerLabel,"Groups invited by your alliance:")
guiGridListAddColumn(allianceGUI.tabs.invites.gridlist, "Group", 0.45)
guiGridListAddColumn(allianceGUI.tabs.invites.gridlist, "Invited by", 0.45)
guiSetText(allianceGUI.tabs.invites.rejectInvite,"Revoke invitation")
else
guiGridListAddColumn(allianceGUI.tabs.invites.gridlist, "Alliance", 0.45)
guiGridListAddColumn(allianceGUI.tabs.invites.gridlist, "Invited by", 0.45)
guiSetText(allianceGUI.tabs.invites.headerLabel,"Alliance invites:")
guiSetText(allianceGUI.tabs.invites.rejectInvite,"Reject alliance invitation")
end
guiGridListClear(allianceGUI.tabs.invites.gridlist)
guiGridListClear(allianceGUI.tabs.alliances.gridlist)
for ID,allianceInfo in pairs(originalAlliances) do
if allianceInfo then
if not inAlliance then
local invitedGroups = allianceInfo.invites or {}
for i=1,#invitedGroups do
if invitedGroups[i][1] == myGroup then
table.insert(invites,{ ID,unpack(invitedGroups[i])})
end
end
end
-- alliances tab
local allianceRow = guiGridListAddRow(allianceGUI.tabs.alliances.gridlist)
guiGridListSetItemText(allianceGUI.tabs.alliances.gridlist,allianceRow,1,allianceInfo.name,false,false)
if getGroupInfoByID(allianceInfo.founderGroup) ~= nil then
guiGridListSetItemText(allianceGUI.tabs.alliances.gridlist,allianceRow,2,getGroupInfoByID(allianceInfo.founderGroup).groupname,false,false)
else
guiGridListSetItemText(allianceGUI.tabs.alliances.gridlist,allianceRow,2,"Not Available",false,false)
end
guiGridListSetItemText(allianceGUI.tabs.alliances.gridlist,allianceRow,3,#allianceInfo.groups,false,true)
end
end
for i=1,#invites do
local inviteRow = guiGridListAddRow(allianceGUI.tabs.invites.gridlist)
local allianceID = invites[i][1]
local groupID
local invitedBy = invites[i][3]
local data = allianceID
if inAlliance then
allianceID = myAllianceID
groupID = invites[i][1]
data = groupID
invitedBy = invites[i][2]
end
local name = alliances[allianceID].name
if inAlliance then
name = getGroupInfoByID(groupID).groupname
end
local groupInfo = getGroupInfoByID(invitedBy) or {}
guiGridListSetItemText(allianceGUI.tabs.invites.gridlist,inviteRow,1,name or "",false,false)
guiGridListSetItemData(allianceGUI.tabs.invites.gridlist,inviteRow,1,data,false,false)
guiGridListSetItemText(allianceGUI.tabs.invites.gridlist,inviteRow,2,groupInfo.groupname or "",false,false)
end
end
function onClientHideAllianceGUI()
showCursor(false)
allianceGUIVisible = false
guiSetVisible(allianceGUI.window,false)
getNoteText_close()
closeInviteGroupsGUI()
alliance_closeConfirmGUI()
-- manage alliance settings
local changed = false
local newValues = {}
for setting,_ in pairs(allianceSettings) do
if configuredSettings[setting] ~= guiCheckBoxGetSelected(allianceGUI.tabs.maintenance[setting]) then
newValues[setting] = guiCheckBoxGetSelected(allianceGUI.tabs.maintenance[setting])
changed = true
end
end
if changed and myAlliance then
triggerServerEvent("alliances_settingsAdjusted",localPlayer,myAlliance,newValues)
end
end
function backToGroups()
onClientHideAllianceGUI()
setGroupWindowVisable ( unpack(groupInfo) )
end
function onClientOpenAllianceGUI()
if requestingData then return false end
triggerServerEvent("requestAllianceData",localPlayer)
end
addEvent("onRequestAllianceDataCallBack",true)
addEventHandler("onRequestAllianceDataCallBack",root,
function (allianceInfo,myAllianceID,settingsAvailable)
alliances = allianceInfo
myAlliance = myAllianceID
setGroupsWindowDisabled () -- hide F6
if not isElement( allianceGUI.window ) then
createAllianceGUI()
else
guiSetVisible(allianceGUI.window,true)
end
allianceSettings = settingsAvailable or allianceSettings
updateAllianceGUI(allianceInfo,myAlliance)
showCursor(true)
allianceGUIVisible = true
end
)
|
local M = {}
local util = require 'core.util'
function M.thread_run(thi)
local fns = {}
function fns.async_read()
local uid = api_thread_respond(thi, '')
api_thread_respond(thi, util.sync_read(uid))
end
function fns.async_write()
local uid = api_thread_respond(thi, '')
local data = api_thread_respond(thi, '')
util.sync_write(uid, data)
end
fns[api_thread_respond(thi, '')]()
end
return M
|
WebClient = {};
luanet.load_assembly("log4net")
local types = {};
types["log4net.LogManager"] = luanet.import_type("log4net.LogManager");
types["System.Net.WebClient"] = luanet.import_type("System.Net.WebClient");
types["System.Text.Encoding"] = luanet.import_type("System.Text.Encoding");
types["System.Xml.XmlTextReader"] = luanet.import_type("System.Xml.XmlTextReader");
types["System.Xml.XmlDocument"] = luanet.import_type("System.Xml.XmlDocument");
-- Create a logger
local log = nil;
if(rootLogger) then
log = types["log4net.LogManager"].GetLogger(rootLogger .. ".WebClient");
else
log = types["log4net.LogManager"].GetLogger("WebClient");
end
local function GetRequest(requestUrl, headers)
local webClient = types["System.Net.WebClient"]();
local response = nil;
log:Debug("Created Web Client");
webClient.Encoding = types["System.Text.Encoding"].UTF8;
for _, header in ipairs(headers) do
webClient.Headers:Add(header);
end
local success, error = pcall(function ()
response = webClient:DownloadString(requestUrl);
end);
webClient:Dispose();
log:Debug("Disposed Web Client");
if(success) then
return response;
else
log:DebugFormat("Unable to get response from the request url: {0}", error);
end
end
local function ReadResponse( responseString )
if (responseString and #responseString > 0) then
local responseDocument = types["System.Xml.XmlDocument"]();
local documentLoaded, error = pcall(function ()
responseDocument:LoadXml(responseString);
end);
if (documentLoaded) then
return responseDocument;
else
log:InfoFormat("Unable to load response content as XML: {0}", error);
return nil;
end
else
log:Info("Unable to read response content");
end
return nil;
end
--Exports
WebClient.GetRequest = GetRequest;
WebClient.ReadResponse = ReadResponse; |
ENT.Base = "sent_sakarias_scar_base"
ENT.Type = "anim"
ENT.PrintName = "UAZ Van"
ENT.Author = "Prof.Heavy"
ENT.Category = "Call of Duty 4"
ENT.Information = ""
ENT.AdminOnly = false
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.AddSpawnHeight = 50
ENT.ViewDist = 200
ENT.ViewDistUp = 10
ENT.NrOfSeats = 2
ENT.NrOfWheels = 4
ENT.NrOfExhausts = 0
ENT.NrOfFrontLights = 2
ENT.NrOfRearLights = 2
ENT.SeatPos = {}
ENT.WheelInfo = {}
ENT.ExhaustPos = {}
ENT.FrontLightsPos = {}
ENT.RearLightsPos = {}
ENT.effectPos = NULL
ENT.DefaultSoftnesFront =15
ENT.DefaultSoftnesRear =15
ENT.CarMass =350
ENT.StabiliserOffset = NULL
ENT.StabilisationMultiplier = 70
ENT.DefaultSound = "vehicles/diesel_loop2.wav"
ENT.EngineEffectName = "Rally"
ENT.HornSound = "scarhorns/horn 1.wav"
ENT.CarModel = "models/uaz_van_body.mdl"
ENT.TireModel = "models/uaz_van_wheel.mdl"
ENT.AnimType = 1
ENT.FrontLightColor = "220 220 160"
------------------------------------VARIABLES END
for i = 1, ENT.NrOfWheels do
ENT.WheelInfo[i] = {}
end
local xPos = 0
local yPos = 0
local zPos = 0
//SEAT POSITIONS
--Seat Position 1
xPos = 36.900001525879
yPos = -40.299999237061
zPos = 40.799999237061
ENT.SeatPos[1] = Vector(xPos, yPos, zPos)
--Seat Position 2
xPos = 36.599998474121
yPos = 1.6000000238419
zPos = 39.5
ENT.SeatPos[2] = Vector(xPos, yPos, zPos)
//WHEEL POSITIONS
--Wheel Position 1
xPos = 41
yPos = -50.799999237061
zPos = 9.6000003814697
ENT.WheelInfo[1].Pos = Vector(xPos, yPos, zPos)
ENT.WheelInfo[1].Side = true
ENT.WheelInfo[1].Torq = true
ENT.WheelInfo[1].Steer = 1
--Wheel Position 2
xPos = -69.099998474121
yPos = -51
zPos = 9.6000003814697
ENT.WheelInfo[2].Pos = Vector(xPos, yPos, zPos)
ENT.WheelInfo[2].Side = true
ENT.WheelInfo[2].Torq = true
ENT.WheelInfo[2].Steer = 0
--Wheel Position 3
xPos = 40.799999237061
yPos = 19.799999237061
zPos = 9.6000003814697
ENT.WheelInfo[3].Pos = Vector(xPos, yPos, zPos)
ENT.WheelInfo[3].Side = false
ENT.WheelInfo[3].Torq = true
ENT.WheelInfo[3].Steer = 1
--Wheel Position 4
xPos = -67
yPos = 19.39999961853
zPos = 9.6000003814697
ENT.WheelInfo[4].Pos = Vector(xPos, yPos, zPos)
ENT.WheelInfo[4].Side = false
ENT.WheelInfo[4].Torq = true
ENT.WheelInfo[4].Steer = 0
//FRONT LIGHT POSITIONS
--Front light 1
xPos = 87.199996948242
yPos = -43.099998474121
zPos = 40.599998474121
ENT.FrontLightsPos[1] = Vector(xPos, yPos, zPos)
--Front light 2
xPos = 86.900001525879
yPos = 9.5
zPos = 40.200000762939
ENT.FrontLightsPos[2] = Vector(xPos, yPos, zPos)
//REAR LIGHT POSITIONS
--Rear light 1
xPos = -111.19999694824
yPos = 20.60000038147
zPos = 33.400001525879
ENT.RearLightsPos[1] = Vector(xPos, yPos, zPos)
--Rear light 2
xPos = -111.69999694824
yPos = -53.5
zPos = 32.799999237061
ENT.RearLightsPos[2] = Vector(xPos, yPos, zPos)
//EXHAUST POSITIONS
//EFFECT POSITION
xPos = 79.199996948242
yPos = -24.10000038147
zPos = 36.700000762939
ENT.effectPos = Vector(xPos, yPos, zPos)
//CAR CHARACTERISTICS
ENT.DefaultAcceleration = 1080.6999511719
ENT.DefaultMaxSpeed = 1065.5
ENT.DefaultTurboEffect = 2
ENT.DefaultTurboDuration = 4
ENT.DefaultTurboDelay = 10
ENT.DefaultReverseForce = 1000
ENT.DefaultReverseMaxSpeed = 200
ENT.DefaultBreakForce = 2000
ENT.DefaultSteerForce = 5
ENT.DefautlSteerResponse = 0.30000001192093
ENT.DefaultStabilisation = 2000
ENT.DefaultNrOfGears = 5
ENT.DefaultAntiSlide = 10
ENT.DefaultAutoStraighten = 5
ENT.DeafultSuspensionAddHeight = 10
ENT.DefaultHydraulicActive = 0
list.Set( "SCarsList", ENT.PrintName, ENT )
function ENT:Initialize()
self:Setup()
if (SERVER) then
--Setting up the car characteristics
self:SetAcceleration( self.DefaultAcceleration )
self:SetMaxSpeed( self.DefaultMaxSpeed )
self:SetTurboEffect( self.DefaultTurboEffect )
self:SetTurboDuration( self.DefaultTurboDuration )
self:SetTurboDelay( self.DefaultTurboDelay )
self:SetReverseForce( self.DefaultReverseForce )
self:SetReverseMaxSpeed( self.DefaultReverseMaxSpeed )
self:SetBreakForce( self.DefaultBreakForce )
self:SetSteerForce( self.DefaultSteerForce )
self:SetSteerResponse( self.DefautlSteerResponse )
self:SetStabilisation( self.DefaultStabilisation )
self:SetNrOfGears( self.DefaultNrOfGears )
self:SetAntiSlide( self.DefaultAntiSlide )
self:SetAutoStraighten( self.DefaultAutoStraighten )
self:SetSuspensionAddHeight( self.DeafultSuspensionAddHeight )
self:SetHydraulicActive( self.DefaultHydraulicActive )
end
end
function ENT:SpecialThink()
end
function ENT:SpecialRemove()
end
function ENT:SpecialReposition()
end |
pg = pg or {}
pg.enemy_data_statistics_362 = {
[50000043] = {
cannon = 75,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
rarity = 3,
air = 160,
torpedo = 0,
dodge = 11,
durability_growth = 240000,
antiaircraft = 190,
luck = 15,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 4,
hit = 16,
antisub_growth = 0,
air_growth = 3500,
battle_unit_type = 90,
base = 252,
durability = 11730,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 20,
armor = 0,
id = 50000043,
antiaircraft_growth = 3200,
antisub = 0,
equipment_list = {
569151,
569152,
569153,
569154,
569155
}
},
[50000044] = {
cannon = 140,
reload = 150,
speed_growth = 0,
cannon_growth = 2500,
rarity = 3,
air = 0,
torpedo = 0,
dodge = 11,
durability_growth = 272000,
antiaircraft = 175,
luck = 15,
reload_growth = 0,
dodge_growth = 156,
hit_growth = 210,
star = 4,
hit = 16,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 90,
base = 251,
durability = 13940,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 20,
armor = 0,
id = 50000044,
antiaircraft_growth = 3600,
antisub = 0,
equipment_list = {
569141,
569142,
569143,
569144,
569145
},
buff_list = {
{
ID = 50500,
LV = 3
}
}
},
[50000045] = {
cannon = 7,
prefab = "srDD2",
reload = 150,
cannon_growth = 560,
speed_growth = 0,
air = 0,
rarity = 2,
dodge = 0,
torpedo = 33,
durability_growth = 10000,
antiaircraft = 60,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 0,
hit_growth = 144,
base = 123,
durability = 300,
armor_growth = 0,
torpedo_growth = 3250,
luck_growth = 0,
speed = 15,
armor = 0,
battle_unit_type = 25,
antisub = 0,
id = 50000045,
antiaircraft_growth = 1000,
equipment_list = {
569001,
569002,
569003
}
},
[50000046] = {
cannon = 16,
prefab = "srCL2",
reload = 150,
cannon_growth = 880,
speed_growth = 0,
air = 0,
rarity = 2,
dodge = 0,
torpedo = 26,
durability_growth = 19200,
antiaircraft = 120,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
star = 2,
hit = 10,
antisub_growth = 0,
air_growth = 0,
hit_growth = 144,
base = 124,
durability = 510,
armor_growth = 0,
torpedo_growth = 2250,
luck_growth = 0,
speed = 15,
armor = 0,
battle_unit_type = 30,
antisub = 0,
id = 50000046,
antiaircraft_growth = 2250,
equipment_list = {
569011,
569012
}
},
[201101] = {
cannon = 3,
battle_unit_type = 20,
rarity = 1,
speed_growth = 0,
pilot_ai_template_id = 20005,
air = 0,
luck = 0,
dodge = 0,
cannon_growth = 300,
speed = 15,
reload = 150,
reload_growth = 0,
dodge_growth = 0,
id = 201101,
star = 2,
hit = 7,
antisub_growth = 0,
air_growth = 0,
torpedo = 16,
base = 100,
durability = 42,
armor_growth = 0,
torpedo_growth = 1600,
luck_growth = 0,
hit_growth = 108,
armor = 0,
durability_growth = 6720,
antiaircraft = 7,
antisub = 0,
antiaircraft_growth = 740,
world_enhancement = {
3,
3.5,
1.5,
2.1,
2.6,
1.5,
0
},
appear_fx = {
"appearsmall"
},
equipment_list = {
311002,
311004,
311092
}
},
[201102] = {
cannon = 6,
reload = 150,
speed_growth = 0,
cannon_growth = 480,
pilot_ai_template_id = 10001,
air = 0,
base = 150,
dodge = 22,
durability_growth = 42000,
speed = 33,
luck = 0,
reload_growth = 0,
dodge_growth = 270,
battle_unit_type = 50,
antiaircraft_growth = 1764,
hit = 13,
antisub_growth = 0,
air_growth = 0,
luck_growth = 0,
torpedo = 48,
durability = 105,
armor_growth = 0,
torpedo_growth = 3840,
antiaircraft = 22,
hit_growth = 189,
armor = 0,
id = 201102,
antisub = 0,
world_enhancement = {
2.5,
7.3,
1.7,
0.8,
1.2,
1.2,
0
},
equipment_list = {
1100000,
1100135,
1100495
},
random_equipment_list = {
{
2021001,
2021002,
2021003,
2021004,
2021005,
2021006
}
},
random_nub = {
1
}
},
[201103] = {
cannon = 5,
reload = 150,
speed_growth = 0,
cannon_growth = 432,
pilot_ai_template_id = 10001,
air = 0,
base = 151,
dodge = 22,
durability_growth = 37800,
antiaircraft = 22,
speed = 33,
reload_growth = 0,
dodge_growth = 270,
luck = 0,
battle_unit_type = 50,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 1764,
torpedo = 46,
durability = 95,
armor_growth = 0,
torpedo_growth = 3648,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 201103,
antisub = 0,
world_enhancement = {
2.5,
7.3,
1.7,
0.8,
1.2,
1.2,
0
},
equipment_list = {
1100000,
1100135,
1100495
}
},
[201104] = {
cannon = 5,
reload = 150,
speed_growth = 0,
cannon_growth = 432,
pilot_ai_template_id = 10001,
air = 0,
base = 152,
dodge = 22,
durability_growth = 37800,
antiaircraft = 22,
speed = 33,
reload_growth = 0,
dodge_growth = 270,
luck = 0,
battle_unit_type = 50,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 1764,
torpedo = 46,
durability = 95,
armor_growth = 0,
torpedo_growth = 3648,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 201104,
antisub = 0,
world_enhancement = {
2.5,
7.3,
1.7,
0.8,
1.2,
1.2,
0
},
equipment_list = {
1100000,
1100135,
1100495
}
},
[201105] = {
cannon = 6,
reload = 150,
speed_growth = 0,
cannon_growth = 480,
pilot_ai_template_id = 10001,
air = 0,
base = 153,
dodge = 22,
durability_growth = 44100,
antiaircraft = 22,
speed = 33,
reload_growth = 0,
dodge_growth = 270,
luck = 0,
battle_unit_type = 50,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 1764,
torpedo = 46,
durability = 110,
armor_growth = 0,
torpedo_growth = 3648,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 201105,
antisub = 0,
world_enhancement = {
2.5,
7.3,
1.7,
0.8,
1.2,
1.2,
0
},
equipment_list = {
1100000,
1100135,
1100495
}
},
[201106] = {
cannon = 3,
reload = 150,
speed_growth = 0,
cannon_growth = 300,
base = 296,
air = 0,
durability_growth = 6720,
dodge = 0,
antiaircraft = 7,
speed = 15,
luck = 0,
reload_growth = 0,
dodge_growth = 0,
battle_unit_type = 20,
antiaircraft_growth = 740,
hit = 7,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 16,
durability = 42,
armor_growth = 0,
torpedo_growth = 1600,
luck_growth = 0,
hit_growth = 108,
armor = 0,
id = 201106,
world_enhancement = {
3,
3.5,
1.5,
2.1,
2.6,
1.5,
0
},
equipment_list = {
1100135,
1100510
}
},
[201107] = {
cannon = 6,
reload = 150,
speed_growth = 0,
cannon_growth = 492,
base = 297,
air = 0,
durability_growth = 42840,
dodge = 22,
antiaircraft = 23,
speed = 33,
luck = 0,
reload_growth = 0,
dodge_growth = 270,
battle_unit_type = 50,
antiaircraft_growth = 1800,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 49,
durability = 107,
armor_growth = 0,
torpedo_growth = 3912,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 201107,
world_enhancement = {
2.5,
7.3,
1.7,
0.8,
1.2,
1.2,
0
},
equipment_list = {
1100000,
1100135,
1100510
}
},
[201108] = {
cannon = 6,
reload = 150,
speed_growth = 0,
cannon_growth = 480,
base = 298,
air = 0,
durability_growth = 39900,
dodge = 22,
antiaircraft = 22,
speed = 33,
luck = 0,
reload_growth = 0,
dodge_growth = 270,
battle_unit_type = 50,
antiaircraft_growth = 1764,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 50,
durability = 100,
armor_growth = 0,
torpedo_growth = 4032,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 201108,
world_enhancement = {
2.5,
7.3,
1.7,
0.8,
1.2,
1.2,
0
},
equipment_list = {
1100000,
1100135,
1100510
}
},
[201109] = {
cannon = 6,
reload = 150,
speed_growth = 0,
cannon_growth = 504,
base = 293,
air = 0,
durability_growth = 39900,
dodge = 22,
antiaircraft = 22,
speed = 33,
luck = 0,
reload_growth = 0,
dodge_growth = 270,
battle_unit_type = 50,
antiaircraft_growth = 1764,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 48,
durability = 100,
armor_growth = 0,
torpedo_growth = 3840,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 201109,
world_enhancement = {
2.5,
7.3,
1.7,
0.8,
1.2,
1.2,
0
},
equipment_list = {
1100000,
1100135,
1100510
}
},
[201110] = {
cannon = 6,
reload = 150,
speed_growth = 0,
cannon_growth = 480,
base = 294,
air = 0,
durability_growth = 39900,
dodge = 22,
antiaircraft = 23,
speed = 33,
luck = 0,
reload_growth = 0,
dodge_growth = 270,
battle_unit_type = 50,
antiaircraft_growth = 1848,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 48,
durability = 100,
armor_growth = 0,
torpedo_growth = 3840,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 201110,
world_enhancement = {
2.5,
7.3,
1.7,
0.8,
1.2,
1.2,
0
},
equipment_list = {
1100000,
1100135,
1100510
}
},
[201201] = {
cannon = 11,
reload = 150,
speed_growth = 0,
cannon_growth = 864,
pilot_ai_template_id = 10001,
air = 0,
base = 182,
dodge = 16,
durability_growth = 47260,
antiaircraft = 50,
speed = 24,
reload_growth = 0,
dodge_growth = 200,
luck = 0,
battle_unit_type = 55,
hit = 13,
antisub_growth = 0,
air_growth = 0,
antiaircraft_growth = 4032,
torpedo = 34,
durability = 118,
armor_growth = 0,
torpedo_growth = 2736,
luck_growth = 0,
hit_growth = 189,
armor = 0,
id = 201201,
antisub = 0,
world_enhancement = {
2.5,
6.3,
1.5,
0,
1.2,
1.2,
0
},
equipment_list = {
1100245,
1100275,
1100435,
1100465
}
},
[201202] = {
cannon = 6,
reload = 150,
speed_growth = 0,
cannon_growth = 600,
base = 299,
air = 0,
durability_growth = 12600,
dodge = 0,
antiaircraft = 17,
speed = 15,
luck = 0,
reload_growth = 0,
dodge_growth = 0,
battle_unit_type = 20,
antiaircraft_growth = 1680,
hit = 7,
antisub_growth = 0,
air_growth = 0,
antisub = 0,
torpedo = 12,
durability = 79,
armor_growth = 0,
torpedo_growth = 1200,
luck_growth = 0,
hit_growth = 108,
armor = 0,
id = 201202,
scale = 170,
world_enhancement = {
3,
2.6,
1.5,
1.4,
2.6,
1.5,
0
},
equipment_list = {
1100120,
1100360
}
}
}
return
|
---@param t table
local function set_hl(t)
for name, val in pairs(t) do
vim.api.nvim_set_hl(0, name, val)
end
end
local color = require("OneDark-Pro.color")
local hl = {
--------------------------
-- :h highlight-default --
--------------------------
--ColorColumn = {},
--Conceal = {},
Cursor = { fg = color.cursor_fg, bg = color.cursor_bg },
--lCursor = {},
--CursorIM = {},
CursorColumn = { link = "CursorLine" },
CursorLine = { bg = color.cursorline },
Directory = { fg = color.fg },
DiffAdd = { bg = color.diff_add },
--DiffChange = {}, -- TODO
DiffDelete = { bg = color.diff_delele },
DiffText = { bg = color.difftext },
EndOfBuffer = { fg = color.bg },
--TermCursor = {},
--TermCursorNC = {},
ErrorMsg = { fg = color.error },
VertSplit = { fg = color.border },
WinSeparator = { fg = color.border },
Folded = { bg = "#2F343E" },
FoldColumn = { fg = "#97989B", bg = color.bg },
SignColumn = { bg = color.bg },
Search = { bg = "#3B4A64" },
IncSearch = { bg = color.match_find },
Substitute = { bg = color.match_find },
LineNr = { fg = color.line_nr, bg = color.bg },
CursorLineNr = { fg = color.cursorline_nr },
MatchParen = { bg = color.match_paren },
--ModeMsg = {},
--MsgArea = {},
--MsgSeparator = {},
--MoreMsg = {},
NonText = { fg = color.gray },
Normal = { fg = color.fg, bg = color.bg },
NormalFloat = { bg = color.float_bg },
--NormalFloat = { bg = color.bg },
FloatBorder = { fg = color.border, bg = color.float_bg },
--FloatBorder = { fg = color.border },
Pmenu = { link = "NormalFloat" },
PmenuSel = { bg = color.selection_bg },
PmenuSbar = { link = "Pmenu" },
PmenuThumb = { bg = "#393F4B" },
Question = { link = "Comment" },
--QuickFixLine = { bg = "#323842" },
QuickFixLine = { link = "CursorLine" },
--SpecialKey = {}, --??
SpellBad = { sp = color.error, undercurl = true },
SpellCap = { sp = color.blue, undercurl = true },
SpellLocal = { sp = color.cyan, undercurl = true },
SpellRare = { sp = color.purple, undercurl = true },
StatusLine = { fg = color.statusline_fg, bg = color.statusline_bg },
StatusLineNC = { fg = color.statusline_nc_fg, bg = color.statusline_bg },
TabLine = { fg = color.tab_inactive_fg, bg = color.tab_inactive_bg },
TabLineFill = { bg = color.tabline_bg },
TabLineSel = { fg = color.tab_active_fg, bg = color.tab_active_bg },
Title = { fg = color.purple, bold = true },
Visual = { bg = color.visual_bg },
WarningMsg = { fg = color.warn },
Whitespace = { fg = color.whitespace },
WildMenu = { link = "PmenuSel" },
--
-- :h group-name
--
Comment = { fg = color.gray, italic = true },
Constant = { fg = color.orange },
String = { fg = color.green },
--Character = {},
--Number = {},
--Boolean = {},
--Float = {},
Identifier = { fg = color.red },
Function = { fg = color.blue },
Statement = { fg = color.purple },
--Conditional = {},
--Repeat = {},
--Label = {},
--Operator = { fg = color.fg },
--Keyword = {},
--Exception = {},
PreProc = { fg = color.purple },
--Include = {} ,
--Define = {} ,
--Macro = {} ,
--PreCondit = {} ,
Type = { fg = color.purple },
--StorageClass = {},
--Structure = {},
--Typedef = {},
Special = { fg = color.yellow },
--SpecialChar = { fg = color.cyan },
--Tag = {},
Delimiter = { fg = color.fg },
--SpecialComment = {},
--Debug = {},
--Underlined = {},
--Ignore = {},
Error = { fg = color.error },
--Todo = {},
--
-- Diagnostic
--
DiagnosticError = { fg = color.error },
DiagnosticWarn = { fg = color.warn },
DiagnosticHint = { fg = color.hint },
DiagnosticInfo = { fg = color.info },
DiagnosticUnderlineError = { sp = color.error, undercurl = true },
DiagnosticUnderlineWarn = { sp = color.warn, undercurl = true },
DiagnosticUnderlineInfo = { sp = color.info, undercurl = true },
DiagnosticUnderlineHint = { sp = color.hint, undercurl = true },
--
-- LSP
--
LspReferenceText = { link = "LspReferenceRead" },
LspReferenceRead = { bg = "#474D59" }, -- editor.wordHighlightBackground #d2e0ff2f
LspReferenceWrite = { bg = "#3C4049" }, -- editor.wordHighlightStrongBackground #abb2bf26
LspSignatureActiveParameter = { fg = color.blue, bold = true },
--
-- Treesitter
--
TSVariable = { fg = color.red },
--commentTSConstant = { fg = color.purple },
cTSFunction = { fg = color.blue },
cTSType = { fg = color.yellow }, -- builtin(int, ..) -> purple / struct(Foo) -> yellow
luaTSField = { fg = color.red },
luaTSFuncBuiltin = { fg = color.cyan },
luaTSConstructor = { fg = color.fg },
luaTSOperator = { fg = color.fg },
luaTSPunctDelimiter = { fg = color.fg },
luaTSPunctBracket = { fg = color.fg },
rustTSNamespace = { fg = color.yellow },
rustTSType = { fg = color.yellow },
rustTSTypeBuiltin = { link = "rustTSType" },
--
-- telescope
--
TelescopeNormal = { link = "NormalFloat" },
--TelescopeSelection = { fg = "#F0F0F0", bg = "#323842" }, -- list.focus{Back,Fore}ground
TelescopeSelection = { bg = color.selection_bg },
TelescopeMatching = { fg = color.match, bold = true },
--
-- Gitsigns
--
GitSignsAdd = { fg = color.git_sign_add },
GitSignsChange = { fg = color.git_sign_change },
GitSignsDelete = { fg = color.git_sign_delete },
GitSignsAddInline = { bg = color.git_diff_inline_add },
GitSignsDeleteInline = { bg = color.git_diff_inline_delete },
}
set_hl(hl)
|
--[[ FTP library
Copyright (C) 2010-2020 Christophe Delord
http://cdelord.fr/bl/bonaluna.html
BonaLuna is based on Lua 5.3
Copyright (C) 1994-2017 Lua.org, PUC-Rio
Freely available under the terms of the MIT license.
--]]
function FTP(url, user, password)
local ftp = {}
local t = socket.url.parse(url)
if user then t.user = user end
if password then t.password = password end
local open = socket.protect(function()
local f = socket.ftp.open(t.host, t.port, t.create)
f:greet()
f:login(t.user, t.password)
return f
end)
local f, err = open()
if not f then return nil, err end
ftp.close = socket.protect(function()
f:quit()
return f:close()
end)
ftp.cd = socket.protect(function(path)
f:pasv()
return f:cwd(path)
end)
ftp.pwd = socket.protect(function()
f.try(f.tp:command("PWD"))
local code, path = f.try(f.tp:check{257})
if not code then return code, path end
return (path:gsub('^[^"]*"(.*)"[^"]*$', "%1"))
end)
ftp.get = socket.protect(function(path)
local t = {}
f:pasv()
f:receive{path=path, command="RETR", sink=ltn12.sink.table(t)}
return table.concat(t)
end)
ftp.put = socket.protect(function(path, data)
local partial = path..".part"
f:pasv()
local sent = f:send{path=partial, command="STOR", source=ltn12.source.string(data)}
f:pasv()
f.try(f.tp:command("RNFR", partial))
f.try(f.tp:check{350})
f.try(f.tp:command("RNTO", path))
f.try(f.tp:check{250})
return sent
end)
ftp.rm = socket.protect(function(path)
f.try(f.tp:command("DELE", path))
return f.try(f.tp:check{250})
end)
ftp.mkdir = socket.protect(function(path)
f.try(f.tp:command("MKD", path))
return f.try(f.tp:check{257})
end)
ftp.rmdir = socket.protect(function(path)
f.try(f.tp:command("RMD", path))
return f.try(f.tp:check{250})
end)
ftp.list = socket.protect(function(path)
local t = {}
f:pasv()
f:receive{path=(path or "."), command="LIST", sink=ltn12.sink.table(t)}
local files = {}
for line in table.concat(t):gmatch("[^\r\n]+") do
local dir, size, name = line:match "([d-])[rwx-]+%s+%d+%s+%w+%s+%w+%s+(%d+)%s+%w+%s+%w+%s+[%w:]+%s+(.*)"
if not name:match("^%.%.?$") then
if dir == "d" then table.insert(files, {name, dir})
else table.insert(files, {name, tonumber(size)})
end
end
end
local i = 0
return function()
i = i+1
if files[i] then
return table.unpack(files[i])
end
end
end)
-- TODO: ftp.walk (as fs.walk)
return ftp
end
|
-- @define insert(t, v) t[#t + 1] = v
-- @define insert(t, v, i) table.insert( t, i, v )
-- @define pop_bottom(t) table.remove( t, 1 )
-- not used as they break the linter :/
--/ @define foreach(x) for i = 1, #x do
--/ @define foreach(i, x) for i = 1, #x do
--/ @define foreach(i, v, x) for i = 1, #x do local v = x[i]
local function fmtcmd( cmd, nodesc )
return cmd.name
.. (cmd.alias and " (-" .. cmd.alias .. ")" or "")
.. (#cmd.params > 0 and " <" or "") .. table.concat( cmd.params, "> <" ) .. (#cmd.params > 0 and ">" or "")
.. (#cmd.flags > 0 and " [--" or "") .. table.concat( cmd.flags, "] [--" ) .. (#cmd.flags > 0 and "]" or "")
.. (nodesc and "" or " - " .. cmd.description)
end
local function recur_cmd( t, f, p )
for i = 1, #t do
f( t[i], p or {} )
if t[i].commands then
recur_cmd( t[i].commands,f, { t[i], unpack( p or {} ) } )
end
end
end
local function assert0( a, ... )
return a or error( ..., 0 ), ...
end
local function getconf( idx )
local h = fs.open( ".workspace", "r" )
local contents = h and h.readAll() or ""
if h then h.close() end
local data = textutils.unserialize( contents )
return type( data ) == "table" and (idx and data[idx] or data) or nil
end
local function setconf( conf )
local data = textutils.serialize( conf )
local h = fs.open( ".workspace", "w" )
if h then
h.write( data )
h.close()
return true
end
return false
end
local function initconf()
return setconf {
workspaces_path = "/workspaces";
install_path = fs.getDir( shell.getRunningProgram() );
}
end
local function getcmd( name )
local t = program
for section in name:gmatch "%.([^%.]+)" do
if t.commands then
for i = 1, #t.commands do
if t.commands[i].name == section then
t = t.commands[i]
break
end
end
else
return nil
end
end
return t
end
local function escape_patterns( pat )
return pat:gsub( "[%.%^%$%*%+%-%?%%%[%]]", "%%%1" )
end
local function get_command_and_data( args )
local t = program
local command = t.name
local parameters = {}
local flags = {}
local warnings = {}
while t.commands do
local cmd = args[1]
local set = false
for i = 1, #t.commands do
if t.commands[i].name == cmd or t.commands[i].alias and "-" .. t.commands[i].alias == cmd then
command = command .. "." .. t.commands[i].name
pop_bottom( args )
t = t.commands[i]
set = true
break
end
end
if not set then
break
end
end
for i = 1, #t.params do
if t.params[i] == "current-workspace-name" and workspace.get_active() then
insert( parameters, workspace.get_active().name )
elseif args[1] and args[1]:sub( 1, 2 ) ~= "--" and (args[1]:sub( 1, 1 ) ~= "-" or #args[1] ~= 2) then
insert( parameters, pop_bottom( args ) )
else
break
end
end
for i = 1, #t.flags do
flags[t.flags[i]] = false
end
while args[1] do
local set = false
for i = 1, #t.flags do
if args[1] == "--" .. t.flags[i] or args[1] == "-" .. t.flags[i]:sub( 1, 1 ) then
if flags[t.flags[i]] then
insert( warnings, "duplicated flag set '" .. t.flags[i] .. "'" )
else
flags[t.flags[i]] = true
end
set = true
pop_bottom( args )
break
end
end
if not set then
break
end
end
while args[1] do
insert( warnings, ("unused argument %q"):format( pop_bottom( args ) ) )
end
return command, parameters, flags, warnings
end
local function filter_command_list( list, cur_text )
local t = {}
for i = 1, #list do
if cur_text == "" or list[i].name:find( "^" .. escape_patterns( cur_text ) ) then
insert( t, list[i].name:sub( #cur_text + 1 ) .. " " )
elseif list[i].alias and ("-" .. list[i].alias):find( "^" .. escape_patterns( cur_text ) ) then
insert( t, list[i].alias:sub( #cur_text ) .. " " )
end
end
return t
end
local function filter_text( list, cur_text )
local r = {}
for i = 1, #list do
if list[i]:find( "^" .. escape_patterns( cur_text ) ) then
insert( r, list[i]:sub( #cur_text + 1 ) )
end
end
return r
end
local function file_find( cur_text, incl_refs )
local begin = cur_text:match ".+/" or ""
local dir = (cur_text:match "(.+)/" or ""); if incl_refs then dir = dir:gsub( "^@([^/]+)", workspace.get_path, 1 ) end
local file = cur_text:gsub( ".+/", "" )
local files = fs.isDir( dir ) and fs.list( dir ) or {}
local r = {}
for i = 1, #files do
if files[i]:find( "^" .. escape_patterns( file ) ) then
r[#r + 1] = begin .. files[i] .. (fs.isDir( dir .. "/" .. files[i] ) and "/" or "")
end
end
if incl_refs and not cur_text:find "/" then
local t = workspace.list_workspaces( workspace.WORKSPACE_EMPTY ):names()
for i = #t, 1, -1 do
t[i] = "@" .. t[i]
if t[i]:find( "^" .. escape_patterns( cur_text ) ) then
r[#r + 1] = t[i] .. "/"
else
table.remove( t, i )
end
end
end
return r
end
local function linewrap( text, len )
local i = 1
local s = nil
local sc = 0
while i <= len and i <= #text do
local ch = text:sub( i, i )
if ch == "\n" then
return text:sub( 1, i - 1 ), text:sub( i + 1 )
elseif ch:find "%s" then
if s and i == s + sc then
sc = sc + 1
else
s = i
sc = 1
end
end
i = i + 1
end
if i <= len then
return text, ""
elseif s then
return text:sub( 1, s - 1 ), text:sub( s + sc )
else
return text:sub( 1, len ), text:sub( len + 1 )
end
end
local function wordwrap( text, len )
local t = {}
t[1], text = linewrap( text, len )
while #text > 0 do
t[#t + 1], text = linewrap( text, len )
end
return t
end
local function writef( text, s, primary, secondary )
if s == "`" or s == "%]" or s == ">" then
term.setTextColour( secondary )
if text:find( s ) then
term.write( text:sub( 1, text:find( s ) ) )
text = text:match( "^.-" .. s .. "(.*)" )
else
term.write( text )
return s
end
end
term.setTextColour( primary )
if text:find "%[" or text:find "<" or text:find "`" then
local a, b, c = text:find "%[", text:find "<", text:find "`"
local _p = b and c and math.min( b, c ) or b or c
local p = a and _p and math.min( a, _p ) or a or _p
term.write( text:sub( 1, p - 1 ) )
term.setTextColour( secondary )
term.write( text:sub( p, p ) )
return writef( text:sub( p + 1 ), text:sub( p, p ) == "`" and "`" or text:sub( p, p ) == "<" and ">" or "%]", primary, secondary )
else
term.write( text )
return nil
end
end
|
--- === cp.ui.Splitter ===
---
--- Represents an `AXSplitter`.
local require = require
local ax = require "cp.fn.ax"
local Element = require "cp.ui.Element"
local Splitter = Element:subclass("cp.ui.Splitter")
--- cp.ui.Splitter.VERTICAL_ORIENTATION <string>
--- Constant
--- The value for `AXOrientation` when it is vertical.
Splitter.static.VERTICAL_ORIENTATION = "AXVerticalOrientation"
--- cp.ui.Splitter.HORIZONTAL_ORIENTATION <string>
--- Constant
--- The value for `AXOrientation` when it is horizontal.
Splitter.static.HORIZONTAL_ORIENTATION = "AXHorizontalOrientation"
--- cp.ui.Splitter.matches(value) -> boolean
--- Function
--- Checks to see if an element matches what we think it should be.
---
--- Parameters:
--- * value - The value to check.
---
--- Returns:
--- * `true` if the value matches, `false` otherwise.
Splitter.static.matches = ax.matchesIf(Element.matches, ax.hasRole "AXSplitter")
--- cp.ui.Splitter.maxValue <cp.prop: number, read-only>
--- Field
--- The maximum value of the splitter.
function Splitter.lazy.prop:maxValue()
return ax.prop(self.UI, "AXMaxValue")
end
--- cp.ui.Splitter.minValue <cp.prop: number, read-only>
--- Field
--- The minimum value of the splitter.
function Splitter.lazy.prop:minValue()
return ax.prop(self.UI, "AXMinValue")
end
--- cp.ui.Splitter.nextContentsUI <cp.prop: axuielementObject, read-only, live?>
--- Field
--- The `axuielementObject` for the next contents of the splitter.
function Splitter.lazy.prop:nextContentsUI()
return ax.prop(self.UI, "AXNextContents")
end
--- cp.ui.Splitter.previousContentsUI <cp.prop: axuielementObject, read-only, live?>
--- Field
--- The `axuielementObject` for the previous contents of the splitter.
function Splitter.lazy.prop:previousContentsUI()
return ax.prop(self.UI, "AXPreviousContents")
end
--- cp.ui.Splitter.orientation <cp.prop: string; read-only>
--- Field
--- The `AXOrientation` string.
function Splitter.lazy.prop:orientation()
return ax.prop(self.UI, "AXOrientation")
end
--- cp.ui.Splitter.vertical <cp.prop: boolean; read-only>
--- Field
--- Is `true` if the `Splitter` is vertical, otherwise `false`.
function Splitter.lazy.prop:vertical()
return self.orientation:mutate(function(original)
return original() == Splitter.VERTICAL_ORIENTATION
end)
end
--- cp.ui.Splitter.horizontal <cp.prop: boolean; read-only>
--- Field
--- Is `true` if the `Splitter` is horizontal, otherwise `false`.
function Splitter.lazy.prop:horizontal()
return self.orientation:mutate(function(original)
return original() == Splitter.HORIZONTAL_ORIENTATION
end)
end
function Splitter.lazy.prop:value()
return ax.prop(self.UI, "AXValue")
end
return Splitter |
puck_counter = class({})
LinkLuaModifier("modifier_puck_counter_banish", "abilities/heroes/puck/puck_counter/modifier_puck_counter_banish", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_puck_counter_charges", "abilities/heroes/puck/puck_counter/modifier_puck_counter_charges", LUA_MODIFIER_MOTION_NONE)
function puck_counter:GetIntrinsicModifierName()
return "modifier_puck_counter_charges"
end
function puck_counter:OnSpellStart()
local caster = self:GetCaster()
local origin = caster:GetAbsOrigin()
local point = CustomAbilitiesLegacy:GetCursorPosition(self)
local banish_duration = self:GetSpecialValueFor("banish_duration")
caster:AddNewModifier(caster, self, "modifier_puck_counter_banish", { duration = banish_duration })
if self:GetLevel() >= 2 then
caster:FindModifierByName("modifier_puck_basic_attack_cooldown"):Replenish()
end
local ability = caster:FindAbilityByName("puck_basic_attack")
ability:LaunchProjectile(self:GetCaster():GetOrigin(), CustomAbilitiesLegacy:GetCursorPosition(ability))
end
|
-- Copyright 2022 philh30
--
-- 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 log = require "log"
local to_send_queue = {}
local timers = {}
--- @param device st.zwave.Device
local function throttle_send(device)
local function throttle_loop()
if #to_send_queue[device.id] > 0 then
log.trace (string.format('~~~~~ THROTTLE: %s commands to send ~~~~~',#to_send_queue[device.id]))
local to_send = table.remove(to_send_queue[device.id],1)
local msg = to_send.msg
local delay = to_send.delay or 1
device:send(msg)
timers[device.id] = device.thread:call_with_delay(delay, throttle_loop)
else
log.trace('~~~~~ THROTTLE: No more commands to send ~~~~~')
device.thread:cancel_timer(timers[device.id])
timers[device.id] = nil
end
end
if timers[device.id] then
log.trace ('~~~~~ THROTTLE: Message queued ~~~~~')
else
timers[device.id] = device.thread:call_with_delay(0, throttle_loop)
end
end
--- @param device st.zwave.Device
local function send_command(device,commands)
if not (to_send_queue[device.id]) then to_send_queue[device.id] = {} end
for _,cmd in pairs(commands) do
cmd.delay = cmd.delay or (device.preferences.zwDelay and device.preferences.zwDelay / 1000) or 1
table.insert(to_send_queue[device.id],cmd)
end
throttle_send(device)
end
return send_command |
--BeatFever fileparser module
--Contains ".osu" file parsing functions
local moduleName = "[FileParser]"
noteCount = 1
local fileLines = {} --Where we'll hold the current osu file data.
parser = {}
local fileLoaded = nil
local ObjectTypes = {HitCircle = 1, Slider = 2, NewCombo = 4, Spinner = 8}
function parser.loadOsuFile(file)
fileLoaded = file
fileLines = {}
--debugLog("Processando arquivo '" .. file .. "'...", 1, moduleName)
if love.filesystem.isFile(file) then
for line in love.filesystem.lines(file) do
table.insert(fileLines, line) --Needs to check if the file really exists or not, otherwise, wild crashes may occur.
end
--debugLog("Arquivo " .. file .. " carregado", 1, moduleName)
return true
else
--debugLog("Falha ao carregar arquivo, saindo", 2, moduleName)
return false
end
end
-- Commence insane string splitting funcs
function parser.getAudioFileName()
for key, line in ipairs(fileLines) do
if #line>0 then
if string.find(line, "AudioFilename:") ~= nil then
audioFile = string.split(line, ': ')
end
end
end
--debugLog("AudioFile is: "..audioFile[2], 1, moduleName)
return audioFile[2]
end
function parser.getAudioLeadIn()
for key, line in ipairs(fileLines) do
if #line>0 then
if string.find(line, "AudioLeadIn:") ~= nil then
audioLead = string.split(line, ': ')
end
end
end
return audioLead[2]
end
function parser.getPreviewTime()
for key, line in ipairs(fileLines) do
if #line>0 then
if string.find(line, "PreviewTime:") ~= nil then
previewTime = string.split(line, ': ');
end
end
end
--debugLog("Preview time is "..previewTime[2], 1, moduleName)
return tonumber(previewTime[2]);
end
function parser.getTimingPoints()
local timingpointstring = {}
local timingpoint = {}
local save = false
for key1, line in ipairs(fileLines) do
if #line > 2 then
if save then
table.insert(timingpointstring, line) --inserts a value in a given table
end
else
save = false
end
if string.find(line, '%[TimingPoints%]') ~= nil then
save = true
end
end -- closes "for" loop
for key2, point in ipairs(timingpointstring) do
--thankfully this is static! which means it never changes... I hope.
parameters = string.split(point, ",")
newpoint = {offset = tonumber(parameters[1]), mpb = tonumber(parameters[2]), meter = tonumber(parameters[3]), sampleType = tonumber(parameters[4]),
sampleSet = tonumber(parameters[5]), volume = tonumber(parameters[6]), inherited = tonumber(parameters[7]), kiai = tonumber(parameters[8])}
--Offset, Milliseconds per Beat, Meter, Sample Type, Sample Set, Volume, Inherited, Kiai Mode
table.insert(timingpoint, newpoint)
end
--debugLog("Parsed timing points for osu file!", 1, moduleName)
return timingpoint
end
function parser.getFilteredTimingPoints()
local timingPoints = parser.getTimingPoints()
local timingPointsInherited = {}
local timingPointsBPM = {}
--Inherited == 0 means the timing point IS inherited.
for i, value in ipairs(timingPoints) do
if tonumber(value.inherited) == 0 then
table.insert(timingPointsInherited, value)
else
table.insert(timingPointsBPM, value)
end
end
--for j, v in ipairs(timingPointsInherited) do print(v.offset, v.mpb) end
--print("------")
return timingPointsBPM, timingPointsInherited
end
function parser.getSongTitle()
for key, line in ipairs(fileLines) do
if #line>0 then
if string.find(line, "Title:") ~= nil then
songName = string.split(line, ':')
end
end
end
--debugLog("Song name: "..songName[2], 1, moduleName)
return songName[2]
end
function parser.getSongVersion()
for key, line in ipairs(fileLines) do
if #line>0 then
if string.find(line, "Version:") ~= nil then
songVer = string.split(line, ':')
end
end
end
--debugLog("Song difficulty: "..songName[2], 1, moduleName)
return songVer[2]
end
function parser.getArtist()
for key, line in ipairs(fileLines) do
if #line>0 then
if string.find(line, "Artist:") ~= nil then
artist = string.split(line, ':')
end
end
end
--debugLog("Artist name: "..artist[2], 1, moduleName)
return artist[2]
end
function parser.getBMCreator()
for key, line in ipairs(fileLines) do
if #line>0 then
if string.find(line, "Creator:") ~= nil then
creator = string.split(line, ':')
end
end
end
--debugLog("Creator: "..creator[2], 1, moduleName)
return creator[2]
end
function parser.getComboColors()
local colorstring = {}
local colors = {}
local save = false
for key1, line in ipairs(fileLines) do
if #line > 2 then
if save then
table.insert(colorstring, line) --inserts a value in a given table
end
else
save = false
end
if string.find(line, '%[Colours%]') ~= nil then
save = true
end
end -- closes "for" loop
for key2, color in ipairs(colorstring) do
parameters = string.split(color, " : ")
comboColour = string.split(parameters[2], ",")
newComboColour = {comboColour[1], comboColour[2], comboColour[3]}
--R, G, B
table.insert(colors, newComboColour)
end
--What if the beatmap has no colour setting?
if colors[1] == nil then
debugLog("No colors could be found in beatmap! Returning default values..", 2, moduleName)
newComboColour = {255, 255, 255}
--R, G, B
table.insert(colors, newComboColour)
end
return colors
end
function parser.getSliderMultiplier()
for key, line in ipairs(fileLines) do
if #line>0 then
if string.find(line, "SliderMultiplier:") ~= nil then
multiplier = string.split(line, ':')
end
end
end
--debugLog("Slider multiplier: "..multiplier[2], 1, moduleName)
return multiplier[2]
end
function parser.getCurrentLoadedFile()
debugLog("Currently, the file "..fileLoaded.." is loaded on the parser.", 1, moduleName)
return fileLoaded
end
function parser.getBreakPeriods()
debugLog("In function parser.getBreakPeriods()", 3, moduleName)
debugLog("This function is not working correctly yet! Refer to implementation notes in source.", 3, moduleName)
--Simples, vou explicar:
--Você não possui o endTime de um break period na verdade. Você só possui startTimes.
--O tempo final de um break é determinado pelo proximo hitObject apos o tempo do breakStart.
--Ou seja, precisamos mexer nessa função!
local breakpstring = {}
local breakpoints = {}
local save = false
for key1, line in ipairs(fileLines) do
if string.find(line, "%/%/") == nil then
if save then
table.insert(breakpstring, line)
end
else
save = false
end
if string.find(line, "%/%/Break Periods") ~= nil then
save = true
end
end
for key2, value in ipairs(breakpstring) do
params = string.split(value, ",")
breakpoint = {tonumber(params[1]), tonumber(params[2])} --startTime and endTime
table.insert(breakpoints, breakpoint)
end
--debugLog("Loaded song breakpoints!", 1, moduleName)
return breakpoints
end
function parser.getBGFile()
local breakpstring = {}
local breakpoints = {}
local save = false
for key1, line in ipairs(fileLines) do
if string.find(line, "%/%/") == nil then
if save then
table.insert(breakpstring, line)
end
else
save = false
end
if string.find(line, "%/%/Background and Video events") ~= nil then
save = true
end
end
for key2, value in ipairs(breakpstring) do
params = string.split(value, ",")
for key, value in ipairs(params) do
if (string.find(value, ".jpg") or string.find(value, ".png") or string.find(value, ".bmp")) ~= nil then
BG = params[key]
end
end
end
if BG ~= nil then
BG = BG:gsub('"', "") --GODAMNIT TOOK ME SO LONG TO MAKE THIS WORK I CAN FINALLY SLEEP
return BG
else
debugLog("FAILED TO PARSE BG! Falling back to standard background", 3, moduleName)
return "error"
end
end
function parser.getHitObjects(hitCircleImage, sliderTickImage)
--Sets up graphics to be used in the ingame
objectParser.setNoteGraphics(hitCircleImage, sliderTickImage)
local noteList = {}
local splitLines = {}
local foundSection = false
timingPointList = parser.getTimingPoints()
for key1, line in ipairs(fileLines) do
if #line > 0 then
if foundSection then --Splits file in many lines, read each one
table.insert(splitLines, line) --looking for section, copy everything after section marker.
end
if string.find(line, "%[HitObjects%]") ~= nil then
foundSection = true
end
end
end
for key2, line in ipairs(splitLines) do
if #line > 3 then
note = parser.parseHitObject(line)
for i, v in ipairs(note) do
table.insert(noteList, v)
end
end
end
return noteList
end
function parser.parseHitObject(str)
--Local vars for type
local HitCircle = false
local Spinner = false
local Slider = false
local newCombo = false
--Get note type from string
local params = string.split(str, ",")
local objType = tonumber(params[4])
--Checks new combo
if (bit.band(objType, 4) > 0) then
newCombo = true
else
newCombo = false
end
--Determines note type based on splitted value
if (bit.band(objType, 1) > 0) then
--Hit circle
note = objectParser.parseHitCircle(str, newCombo)
end
if (bit.band(objType, 2) > 0) then
--Slider
note = objectParser.parseSlider(str, newCombo)
end
if (bit.band(objType, 8) > 0) then
--Spinner
note = objectParser.parseHitCircle(str, newCombo)
end
--At this point, we just effin hope we have no sliding spinners or something
--Return to the user the object processed (table)
assert(note, "Returned note is nil!")
return note
end
|
ITEM.name = "Kitchen Knife"
ITEM.description = "An old, pre-war looking Knife. "
ITEM.model = "models/weapons/tfa_nmrih/w_me_kitknife.mdl"
ITEM.class = "tfa_nmrih_kknife"
ITEM.weaponCategory = "melee"
ITEM.flag = "v"
ITEM.width = 2
ITEM.height = 1
ITEM.bDropOnDeath = true
ITEM.iconCam = {
ang = Angle(-0.23955784738064, 270.44906616211, 0),
fov = 10.780103254469,
pos = Vector(0, 200, 0)
} |
-- SilentsReplacement
-- init
-- August 12, 2021
--[[
Client.OnPlayerFling : Signal ()
Client.OnPlayerHardGroundLand : Signal ()
Client.Start() --> nil []
Client.Stop() --> nil []
Client.IsStarted() --> boolean [IsStarted]
Client.IsStopped() --> boolean [IsStopped]
]]
local Client = {
_isStarted = false,
_isStopped = false,
_areModulesInit = false,
}
local Players = game:GetService("Players")
local Octagon = script:FindFirstAncestor("Octagon")
local SharedConstants = require(Octagon.Shared.SharedConstants)
local Signal = require(Octagon.Shared.Signal)
local SafeWaitForChild = require(Octagon.Shared.SafeWaitForChild)
local Maid = require(Octagon.Shared.Maid)
local InitMaidFor = require(Octagon.Shared.InitMaidFor)
local DestroyAllMaids = require(Octagon.Shared.DestroyAllMaids)
local LocalConstants = { MinPlayerHardGroundLandYVelocity = 145 }
Client.OnPlayerFling = Signal.new()
Client.OnPlayerHardGroundLand = Signal.new()
Client._maid = Maid.new()
local localPlayer = Players.LocalPlayer
function Client.IsStarted()
return Client._isStarted
end
function Client.IsStopped()
return Client._isStopped
end
function Client.Start()
assert(not Client.IsStopped(), "Can't start Octagon as Octagon is stopped")
assert(not Client.IsStarted(), "Can't start Octagon as Octagon is already started")
print(("%s: Started"):format(SharedConstants.FormattedOutputMessages.Octagon.Log))
Client._isStarted = true
Client._init()
Client._trackHumanoidState(localPlayer.Character or localPlayer.CharacterAdded:Wait())
-- Track humanoid state again whenever a new
-- character is added so that the code works
-- with the new character rather than working with the
-- old one:
Client._maid:AddTask(localPlayer.CharacterAdded:Connect(function(character)
Client._trackHumanoidState(character)
end))
return nil
end
function Client.Stop()
assert(not Client.IsStopped(), "Can't stop Octagon as Octagon is already stopped")
assert(Client.IsStarted(), "Can't stop Octagon as Octagon isn't started")
print(("%s: Stopped"):format(SharedConstants.FormattedOutputMessages.Octagon.Log))
Client._isStopped = true
Client._isStarted = false
Client._cleanup()
return nil
end
function Client._init()
Client._initSignals()
return nil
end
function Client._cleanup()
DestroyAllMaids(Client)
return nil
end
function Client._trackHumanoidState(character)
local humanoid = SafeWaitForChild(character, "Humanoid")
if not humanoid then
return nil
end
humanoid.StateChanged:Connect(function(_, newState)
if newState == Enum.HumanoidStateType.Ragdoll then
Client.OnPlayerFling:Fire()
elseif
newState == Enum.HumanoidStateType.Landed and localPlayer.Character.PrimaryPart
then
if
math.abs(localPlayer.Character.PrimaryPart.AssemblyLinearVelocity.Y)
>= LocalConstants.MinPlayerHardGroundLandYVelocity
then
Client.OnPlayerHardGroundLand:Fire()
end
end
end)
return nil
end
function Client._initModules()
Client._areModulesInit = true
script.Parent.Server:Destroy()
for _, child in ipairs(script:GetChildren()) do
Client[child.Name] = child
end
for _, child in ipairs(script.Parent:GetChildren()) do
if child.Name ~= "Client" then
Client[child.Name] = child
end
end
return nil
end
function Client._initSignals()
InitMaidFor(Client, Client._maid, Signal.IsSignal)
Client.OnPlayerFling:Connect(function()
-- Zero out their velocity to prevent them from flinging:
localPlayer.Character.PrimaryPart.AssemblyLinearVelocity *= SharedConstants.Vectors.Default
end)
Client.OnPlayerHardGroundLand:Connect(function()
-- Zero out their velocity to prevent them from flinging:
localPlayer.Character.PrimaryPart.AssemblyLinearVelocity *= SharedConstants.Vectors.XZ
end)
return nil
end
if not Client._areModulesInit then
Client._initModules()
end
return Client
|
---@meta
---@class cc.ControlSlider :cc.Control
local ControlSlider={ }
cc.ControlSlider=ControlSlider
---*
---@return float
function ControlSlider:getMaximumAllowedValue () end
---@overload fun(cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite):self
---@overload fun(cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite):self
---@param backgroundSprite cc.Sprite
---@param progressSprite cc.Sprite
---@param thumbSprite cc.Sprite
---@param selectedThumbSprite cc.Sprite
---@return boolean
function ControlSlider:initWithSprites (backgroundSprite,progressSprite,thumbSprite,selectedThumbSprite) end
---*
---@return float
function ControlSlider:getMinimumAllowedValue () end
---*
---@return float
function ControlSlider:getMaximumValue () end
---*
---@return cc.Sprite
function ControlSlider:getSelectedThumbSprite () end
---*
---@param var cc.Sprite
---@return self
function ControlSlider:setProgressSprite (var) end
---*
---@param val float
---@return self
function ControlSlider:setMaximumValue (val) end
---*
---@return float
function ControlSlider:getMinimumValue () end
---*
---@param var cc.Sprite
---@return self
function ControlSlider:setThumbSprite (var) end
---*
---@return float
function ControlSlider:getValue () end
---*
---@return cc.Sprite
function ControlSlider:getBackgroundSprite () end
---*
---@return cc.Sprite
function ControlSlider:getThumbSprite () end
---*
---@param val float
---@return self
function ControlSlider:setValue (val) end
---*
---@param touch cc.Touch
---@return vec2_table
function ControlSlider:locationFromTouch (touch) end
---*
---@param val float
---@return self
function ControlSlider:setMinimumValue (val) end
---*
---@param var float
---@return self
function ControlSlider:setMinimumAllowedValue (var) end
---*
---@return cc.Sprite
function ControlSlider:getProgressSprite () end
---*
---@param var cc.Sprite
---@return self
function ControlSlider:setSelectedThumbSprite (var) end
---*
---@param var cc.Sprite
---@return self
function ControlSlider:setBackgroundSprite (var) end
---*
---@param var float
---@return self
function ControlSlider:setMaximumAllowedValue (var) end
---@overload fun(cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite):self
---@overload fun(cc.Sprite0:char,cc.Sprite1:char,cc.Sprite2:char):self
---@overload fun(cc.Sprite0:char,cc.Sprite1:char,cc.Sprite2:char,cc.Sprite3:char):self
---@overload fun(cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite):self
---@param backgroundSprite cc.Sprite
---@param pogressSprite cc.Sprite
---@param thumbSprite cc.Sprite
---@param selectedThumbSprite cc.Sprite
---@return self
function ControlSlider:create (backgroundSprite,pogressSprite,thumbSprite,selectedThumbSprite) end
---*
---@param touch cc.Touch
---@return boolean
function ControlSlider:isTouchInside (touch) end
---*
---@param enabled boolean
---@return self
function ControlSlider:setEnabled (enabled) end
---*
---@return self
function ControlSlider:needsLayout () end
---* js ctor<br>
---* lua new
---@return self
function ControlSlider:ControlSlider () end |
math.randomseed( os.time() )
local from = 1
local to = 100
local rand = math.random( from, to )
local guess = 0
local guesses = 0
repeat
print("Guess the number: ")
guesses = guesses + 1
guess = tonumber( io.read() )
if guess > rand then
print("Too high!")
elseif guess < rand then
print("Too low!")
else
print("You got it!")
print("It took you " .. guesses .. " guesses.")
end
until guess == rand |
--[[
Copyright (c) 2018, Vsevolod Stakhov <[email protected]>
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.
]]--
--[[[
-- @module clamav
-- This module contains clamav access functions
--]]
local lua_util = require "lua_util"
local tcp = require "rspamd_tcp"
local upstream_list = require "rspamd_upstream_list"
local rspamd_util = require "rspamd_util"
local rspamd_logger = require "rspamd_logger"
local common = require "lua_scanners/common"
local N = "clamav"
local default_message = '${SCANNER}: virus found: "${VIRUS}"'
local function clamav_config(opts)
local clamav_conf = {
name = N,
scan_mime_parts = true,
scan_text_mime = false,
scan_image_mime = false,
default_port = 3310,
log_clean = false,
timeout = 5.0, -- FIXME: this will break task_timeout!
detection_category = "virus",
retransmits = 2,
cache_expire = 3600, -- expire redis in one hour
message = default_message,
}
clamav_conf = lua_util.override_defaults(clamav_conf, opts)
if not clamav_conf.prefix then
clamav_conf.prefix = 'rs_' .. clamav_conf.name .. '_'
end
if not clamav_conf.log_prefix then
if clamav_conf.name:lower() == clamav_conf.type:lower() then
clamav_conf.log_prefix = clamav_conf.name
else
clamav_conf.log_prefix = clamav_conf.name .. ' (' .. clamav_conf.type .. ')'
end
end
if not clamav_conf['servers'] then
rspamd_logger.errx(rspamd_config, 'no servers defined')
return nil
end
clamav_conf['upstreams'] = upstream_list.create(rspamd_config,
clamav_conf['servers'],
clamav_conf.default_port)
if clamav_conf['upstreams'] then
lua_util.add_debug_alias('antivirus', clamav_conf.name)
return clamav_conf
end
rspamd_logger.errx(rspamd_config, 'cannot parse servers %s',
clamav_conf['servers'])
return nil
end
local function clamav_check(task, content, digest, rule)
local function clamav_check_uncached ()
local upstream = rule.upstreams:get_upstream_round_robin()
local addr = upstream:get_addr()
local retransmits = rule.retransmits
local header = rspamd_util.pack("c9 c1 >I4", "zINSTREAM", "\0",
#content)
local footer = rspamd_util.pack(">I4", 0)
local function clamav_callback(err, data)
if err then
-- set current upstream to fail because an error occurred
upstream:fail()
-- retry with another upstream until retransmits exceeds
if retransmits > 0 then
retransmits = retransmits - 1
-- Select a different upstream!
upstream = rule.upstreams:get_upstream_round_robin()
addr = upstream:get_addr()
lua_util.debugm(rule.name, task, '%s: retry IP: %s',
rule.log_prefix, addr)
tcp.request({
task = task,
host = addr:to_string(),
port = addr:get_port(),
timeout = rule['timeout'],
callback = clamav_callback,
data = { header, content, footer },
stop_pattern = '\0'
})
else
rspamd_logger.errx(task, '%s: failed to scan, maximum retransmits exceed', rule.log_prefix)
common.yield_result(task, rule, 'failed to scan and retransmits exceed', 0.0, 'fail')
end
else
upstream:ok()
data = tostring(data)
local cached
lua_util.debugm(rule.name, task, '%s: got reply: %s',
rule.log_prefix, data)
if data == 'stream: OK' then
cached = 'OK'
if rule['log_clean'] then
rspamd_logger.infox(task, '%s: message or mime_part is clean',
rule.log_prefix)
else
lua_util.debugm(rule.name, task, '%s: message or mime_part is clean', rule.log_prefix)
end
else
local vname = string.match(data, 'stream: (.+) FOUND')
if string.find(vname, '^Heuristics%.Encrypted') then
rspamd_logger.errx(task, '%s: File is encrypted', rule.log_prefix)
common.yield_result(task, rule, 'File is encrypted: '.. vname, 0.0, 'encrypted')
elseif string.find(vname, '^Heuristics%.Limits%.Exceeded') then
rspamd_logger.errx(task, '%s: ClamAV Limits Exceeded', rule.log_prefix)
common.yield_result(task, rule, 'Limits Exceeded: '.. vname, 0.0, 'fail')
elseif vname then
common.yield_result(task, rule, vname)
cached = vname
else
rspamd_logger.errx(task, '%s: unhandled response: %s', rule.log_prefix, data)
common.yield_result(task, rule, 'unhandled response:' .. vname, 0.0, 'fail')
end
end
if cached then
common.save_av_cache(task, digest, rule, cached)
end
end
end
if rule.dynamic_scan then
local pre_check, pre_check_msg = common.check_metric_results(task, rule)
if pre_check then
rspamd_logger.infox(task, '%s: aborting: %s', rule.log_prefix, pre_check_msg)
return true
end
end
tcp.request({
task = task,
host = addr:to_string(),
port = addr:get_port(),
timeout = rule['timeout'],
callback = clamav_callback,
data = { header, content, footer },
stop_pattern = '\0'
})
end
if common.need_av_check(task, content, rule) then
if common.check_av_cache(task, digest, rule, clamav_check_uncached) then
return
else
clamav_check_uncached()
end
end
end
return {
type = 'antivirus',
description = 'clamav antivirus',
configure = clamav_config,
check = clamav_check,
name = N
}
|
return function(world)
return function(scene, dt)
for entity in pairs(scene:entities_with('velocity', 'position', 'size', 'one_way_platform_position', 'on_ground')) do
local collisions
local resolved_x, resolved_y
local dx = entity.velocity.x * dt
local dy = entity.velocity.y * dt
local target_x = entity.position.x + dx
local target_y = entity.position.y + dy
_, _, collisions = world:check(entity, target_x, target_y, function() return 'cross' end)
resolved_x = target_x
resolved_y = target_y
entity.on_ground = false
for _, collision in pairs(collisions) do
local other = collision.other
if collision.normal.y == -1 and other.solid and not collision.overlaps then
local bounciness = other.bounciness or 0
if bounciness == 0 then
entity.on_ground = true
entity.velocity.y = 0
else
entity.velocity.y = -entity.velocity.y * bounciness
end
scene:new_entity({
event = true,
jumped_on = {
jumper = entity,
jumpee = other,
damage = entity.jump_damage
}
})
resolved_y = collision.touch.y
else
scene:new_entity({
event = true,
ran_into = {
entity = entity,
other = other
}
})
end
end
entity.position.x = resolved_x
entity.position.y = resolved_y
world:update(entity, entity.position.x, entity.position.y)
end
end
end
|
--[[
© CloudSixteen.com do not share, re-distribute or modify
without permission of its author ([email protected]).
Clockwork was created by Conna Wiles (also known as kurozael.)
http://cloudsixteen.com/license/clockwork.html
--]]
local cwStaticEnts = cwStaticEnts;
local Clockwork = Clockwork;
--Called when the plugin is initialized.
function cwStaticEnts:Initialize()
CW_CONVAR_STATICESP = Clockwork.kernel:CreateClientConVar("cwStaticESP", 0, true, true);
Clockwork.setting:AddCheckBox("AdminESP", "ShowStaticEntities", "cwStaticESP", "ShowStaticEntitiesDesc", function()
return Clockwork.player:IsAdmin(Clockwork.Client);
end);
end;
local classTranslate = {
["gmod_light"] = "Light",
["prop_physics"] = "Prop",
["prop_ragdoll"] = "Ragdoll",
["gmod_lamp"] = "Lamp"
};
-- Called when the ESP info is needed.
function cwStaticEnts:GetAdminESPInfo(info)
if (self.staticEnts) then
if (CW_CONVAR_STATICESP:GetInt() == 1) then
for k, v in ipairs(self.staticEnts) do
if (IsValid(v) and v:IsValid()) then
local class = v:GetClass();
if (class != "worldspawn") then
local translatedClass = classTranslate[class] or class;
table.insert(info,{
position = v:GetPos() + Vector(0, 0, 32),
color = Color(0, 210, 255, 255),
text = "[Static "..translatedClass.."]"
});
end;
end;
end;
end;
end;
end;
-- Called to sync up the ESP data from the server.
Clockwork.datastream:Hook("StaticESPSync", function(data)
cwStaticEnts.staticEnts = data;
end) |
local XBar = _G.XBar
local setDate, setOnline, setFormat
local Clock={
["start"]=GetTime(),["hour"]=0,["mins"]=0,["game"]="00:00",["total"]="00:00",["update"]=0,
}
local function Indicator(duration,remaining)
if remaining>0 then
XBarClock_B_Icon:SetCooldown(duration,remaining)
end
end
local function TimeFormat(m, total)
local h = math.floor(m/60)
if total then
return string.format("%d %s %02d:%02d", math.floor(h/24), DAYS, h%24, m%60)
else
return string.format("%02d:%02d", h, m%60)
end
end
function XBar.Clock_OnUpdate(elapsedTime)
Clock["update"]=Clock["update"]+elapsedTime
if Clock["update"]>=1 then
Clock["update"]=0
Indicator(60,60-tonumber(os.date("%S")))
Clock["time"]=GetTime()-Clock["start"]
if not Clock["date"] then Clock["date"]=GetLanguage()=="ENUS" and os.date("%a %m-%d-%Y") or os.date("%a-%d.%m.%Y") end
if Clock["mins"]<math.floor(Clock["time"]%3600/60) then
XBSet["PlayedMins"]=XBSet["PlayedMins"]+1
Clock["mins"]=math.floor(Clock["time"]%3600/60)
Clock["game"]=TimeFormat(Clock["mins"])
Clock["total"]=TimeFormat(XBSet["PlayedMins"], true)
end
-- Output
local usrtxt={[1]=XBSet["ClockV1"],[2]=XBSet["ClockV2"],[3]=XBSet["ClockV3"],[4]=XBSet["ClockV4"],[5]=XBSet["ClockV5"]}
local output=""
for i=1,5 do
usrtxt[i],_=string.gsub(usrtxt[i],"%[TIME24%]",os.date("%H:%M.%S"))
usrtxt[i],_=string.gsub(usrtxt[i],"%[TIME12%]",os.date("%I:%M.%S %p"))
usrtxt[i],_=string.gsub(usrtxt[i],"%[DATE%]",Clock["date"] or NONE)
usrtxt[i],_=string.gsub(usrtxt[i],"%[ONLINE%]",Clock["game"])
usrtxt[i],_=string.gsub(usrtxt[i],"%[TOTALONLINE%]",Clock["total"])
end
if XBSet["ClockT1"] then
if setDate==1 then output=usrtxt[3] elseif setFormat==12 then output=usrtxt[2] else output=usrtxt[1] end
end
if XBSet["ClockT2"] then
if setOnline==1 then if XBSet["ClockT1"] then output=output.."\n"..usrtxt[5] else output=usrtxt[5] end
else if XBSet["ClockT1"] then output=output.."\n"..usrtxt[4] else output=usrtxt[4] end end
end
XBarClock_F_S:SetText(output)
end
end
function XBar.Clock_OnClick(key)
if key=="RBUTTON" and not IsShiftKeyDown() then if setDate==1 then setDate=0 else setDate=1 end
elseif key=="LBUTTON" and IsShiftKeyDown() then if setOnline==1 then setOnline=0 else setOnline=1 end
elseif key=="LBUTTON" then if setFormat==12 then setFormat=24 else setFormat=12 end end
end
function XBar.Clock_OnEnter(this)
Clock["date"]=GetLanguage()=="ENUS" and os.date("%a %m-%d-%Y") or os.date("%a-%d.%m.%Y")
XBarClock_B_Icon:SetTexture("interface/icons/Skill_ran54-1")
XBar.TooltipMod(this)
GameTooltip:SetText(TIMEFLAG_STATE.." / "..GUILD_RESOURCE_DATE)
GameTooltip:AddLine(XBar.Lng["Ttip"]["Clock1"],0,.7,.9)
GameTooltip:AddSeparator()
GameTooltip:AddDoubleLine("|cffFFE855"..GUILD_RESOURCE_DATE.."|r", Clock["date"] or NONE)
GameTooltip:AddDoubleLine("|cffFFE855"..TIMEFLAG_STATE.."|r", os.date("%H:%M.%S"))
GameTooltip:AddDoubleLine("|cffFFE855"..XBar.Lng["Config"]["Clock1"].."|r", Clock["game"])
GameTooltip:AddDoubleLine("|cffFFE855"..XBar.Lng["Ttip"]["Clock2"].."|r", Clock["total"])
end
if d303Fix then d303Fix.Strings.WeekDaysShort = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"} end
|
--[[----------------------------------------------------------------------------
KwUtils.lua
Utility functions for Lightroom Keywords
--------------------------------------------------------------------------------
Copyright 2016 Lowell "LoweMo / LoMo" Montgomery
https://lowemo.photo
Latest version: https://lowemo.photo/lightroom-keyword-utils
This file is used in a few Lightroom plugins.
This code is released under a Creative Commons CC-BY "Attribution" License:
http://creativecommons.org/licenses/by/3.0/deed.en_US
This bundle may be used for any purpose, provided that the copyright notice
and web-page links, above, as well as the 'AUTHOR_NOTE' and 'Attribution'
strings, below are maintained. Enjoy.
------------------------------------------------------------------------------]]
local LUTILS = require 'LUTILS'
KwUtils = {}
KwUtils.catKws = nil
KwUtils.catKwPaths = nil
KwUtils.VERSION = 20161126.03 -- version history at end of file
KwUtils.AUTHOR_NOTE = "KwUtils.lua is a set of Lightroom keyword utility functions, © 2016 by Lowell Montgomery (https://lowemo.photo/lightroom-keyword-utils) version: " .. KwUtils.VERSION
-- The following provides an 80 character-width attribution text that can be inserted for display
-- in a plugin derived using these helper functions.
KwUtils.Attribution = "This plugin uses KwUtils, Lightroom keyword utilities, © 2016 by Lowell Montgomery\n (https://lowemo.photo/lightroom-keyword-utils) version: " .. KwUtils.VERSION .. "\n\nThis code is released under a Creative Commons CC-BY “Attribution” License:\n http://creativecommons.org/licenses/by/3.0/deed.en_US"
function KwUtils.addKeywordWithParents(photo, keyword)
photo:addKeyword(keyword)
local parent = keyword:getParent()
if parent ~= nil then
KwUtils.addKeywordWithParents(photo, parent)
end
end
-- Call this function with just a keyword object. This recursively calls kw:getParent,
-- adding each parent to the table of parent keywords. When the top of the hierarchy
-- is reached, the "ancestry table" of keywords is returned.
function KwUtils.getAllParentKeywords(kw, parents)
-- Set parents to empty table if not already existing
parents = parents ~= nil and parents or {}
local p = kw:getParent()
if p ~= nil then
parents[#parents+1] = p
KwUtils.getAllParentKeywords(p, parents)
end
return parents
end
-- A photo may have keywords selected without the parent keywords actually being
-- selected. Although any parents not set to be suppressed on export will be
-- included during the export process, the photo will not show up in the library
-- if you filter by the such a term. This function explicitly adds all keyword parents.
function KwUtils.addAllKeywordParentsForPhoto(photo)
local keywordsForPhoto = photo:getRawMetadata('keywords')
local keywordsToAdd = {}
for _,kw in ipairs(keywordsForPhoto) do
local kwParents = KwUtils.getAllParentKeywords(kw)
if (kwParents ~= nil) and (type(kwParents) == 'table') and (#kwParents ~= 0) then
for _,parentKey in ipairs(kwParents) do
if (not LUTILS.inTable(parentKey, keywordsForPhoto)) and (not LUTILS.inTable(parentKey, keywordsToAdd)) then
keywordsToAdd[#keywordsToAdd+1] = parentKey
end
end
end
end
for _,kwToAdd in ipairs(keywordsToAdd) do
photo:addKeyword(kwToAdd)
end
-- Return the keywords which have been added
return keywordsToAdd
end
-- Add or remove a keyword based on the "state" of the associated checkbox.
-- Presumed is that we call this when the state differs from what is already on this image,
-- i.e. that they keyword is being changed for the photo (added or removed)
function KwUtils.addOrRemoveKeyword(photo, keyword, state)
if state then
KwUtils.addKeywordWithParents(photo, keyword)
else
-- We cannot assume parents should be removed if already there.
photo:removeKeyword(keyword)
end
end
--Returns array of keywords with a given name
function KwUtils.getAllKeywordsByName(name, keywords, found)
found = found or {}
if type(found) == 'LrKeyword' then
found = {found}
elseif type(found) ~= 'table' then
found = {}
end
for i, kw in pairs(keywords) do
-- If we have found the keyword we want, return it:
if kw:getName() == name and LUTILS.inTable(kw, found) == false then
found[#found + 1] = kw
-- Otherwise, use recursion to check next level if kw has child keywords:
else
local kchildren = kw:getChildren()
if #kchildren > 0 then
found = KwUtils.getAllKeywordsByName(name, kchildren, found)
end
end
end
-- By now, we should have them all
return found
end
-- Gets string representing a keywords parent names in hierarchical order, e.g.
-- "TOP_LEVEL_CATEGORY | second_level_parent | parent"
function KwUtils.getAncestryString(kw, ancestryString)
ancestryString = ancestryString or ''
local parent = kw:getParent()
if parent ~= nil then
ancestryString = parent:getName() .. " | " .. ancestryString
ancestryString = KwUtils.getAncestryString(parent, ancestryString)
end
return ancestryString;
end
-- Return a comma-separated string listing all children of a term
function KwUtils.getChildrenString(kw)
local childNamesTable = KwUtils.getKeywordChildNamesTable(kw)
if #childNamesTable > 0 then
return table.concat(childNamesTable, ", ")
else return ""
end
end
-- Find a keyword by a given name within a table of keyword objects
-- arg: lookfor Name of keyword to search for
-- arg: keywordSet Table of keywords, usually the top level keywords returned by Lightroom
-- API call to catalog:getKeywords(). If the sought keyword is not found
-- any "branches" of child terms are also examined (by recursive calls to this function)
function KwUtils.getKeywordByName(lookfor, keywordSet)
for i, kw in pairs(keywordSet) do
-- If we have found the keyword we want, return it:
if kw:getName() == lookfor then
return kw
-- Otherwise, use recursion to check next level if kw has child keywords:
else
local kchildren = kw:getChildren()
if kchildren and #kchildren > 0 then
local nextkw = KwUtils.getKeywordByName(lookfor, kchildren)
if nextkw ~= nil then
return nextkw
end
end
end
end
-- If we have not returned the sought keyword, it's not there:
return nil
end
--General Lightroom API helper functions for keywords
function KwUtils.getKeywordChildNamesTable(parentKey)
local kchildren = parentKey:getChildren()
local childNames = {}
if kchildren and #kchildren > 0 then
childNames = KwUtils.getKeywordNames(kchildren)
end
-- Return the table of child terms (empty if no child terms for passed keyword)
return childNames
end
-- Get names of all Keyword objects in a table
function KwUtils.getKeywordNames(keywords)
local names = {}
if type(keywords) == 'table' then
for _,kw in ipairs(keywords) do
names[#names+1] = kw:getName()
end
end
return names
end
-- This is used by the KwUtils.findAllKeywords and allows skipping over branches that
-- would not be helpful for whatever purpose. A plugin does not NEED to implement
-- the ignore_keyword_branches preference. If it does not exist, we skip no branches,
-- just as if it did exist, but the field was empty.
function KwUtils.getIgnoreKeywordsTable()
local prefs = import 'LrPrefs'.prefsForPlugin(_PLUGIN.id)
local ignoreKeywordsList = ''
if prefs.ignore_keyword_branches ~= nil then
ignoreKeywordsList = prefs.ignore_keyword_branches
end
local ignoreKeysTable = LUTILS.split(ignoreKeywordsList, ', ')
for i, kw in ipairs(ignoreKeysTable) do
local val = LUTILS.trim(kw)
if val == '' then
ignoreKeysTable[i] = nil
else
ignoreKeysTable[i] = val
end
end
return ignoreKeysTable
end
-- This function must be called from within an asynchronous task started using LrTasks.
function KwUtils.getAllKeywords(catalog)
if KwUtils.catKws == nil then
KwUtils.catKws = {}
KwUtils.catKwPaths = {}
local topLevelKeywords = catalog:getKeywords()
return KwUtils.findAllKeywords(topLevelKeywords)
end
return KwUtils.catKws
end
-- Given a set of keywords (normally starting with a top level of a hierarchy),
-- get all keywords in the set with any child/descendant keywords) and populate
-- our top-level keyword table variables with data we can quickly use.
function KwUtils.findAllKeywords(keywords, kpath)
kpath = kpath or ''
local ignoreKeysTable = KwUtils.getIgnoreKeywordsTable()
for _, kw in pairs(keywords) do
local name = kw:getName()
-- Skip any keywords (and descendants) listed in the ignoreKeysTable
if not LUTILS.inTable(name, ignoreKeysTable) then
local keyname = string.lower(name)
if KwUtils.catKws[keyname] ~= nil then
local count = #KwUtils.catKws[keyname]
KwUtils.catKws[keyname][count + 1] = kw
KwUtils.catKwPaths[keyname][count + 1] = kpath
else
KwUtils.catKws[keyname] = {kw}
KwUtils.catKwPaths[keyname] = {kpath}
end
local kids = kw:getChildren()
if kids and #kids > 0 then
local new_kpath = kpath ~= '' and kpath .. ' | ' .. name or name
KwUtils.findAllKeywords(kids, new_kpath)
end
end
end
return KwUtils.catKws;
end
-- Get number of keywords by a given name (adjusted to lower case) or false
-- if the keyword does not exist. This functionality depends on first running
-- KwUtils.findAllKeywords() to populate the catKws table.
function KwUtils.keywordExists(keyword)
if KwUtils.catKws[string.lower(keyword)] ~= nil then
return #KwUtils.catKws[string.lower(keyword)]
end
return false
end
-- Get existing keywords for a photo which are not in a given set (table)
function KwUtils.getOtherKeywords(photo, keywordNames)
local photoKeywordList = photo:getFormattedMetadata('keywordTags')
local photoKeywordNames = LUTILS.split(photoKeywordList, ', ')
local ret = {}
for _, keyName in ipairs(photoKeywordNames) do
if not LUTILS.inTable(keyName, keywordNames) then
ret[#ret + 1] = keyName
end
end
return ret
end
-- Check for actual keyword (by keyword object, not name) associated with a photo
-- Given a catalog photo, check for the presence of any given keyword.
function KwUtils.hasKeywordById(photo, keyword)
local keywordsForPhoto = photo:getRawMetadata('keywords')
--Look for keyword object passed in array of Keyword objects.
return LUTILS.inTable(keyword, keywordsForPhoto)
end
-- Check if photo already has a particular keyword (by name)
-- Converts all keywords to lower case before comparison which "ignores case"
function KwUtils.hasKeywordByName(photo, keywordName)
local photoKeywordList = string.lower(photo:getFormattedMetadata('keywordTags'))
local keywordNamesTable = LUTILS.split(photoKeywordList, ', ')
return LUTILS.inTable(string.lower(keywordName), keywordNamesTable)
end
return KwUtils
-- 20161101.01 Initial release.
-- It includes functions I had found myself writing and re-writing in various plugins.
-- 20161122.02 Minor tweaks and bugfixes; not yet officially released, so will not itemize changes
-- 20161126.03 Moved more logic into the KwUtils. It is no longer a local bundle, so this may have ramifications for memory
-- etc, but allows us to call "expenive" processes (new findAllKeywords() / getAllKeywords() functionality) and
-- hopefully be able to access the results from other scripts in a plugin. Still "pre-release"
|
require 'nn'
require 'nngraph'
require 'hdf5'
require 'data-entail.lua'
require 'models/models-entail.lua'
require 'models/model_utils.lua'
cmd = torch.CmdLine()
-- data files
cmd:text("")
cmd:text("**Data options**")
cmd:text("")
cmd:option('-data_file','data/entail-train.hdf5', [[Path to the training *.hdf5 file]])
cmd:option('-val_data_file', 'data/entail-val.hdf5', [[Path to validation *.hdf5 file]])
cmd:option('-test_data_file','data/entail-test.hdf5',[[Path to test *.hdf5 file]])
cmd:option('-savefile', 'entail', [[Savefile name]])
-- model specs
cmd:option('-hidden_size', 300, [[MLP hidden layer size]])
cmd:option('-word_vec_size', 300, [[Word embedding size]])
cmd:option('-attn', 'none', [[one of {none, simple, struct}.
none = no intra-sentence attention (baseline model)
simple = simple attention model
struct = structured attention (syntactic attention)]])
cmd:option('-num_layers_parser', 1, [[Number of layers for the RNN parsing layer]])
cmd:option('-rnn_size_parser', 100, [[size of the RNN for the parsing layer]])
cmd:option('-use_parent', 1, [[Use soft parents]])
cmd:option('-use_children', 0, [[Use soft children]])
cmd:option('-share_params',1, [[Share parameters between the two sentence encoders]])
cmd:option('-proj', 1, [[Have a projection layer from the Glove embeddings]])
cmd:option('-dropout', 0.2, [[Dropout probability.]])
-- optimization
cmd:option('-epochs', 100, [[Number of training epochs]])
cmd:option('-param_init', 0.01, [[Parameters are initialized over uniform distribution with support
(-param_init, param_init)]])
cmd:option('-optim', 'adagrad', [[Optimization method. Possible options are:
sgd (vanilla SGD), adagrad, adadelta, adam]])
cmd:option('-learning_rate', 0.05, [[Starting learning rate. If adagrad/adadelta/adam is used,
then this is the global learning rate.]])
cmd:option('-max_grad_norm', 5, [[If the norm of the gradient vector exceeds this renormalize it
to have the norm equal to max_grad_norm]])
cmd:option('-pre_word_vecs', 'data/glove.hdf5', [[If a valid path is specified, then this will load
pretrained word embeddings (hdf5 file)]])
cmd:option('-fix_word_vecs', 1, [[If = 1, fix word embeddings]])
cmd:option('-max_batch_l', 32, [[If blank, then it will infer the max batch size from validation
data. You should only use this if your validation set uses a different
batch size in the preprocessing step]])
cmd:option('-gpuid', -1, [[Which gpu to use. -1 = use CPU]])
cmd:option('-print_every', 1000, [[Print stats after this many batches]])
cmd:option('-seed', 3435, [[Seed for random initialization]])
opt = cmd:parse(arg)
torch.manualSeed(opt.seed)
function zero_table(t)
for i = 1, #t do
t[i]:zero()
end
end
function train(train_data, valid_data)
local timer = torch.Timer()
local start_decay = 0
params, grad_params = {}, {}
opt.train_perf = {}
opt.val_perf = {}
for i = 1, #layers do
local p, gp = layers[i]:getParameters()
local rand_vec = torch.randn(p:size(1)):mul(opt.param_init)
if opt.gpuid >= 0 then
rand_vec = rand_vec:cuda()
end
p:copy(rand_vec)
params[i] = p
grad_params[i] = gp
end
if opt.pre_word_vecs:len() > 0 then
print("loading pre-trained word vectors")
local f = hdf5.open(opt.pre_word_vecs)
local pre_word_vecs = f:read('word_vecs'):all()
for i = 1, pre_word_vecs:size(1) do
word_vecs_enc1.weight[i]:copy(pre_word_vecs[i])
word_vecs_enc2.weight[i]:copy(pre_word_vecs[i])
end
end
--copy shared params
params[2]:copy(params[1])
if opt.attn ~= 'none' then
params[7]:copy(params[6])
end
if opt.share_params == 1 then
if opt.proj == 1 then
entail_layers.proj2.weight:copy(entail_layers.proj1.weight)
end
for k = 2, 5, 3 do
entail_layers.f2.modules[k].weight:copy(entail_layers.f1.modules[k].weight)
entail_layers.f2.modules[k].bias:copy(entail_layers.f1.modules[k].bias)
entail_layers.g2.modules[k].weight:copy(entail_layers.g1.modules[k].weight)
entail_layers.g2.modules[k].bias:copy(entail_layers.g1.modules[k].bias)
end
end
-- prototypes for gradients so there is no need to clone
word_vecs1_grad_proto = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.word_vec_size)
word_vecs2_grad_proto = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.word_vec_size)
sent1_context_proto = torch.zeros(opt.max_batch_l, opt.rnn_size_parser * 2)
sent2_context_proto = torch.zeros(opt.max_batch_l, opt.rnn_size_parser * 2)
parser_context1_proto = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size_parser * 2)
parser_graph1_grad_proto = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.word_vec_size*2)
parser_context2_proto = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.rnn_size_parser * 2)
parser_graph2_grad_proto = torch.zeros(opt.max_batch_l, opt.max_sent_l, opt.word_vec_size*2)
-- clone encoder/decoder up to max source/target length
if opt.attn ~= 'none' then
parser_fwd_clones = clone_many_times(parser_fwd, opt.max_sent_l_src + opt.max_sent_l_targ)
parser_bwd_clones = clone_many_times(parser_bwd, opt.max_sent_l_src + opt.max_sent_l_targ)
for i = 1, opt.max_sent_l_src + opt.max_sent_l_targ do
if parser_fwd_clones[i].apply then
parser_fwd_clones[i]:apply(function(m) m:setReuse() end)
end
if parser_bwd_clones[i].apply then
parser_bwd_clones[i]:apply(function(m) m:setReuse() end)
end
end
end
local h_init_parser = torch.zeros(opt.max_batch_l, opt.rnn_size_parser)
if opt.gpuid >= 0 then
h_init_parser = h_init_parser:cuda()
cutorch.setDevice(opt.gpuid)
word_vecs1_grad_proto = word_vecs1_grad_proto:cuda()
word_vecs2_grad_proto = word_vecs2_grad_proto:cuda()
parser_context1_proto = parser_context1_proto:cuda()
parser_context2_proto = parser_context2_proto:cuda()
parser_graph1_grad_proto = parser_graph1_grad_proto:cuda()
parser_graph2_grad_proto = parser_graph1_grad_proto:cuda()
sent1_context_proto = sent1_context_proto:cuda()
sent2_context_proto = sent2_context_proto:cuda()
end
-- these are initial states of parser/encoder/decoder for fwd/bwd steps
init_parser = {}
for L = 1, opt.num_layers_parser do
table.insert(init_parser, h_init_parser:clone())
table.insert(init_parser, h_init_parser:clone())
end
function reset_state(state, batch_l, t)
if t == nil then
local u = {}
for i = 1, #state do
state[i]:zero()
table.insert(u, state[i][{{1, batch_l}}])
end
return u
else
local u = {[t] = {}}
for i = 1, #state do
state[i]:zero()
table.insert(u[t], state[i][{{1, batch_l}}])
end
return u
end
end
function train_batch(data, epoch)
local train_loss = 0
local train_sents = 0
local batch_order = torch.randperm(data.length) -- shuffle mini batch order
local start_time = timer:time().real
local num_words_target = 0
local num_words_source = 0
local train_num_correct = 0
sent_encoder:training()
for i = 1, data:size() do
zero_table(grad_params, 'zero')
local d = data[batch_order[i]]
local target, source, batch_l, target_l, source_l, label = table.unpack(d)
-- resize the various temporary tensors that are going to hold contexts/grads
local word_vecs1_grads = word_vecs1_grad_proto[{{1, batch_l}, {1, source_l}}]:zero()
local word_vecs2_grads = word_vecs2_grad_proto[{{1, batch_l}, {1, target_l}}]:zero()
local parser_context1 = parser_context1_proto[{{1, batch_l}, {1, source_l}}]
local parser_context2 = parser_context2_proto[{{1, batch_l}, {1, target_l}}]
local sent1_context = sent1_context_proto[{{1, batch_l}}]
local sent2_context = sent2_context_proto[{{1, batch_l}}]
local word_vecs1 = word_vecs_enc1:forward(source)
local word_vecs2 = word_vecs_enc2:forward(target)
if opt.attn ~= 'none' then
set_size_encoder(batch_l, source_l, target_l, opt.word_vec_size,
opt.hidden_size, entail_layers)
set_size_parser(batch_l, source_l, opt.rnn_size_parser*2, parser_layers1)
set_size_parser(batch_l, target_l, opt.rnn_size_parser*2, parser_layers2)
------ fwd prop for parser brnn for sent 1------
-- fwd direction
local rnn_state_parser_fwd1 = reset_state(init_parser, batch_l, 0)
parser_fwd_inputs1 = {}
for t = 1, source_l do
parser_fwd_clones[t]:training()
parser_fwd_inputs1[t] = {word_vecs1[{{}, t}],
table.unpack(rnn_state_parser_fwd1[t-1])}
local out = parser_fwd_clones[t]:forward(parser_fwd_inputs1[t])
rnn_state_parser_fwd1[t] = out
parser_context1[{{}, t, {1, opt.rnn_size_parser}}]:copy(out[#out])
end
-- bwd direction
local rnn_state_parser_bwd1 = reset_state(init_parser, batch_l, source_l+1)
parser_bwd_inputs1 = {}
for t = source_l, 1, -1 do
parser_bwd_clones[t]:training()
parser_bwd_inputs1[t] = {word_vecs1[{{}, t}],
table.unpack(rnn_state_parser_bwd1[t+1])}
local out = parser_bwd_clones[t]:forward(parser_bwd_inputs1[t])
rnn_state_parser_bwd1[t] = out
parser_context1[{{}, t,
{opt.rnn_size_parser+1, opt.rnn_size_parser*2}}]:copy(out[#out])
end
------ fwd prop for parser brnn for sent 2------
-- fwd direction
local rnn_state_parser_fwd2 = reset_state(init_parser, batch_l, 0)
parser_fwd_inputs2 = {}
for t = 1, target_l do
parser_fwd_clones[t+source_l]:training()
parser_fwd_inputs2[t] = {word_vecs2[{{}, t}],
table.unpack(rnn_state_parser_fwd2[t-1])}
local out = parser_fwd_clones[t+source_l]:forward(parser_fwd_inputs2[t])
rnn_state_parser_fwd2[t] = out
parser_context2[{{}, t, {1, opt.rnn_size_parser}}]:copy(out[#out])
end
-- bwd direction
local rnn_state_parser_bwd2 = reset_state(init_parser, batch_l, target_l+1)
parser_bwd_inputs2 = {}
for t = target_l, 1, -1 do
parser_bwd_clones[t+source_l]:training()
parser_bwd_inputs2[t] = {word_vecs2[{{}, t}],
table.unpack(rnn_state_parser_bwd2[t+1])}
local out = parser_bwd_clones[t+source_l]:forward(parser_bwd_inputs2[t])
rnn_state_parser_bwd2[t] = out
parser_context2[{{}, t, {opt.rnn_size_parser+1,
opt.rnn_size_parser*2}}]:copy(out[#out])
end
parser_context1 = parser_context1:contiguous()
parser_context2 = parser_context2:contiguous()
parsed_context1 = parser_graph1:forward(parser_context1)
parsed_context2 = parser_graph2:forward(parser_context2)
pred_input = {word_vecs1, word_vecs2, parsed_context1, parsed_context2}
else
set_size_encoder(batch_l, source_l, target_l,
opt.word_vec_size, opt.hidden_size, entail_layers)
pred_input = {word_vecs1, word_vecs2}
end
local pred_label = sent_encoder:forward(pred_input)
local _, pred_argmax = pred_label:max(2)
train_num_correct = train_num_correct + pred_argmax:double():view(batch_l):eq(label:double()):sum()
local loss = disc_criterion:forward(pred_label, label)
local dl_dp = disc_criterion:backward(pred_label, label)
dl_dp:div(batch_l)
if opt.attn ~= 'none' then
local dl_dinput1, dl_dinput2, dl_dparser1, dl_dparser2 = table.unpack(
sent_encoder:backward(pred_input, dl_dp))
------ backprop for graph-based parser ------
parser_grads1 = parser_graph1:backward(parser_context1, dl_dparser1)
parser_grads2 = parser_graph2:backward(parser_context2, dl_dparser2)
word_vecs1_grads:add(dl_dinput1)
word_vecs2_grads:add(dl_dinput2)
------ backprop for parser brnn ------
-- backprop through fwd parser rnn
local drnn_state = reset_state(init_parser, batch_l)
for t = source_l, 1, -1 do
drnn_state[#drnn_state]:add(
parser_grads1[{{}, t, {1, opt.rnn_size_parser}}])
local dlst = parser_fwd_clones[t]:backward(parser_fwd_inputs1[t], drnn_state)
for j = 1, #drnn_state do
drnn_state[j]:copy(dlst[j+1])
end
word_vecs1_grads[{{}, t}]:add(dlst[1])
end
-- backprop through bwd parser rnn
local drnn_state = reset_state(init_parser, batch_l)
for t = 1, source_l do
drnn_state[#drnn_state]:add(
parser_grads1[{{}, t, {opt.rnn_size_parser+1, 2*opt.rnn_size_parser}}])
local dlst = parser_bwd_clones[t]:backward(parser_bwd_inputs1[t], drnn_state)
for j = 1, #drnn_state do
drnn_state[j]:copy(dlst[j+1])
end
word_vecs1_grads[{{}, t}]:add(dlst[1])
end
------ backprop through source word vectors ------
if opt.proj == 0 then
word_vecs_enc1:backward(source, word_vecs1_grads:contiguous())
end
------ backprop for parser brnn ------
-- backprop through fwd parser rnn
local drnn_state = reset_state(init_parser, batch_l)
for t = target_l, 1, -1 do
drnn_state[#drnn_state]:add(
parser_grads2[{{}, t, {1, opt.rnn_size_parser}}])
local dlst = parser_fwd_clones[t+source_l]:backward(parser_fwd_inputs2[t], drnn_state)
for j = 1, #drnn_state do
drnn_state[j]:copy(dlst[j+1])
end
word_vecs2_grads[{{}, t}]:add(dlst[1])
end
-- backprop through bwd parser rnn
local drnn_state = reset_state(init_parser, batch_l)
for t = 1, target_l do
drnn_state[#drnn_state]:add(
parser_grads2[{{}, t, {opt.rnn_size_parser+1, 2*opt.rnn_size_parser}}])
local dlst = parser_bwd_clones[t+source_l]:backward(parser_bwd_inputs2[t], drnn_state)
for j = 1, #drnn_state do
drnn_state[j]:copy(dlst[j+1])
end
word_vecs2_grads[{{}, t}]:add(dlst[1])
end
------ backprop through source word vectors ------
if opt.proj == 0 then
word_vecs_enc2:backward(target, word_vecs2_grads)
end
else
local dl_dinput1, dl_dinput2 = table.unpack(sent_encoder:backward(pred_input, dl_dp))
word_vecs_enc1:backward(source, dl_dinput1)
word_vecs_enc2:backward(target, dl_dinput2)
end
if opt.fix_word_vecs == 1 then
word_vecs_enc1.gradWeight:zero()
word_vecs_enc2.gradWeight:zero()
end
-- word vec layer and parser_graph layers are shared
grad_params[1]:add(grad_params[2])
grad_params[2]:zero()
if opt.attn ~= 'none' then
grad_params[6]:add(grad_params[7])
grad_params[7]:zero()
end
if opt.share_params == 1 then
if opt.proj == 1 then
entail_layers.proj1.gradWeight:add(entail_layers.proj2.gradWeight)
entail_layers.proj2.gradWeight:zero()
end
for k = 2, 5, 3 do
entail_layers.f1.modules[k].gradWeight:add(entail_layers.f2.modules[k].gradWeight)
entail_layers.f1.modules[k].gradBias:add(entail_layers.f2.modules[k].gradBias)
entail_layers.g1.modules[k].gradWeight:add(entail_layers.g2.modules[k].gradWeight)
entail_layers.g1.modules[k].gradBias:add(entail_layers.g2.modules[k].gradBias)
entail_layers.f2.modules[k].gradWeight:zero()
entail_layers.f2.modules[k].gradBias:zero()
entail_layers.g2.modules[k].gradWeight:zero()
entail_layers.g2.modules[k].gradBias:zero()
end
end
local grad_norm = 0
for i = 1, #grad_params do
grad_norm = grad_norm + grad_params[i]:norm()^2
end
grad_norm = grad_norm^0.5
-- Shrink norm and update params
local param_norm = 0
local shrinkage = opt.max_grad_norm / grad_norm
for j = 1, #grad_params do
if shrinkage < 1 then
grad_params[j]:mul(shrinkage)
end
if opt.optim == 'adagrad' then
adagrad_step(params[j], grad_params[j], layer_etas[j], optStates[j])
elseif opt.optim == 'adadelta' then
adadelta_step(params[j], grad_params[j], layer_etas[j], optStates[j])
elseif opt.optim == 'adam' then
adam_step(params[j], grad_params[j], layer_etas[j], optStates[j])
else
params[j]:add(grad_params[j]:mul(-opt.learning_rate))
end
if j ~= 2 and j ~= 6 then
param_norm = param_norm + params[j]:norm()^2
end
end
param_norm = param_norm^0.5
params[2]:copy(params[1])
if opt.attn ~= 'none' then
params[7]:copy(params[6])
end
if opt.share_params == 1 then
if opt.proj == 1 then
entail_layers.proj2.weight:copy(entail_layers.proj1.weight)
end
for k = 2, 5, 3 do
entail_layers.f2.modules[k].weight:copy(entail_layers.f1.modules[k].weight)
entail_layers.f2.modules[k].bias:copy(entail_layers.f1.modules[k].bias)
entail_layers.g2.modules[k].weight:copy(entail_layers.g1.modules[k].weight)
entail_layers.g2.modules[k].bias:copy(entail_layers.g1.modules[k].bias)
end
end
-- Bookkeeping
num_words_target = num_words_target + batch_l*target_l
num_words_source = num_words_source + batch_l*source_l
train_loss = train_loss + loss
train_sents = train_sents + batch_l
local time_taken = timer:time().real - start_time
if i % opt.print_every == 0 then
local stats = string.format('Epoch: %d, Batch: %d/%d, Batch size: %d, LR: %.4f, ',
epoch, i, data:size(), batch_l, opt.learning_rate)
stats = stats .. string.format('NLL: %.4f, Acc: %.4f, |Param|: %.2f, |GParam|: %.2f, ',
train_loss/train_sents, train_num_correct/train_sents,
param_norm, grad_norm)
stats = stats .. string.format('Training: %d/%d/%d total/source/target tokens/sec',
(num_words_target+num_words_source) / time_taken,
num_words_source / time_taken,
num_words_target / time_taken)
print(stats)
end
if i % 200 == 0 then
collectgarbage()
end
end
return train_loss, train_sents, train_num_correct
end
-- eval(valid_data)
-- eval(test_data)
local best_val_perf = 0
local test_perf = 0
for epoch = 1, opt.epochs do
local total_loss, total_sents, total_correct = train_batch(train_data, epoch)
local train_score = total_correct/total_sents
print('Train', train_score)
opt.train_perf[#opt.train_perf + 1] = train_score
local score = eval(valid_data)
local savefile = string.format('%s.t7', opt.savefile)
if score > best_val_perf then
best_val_perf = score
test_perf = eval(test_data)
print('saving checkpoint to ' .. savefile)
torch.save(savefile, {layers, opt, layer_etas, optStates})
end
opt.val_perf[#opt.val_perf + 1] = score
print(opt.train_perf)
print(opt.val_perf)
end
print("Best Val", best_val_perf)
print("Test", test_perf)
-- save final model
local savefile = string.format('%s_final.t7', opt.savefile)
print('saving final model to ' .. savefile)
for i = 1, #layers do
layers[i]:double()
end
torch.save(savefile, {layers, opt, layer_etas, optStates})
end
function eval(data)
sent_encoder:evaluate()
local nll = 0
local num_sents = 0
local num_correct = 0
for i = 1, data:size() do
local d = data[i]
local target, source, batch_l, target_l, source_l, label = table.unpack(d)
local sent1_context = sent1_context_proto[{{1, batch_l}}]
local sent2_context = sent2_context_proto[{{1, batch_l}}]
local word_vecs1 = word_vecs_enc1:forward(source)
local word_vecs2 = word_vecs_enc2:forward(target)
if opt.attn ~= 'none' then
set_size_encoder(batch_l, source_l, target_l,
opt.word_vec_size, opt.hidden_size, entail_layers)
set_size_parser(batch_l, source_l, opt.rnn_size_parser*2, parser_layers1)
set_size_parser(batch_l, target_l, opt.rnn_size_parser*2, parser_layers2)
-- resize the various temporary tensors that are going to hold contexts/grads
local parser_context1 = parser_context1_proto[{{1, batch_l}, {1, source_l}}]
local parser_context2 = parser_context2_proto[{{1, batch_l}, {1, target_l}}]
------ fwd prop for parser brnn for sent 1------
-- fwd direction
local rnn_state_parser_fwd1 = reset_state(init_parser, batch_l, 0)
local parser_fwd_inputs1 = {}
for t = 1, source_l do
parser_fwd_clones[t]:evaluate()
parser_fwd_inputs1[t] = {word_vecs1[{{}, t}], table.unpack(rnn_state_parser_fwd1[t-1])}
local out = parser_fwd_clones[t]:forward(parser_fwd_inputs1[t])
rnn_state_parser_fwd1[t] = out
parser_context1[{{}, t, {1, opt.rnn_size_parser}}]:copy(out[#out])
end
-- bwd direction
local rnn_state_parser_bwd1 = reset_state(init_parser, batch_l, source_l+1)
local parser_bwd_inputs1 = {}
for t = source_l, 1, -1 do
parser_bwd_clones[t]:evaluate()
parser_bwd_inputs1[t] = {word_vecs1[{{}, t}], table.unpack(rnn_state_parser_bwd1[t+1])}
local out = parser_bwd_clones[t]:forward(parser_bwd_inputs1[t])
rnn_state_parser_bwd1[t] = out
parser_context1[{{}, t, {opt.rnn_size_parser+1, opt.rnn_size_parser*2}}]:copy(out[#out])
end
------ fwd prop for parser brnn for sent 2------
-- fwd direction
local rnn_state_parser_fwd2 = reset_state(init_parser, batch_l, 0)
local parser_fwd_inputs2 = {}
for t = 1, target_l do
parser_fwd_clones[t+source_l]:training()
parser_fwd_inputs2[t] = {word_vecs2[{{}, t}], table.unpack(rnn_state_parser_fwd2[t-1])}
local out = parser_fwd_clones[t+source_l]:forward(parser_fwd_inputs2[t])
rnn_state_parser_fwd2[t] = out
parser_context2[{{}, t, {1, opt.rnn_size_parser}}]:copy(out[#out])
end
-- bwd direction
local rnn_state_parser_bwd2 = reset_state(init_parser, batch_l, target_l+1)
local parser_bwd_inputs2 = {}
for t = target_l, 1, -1 do
parser_bwd_clones[t+source_l]:training()
parser_bwd_inputs2[t] = {word_vecs2[{{}, t}], table.unpack(rnn_state_parser_bwd2[t+1])}
local out = parser_bwd_clones[t+source_l]:forward(parser_bwd_inputs2[t])
rnn_state_parser_bwd2[t] = out
parser_context2[{{}, t, {opt.rnn_size_parser+1, opt.rnn_size_parser*2}}]:copy(out[#out])
end
parsed_context1 = parser_graph1:forward(parser_context1:contiguous())
parsed_context2 = parser_graph2:forward(parser_context2:contiguous())
pred_input = {word_vecs1, word_vecs2, parsed_context1, parsed_context2}
else
set_size_encoder(batch_l, source_l, target_l,
opt.word_vec_size, opt.hidden_size, entail_layers)
pred_input = {word_vecs1, word_vecs2}
end
local pred_label = sent_encoder:forward(pred_input)
local loss = disc_criterion:forward(pred_label, label)
local _, pred_argmax = pred_label:max(2)
num_correct = num_correct + pred_argmax:double():view(batch_l):eq(label:double()):sum()
num_sents = num_sents + batch_l
nll = nll + loss
end
local acc = num_correct/num_sents
print("Acc", acc)
print("NLL", nll / num_sents)
collectgarbage()
return acc
end
function get_layer(layer)
if layer.name ~= nil then
if layer.name == 'word_vecs_enc2' then
word_vecs_dec = layer
elseif layer.name == 'parser' then
parser = layer
end
end
end
function main()
-- parse input params
opt = cmd:parse(arg)
if opt.gpuid >= 0 then
print('using CUDA on GPU ' .. opt.gpuid .. '...')
require 'cutorch'
require 'cunn'
if opt.cudnn == 1 then
print('loading cudnn...')
require 'cudnn'
end
cutorch.setDevice(opt.gpuid)
cutorch.manualSeed(opt.seed)
end
-- Create the data loader class.
print('loading data...')
train_data = data.new(opt, opt.data_file)
valid_data = data.new(opt, opt.val_data_file)
test_data = data.new(opt, opt.test_data_file)
print('done!')
print(string.format('Source vocab size: %d, Target vocab size: %d',
valid_data.source_size, valid_data.target_size))
opt.max_sent_l_src = valid_data.source:size(2)
opt.max_sent_l_targ = valid_data.target:size(2)
opt.max_sent_l = math.max(opt.max_sent_l_src, opt.max_sent_l_targ)
if opt.max_batch_l == '' then
opt.max_batch_l = valid_data.batch_l:max()
end
print(string.format('Source max sent len: %d, Target max sent len: %d',
valid_data.source:size(2), valid_data.target:size(2)))
-- Build model
word_vecs_enc1 = nn.LookupTable(valid_data.source_size, opt.word_vec_size)
word_vecs_enc2 = nn.LookupTable(valid_data.target_size, opt.word_vec_size)
if opt.attn ~= 'none' then
parser_fwd = make_lstm(valid_data, opt.rnn_size_parser, opt.word_vec_size,
opt.num_layers_parser, opt, 'enc')
parser_bwd = make_lstm(valid_data, opt.rnn_size_parser, opt.word_vec_size,
opt.num_layers_parser, opt, 'enc')
parser_graph1 = make_parser(opt.rnn_size_parser*2)
parser_graph2 = make_parser(opt.rnn_size_parser*2)
sent_encoder = make_sent_encoder(opt.word_vec_size, opt.hidden_size,
valid_data.label_size, opt.dropout)
else
sent_encoder = make_sent_encoder(opt.word_vec_size, opt.hidden_size,
valid_data.label_size, opt.dropout)
end
disc_criterion = nn.ClassNLLCriterion()
disc_criterion.sizeAverage = false
if opt.attn ~= 'none' then
layers = {word_vecs_enc1, word_vecs_enc2, sent_encoder,
parser_fwd, parser_bwd,
parser_graph1, parser_graph2}
else
layers = {word_vecs_enc1, word_vecs_enc2, sent_encoder}
end
layer_etas = {}
optStates = {}
for i = 1, #layers do
layer_etas[i] = opt.learning_rate -- can have layer-specific lr, if desired
optStates[i] = {}
end
if opt.gpuid >= 0 then
for i = 1, #layers do
layers[i]:cuda()
end
disc_criterion:cuda()
end
-- these layers will be manipulated during training
if opt.attn ~= 'none' then
parser_layers1 = {}
parser_layers2 = {}
parser_graph1:apply(get_parser_layer1)
parser_graph2:apply(get_parser_layer2)
end
entail_layers = {}
sent_encoder:apply(get_entail_layer)
if opt.attn ~= 'none' then
if opt.cuda_mod == 1 then
require 'cuda-mod'
parser_layers1.dep_parser.cuda_mod = 1
parser_layers2.dep_parser.cuda_mod = 1
else
if opt.attn == 'struct' then
parser_layers1.dep_parser:double()
parser_layers2.dep_parser:double()
end
end
end
train(train_data, valid_data)
end
main()
|
LinkLuaModifier('modifier_is_in_offside', 'modifiers/modifier_offside.lua', LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier('modifier_offside', 'modifiers/modifier_offside.lua', LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier('modifier_onside_buff', 'modifiers/modifier_onside_buff.lua', LUA_MODIFIER_MOTION_NONE)
modifier_is_in_offside = class(ModifierBaseClass)
modifier_offside = class(ModifierBaseClass)
modifier_onside_buff = class(ModifierBaseClass)
local TICKS_PER_SECOND = 5
function modifier_is_in_offside:OnCreated()
if IsServer() then
local parent = self:GetParent()
if not parent:HasModifier("modifier_offside") then
parent:AddNewModifier(self:GetCaster(), nil, "modifier_offside", {})
end
end
end
function modifier_is_in_offside:IsHidden()
return true
end
function modifier_is_in_offside:IsPurgable()
return false
end
modifier_is_in_offside.OnRefresh = modifier_is_in_offside.OnCreated
--------------------------------------------------------------------
function modifier_offside:OnCreated()
if IsServer() then
self:SetStackCount(0)
self:StartIntervalThink(1 / TICKS_PER_SECOND)
end
end
modifier_offside.OnRefresh = modifier_offside.OnCreated
function modifier_offside:IsPurgable()
return false
end
--------------------------------------------------------------------
--aura
function modifier_offside:IsAura()
return true
end
function modifier_offside:GetAuraSearchType()
return DOTA_UNIT_TARGET_HERO
end
function modifier_offside:GetAuraSearchTeam()
return DOTA_UNIT_TARGET_TEAM_ENEMY
end
function modifier_offside:GetAuraRadius()
return 2500
end
function modifier_offside:GetModifierAura()
return "modifier_onside_buff"
end
--------------------------------------------------------------------
--% health damage
function modifier_offside:GetTexture()
return "custom/modifier_offside"
end
function modifier_offside:IsDebuff()
return true
end
function modifier_offside:ReleaseParticles()
if self.stackParticle ~= nil then
ParticleManager:DestroyParticle(self.stackParticle, false)
ParticleManager:ReleaseParticleIndex( self.stackParticle )
end
if self.BloodOverlay ~= nil then
ParticleManager:SetParticleControl( self.BloodOverlay, 1, Vector( 0, 0, 0 ) )
ParticleManager:DestroyParticle(self.BloodOverlay, false)
ParticleManager:ReleaseParticleIndex( self.BloodOverlay )
end
end
function modifier_offside:DrawParticles()
-- avoid firing new particle every tick
if self.stackOffset == 0 then
local stackCount = self:GetStackCount()
local isInOffside = self:GetParent():HasModifier("modifier_is_in_offside")
local alpha = (stackCount -10) * 255/15
if alpha >= 0 and isInOffside then
if self.BloodOverlay == nil then
-- Creates a new particle effect
self.BloodOverlay = ParticleManager:CreateParticleForPlayer( "particles/misc/screen_blood_overlay.vpcf", PATTACH_WORLDORIGIN, self:GetParent(), self:GetParent():GetPlayerOwner() )
ParticleManager:SetParticleControl( self.BloodOverlay, 1, Vector( alpha, 0, 0 ) )
print("Create Blood Overlay Alpha =" ..alpha)
end
ParticleManager:SetParticleControl( self.BloodOverlay, 1, Vector( alpha, 0, 0 ) )
elseif self.BloodOverlay ~= nil and not isInOffside then
ParticleManager:SetParticleControl( self.BloodOverlay, 1, Vector( 0, 0, 0 ) )
end
if self.stackParticle ~= nil then
ParticleManager:DestroyParticle(self.stackParticle, false)
end
self.stackParticle = ParticleManager:CreateParticleForPlayer( "particles/dungeon_overhead_timer_colored.vpcf", PATTACH_OVERHEAD_FOLLOW, self:GetParent(), self:GetParent():GetPlayerOwner() )
ParticleManager:SetParticleControl( self.stackParticle, 1, Vector( 0, stackCount, 0 ) )
ParticleManager:SetParticleControl( self.stackParticle, 2, Vector( 2, 0, 0 ) )
ParticleManager:SetParticleControl( self.stackParticle, 3, Vector( 255, 50, 0 ) )
ParticleManager:ReleaseParticleIndex( self.stackParticle )
end
end
function modifier_offside:OnIntervalThink()
if not ProtectionAura then
self:ReleaseParticles()
self:Destroy()
return
end
local isInOffside = self:GetParent():HasModifier("modifier_is_in_offside")
if not self.stackOffset then
self.stackOffset = 1
else
self.stackOffset = self.stackOffset + 1
end
if self.stackOffset >= TICKS_PER_SECOND then
if isInOffside then
self:IncrementStackCount()
else
self:DecrementStackCount()
end
self.stackOffset = 0
end
local playerHero = self:GetCaster()
local h = self:GetParent():GetMaxHealth()
local stackCount = self:GetStackCount()
self:DrawParticles()
if not isInOffside then
if stackCount <= 0 then
self:ReleaseParticles()
self:Destroy()
end
return
end
local location = self:GetParent():GetAbsOrigin()
local team = self:GetParent():GetTeamNumber()
local defenders = FindUnitsInRadius(
team,
location,
nil,
2000,
DOTA_UNIT_TARGET_TEAM_ENEMY,
DOTA_UNIT_TARGET_HERO,
DOTA_UNIT_TARGET_FLAG_NONE,
FIND_ANY_ORDER,
false) or nil
if #defenders == 0 then
defenders = nil
end
if defenders then
defenders = defenders[1]
else
defenders = Entities:FindByClassnameNearest("ent_dota_fountain", location, 10000)
end
local damageTable = {
victim = self:GetParent(),
attacker = defenders,
damage = (h * ((0.15 * ((stackCount - 10)^2 + 10 * (stackCount - 10)))/100)) / TICKS_PER_SECOND,
damage_type = DAMAGE_TYPE_PURE,
damage_flags = DOTA_DAMAGE_FLAG_HPLOSS + DOTA_DAMAGE_FLAG_NO_DAMAGE_MULTIPLIERS + DOTA_DAMAGE_FLAG_REFLECTION,
ability = nil
}
if stackCount >= 10 then
return ApplyDamage(damageTable)
end
end
|
local process = require("process")
--Initialize coroutine library--
local _coroutine = coroutine -- real coroutine backend
_G.coroutine = {}
package.loaded.coroutine = _G.coroutine
for key,value in pairs(_coroutine) do
if type(value) == "function" and value ~= "running" and value ~= "create" then
_G.coroutine[key] = function(...)
local thread = _coroutine.running()
local info = process.info(thread)
-- note the gc thread does not have a process info
assert(info,"process not found for " .. tostring(thread))
local data = info.data
local co = data.coroutine_handler
local handler = co[key]
return handler(...)
end
else
_G.coroutine[key] = value
end
end
local kernel_create = _coroutine.create
local function install(path, name)
_coroutine.create = function(f,standAlone)
local co = kernel_create(f)
if not standAlone then
table.insert(process.findProcess().instances, co)
end
return co
end
local load = load
_G.load = function(ld, source, mode, env)
env = env or select(2, process.running())
return load(ld, source, mode, env)
end
local thread = _coroutine.running()
process.list[thread] = {
path = path,
command = name,
env = _ENV,
data =
{
vars={},
io={}, --init will populate this
coroutine_handler=setmetatable({}, {__index=_coroutine})
},
instances = setmetatable({}, {__mode="v"})
}
end
install("/init.lua", "init")
|
local M = {}
local fn = vim.fn
local api = vim.api
local utils = require('hlslens.utils')
local win_mids = {}
function M.add_hl(winid, start_p, end_p, higroup)
winid = winid == 0 and api.nvim_get_current_win() or winid
M.clear_hl()
local s_lnum, s_col = unpack(start_p)
local e_lnum, e_col = unpack(end_p)
local pos
if e_lnum == s_lnum then
pos = {{s_lnum, s_col, e_col - s_col + 1}}
else
pos = {{s_lnum, s_col, vim.o.co}}
for i = 1, e_lnum - s_lnum - 1 do
table.insert(pos, {s_lnum + i})
end
table.insert(pos, {e_lnum, 1, e_col})
end
local matchids = utils.matchaddpos(higroup, pos, 1, winid)
win_mids = {winid, matchids}
return matchids
end
function M.clear_hl()
local winid, matchids = unpack(win_mids)
if matchids then
if api.nvim_win_is_valid(winid) then
for _, id in ipairs(matchids) do
pcall(fn.matchdelete, id, winid)
end
end
win_mids = {}
end
end
return M
|
vim.g.nvim_tree_icons = {
default = "",
symlink = "",
git = {
unstaged = "",
staged = "",
unmerged = "",
renamed = "",
untracked = "",
deleted = "",
ignored = "",
},
}
vim.g.nvim_tree_ignore = {
".git",
".cache",
".node_modules",
}
vim.g.nvim_tree_root_folder_modifier = ":t"
vim.g.nvim_tree_git_hl = 1
require("nvim-tree").setup {
diagnostics = { enable = true }, -- show lsp diagnostics in the signcolumn
view = {
width = 35,
side = "left",
hide_root_folder = true,
},
hijack_cursor = true,
}
utils.nnoremap("<C-n>", "<CMD>NvimTreeToggle<CR>")
|
local n1 = { name = "default:ice" }
local n2 = { name = "stairs:slab_snowblock", param2 = 2 }
local n3 = { name = "air" }
local n4 = { name = "stairs:stair_outer_snowblock", param2 = 1 }
local n5 = { name = "stairs:stair_outer_snowblock" }
local n6 = { name = "stairs:stair_inner_straw", param2 = 3 }
local n7 = { name = "stairs:stair_straw", param2 = 2 }
local n8 = { name = "stairs:slab_straw", param2 = 2 }
local n9 = { name = "stairs:stair_inner_straw", param2 = 2 }
local n10 = { name = "stairs:stair_inner_snowblock", param2 = 1 }
local n11 = { name = "default:snowblock" }
local n12 = { name = "stairs:stair_inner_snowblock" }
local n13 = { name = "stairs:slab_snowblock", param2 = 20 }
local n14 = { name = "stairs:stair_straw", param2 = 3 }
local n15 = { name = "stairs:slab_straw", param2 = 1 }
local n16 = { name = "default:chest", param2 = 1 }
local n17 = { name = "stairs:stair_snowblock", param2 = 21 }
local n18 = { name = "stairs:stair_snowblock", param2 = 23 }
local n19 = { name = "stairs:stair_snowblock", param2 = 1 }
local n20 = { name = "stairs:stair_snowblock", param2 = 3 }
local n21 = { name = "stairs:slab_snowblock" }
local n22 = { name = "stairs:slab_straw" }
local n23 = { name = "default:torch", param2 = 1 }
local n24 = { name = "beds:bed_bottom" }
local n25 = { name = "stairs:stair_straw", param2 = 1 }
local n26 = { name = "stairs:slab_snowblock", param2 = 22 }
local n27 = { name = "beds:bed_bottom", param2 = 1 }
local n28 = { name = "beds:bed_top", param2 = 1 }
local n29 = { name = "beds:bed_top" }
local n30 = { name = "stairs:stair_outer_snowblock", param2 = 2 }
local n31 = { name = "stairs:stair_outer_snowblock", param2 = 3 }
local n32 = { name = "stairs:stair_inner_straw" }
local n33 = { name = "stairs:stair_straw" }
local n34 = { name = "stairs:stair_inner_straw", param2 = 1 }
local n35 = { name = "stairs:stair_inner_snowblock", param2 = 2 }
local n36 = { name = "stairs:stair_snowblock", param2 = 20 }
local n37 = { name = "stairs:stair_inner_snowblock", param2 = 3 }
local n38 = { name = "stairs:stair_snowblock", param2 = 2 }
return {
yslice_prob = {
},
size = {
y = 4,
x = 7,
z = 7
}
,
data = {
-- z=-6, y=-3
n1, n1, n1, n2, n1, n1, n1,
-- z=-6, y=-2
n3, n3, n4, n3, n5, n3, n3,
-- z=-6, y=-1
n3, n3, n3, n3, n3, n3, n3,
-- z=-6, y=0
n3, n3, n3, n3, n3, n3, n3,
-- z=-5, y=-3
n1, n6, n7, n8, n7, n9, n1,
-- z=-5, y=-2
n3, n10, n11, n3, n11, n12, n3,
-- z=-5, y=-1
n3, n3, n10, n13, n12, n3, n3,
-- z=-5, y=0
n3, n3, n3, n3, n3, n3, n3,
-- z=-4, y=-3
n1, n14, n8, n8, n15, n16, n1,
-- z=-4, y=-2
n4, n17, n3, n3, n3, n18, n5,
-- z=-4, y=-1
n3, n19, n3, n3, n3, n20, n3,
-- z=-4, y=0
n3, n3, n21, n21, n21, n3, n3,
-- z=-3, y=-3
n1, n14, n22, n23, n24, n25, n1,
-- z=-3, y=-2
n19, n17, n3, n3, n3, n18, n20,
-- z=-3, y=-1
n3, n19, n3, n3, n3, n20, n3,
-- z=-3, y=0
n3, n3, n21, n26, n21, n3, n3,
-- z=-2, y=-3
n1, n14, n27, n28, n29, n25, n1,
-- z=-2, y=-2
n30, n17, n3, n3, n3, n18, n31,
-- z=-2, y=-1
n3, n19, n3, n3, n3, n20, n3,
-- z=-2, y=0
n3, n3, n21, n21, n21, n3, n3,
-- z=-1, y=-3
n1, n32, n33, n33, n33, n34, n1,
-- z=-1, y=-2
n3, n35, n36, n36, n36, n37, n3,
-- z=-1, y=-1
n3, n3, n38, n38, n38, n3, n3,
-- z=-1, y=0
n3, n3, n3, n3, n3, n3, n3,
-- z=0, y=-3
n1, n1, n1, n1, n1, n1, n1,
-- z=0, y=-2
n3, n3, n30, n38, n31, n3, n3,
-- z=0, y=-1
n3, n3, n3, n3, n3, n3, n3,
-- z=0, y=0
n3, n3, n3, n3, n3, n3, n3,
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.