content
stringlengths 5
1.05M
|
|---|
local x = 100000000
local k = 1
--local o = function (a) k = k + a end
while (k < x) do
-- o(1)
k = k + 1
end
print(tostring(os.clock()* 1000) .. " ms")
|
local PlayerLightningTarget = Class(function(self, inst)
self.inst = inst
end)
function PlayerLightningTarget:CanBeHit()
for k,v in pairs (self.inst.components.inventory.equipslots) do
if v.components.dapperness and v.components.dapperness.mitigates_rain then
return false
end
end
return true
end
return PlayerLightningTarget
|
local kernel = {}
kernel.language = "glsl"
kernel.category = "filter"
kernel.name = "sharpenLuminance"
kernel.vertexData =
{
{
name = "sharpness",
default = 0,
min = 0,
max = 1,
index = 0, -- v_UserData.x
},
}
kernel.fragment =
[[
P_COLOR vec4 FragmentKernel( P_UV vec2 texCoord )
{
P_COLOR float unit_sharpness = v_UserData.x;
P_COLOR float sharpness_factor = ( 10.0 + ( 40.0 * unit_sharpness ) );
P_COLOR vec4 color = texture2D( u_FillSampler0, texCoord );
P_COLOR float original_alpha = color.a;
color -= texture2D( u_FillSampler0, texCoord + 0.0001 ) * sharpness_factor;
color += texture2D( u_FillSampler0, texCoord - 0.0001 ) * sharpness_factor;
color.a = original_alpha;
return color;
}
]]
return kernel
|
--保留关键定: id(默认,可以通过加载文件时传入,空格分格多个关键字), is_array, _data
--数组用 id 可以转为数值则为索引, 如果有重复的child.tag 则自动转为数组
--如果有 is_array 字段则属性数据为数组,顺序重左到右为1.2.3.4... 否则就是一个table, 属性值为键值
--is_array 必须放在tag 后的第一们位置
--<test>xxx</test> xxx的值用test._data 来取,如果xxx是数字则自动转为数值,
--自动把可以转为数值的值转为数值,如果不想转则用str_ 开头
local lom = require("lom")
local xmlFileName = ""
local function parse_field(k, v)
if 1 == string.find(k, "str_", 1) then
return string.sub(k, 5), v
end
return k, tonumber(v) or v
end
local function parse_node(tree, key_world)
--print("tree.tag", TablePrint(tree))
--
local tag_list = {}
local tag_array = {}
local tag_table = {}
for _, node in pairs(tree) do
if node.tag ~= nil then
--print("node.tag", node.tag)
local k, v, a_id = parse_node(node, key_world)
if a_id ~= nil then
if tag_table[k] == nil then
tag_table[k] = {}
end
if tag_table[k][a_id] ~= nil then
print("error double attr _id:", xmlFileName, k, a_id)
end
tag_table[k][a_id] = v
else
if tag_list[k] ~= nil then
if tag_array[k] == nil then
tag_array[k] = {}
table.insert(tag_array[k], tag_list[k])
end
table.insert(tag_array[k], v)
end
tag_list[k] = v
end
end
end
--
local tag = {}
local is_array = tree.attr["is_array"] ~= nil
local array_id = nil
if key_world then
local key = tree.attr[1]
array_id = key_world[key] and tonumber(tree.attr[key]) or nil
else
array_id = tonumber(tree.attr["id"])
end
if is_array then
if "is_array" ~= tree.attr[1] then
print("error is_array must is first position")
else
-- attr
for k, v in ipairs(tree.attr) do
--print("attr", type(k), count, k, v, tree.attr[v])
if type(k) == "number" and k > 1 then
local r1, r2 = parse_field(v, tree.attr[v])
tag[k-1] = r2
end
end
end
else
for k, v in pairs(tree.attr) do
--print("attr", type(k), count, k, v, tree.attr[v])
if type(k) == "string" then
if "is_array" ~= k then
local r1, r2 = parse_field(k, v)
tag[r1] = r2
end
end
end
end
--<>data 的内容<>
if tree[1] ~= nil and next(tag_array) == nil and next(tag_table) == nil then
--print("_data", type(tree[1]), tree[1], print(engine.json.encode(tree[1])))
local r1, r2 = parse_field("", tree[1])
tag._data = r2
end
for k, v in pairs(tag_list) do
if tag[k] ~= nil then
print("error double attr list:", k)
else
tag[k] = v
end
end
for k, v in pairs(tag_array) do
tag[k] = v
end
for k, v in pairs(tag_table) do
if tag[k] == nil then
tag[k] = {}
else
print("error double attr list:", k)
end
for a_id, entry in pairs(v) do
tag[k][a_id] = entry
end
end
return tree.tag, tag, array_id
end
-- XML数据结构解析
local function handleXmlTree(xml_tree, key_world)
if not xml_tree then
debug_print("handleXmlTree tree is nil return")
return
end
local k, v, a_id = parse_node(xml_tree, key_world)
return v
end
local tbl = {}
-- 从XML文件中读取数据
function tbl.handleXmlFile(str_file, key_world)
xmlFileName = str_file
if key_world ~= nil then
t = {}
for w in string.gmatch(key_world,"%a+") do
t[w] = 1
end
key_world = t
--tbl.tablePrint(t)
end
local file_handle = io.open(str_file)
if not file_handle then
print("error no xml file:", str_file)
return
end
local file_data = file_handle:read("*a")
file_handle:close()
local xml_tree,err = lom.parse(file_data)
if err then
print("error format xml:", str_file)
return
end
return handleXmlTree(xml_tree, key_world)
end
function tbl.tablePrint(value,fmt,tabnum)
local num = tabnum or 1
local fmt = fmt or '\t'
if type(value) =="table" then
local left = fmt .. '{'
local right = fmt .. '}' ..','
local newfmt = fmt .. '\t'
if num<= 1 then
left = '{'
right = '}'
newfmt = fmt
end
print (left)
for k,v in pairs(value) do
if type(v) == "table" then
print(newfmt..k.. " = ")
tbl.tablePrint(v,newfmt,num+1)
else
if type(k) == "string" then
print(newfmt..'"'..k..'"'.." = " .. v .. ',')
else
print(newfmt..k.." = " .. v .. ',')
end
end
end
print(right)
end
end
return tbl
--使用测试例子
--local config = handleXmlFile("../config/xml/faction/sample1.xml")
--local config = handleXmlFile("../config/xml/faction/sample2.xml")
--local config = handleXmlFile("../config/xml/faction/sample3.xml")
--print(engine.json.encode(config))
--print(TablePrint(config))
|
local collider = {}
local mtl1 = {
with = function(self, w)
self.collides_with[w] = true
return({
f = self.collides_with,
w = w,
does = function(self, func)
self.f[w] = func
end
}
)
end
}
mtl1.__index = mtl1
function collider:give()
return setmetatable(
{
cells = {},
dynamic = true,
collides_with = {}
}
, mtl1)
end
local box = {}
box.collides = collider.give()
box.collides
:with("box")
:does(function()
print("The box hit another box")
end
)
box.collides.collides_with["box"]()
|
---
-- The Store provides storage for all of the configuration settings pushed in by the
-- user scripts, and methods to query those settings for use by the actions and
-- exporters.
---
local Block = require('block')
local Condition = require('condition')
local Stack = require('stack')
local Type = require('type')
local Store = Type.declare('Store')
---
-- Blocks are categorized by their operation, one of ADD or REMOVE, indicating
-- whether they are adding values to the state (e.g. `defines('a')`) or removing
-- from it (`removeDefines('a')`).
---
local function _getBlockFor(self, operation)
local block = self._currentBlock
if block == nil or block.operation ~= operation then
local condition = Stack.top(self._conditions)
block = Block.new(operation, condition)
table.insert(self._blocks, block)
self._currentBlock = block
end
return block
end
---
-- Construct a new Store.
--
-- @return
-- A new Store instance.
---
function Store.new()
-- if new fields are added here, update `snapshot()` and `restore()` too
return Type.assign(Store, {
_conditions = Stack.new({ Condition.new(_EMPTY) }),
_blocks = {},
_currentBlock = nil
})
end
---
-- Return the list of configuration blocks contained by the store.
---
function Store.blocks(self)
return self._blocks
end
---
-- Print the current contents of the store.
---
function Store.debug(self)
print(table.toString(self._blocks))
end
---
-- Pushes a new configuration condition onto the condition stack.
--
-- @param clauses
-- A collection of key-value pairs of conditional clauses,
-- ex. `{ workspaces='Workspace1', configurations='Debug' }`
---
function Store.pushCondition(self, clauses)
local conditions = self._conditions
local condition = Condition.new(clauses)
local outerCondition = Stack.top(conditions)
if outerCondition ~= nil then
condition = Condition.merge(outerCondition, condition)
end
Stack.push(conditions, condition)
self._currentBlock = nil
return self
end
---
-- Pops a configuration condition from the top of the condition stack.
---
function Store.popCondition(self)
Stack.pop(self._conditions)
self._currentBlock = nil
return self
end
---
-- Adds a value or values to the current configuration.
---
function Store.addValue(self, field, value)
local block = _getBlockFor(self, Block.ADD)
Block.receive(block, field, value)
return self
end
---
-- Flags one or more values for removal from the current configuration.
---
function Store.removeValue(self, field, value)
local block = _getBlockFor(self, Block.REMOVE)
Block.receive(block, field, value)
return self
end
---
-- Make a note of the current store state, so it can be rolled back later.
---
function Store.snapshot(self)
local snapshot = {
_conditions = self._conditions,
_blocks = self._blocks
}
self._conditions = table.shallowCopy(self._conditions)
self._blocks = table.shallowCopy(self._blocks)
Store.pushCondition(self, _EMPTY)
return snapshot
end
---
-- Roll back the store state to a previous snapshot.
---
function Store.rollback(self, snapshot)
self._conditions = table.shallowCopy(snapshot._conditions)
self._blocks = table.shallowCopy(snapshot._blocks)
end
return Store
|
--[[
Sets options panel
--]]
local ADDON, Addon = ...
local Panel = Addon:NewPanel('Sets')
local L = LibStub('AceLocale-3.0'):GetLocale('Combuctor')
local Sets = Combuctor('Sets')
local selected, items = {}, {}
local frame
local MAX_ITEMS = 14
local HEIGHT = 26
local sendMessage = function(msg, ...)
Sets:Send(msg, Addon.frame, ...)
end
local getInfo = function()
return Combuctor:GetProfile()[Addon.frame]
end
local function AddSet(name)
local info = getInfo()
local sets = info.sets
for i, set in pairs(sets) do
if set.name == name then
return
end
end
tinsert(sets, name)
sendMessage('COMBUCTOR_CONFIG_SET_ADD', name)
end
local function RemoveSet(name)
local info = getInfo()
local sets = info.sets
for i,set in pairs(sets) do
if set == name then
tremove(sets, i)
sendMessage('COMBUCTOR_CONFIG_SET_REMOVE', name)
break
end
end
end
local function AddSubSet(name, parent)
local info = getInfo()
local exclude = info.exclude[parent]
if exclude then
for i,set in pairs(exclude) do
if set == name then
tremove(exclude, i)
if #exclude < 1 then
info.exclude[parent] = nil
end
sendMessage('COMBUCTOR_CONFIG_SUBSET_ADD', name, parent)
break
end
end
end
end
local function RemoveSubSet(name, parent)
local info = getInfo()
local exclude = info.exclude[parent]
if exclude then
for i,set in pairs(exclude) do
if set == name then
return
end
end
tinsert(exclude, name)
else
info.exclude[parent] = {name}
end
sendMessage('COMBUCTOR_CONFIG_SUBSET_REMOVE', name, parent)
end
local function HasSet(name)
local info = getInfo()
for i,setName in pairs(info.sets) do
if setName == name then
return true
end
end
return false
end
local function HasSubSet(name, parent)
local info = getInfo()
local exclude = info.exclude[parent]
if exclude then
for j,child in pairs(exclude) do
if child == name then
return false
end
end
end
return true
end
--list button
local function ListButtonCheck_OnClick(self)
local set = self:GetParent().set
if set.parent then
if self:GetChecked() then
AddSubSet(set.name, set.parent)
else
RemoveSubSet(set.name, set.parent)
end
else
if self:GetChecked() then
AddSet(set.name)
else
RemoveSet(set.name)
end
end
end
local function ListButtonToggle_OnClick(self)
local set = self:GetParent().set
selected[set.name] = not selected[set.name]
self:GetParent():GetParent():UpdateList()
end
local function ListButton_Set(self, set)
self.set = set
if set.icon then
_G[self.check:GetName() .. 'Text']:SetFormattedText('|T%s:%d|t %s', set.icon, 26, set.name)
else
_G[self.check:GetName() .. 'Text']:SetText(set.name)
end
if set.parent then
self.toggle:Hide()
else
self.toggle:Show()
if selected[set.name] then
self.toggle:SetNormalTexture('Interface\\Buttons\\UI-MinusButton-UP')
self.toggle:SetPushedTexture('Interface\\Buttons\\UI-MinusButton-DOWN')
else
self.toggle:SetNormalTexture('Interface\\Buttons\\UI-PlusButton-UP')
self.toggle:SetPushedTexture('Interface\\Buttons\\UI-PlusButton-DOWN')
end
end
if set.parent then
self.check:SetChecked(HasSubSet(set.name, set.parent))
else
self.check:SetChecked(HasSet(set.name))
end
end
local function ListButton_Create(id, parent)
local name = format('%sButton%d', parent:GetName(), id)
local b = CreateFrame('Frame', name, parent)
b:SetWidth(200)
b:SetHeight(24)
b.Set = ListButton_Set
local toggle = CreateFrame('Button', nil, b)
toggle:SetPoint('LEFT', b)
toggle:SetWidth(14)
toggle:SetHeight(14)
toggle:SetNormalTexture('Interface\\Buttons\\UI-PlusButton-UP')
toggle:SetPushedTexture('Interface\\Buttons\\UI-PlusButton-DOWN')
toggle:SetHighlightTexture('Interface\\Buttons\\UI-PlusButton-Hilight')
toggle:SetScript('OnClick', ListButtonToggle_OnClick)
b.toggle = toggle
local check = CreateFrame('CheckButton', name .. 'Check', b, 'InterfaceOptionsCheckButtonTemplate')
check:SetScript('OnClick', ListButtonCheck_OnClick)
check:SetPoint('LEFT', toggle, 'RIGHT', 4, 0)
b.check = check
return b
end
--[[ Panel Functions ]]--
local function Panel_UpdateList(self)
local items = {}
for _,parentSet in Sets:GetParentSets() do
tinsert(items, parentSet)
if selected[parentSet.name] then
for _,childSet in Sets:GetChildSets(parentSet.name) do
tinsert(items, childSet)
end
end
end
local scrollFrame = self.scrollFrame
local offset = FauxScrollFrame_GetOffset(scrollFrame)
local i = 1
while i <= MAX_ITEMS and items[i + offset] do
local button = self.buttons[i]
button:Set(items[i + offset])
local offLeft = button.set.parent and 24 or 0
button:SetPoint('TOPLEFT', 14 + offLeft, -(100 + 30 * i))
button:Show()
i = i + 1
end
for j = i, #self.buttons do
self.buttons[j]:Hide()
end
FauxScrollFrame_Update(scrollFrame, #items, MAX_ITEMS, self.buttons[1]:GetHeight())
end
do
Panel.UpdateList = Panel_UpdateList
Panel.OnFrameChanged = Panel_UpdateList
Panel:SetScript('OnHide', function(self) selected = {} end)
local scroll = CreateFrame('ScrollFrame', '$parentScrollFrame', Panel, 'FauxScrollFrameTemplate')
scroll:SetPoint('TOPLEFT', 6, -120)
scroll:SetPoint('BOTTOMRIGHT', -32, 8)
scroll:SetScript('OnVerticalScroll', function(self, arg1)
FauxScrollFrame_OnVerticalScroll(self, arg1, HEIGHT, function()
Panel:UpdateList()
end)
end)
local bg = scroll.ScrollBar:CreateTexture()
bg:SetTexture(0, 0, 0, .3)
bg:SetAllPoints()
Panel.scrollFrame = scroll
Panel.buttons = setmetatable({}, {__index = function(t, k)
t[k] = ListButton_Create(k, Panel)
return t[k]
end})
end
|
local ObjectManager = require("managers.object.object_manager")
local QuestManager = require("managers.quest.quest_manager")
require("utils.helpers")
FsCrafting4Theater = GoToTheater:new {
-- Task properties
taskName = "FsCrafting4Theater",
-- GoToTheater properties
minimumDistance = 60,
maximumDistance = 100,
theater = {
{ template = "object/tangible/item/quest/force_sensitive/fs_crafting4_downed_satellite.iff", xDiff = 0, zDiff = 1, yDiff = 0, heading = 0 },
},
waypointDescription = "Downed Satellite",
mobileList = {},
activeAreaRadius = 32
}
return FsCrafting4Theater
|
local _G = _G
local tinsert = tinsert
local wipe = wipe
local gsub = gsub
local hooksecurefunc = hooksecurefunc
local GetNumQuestLogEntries = GetNumQuestLogEntries
local GetQuestLogTitle = GetQuestLogTitle
local IsQuestComplete = IsQuestComplete
local C_QuestLog = C_QuestLog
local MAX_NUM_QUESTS = MAX_NUM_QUESTS
local NUMGOSSIPBUTTONS = NUMGOSSIPBUTTONS
local QuestFrameGreetingPanel = QuestFrameGreetingPanel
local escapes = {
["|c%x%x%x%x%x%x%x%x"] = "", -- color start
["|r"] = "" -- color end
}
local function unescape(str)
for k, v in pairs(escapes) do
str = gsub(str, k, v)
end
return str
end
local completedActiveQuests = {}
local function getCompletedQuestsInLog()
wipe(completedActiveQuests)
local numEntries = GetNumQuestLogEntries()
local questLogTitleText, isComplete, questId, _
for i = 1, numEntries, 1 do
_, _, _, _, _, isComplete, _, questId = GetQuestLogTitle(i)
if (isComplete == 1 or IsQuestComplete(questId)) then
questLogTitleText = C_QuestLog.GetQuestInfo(questId)
completedActiveQuests[questLogTitleText] = true
end
end
return completedActiveQuests
end
local function setDesaturation(maxLines, lineMap, iconMap, activePred)
local completedQuests = getCompletedQuestsInLog()
for i = 1, maxLines do
local line = lineMap[i]
local icon = iconMap[i]
icon:SetDesaturated(nil)
if (line:IsVisible() and activePred(line)) then
local questName = unescape(line:GetText())
if (not completedQuests[questName]) then
icon:SetDesaturated(1)
end
end
end
end
local function getLineAndIconMaps(maxLines, titleIdent, iconIdent)
local lines = {}
local icons = {}
for i = 1, maxLines do
local titleLine = _G[titleIdent .. i]
tinsert(lines, titleLine)
tinsert(icons, _G[titleLine:GetName() .. iconIdent])
end
return lines, icons
end
local questFrameTitleLines, questFrameIconTextures = getLineAndIconMaps(MAX_NUM_QUESTS, "QuestTitleButton", "QuestIcon")
QuestFrameGreetingPanel:HookScript(
"OnShow",
function()
setDesaturation(
MAX_NUM_QUESTS,
questFrameTitleLines,
questFrameIconTextures,
function(line)
return line.isActive == 1
end
)
end
)
local gossipFrameTitleLines, gossipFrameIconTextures =
getLineAndIconMaps(NUMGOSSIPBUTTONS, "GossipTitleButton", "GossipIcon")
hooksecurefunc(
"GossipFrameUpdate",
function()
setDesaturation(
NUMGOSSIPBUTTONS,
gossipFrameTitleLines,
gossipFrameIconTextures,
function(line)
return line.type == "Active"
end
)
end
)
|
local a=module("_core","libs/Tunnel")local b=module("_core","libs/Proxy")emP=a.getInterface("hpp_trucker")local c=false;local d=0;local e=""local f=false;local g=nil;local h=1257.29;local i=-3180.40;local j=5.80;local k=0.0;local l=0.0;local m=0.0;local n=nil;Citizen.CreateThread(function()while true do Citizen.Wait(5*60*1000)collectgarbage("count")collectgarbage("collect")end end)local o={[1]={['x']=43.06,['y']=2803.80,['z']=57.87},[2]={['x']=243.15,['y']=2602.41,['z']=45.11},[3]={['x']=1059.15,['y']=2660.69,['z']=39.55},[4]={['x']=1990.22,['y']=3763.54,['z']=32.18},[5]={['x']=81.23,['y']=6334.27,['z']=31.22},[6]={['x']=2770.81,['y']=1439.26,['z']=24.51}}local p={[1]={['x']=-2530.05,['y']=2325.91,['z']=33.05},[2]={['x']=-2082.05,['y']=-319.80,['z']=13.05},[3]={['x']=-1413.47,['y']=-279.95,['z']=46.33},[4]={['x']=280.64,['y']=-1259.95,['z']=29.21},[5]={['x']=1208.38,['y']=-1402.58,['z']=35.22},[6]={['x']=1181.46,['y']=-334.74,['z']=69.17},[7]={['x']=2567.72,['y']=362.65,['z']=108.45},[8]={['x']=183.97,['y']=-1554.69,['z']=29.20},[9]={['x']=-331.75,['y']=-1479.03,['z']=30.54},[10]={['x']=2534.50,['y']=2588.13,['z']=37.94},[11]={['x']=2684.40,['y']=3261.81,['z']=55.24},[12]={['x']=-1803.10,['y']=800.33,['z']=138.51}}local q={[1]={['x']=-774.19,['y']=-254.45,['z']=37.10},[2]={['x']=-231.64,['y']=-1170.94,['z']=22.83},[3]={['x']=925.59,['y']=-8.79,['z']=78.76},[4]={['x']=-506.18,['y']=-2191.37,['z']=6.53},[5]={['x']=1209.15,['y']=2712.03,['z']=38.00}}local r={[1]={['x']=-581.20,['y']=5317.28,['z']=70.24},[2]={['x']=2701.74,['y']=3450.62,['z']=55.79},[3]={['x']=1203.52,['y']=-1309.33,['z']=35.22},[4]={['x']=16.99,['y']=-386.11,['z']=39.32}}local s={[1]={['x']=1994.91,['y']=3061.17,['z']=47.04},[2]={['x']=-1397.32,['y']=-581.99,['z']=30.28},[3]={['x']=-552.43,['y']=303.34,['z']=83.21},[4]={['x']=-227.52,['y']=-2051.27,['z']=27.62}}RegisterCommand("pack",function(t,u)local v=PlayerPedId()local w,x,y=table.unpack(GetEntityCoords(v))local z,A=GetGroundZFor_3dCoord(h,i,j)local B=GetDistanceBetweenCoords(h,i,A,w,x,y,true)if B<=50.1 and not f then if u[1]=="diesel"then f=true;e=u[1]g=-1207431159;d=emP.getTruckpoint(e)k=o[d].x;l=o[d].y;m=o[d].z;CriandoBlip(k,l,m)TriggerEvent("Notify","importante","Entrega de <b>Diesel</b> iniciada, pegue o caminhão, a carga e vá até o destino marcado.")elseif u[1]=="gas"then f=true;e=u[1]g=1956216962;d=emP.getTruckpoint(e)k=p[d].x;l=p[d].y;m=p[d].z;CriandoBlip(k,l,m)TriggerEvent("Notify","importante","Entrega de <b>Combustível</b> iniciada, pegue o caminhão, a carga e vá até o destino marcado.")elseif u[1]=="cars"then f=true;e=u[1]g=2091594960;d=emP.getTruckpoint(e)k=q[d].x;l=q[d].y;m=q[d].z;CriandoBlip(k,l,m)TriggerEvent("Notify","importante","Entrega de <b>Veículos</b> iniciada, pegue o caminhão, a carga e vá até o destino marcado.")elseif u[1]=="woods"then f=true;e=u[1]g=2016027501;d=emP.getTruckpoint(e)k=r[d].x;l=r[d].y;m=r[d].z;CriandoBlip(k,l,m)TriggerEvent("Notify","importante","Entrega de <b>Madeiras</b> iniciada, pegue o caminhão, a carga e vá até o destino marcado.")elseif u[1]=="show"then f=true;e=u[1]g=-1770643266;d=emP.getTruckpoint(e)k=s[d].x;l=s[d].y;m=s[d].z;CriandoBlip(k,l,m)TriggerEvent("Notify","importante","Entrega de <b>Shows</b> iniciada, pegue o caminhão, a carga e vá até o destino marcado.")else TriggerEvent("Notify","aviso","<b>Disponíveis:</b> diesel, cars, show, woods e gas")end;vehicle=hpp_spawnCar(g,"CARGA000",1274.2974853516,-3225.990234375,5.9015898704529)if not IsEntityAVehicle(n)then n=hpp_spawnCar(569305213,"ALUGUEL",1273.658203125,-3201.7424316406,5.8973417282104)end end end)local C=3000;Citizen.CreateThread(function()while true do Citizen.Wait(C)if f then C=1;if IsControlJustPressed(0,168)then deleteVehicle(vehicle)RemoveBlip(c)f=false;deleteVehicle(n)end;local v=PlayerPedId()local w,x,y=table.unpack(GetEntityCoords(v))local z,A=GetGroundZFor_3dCoord(k,l,m)local B=GetDistanceBetweenCoords(k,l,A,w,x,y,true)if B<=100.0 then DrawMarker(23,k,l,m-0.96,0,0,0,0,0,0,10.0,10.0,1.0,0,95,140,50,0,0,0,0)if B<=5.9 then if IsControlJustPressed(0,38)then local vehicle=getVehicleInDirection(GetEntityCoords(PlayerPedId()),GetOffsetFromEntityInWorldCoords(PlayerPedId(),0.0,5.0,0.0))if GetEntityModel(vehicle)==g then local D=emP.checkPayment(d,e,parseInt(GetVehicleBodyHealth(GetPlayersLastVehicle())))TriggerEvent("Notify","sucesso","Você ganhou R$"..D)deleteVehicle(vehicle)RemoveBlip(c)f=false end end end end else C=3000 end end end)Citizen.CreateThread(function()local E=AddBlipForCoord(1257.201171875,-3173.8098144531,5.7997231483459)SetBlipSprite(E,477)SetBlipColour(E,4)SetBlipScale(E,0.5)SetBlipAsShortRange(E,false)SetBlipRoute(E,false)BeginTextCommandSetBlipName("STRING")AddTextComponentString("Central | Caminhoneiro")EndTextCommandSetBlipName(E)end)function getVehicleInDirection(F,G)local H=CastRayPointToPoint(F.x,F.y,F.z,G.x,G.y,G.z,10,PlayerPedId(),false)local I,J,K,L,vehicle=GetRaycastResult(H)return vehicle end;function hpp_spawnCar(vehicle,M,w,x,y,N,O)local P=vehicle;while not HasModelLoaded(P)do RequestModel(P)Citizen.Wait(1)end;if HasModelLoaded(P)then local Q=CreateVehicle(P,w,x,y+0.5,N,true,false)local R=VehToNet(Q)local S=NetworkGetNetworkIdFromEntity(Q)NetworkRegisterEntityAsNetworked(Q)while not NetworkGetEntityIsNetworked(Q)do NetworkRegisterEntityAsNetworked(Q)Citizen.Wait(1)end;if NetworkDoesNetworkIdExist(R)then SetEntitySomething(Q,true)if NetworkGetEntityIsNetworked(Q)then SetNetworkIdExistsOnAllMachines(R,true)end end;if O then setVehMods(O,NetToVeh(R))end;SetNetworkIdCanMigrate(S,true)SetVehicleNumberPlateText(NetToVeh(R),M)Citizen.InvokeNative(0xAD738C3085FE7E11,NetToVeh(R),true,true)SetVehicleHasBeenOwnedByPlayer(NetToVeh(R),true)SetVehicleNeedsToBeHotwired(NetToVeh(R),false)SetModelAsNoLongerNeeded(P)SetVehRadioStation(NetToVeh(R),"OFF")currentCar=Q;return Q end end;function deleteVehicle(vehicle)SetVehicleHasBeenOwnedByPlayer(vehicle,false)Citizen.InvokeNative(0xAD738C3085FE7E11,vehicle,true,true)SetVehicleAsNoLongerNeeded(Citizen.PointerValueIntInitialized(vehicle))DeleteVehicle(vehicle)end;function CriandoBlip(w,x,y)c=AddBlipForCoord(w,x,y)SetBlipSprite(c,1)SetBlipColour(c,5)SetBlipScale(c,0.4)SetBlipAsShortRange(c,false)SetBlipRoute(c,true)BeginTextCommandSetBlipName("STRING")AddTextComponentString("Entrega de Carga")EndTextCommandSetBlipName(c)end
|
local w, h = term.getSize()
term.clear()
term.setCursorPos(1, 1)
local t = { }
for i = 1, 8 do
table.insert(t, '---')
end
for i = 1, 255 do
table.insert(t, string.format('%d %c', i, i))
end
textutils.pagedTabulate(t)
|
local menu = require('projects/guessing game/modules/menu')
local plr = require('projects/guessing game/modules/player')
player = plr:new("Player", 0)
diff = 1
main = function()
os.execute("cls")
choice = 0
if menu.fileExists("projects/guessing game/data/config.cfg") == false then
local file = io.open("projects/guessing game/data/config.cfg", "w")
file:close()
end
repeat
choice = menu.showMainMenu()
os.execute("cls")
if choice == 1 then
menu.showDiffMenu()
elseif choice == 2 then
menu.showPlayerSelectMenu()
elseif choice == 3 then
menu.showPlayerCreateMenu()
elseif choice == 4 then
menu.showPlayers()
else
print("[ERROR]: You have input an invalid choice")
end
until choice == 5
os.execute("cls")
print("Game over!")
end
main()
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('BsePickGold_pb', package.seeall)
local BSEPICKGOLD = protobuf.Descriptor();
local BSEPICKGOLD_GOLD_FIELD = protobuf.FieldDescriptor();
BSEPICKGOLD_GOLD_FIELD.name = "gold"
BSEPICKGOLD_GOLD_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BsePickGold.gold"
BSEPICKGOLD_GOLD_FIELD.number = 1
BSEPICKGOLD_GOLD_FIELD.index = 0
BSEPICKGOLD_GOLD_FIELD.label = 2
BSEPICKGOLD_GOLD_FIELD.has_default_value = false
BSEPICKGOLD_GOLD_FIELD.default_value = 0
BSEPICKGOLD_GOLD_FIELD.type = 5
BSEPICKGOLD_GOLD_FIELD.cpp_type = 1
BSEPICKGOLD.name = "BsePickGold"
BSEPICKGOLD.full_name = ".com.xinqihd.sns.gameserver.proto.BsePickGold"
BSEPICKGOLD.nested_types = {}
BSEPICKGOLD.enum_types = {}
BSEPICKGOLD.fields = {BSEPICKGOLD_GOLD_FIELD}
BSEPICKGOLD.is_extendable = false
BSEPICKGOLD.extensions = {}
BsePickGold = protobuf.Message(BSEPICKGOLD)
_G.BSEPICKGOLD_PB_BSEPICKGOLD = BSEPICKGOLD
|
#!/usr/bin/env texlua
-- Generate the documentation with implementation.
local input_file_name = arg[1]
local output_file_name = arg[2]
local code_doc_str = "%<!--CODEDOC-->"
local code_doc_len = string.len(code_doc_str)
input_file = io.open(input_file_name, "r")
output_file = io.open(output_file_name, "w")
for line in input_file:lines() do
if string.sub(line, 1, code_doc_len) == code_doc_str then
output_file:write(string.sub(line, code_doc_len + 1), "\n")
else
output_file:write(line, "\n")
end
end
input_file:close()
output_file:close()
|
local _, ns = ...
local oUF = oUF or ns.oUF
if not oUF then
return
end
local playerClass = select(2,UnitClass("player"))
local CanDispel = {
PRIEST = { Magic = true, Disease = true },
SHAMAN = { Magic = false, Curse = true },
PALADIN = { Magic = false, Poison = true, Disease = true },
DRUID = { Magic = false, Curse = true, Poison = true, Disease = false },
MONK = { Magic = false, Poison = true, Disease = true },
MAGE = { Curse = true },
}
local blackList = {
[GetSpellInfo(140546)] = true, -- Fully Mutated
[GetSpellInfo(136184)] = true, -- Thick Bones
[GetSpellInfo(136186)] = true, -- Clear mind
[GetSpellInfo(136182)] = true, -- Improved Synapses
[GetSpellInfo(136180)] = true, -- Keen Eyesight
}
local dispellist = CanDispel[playerClass] or {}
local origColors = {}
local origBorderColors = {}
local origPostUpdateAura = {}
local function GetDebuffType(unit, filter, filterTable)
if not unit or not UnitCanAssist("player", unit) then
return nil
end
local i = 1
while true do
local name, texture, _, debufftype, _,_,_,_,_, spellID = UnitAura(unit, i, "HARMFUL")
if not texture then break end
local filterSpell = filterTable[spellID] or filterTable[name]
if (filterTable and filterSpell and filterSpell.enable) then
return debufftype, texture, true, filterSpell.style, filterSpell.color
elseif debufftype and (not filter or (filter and dispellist[debufftype])) and not blackList[name] then
return debufftype, texture
end
i = i + 1
end
end
local function CheckTalentTree(tree)
local activeGroup = GetActiveSpecGroup()
if activeGroup and GetSpecialization(false, false, activeGroup) then
return tree == GetSpecialization(false, false, activeGroup)
end
end
local function CheckSpec(_, event, levels)
if event == "CHARACTER_POINTS_CHANGED" and levels > 0 then
return
end
-- Check for certain talents to see if we can dispel magic or not
if playerClass == "PALADIN" then
if CheckTalentTree(1) then
dispellist.Magic = true
else
dispellist.Magic = false
end
elseif playerClass == "SHAMAN" then
if CheckTalentTree(3) then
dispellist.Magic = true
else
dispellist.Magic = false
end
elseif playerClass == "DRUID" then
if CheckTalentTree(4) then
dispellist.Magic = true
else
dispellist.Magic = false
end
elseif playerClass == "MONK" then
if CheckTalentTree(2) then
dispellist.Magic = true
else
dispellist.Magic = false
end
end
end
local function Update(object, _, unit)
if unit ~= object.unit then
return
end
local debuffType, texture, wasFiltered, style, color = GetDebuffType(unit, object.DebuffHighlightFilter, object.DebuffHighlightFilterTable)
if (wasFiltered) then
if object.DebuffHighlightBackdropBorder then
object:SetBackdropBorderColor(color.r, color.g, color.b, color.a or 1)
else
object.DebuffHighlight:SetVertexColor(color.r, color.g, color.b, color.a or object.DebuffHighlightAlpha or .5)
end
elseif debuffType then
color = DebuffTypeColor[debuffType]
if object.DebuffHighlightUseTexture then
object.DebuffHighlight:SetTexture(texture)
else
object.DebuffHighlight:SetVertexColor(color.r, color.g, color.b, object.DebuffHighlightAlpha or .5)
end
else
if object.DebuffHighlightUseTexture then
object.DebuffHighlight:SetTexture(nil)
else
object.DebuffHighlight:SetVertexColor(0, 0, 0, 0)
end
end
if object.DebuffHighlight.PostUpdate then
object.DebuffHighlight:PostUpdate(object, debuffType, texture, wasFiltered, style, color)
end
end
local function Enable(object)
-- if we're not highlighting this unit return
if not object.DebuffHighlightBackdropBorder and not object.DebuffHighlight then
return
end
-- if we're filtering highlights and we're not of the dispelling type, return
if object.DebuffHighlightFilter and not CanDispel[playerClass] then
return
end
object:RegisterEvent("UNIT_AURA", Update)
if object.DebuffHighlightBackdropBorder then
local r, g, b, a = object:GetBackdropBorderColor()
origBorderColors[object] = {r = r, g = g, b = b, a = a}
elseif not object.DebuffHighlightUseTexture then
local r, g, b, a = object.DebuffHighlight:GetVertexColor()
origColors[object] = {r = r, g = g, b = b, a = a}
end
return true
end
local function Disable(object)
object:UnregisterEvent("UNIT_AURA", Update)
if object.DebuffHighlightBackdropBorder then
local color = origColors[object]
if color then
object:SetBackdropBorderColor(color.r, color.g, color.b, color.a)
end
elseif not object.DebuffHighlightUseTexture then -- color debuffs
local color = origColors[object]
if color then
object.DebuffHighlight:SetVertexColor(color.r, color.g, color.b, color.a)
end
end
end
local EventFrame = CreateFrame("Frame")
EventFrame:RegisterEvent("PLAYER_TALENT_UPDATE")
EventFrame:RegisterEvent("CHARACTER_POINTS_CHANGED")
EventFrame:RegisterEvent("PLAYER_SPECIALIZATION_CHANGED")
EventFrame:SetScript("OnEvent", CheckSpec)
oUF:AddElement('DebuffHighlight', Update, Enable, Disable)
|
local copas = require("copas")
local http = require("copas.http")
local url = assert(arg[1], "missing url argument")
print("Testing copas.http.request with url " .. url)
local switches, max_switches = 0, 1000000
local done = false
copas.addthread(function()
while switches < max_switches do
copas.sleep(0)
switches = switches + 1
end
if not done then
print(("Error: Request not finished after %d thread switches"):format(switches))
os.exit(1)
end
end)
copas.addthread(function()
copas.sleep(0) -- delay, so won't start the test until the copasloop started
print("Starting request")
local content, code, headers, status = http.request(url)
print(("Finished request after %d thread switches"):format(switches))
if type(content) ~= "string" or type(code) ~= "number" or
type(headers) ~= "table" or type(status) ~= "string" then
print("Error: incorrect return values:")
print(content)
print(code)
print(headers)
print(status)
os.exit(1)
end
print(("Status: %s, content: %d bytes"):format(status, #content))
done = true
max_switches = switches + 10 -- just do a few more and finish the test
end)
print("Starting loop")
copas.loop()
if done then
print("Finished loop")
else
print("Error: Finished loop but request is not complete")
os.exit(1)
end
|
local ffi = require("ffi")
local Context = require("udev.context")
local Device = require("udev.device")
local libudev = require("udev.libudev")
local lib = libudev.lib
---@class UDevMonitor
---@field context UDevContext
---@field udev_monitor udev_monitor
local Monitor = {}
---@overload fun(self, from: "'netlink'", context?: UDevContext, source?: string): UDevMonitor|nil
---@param from "'netlink'"
---@param context? UDevContext
---@param name? "'kernel'"|"'udev'"
---@return UDevMonitor
function Monitor:new(from, context, name)
local monitor = setmetatable({}, { __index = self })
context = context or Context:new()
---@type udev_monitor
local udev_monitor
if from == "netlink" then
name = name or "udev"
udev_monitor = lib.udev_monitor_new_from_netlink(context.udev, name)
end
if udev_monitor == nil then
return nil, string.format("Error: failed to create udev monitor.")
end
monitor.context = context
monitor.udev_monitor = udev_monitor
ffi.gc(monitor.udev_monitor, lib.udev_monitor_unref)
return monitor
end
---@return number
function Monitor:enable_receiving()
return lib.udev_monitor_enable_receiving(self.udev_monitor)
end
---@param size number
---@return number
function Monitor:buffer_size(size)
return lib.udev_monitor_set_receive_buffer_size(self.udev_monitor, size)
end
---@return number
function Monitor:fd()
return lib.udev_monitor_get_fd(self.udev_monitor)
end
---@return UDevDevice|nil
function Monitor:receive_device()
local udev_device = lib.udev_monitor_receive_device(self.udev_monitor)
if udev_device == nil then
return
end
return Device:new("*", self.context, udev_device)
end
---@overload fun(self, filter_type: "'subsystem_devtype'", subsystem: string, devtype: string)
---@overload fun(self, filter_type: "'tag'", tag: string)
---@param filter_type "'subsystem_devtype'"|"'tag'"
---@return UDevEnumerator
function Monitor:filter_match(filter_type, ...)
local rc = 0
if filter_type == "subsystem_devtype" then
rc = lib.udev_monitor_filter_add_match_subsystem_devtype(self.udev_monitor, select(1, ...), select(2, ...))
elseif filter_type == "tag" then
rc = lib.udev_monitor_filter_add_match_tag(self.udev_monitor, select(1, ...))
end
if rc == 0 then
return self
end
return self, string.format("Error: failed to add monitor filter match %s", filter_type)
end
---@return number
function Monitor:filter_update()
return lib.udev_monitor_filter_update(self.udev_monitor)
end
---@return number
function Monitor:filter_remove()
return lib.udev_monitor_filter_remove(self.udev_monitor)
end
return Monitor
|
--------------------------------------------------------------------------------
-- Copyright (c) 2015 - 2016 , 蒙占志(topameng) topameng@gmail.com
-- All rights reserved.
-- Use, modification and distribution are subject to the "MIT License"
--------------------------------------------------------------------------------
-- added by wsh @ 2017-12-27
-- 注意:
-- 1、已经被修改,别从tolua轻易替换来做升级
local setmetatable = setmetatable
local xpcall = xpcall
local pcall = pcall
local assert = assert
local rawget = rawget
local error = error
local traceback = debug.traceback
local ilist = ilist
print("load event file!")
event_err_handle = function(msg)
error(msg, 2)
end
local _pcall = {
__call = function(self, ...)
local status, err
if not self.obj then
status, err = pcall(self.func, ...)
else
status, err = pcall(self.func, self.obj, ...)
end
if not status then
event_err_handle(err.."\n"..traceback())
end
return status
end,
__eq = function(lhs, rhs)
return lhs.func == rhs.func and lhs.obj == rhs.obj
end,
}
local function functor(func, obj)
return setmetatable({func = func, obj = obj}, _pcall)
end
local _event = {}
_event.__index = _event
function _event:CreateListener(func, obj)
func = functor(func, obj)
return {value = func, _prev = 0, _next = 0, removed = true}
end
function _event:AddListener(handle)
assert(handle)
if self.lock then
table.insert(self.opList, function() self.list:pushnode(handle) end)
else
self.list:pushnode(handle)
end
end
function _event:RemoveListener(handle)
assert(handle)
if self.lock then
table.insert(self.opList, function() self.list:remove(handle) end)
else
self.list:remove(handle)
end
end
function _event:Count()
return self.list.length
end
function _event:Clear()
self.list:clear()
self.opList = {}
self.lock = false
self.current = nil
end
_event.__call = function(self, ...)
local _list = self.list
self.lock = true
local ilist = ilist
for i, f in ilist(_list) do
self.current = i
if not f(...) then
_list:remove(i)
self.lock = false
end
end
local opList = self.opList
self.lock = false
for i, op in ipairs(opList) do
op()
opList[i] = nil
end
end
function event(name)
return setmetatable({
name = name,
lock = false,
opList = {},
list = list:new(),
}, _event)
end
UpdateBeat = event("Update")
LateUpdateBeat = event("LateUpdate")
FixedUpdateBeat = event("FixedUpdate")
--只在协同使用
CoUpdateBeat = event("CoUpdate")
CoLateUpdateBeat = event("CoLateUpdate")
CoFixedUpdateBeat = event("CoFixedUpdate")
function Update(deltaTime, unscaledDeltaTime)
Time:SetDeltaTime(deltaTime, unscaledDeltaTime)
UpdateBeat()
CoUpdateBeat()
end
function LateUpdate()
LateUpdateBeat()
CoLateUpdateBeat()
Time:SetFrameCount()
end
function FixedUpdate(fixedDeltaTime)
Time:SetFixedDelta(fixedDeltaTime)
FixedUpdateBeat()
CoFixedUpdateBeat()
end
|
local ffi = require 'ffi'
local success, lib = pcall( ffi.load, 'Mfplat' )
if not success then
return false
end
local com = require 'exports.mswindows.com'
local guids = require 'exports.mswindows.guids'
require 'exports.mswindows.automation'
com.predef 'IMFSample'
com.predef 'IMFCollection'
ffi.cdef [[
typedef struct MFT_INPUT_STREAM_INFO {
int64_t hnsMaxLatency;
uint32_t dwFlags;
uint32_t cbSize;
uint32_t cbMaxLookahead;
uint32_t cbAlignment;
} MFT_INPUT_STREAM_INFO;
typedef struct MFT_OUTPUT_STREAM_INFO {
uint32_t dwFlags;
uint32_t cbSize;
uint32_t cbAlignment;
} MFT_OUTPUT_STREAM_INFO;
typedef enum MF_ATTRIBUTE_TYPE {
MF_ATTRIBUTE_UINT32 = VT_UI4,
MF_ATTRIBUTE_UINT64 = VT_UI8,
MF_ATTRIBUTE_DOUBLE = VT_R8,
MF_ATTRIBUTE_GUID = VT_CLSID,
MF_ATTRIBUTE_STRING = VT_LPWSTR,
MF_ATTRIBUTE_BLOB = VT_VECTOR | VT_UI1,
MF_ATTRIBUTE_IUNKNOWN = VT_UNKNOWN
} MF_ATTRIBUTE_TYPE;
typedef enum MF_ATTRIBUTES_MATCH_TYPE {
MF_ATTRIBUTES_MATCH_OUR_ITEMS = 0,
MF_ATTRIBUTES_MATCH_THEIR_ITEMS = 1,
MF_ATTRIBUTES_MATCH_ALL_ITEMS = 2,
MF_ATTRIBUTES_MATCH_INTERSECTION = 3,
MF_ATTRIBUTES_MATCH_SMALLER = 4
} MF_ATTRIBUTES_MATCH_TYPE;
typedef enum MFT_MESSAGE_TYPE {
MFT_MESSAGE_COMMAND_FLUSH = 0,
MFT_MESSAGE_COMMAND_DRAIN = 1,
MFT_MESSAGE_SET_D3D_MANAGER = 2,
MFT_MESSAGE_DROP_SAMPLES = 3,
MFT_MESSAGE_NOTIFY_BEGIN_STREAMING = 0x10000000,
MFT_MESSAGE_NOTIFY_END_STREAMING = 0x10000001,
MFT_MESSAGE_NOTIFY_END_OF_STREAM = 0x10000002,
MFT_MESSAGE_NOTIFY_START_OF_STREAM = 0x10000003,
MFT_MESSAGE_COMMAND_MARKER = 0x20000000
} MFT_MESSAGE_TYPE;
typedef struct MFT_OUTPUT_DATA_BUFFER {
uint32_t dwStreamID;
IMFSample* pSample;
uint32_t dwStatus;
IMFCollection* pEvents;
} MFT_OUTPUT_DATA_BUFFER;
enum {
MF_SOURCE_READER_FIRST_VIDEO_STREAM = 0xFFFFFFFC,
MF_SOURCE_READER_FIRST_AUDIO_STREAM = 0xFFFFFFFD,
MF_SOURCE_READER_ALL_STREAMS = 0xFFFFFFFE
};
typedef enum MFBYTESTREAM_SEEK_ORIGIN {
msoBegin,
msoCurrent
} MFBYTESTREAM_SEEK_ORIGIN;
enum {
MF_MEDIATYPE_EQUAL_MAJOR_TYPES = 1,
MF_MEDIATYPE_EQUAL_FORMAT_TYPES = 2,
MF_MEDIATYPE_EQUAL_FORMAT_DATA = 4,
MF_MEDIATYPE_EQUAL_FORMAT_USER_DATA = 8
};
]]
com.def {
{'IMFTransform';
iid = 'bf94c121-5b05-4e6f-8000-ba598961414d';
methods = {
{'GetStreamLimits', [[
uint32_t* out_input_min,
uint32_t* out_input_max,
uint32_t* out_output_min,
uint32_t* out_output_max]]};
{'GetStreamCount', 'uint32_t* out_input_count, uint32_t* out_output_count'};
{'GetStreamIDs', 'uint32_t* out_input_ids, uint32_t* out_ouput_ids'};
{'GetInputStreamInfo', 'uint32_t input_i, MFT_INPUT_STREAM_INFO* out_info'};
{'GetOutputStreamInfo', 'uint32_t output_i, MFT_OUTPUT_STREAM_INFO* out_info'};
{'GetAttributes', 'IMFAttributes** out_attributes'};
{'GetInputStreamAttributes', 'uint32_t input_id, IMFAttributes** out_attributes'};
{'GetOutputStreamAttributes', 'uint32_t output_id, IMFAttributes** out_attributes'};
{'DeleteInputStream', 'uint32_t stream_id'};
{'AddInputStreams', 'uint32_t count, uint32_t* stream_ids'};
{'GetInputAvailableType', 'uint32_t input_id, uint32_t type_i, IMFMediaType** out_type'};
{'GetOutputAvailableType', 'uint32_t output_id, uint32_t type_i, IMFMediaType** out_type'};
{'SetInputType', 'uint32_t input_id, IMFMediaType*, uint32_t flags'};
{'SetOutputType', 'uint32_t output_id, IMFMediaType*, uint32_t flags'};
{'GetInputCurrentType', 'uint32_t input_id, IMFMediaType** out_type'};
{'GetOutputCurrentType', 'uint32_t output_id, IMFMediaType** out_type'};
{'GetInputStatus', 'uint32_t input_id, uint32_t* out_flags'};
{'GetOutputStatus', 'uint32_t* out_flags'};
{'SetOutputBounds', 'int64_t lower_bound, int64_t upper_bound'};
{'ProcessEvent', 'uint32_t input_id', 'IMFMediaEvent*'};
{'ProcessMessage', 'MFT_MESSAGE_TYPE, uintptr_t param'};
{'ProcessInput', 'uint32_t input_id, IMFSample*, uint32_t flags'};
{'ProcessOutput', [[
uint32_t flags,
uint32_t output_buffer_count,
MFT_OUTPUT_DATA_BUFFER* output_samples,
uint32_t* out_status]]};
};
};
{'IMFAttributes';
iid = '2cd2d921-c447-44a7-a13c-4adabfc247e3';
methods = {
{'GetItem', 'const GUID* key, PROPVARIANT* out_value'};
{'GetItemType', 'const GUID* key, MF_ATTRIBUTE_TYPE* out_type'};
{'CompareItem', 'const GUID* key, const PROPVARIANT* value, bool32* out_comparison'};
{'Compare', 'IMFAttributes* theirs, MF_ATTRIBUTES_MATCH_TYPE, bool32* out_comparison'};
{'GetUINT32', 'const GUID* key, uint32_t* out_value'};
{'GetUINT64', 'const GUID* key, uint64_t* out_value'};
{'GetDouble', 'const GUID* key, double* out_value'};
{'GetGUID', 'const GUID* key, GUID* out_guid'};
{'GetStringLength', 'const GUID* key, uint32_t* out_length'};
{'GetString', 'const GUID* key, wchar_t* out_buf, uint32_t buf_size, uint32_t* out_length'};
{'GetAllocatedString', 'const GUID* key, wchar_t** out_string, uint32_t* out_length'}; -- use CoTaskMemFree
{'GetBlobSize', 'const GUID* key, uint32_t* out_size'};
{'GetBlob', 'const GUID* key, uint8_t* out_buf, uint32_t buf_size, uint32_t* out_size'};
{'GetAllocatedBlob', 'const GUID* key, uint32_t** out_blob, uint32_t* out_size'}; -- use CoTaskMemFree
{'GetUnknown', 'const GUID* key, const GUID* iid, void** out_object'};
{'SetItem', 'const GUID* key, const PROPVARIANT*'};
{'DeleteItem', 'const GUID* key'};
{'DeleteAllItems'};
{'SetUINT32', 'const GUID* key, uint32_t value'};
{'SetUINT64', 'const GUID* key, uint64_t value'};
{'SetDouble', 'const GUID* key, double value'};
{'SetGUID', 'const GUID* key, const GUID*'};
{'SetString', 'const GUID* key, const wchar_t*'};
{'SetBlob', 'const GUID* key, const uint8_t* blob, uint32_t blob_size'};
{'SetUnknown', 'const GUID* key, IUnknown*'};
{'LockStore'};
{'UnlockStore'};
{'GetCount', 'uint32_t* out_count'};
{'GetItemAtIndex', 'uint32_t i, GUID* out_key, PROPVARIANT* out_value'};
{'CopyAllItems', 'IMFAttributes* destination'};
};
};
{'IMFMediaType', inherits='IMFAttributes';
iid = '44ae0fa8-ea31-4109-8d2e-4cae4997c555';
methods = {
{'GetMajorType', 'GUID* out_guid'};
{'IsCompressedFormat', 'bool32* out_compressed'};
{'IsEqual', 'IMFMediaType*, uint32_t* out_flags'};
{'GetRepresentation', 'GUID, void** out_representation'};
{'FreeRepresentation', 'GUID, void* representation'};
};
};
{'IMFMediaEvent', inherits='IMFAttributes';
iid = 'df598932-f10c-4e39-bba2-c308f101daa3';
methods = {
{'GetType', 'uint32_t* out_type'};
{'GetExtendedType', 'GUID* out_type_guid'};
{'GetStatus', 'int32_t* out_hresult'};
{'GetValue', 'PROPVARIANT* out_value'};
};
};
{'IMFSample', inherits='IMFAttributes';
iid = 'c40a00f2-b93a-4d80-ae8c-5a1c634f58e4';
methods = {
{'GetSampleFlags', 'uint32_t* out_flags'};
{'SetSampleFlags', 'uint32_t flags'};
{'GetSampleTime', 'int64_t* out_time'};
{'SetSampleTime', 'int64_t time'};
{'GetSampleDuration', 'int64_t* out_duration'};
{'SetSampleDuration', 'int64_t duration'};
{'GetBufferCount', 'uint32_t* out_count'};
{'GetBufferByIndex', 'uint32_t index, IMFMediaBuffer** out_buffer'};
{'ConvertToContiguousBuffer', 'IMFMediaBuffer** out_buffer'};
{'AddBuffer', 'IMFMediaBuffer*'};
{'RemoveBufferByIndex', 'uint32_t index'};
{'RemoveAllBuffers'};
{'GetTotalLength', 'uint32_t* out_length'};
{'CopyToBuffer', 'IMFMediaBuffer*'};
};
};
{'IMFMediaBuffer';
iid = '045fa593-8799-42b8-bc8d-8968c6453507';
methods = {
{'Lock', 'uint8_t** out_buffer, uint32_t* out_max_length, uint32_t* out_current_length'};
{'Unlock'};
{'GetCurrentLength', 'uint32_t* out_length'};
{'SetCurrentLength', 'uint32_t length'};
{'GetMaxLength', 'uint32_t* out_length'};
};
};
{'IMFCollection';
iid = '5bc8a76b-869a-46a3-9b03-fa218a66aebe';
methods = {
{'GetElementCount', 'uint32_t* out_elements'};
{'GetElement', 'uint32_t index, IUnknown** out_element'};
{'AddElement', 'IUnknown* element'};
{'RemoveElement', 'uint32_t index, IUnknown** out_element'};
{'InsertElementAt', 'uint32_t index, IUnknown* element'};
{'RemoveAllElements'};
};
};
{'IMFSourceReader';
iid = '70ae66f2-c809-4e4f-8915-bdcb406b7993';
methods = {
{'GetStreamSelection', 'uint32_t stream_i, bool32* out_selected'};
{'SetStreamSelection', 'uint32_t stream_i, bool32 selected'};
{'GetNativeMediaType', 'uint32_t stream_i, uint32_t mediatype_i, IMFMediaType** out_type'};
{'GetCurrentMediaType', 'uint32_t stream_i, IMFMediaType** out_type'};
{'SetCurrentMediaType', 'uint32_t stream_i, uint32_t* reserved, IMFMediaType*'};
{'SetCurrentPosition', 'const GUID* time_format_guid, const PROPVARIANT* position'};
{'ReadSample', [[
uint32_t stream_i,
uint32_t control_flags,
uint32_t* out_actual_stream_i,
uint32_t* out_stream_flags,
int64_t* out_timestamp,
IMFSample** out_sample]]};
{'Flush', 'uint32_t stream_i'};
{'GetServiceForStream', [[
uint32_t stream_i,
const GUID* service_guid,
const GUID* iid,
void** out_object]]};
{'GetPresentationAttribute', [[
uint32_t stream_i,
const GUID* attribute_guid,
PROPVARIANT* out_value]]};
};
};
{'IMFByteStream';
iid = 'ad4c1b00-4bf7-422f-9175-756693d9130d';
methods = {
{'GetCapabilities', 'uint32_t* out_caps'};
{'GetLength', 'uint64_t* out_length'};
{'SetLength', 'uint64_t length'};
{'GetCurrentPosition', 'uint64_t* out_pos'};
{'SetCurrentPosition', 'uint64_t pos'};
{'IsEndOfStream', 'bool32* out_ended'};
{'Read', 'uint8_t* buf, uint32_t buf_size, uint32_t* out_actual_read'};
{'BeginRead', 'uint8_t* buf, uint32_t buf_size, IMFAsyncCallback*, IUnknown* state'};
{'EndRead', 'IMFAsyncResult*, uint32_t* out_read'};
{'Write', 'const uint8_t* buf, uint32_t buf_size, uint32_t* out_actual_written'};
{'BeginWrite', 'const uint8_t* buf, uint32_t buf_size, IMFAsyncCallback*, IUnknown* state'};
{'EndWrite', 'IMFAsyncResult* result, uint32_t* out_written'};
{'Seek', 'MFBYTESTREAM_SEEK_ORIGIN, int64_t offset, uint32_t flags, uint64_t* out_pos'};
{'Flush'};
{'Close'};
};
};
{'IMFAsyncResult';
iid = 'ac6b7889-0740-4d51-8619-905994a55cc6';
methods = {
{'GetState', 'IUnknown** out_state'};
{'GetStatus'};
{'SetStatus', 'int32_t hresult'};
{'GetObject', 'IUnknown** out_object'};
{'GetStateNoAddRef', ret='IUnknown*'};
};
};
{'IMFAsyncCallback';
iid = 'a27003cf-2354-4f2a-8d6a-ab7cff15437e';
methods = {
{'GetParameters', 'uint32_t* out_flags, uint32_t* out_queue'};
{'Invoke', 'IMFAsyncResult*'};
};
};
}
ffi.cdef [[
enum {
MF_SDK_VERSION__VISTA = 0x0001,
MF_SDK_VERSION__WINDOWS7 = 0x0002,
MF_API_VERSION__VISTA = 0x0070,
MF_API_VERSION__WINDOWS7 = MF_API_VERSION__VISTA, // seems to be unused after Vista
MF_VERSION__VISTA = (MF_SDK_VERSION__VISTA << 16) | MF_API_VERSION__VISTA,
MF_VERSION__WINDOWS7 = (MF_SDK_VERSION__WINDOWS7 << 16) | MF_API_VERSION__WINDOWS7,
MF_SDK_VERSION = MF_SDK_VERSION__WINDOWS7,
MF_VERSION = MF_VERSION__WINDOWS7,
MFSTARTUP_FULL = 0,
MFSTARTUP_NOSOCKET = 1,
MFSTARTUP_LITE = MFSTARTUP_NOSOCKET
};
int32_t MFStartup(uint32_t version, uint32_t flags);
int32_t MFShutdown();
int32_t MFCreateMemoryBuffer(uint32_t max_length, IMFMediaBuffer** out_buffer);
int32_t MFCreateMediaType(IMFMediaType** out_media_type);
int32_t MFCreateMFByteStreamOnStream(IStream*, IMFByteStream** out_imfstream);
]]
require 'exports.mswindows.errors' {
MF_E_PLATFORM_NOT_INITIALIZED = 0xC00D36B0;
MF_E_BUFFERTOOSMALL = 0xC00D36B1;
MF_E_INVALIDREQUEST = 0xC00D36B2;
MF_E_INVALIDSTREAMNUMBER = 0xC00D36B3;
MF_E_INVALIDMEDIATYPE = 0xC00D36B4;
MF_E_NOTACCEPTING = 0xC00D36B5;
MF_E_NOT_INITIALIZED = 0xC00D36B6;
MF_E_UNSUPPORTED_REPRESENTATION = 0xC00D36B7;
MF_E_NO_MORE_TYPES = 0xC00D36B9;
MF_E_UNSUPPORTED_SERVICE = 0xC00D36BA;
MF_E_UNEXPECTED = 0xC00D36BB;
MF_E_INVALIDNAME = 0xC00D36BC;
MF_E_INVALIDTYPE = 0xC00D36BD;
MF_E_INVALID_FILE_FORMAT = 0xC00D36BE;
MF_E_INVALIDINDEX = 0xC00D36BF;
MF_E_INVALID_TIMESTAMP = 0xC00D36C0;
MF_E_UNSUPPORTED_SCHEME = 0xC00D36C3;
MF_E_UNSUPPORTED_BYTESTREAM_TYPE = 0xC00D36C4;
MF_E_UNSUPPORTED_TIME_FORMAT = 0xC00D36C5;
MF_E_NO_SAMPLE_TIMESTAMP = 0xC00D36C8;
MF_E_NO_SAMPLE_DURATION = 0xC00D36C9;
MF_E_INVALID_STREAM_DATA = 0xC00D36CB;
MF_E_RT_UNAVAILABLE = 0xC00D36CF;
MF_E_UNSUPPORTED_RATE = 0xC00D36D0;
MF_E_THINNING_UNSUPPORTED = 0xC00D36D1;
MF_E_REVERSE_UNSUPPORTED = 0xC00D36D2;
MF_E_UNSUPPORTED_RATE_TRANSITION = 0xC00D36D3;
MF_E_RATE_CHANGE_PREEMPTED = 0xC00D36D4;
MF_E_NOT_FOUND = 0xC00D36D5;
MF_E_NOT_AVAILABLE = 0xC00D36D6;
MF_E_NO_CLOCK = 0xC00D36D7;
MF_S_MULTIPLE_BEGIN = 0x000D36D8;
MF_E_MULTIPLE_BEGIN = 0xC00D36D9;
MF_E_MULTIPLE_SUBSCRIBERS = 0xC00D36DA;
MF_E_TIMER_ORPHANED = 0xC00D36DB;
MF_E_STATE_TRANSITION_PENDING = 0xC00D36DC;
MF_E_UNSUPPORTED_STATE_TRANSITION = 0xC00D36DD;
MF_E_UNRECOVERABLE_ERROR_OCCURRED = 0xC00D36DE;
MF_E_SAMPLE_HAS_TOO_MANY_BUFFERS = 0xC00D36DF;
MF_E_SAMPLE_NOT_WRITABLE = 0xC00D36E0;
MF_E_INVALID_KEY = 0xC00D36E2;
MF_E_BAD_STARTUP_VERSION = 0xC00D36E3;
MF_E_UNSUPPORTED_CAPTION = 0xC00D36E4;
MF_E_INVALID_POSITION = 0xC00D36E5;
MF_E_ATTRIBUTENOTFOUND = 0xC00D36E6;
MF_E_PROPERTY_TYPE_NOT_ALLOWED = 0xC00D36E7;
MF_E_PROPERTY_TYPE_NOT_SUPPORTED = 0xC00D36E8;
MF_E_PROPERTY_EMPTY = 0xC00D36E9;
MF_E_PROPERTY_NOT_EMPTY = 0xC00D36EA;
MF_E_PROPERTY_VECTOR_NOT_ALLOWED = 0xC00D36EB;
MF_E_PROPERTY_VECTOR_REQUIRED = 0xC00D36EC;
MF_E_OPERATION_CANCELLED = 0xC00D36ED;
MF_E_BYTESTREAM_NOT_SEEKABLE = 0xC00D36EE;
MF_E_DISABLED_IN_SAFEMODE = 0xC00D36EF;
MF_E_CANNOT_PARSE_BYTESTREAM = 0xC00D36F0;
MF_E_SOURCERESOLVER_MUTUALLY_EXCLUSIVE_FLAGS = 0xC00D36F1;
MF_E_MEDIAPROC_WRONGSTATE = 0xC00D36F2;
MF_E_RT_THROUGHPUT_NOT_AVAILABLE = 0xC00D36F3;
MF_E_RT_TOO_MANY_CLASSES = 0xC00D36F4;
MF_E_RT_WOULDBLOCK = 0xC00D36F5;
MF_E_NO_BITPUMP = 0xC00D36F6;
MF_E_RT_OUTOFMEMORY = 0xC00D36F7;
MF_E_RT_WORKQUEUE_CLASS_NOT_SPECIFIED = 0xC00D36F8;
MF_E_INSUFFICIENT_BUFFER = 0xC00D7170;
MF_E_CANNOT_CREATE_SINK = 0xC00D36FA;
MF_E_BYTESTREAM_UNKNOWN_LENGTH = 0xC00D36FB;
MF_E_SESSION_PAUSEWHILESTOPPED = 0xC00D36FC;
MF_S_ACTIVATE_REPLACED = 0x000D36FD;
MF_E_FORMAT_CHANGE_NOT_SUPPORTED = 0xC00D36FE;
MF_E_INVALID_WORKQUEUE = 0xC00D36FF;
MF_E_DRM_UNSUPPORTED = 0xC00D3700;
MF_E_UNAUTHORIZED = 0xC00D3701;
MF_E_OUT_OF_RANGE = 0xC00D3702;
MF_E_INVALID_CODEC_MERIT = 0xC00D3703;
MF_E_HW_MFT_FAILED_START_STREAMING = 0xC00D3704;
MF_S_ASF_PARSEINPROGRESS = 0x400D3A98;
MF_E_ASF_PARSINGINCOMPLETE = 0xC00D3A98;
MF_E_ASF_MISSINGDATA = 0xC00D3A99;
MF_E_ASF_INVALIDDATA = 0xC00D3A9A;
MF_E_ASF_OPAQUEPACKET = 0xC00D3A9B;
MF_E_ASF_NOINDEX = 0xC00D3A9C;
MF_E_ASF_OUTOFRANGE = 0xC00D3A9D;
MF_E_ASF_INDEXNOTLOADED = 0xC00D3A9E;
MF_E_ASF_TOO_MANY_PAYLOADS = 0xC00D3A9F;
MF_E_ASF_UNSUPPORTED_STREAM_TYPE = 0xC00D3AA0;
MF_E_ASF_DROPPED_PACKET = 0xC00D3AA1;
MF_E_NO_EVENTS_AVAILABLE = 0xC00D3E80;
MF_E_INVALID_STATE_TRANSITION = 0xC00D3E82;
MF_E_END_OF_STREAM = 0xC00D3E84;
MF_E_SHUTDOWN = 0xC00D3E85;
MF_E_MP3_NOTFOUND = 0xC00D3E86;
MF_E_MP3_OUTOFDATA = 0xC00D3E87;
MF_E_MP3_NOTMP3 = 0xC00D3E88;
MF_E_MP3_NOTSUPPORTED = 0xC00D3E89;
MF_E_NO_DURATION = 0xC00D3E8A;
MF_E_INVALID_FORMAT = 0xC00D3E8C;
MF_E_PROPERTY_NOT_FOUND = 0xC00D3E8D;
MF_E_PROPERTY_READ_ONLY = 0xC00D3E8E;
MF_E_PROPERTY_NOT_ALLOWED = 0xC00D3E8F;
MF_E_MEDIA_SOURCE_NOT_STARTED = 0xC00D3E91;
MF_E_UNSUPPORTED_FORMAT = 0xC00D3E98;
MF_E_MP3_BAD_CRC = 0xC00D3E99;
MF_E_NOT_PROTECTED = 0xC00D3E9A;
MF_E_MEDIA_SOURCE_WRONGSTATE = 0xC00D3E9B;
MF_E_MEDIA_SOURCE_NO_STREAMS_SELECTED = 0xC00D3E9C;
MF_E_CANNOT_FIND_KEYFRAME_SAMPLE = 0xC00D3E9D;
MF_E_UNSUPPORTED_CHARACTERISTICS = 0xC00D3E9E;
MF_E_NO_AUDIO_RECORDING_DEVICE = 0xC00D3E9F;
MF_E_AUDIO_RECORDING_DEVICE_IN_USE = 0xC00D3EA0;
MF_E_AUDIO_RECORDING_DEVICE_INVALIDATED = 0xC00D3EA1;
MF_E_VIDEO_RECORDING_DEVICE_INVALIDATED = 0xC00D3EA2;
MF_E_VIDEO_RECORDING_DEVICE_PREEMPTED = 0xC00D3EA3;
MF_E_NETWORK_RESOURCE_FAILURE = 0xC00D4268;
MF_E_NET_WRITE = 0xC00D4269;
MF_E_NET_READ = 0xC00D426A;
MF_E_NET_REQUIRE_NETWORK = 0xC00D426B;
MF_E_NET_REQUIRE_ASYNC = 0xC00D426C;
MF_E_NET_BWLEVEL_NOT_SUPPORTED = 0xC00D426D;
MF_E_NET_STREAMGROUPS_NOT_SUPPORTED = 0xC00D426E;
MF_E_NET_MANUALSS_NOT_SUPPORTED = 0xC00D426F;
MF_E_NET_INVALID_PRESENTATION_DESCRIPTOR = 0xC00D4270;
MF_E_NET_CACHESTREAM_NOT_FOUND = 0xC00D4271;
MF_I_MANUAL_PROXY = 0x400D4272;
MF_E_NET_REQUIRE_INPUT = 0xC00D4274;
MF_E_NET_REDIRECT = 0xC00D4275;
MF_E_NET_REDIRECT_TO_PROXY = 0xC00D4276;
MF_E_NET_TOO_MANY_REDIRECTS = 0xC00D4277;
MF_E_NET_TIMEOUT = 0xC00D4278;
MF_E_NET_CLIENT_CLOSE = 0xC00D4279;
MF_E_NET_BAD_CONTROL_DATA = 0xC00D427A;
MF_E_NET_INCOMPATIBLE_SERVER = 0xC00D427B;
MF_E_NET_UNSAFE_URL = 0xC00D427C;
MF_E_NET_CACHE_NO_DATA = 0xC00D427D;
MF_E_NET_EOL = 0xC00D427E;
MF_E_NET_BAD_REQUEST = 0xC00D427F;
MF_E_NET_INTERNAL_SERVER_ERROR = 0xC00D4280;
MF_E_NET_SESSION_NOT_FOUND = 0xC00D4281;
MF_E_NET_NOCONNECTION = 0xC00D4282;
MF_E_NET_CONNECTION_FAILURE = 0xC00D4283;
MF_E_NET_INCOMPATIBLE_PUSHSERVER = 0xC00D4284;
MF_E_NET_SERVER_ACCESSDENIED = 0xC00D4285;
MF_E_NET_PROXY_ACCESSDENIED = 0xC00D4286;
MF_E_NET_CANNOTCONNECT = 0xC00D4287;
MF_E_NET_INVALID_PUSH_TEMPLATE = 0xC00D4288;
MF_E_NET_INVALID_PUSH_PUBLISHING_POINT = 0xC00D4289;
MF_E_NET_BUSY = 0xC00D428A;
MF_E_NET_RESOURCE_GONE = 0xC00D428B;
MF_E_NET_ERROR_FROM_PROXY = 0xC00D428C;
MF_E_NET_PROXY_TIMEOUT = 0xC00D428D;
MF_E_NET_SERVER_UNAVAILABLE = 0xC00D428E;
MF_E_NET_TOO_MUCH_DATA = 0xC00D428F;
MF_E_NET_SESSION_INVALID = 0xC00D4290;
MF_E_OFFLINE_MODE = 0xC00D4291;
MF_E_NET_UDP_BLOCKED = 0xC00D4292;
MF_E_NET_UNSUPPORTED_CONFIGURATION = 0xC00D4293;
MF_E_NET_PROTOCOL_DISABLED = 0xC00D4294;
MF_E_ALREADY_INITIALIZED = 0xC00D4650;
MF_E_BANDWIDTH_OVERRUN = 0xC00D4651;
MF_E_LATE_SAMPLE = 0xC00D4652;
MF_E_FLUSH_NEEDED = 0xC00D4653;
MF_E_INVALID_PROFILE = 0xC00D4654;
MF_E_INDEX_NOT_COMMITTED = 0xC00D4655;
MF_E_NO_INDEX = 0xC00D4656;
MF_E_CANNOT_INDEX_IN_PLACE = 0xC00D4657;
MF_E_MISSING_ASF_LEAKYBUCKET = 0xC00D4658;
MF_E_INVALID_ASF_STREAMID = 0xC00D4659;
MF_E_STREAMSINK_REMOVED = 0xC00D4A38;
MF_E_STREAMSINKS_OUT_OF_SYNC = 0xC00D4A3A;
MF_E_STREAMSINKS_FIXED = 0xC00D4A3B;
MF_E_STREAMSINK_EXISTS = 0xC00D4A3C;
MF_E_SAMPLEALLOCATOR_CANCELED = 0xC00D4A3D;
MF_E_SAMPLEALLOCATOR_EMPTY = 0xC00D4A3E;
MF_E_SINK_ALREADYSTOPPED = 0xC00D4A3F;
MF_E_ASF_FILESINK_BITRATE_UNKNOWN = 0xC00D4A40;
MF_E_SINK_NO_STREAMS = 0xC00D4A41;
MF_S_SINK_NOT_FINALIZED = 0x000D4A42;
MF_E_METADATA_TOO_LONG = 0xC00D4A43;
MF_E_SINK_NO_SAMPLES_PROCESSED = 0xC00D4A44;
MF_E_VIDEO_REN_NO_PROCAMP_HW = 0xC00D4E20;
MF_E_VIDEO_REN_NO_DEINTERLACE_HW = 0xC00D4E21;
MF_E_VIDEO_REN_COPYPROT_FAILED = 0xC00D4E22;
MF_E_VIDEO_REN_SURFACE_NOT_SHARED = 0xC00D4E23;
MF_E_VIDEO_DEVICE_LOCKED = 0xC00D4E24;
MF_E_NEW_VIDEO_DEVICE = 0xC00D4E25;
MF_E_NO_VIDEO_SAMPLE_AVAILABLE = 0xC00D4E26;
MF_E_NO_AUDIO_PLAYBACK_DEVICE = 0xC00D4E84;
MF_E_AUDIO_PLAYBACK_DEVICE_IN_USE = 0xC00D4E85;
MF_E_AUDIO_PLAYBACK_DEVICE_INVALIDATED = 0xC00D4E86;
MF_E_AUDIO_SERVICE_NOT_RUNNING = 0xC00D4E87;
MF_E_TOPO_INVALID_OPTIONAL_NODE = 0xC00D520E;
MF_E_TOPO_CANNOT_FIND_DECRYPTOR = 0xC00D5211;
MF_E_TOPO_CODEC_NOT_FOUND = 0xC00D5212;
MF_E_TOPO_CANNOT_CONNECT = 0xC00D5213;
MF_E_TOPO_UNSUPPORTED = 0xC00D5214;
MF_E_TOPO_INVALID_TIME_ATTRIBUTES = 0xC00D5215;
MF_E_TOPO_LOOPS_IN_TOPOLOGY = 0xC00D5216;
MF_E_TOPO_MISSING_PRESENTATION_DESCRIPTOR = 0xC00D5217;
MF_E_TOPO_MISSING_STREAM_DESCRIPTOR = 0xC00D5218;
MF_E_TOPO_STREAM_DESCRIPTOR_NOT_SELECTED = 0xC00D5219;
MF_E_TOPO_MISSING_SOURCE = 0xC00D521A;
MF_E_TOPO_SINK_ACTIVATES_UNSUPPORTED = 0xC00D521B;
MF_E_SEQUENCER_UNKNOWN_SEGMENT_ID = 0xC00D61AC;
MF_S_SEQUENCER_CONTEXT_CANCELED = 0x000D61AD;
MF_E_NO_SOURCE_IN_CACHE = 0xC00D61AE;
MF_S_SEQUENCER_SEGMENT_AT_END_OF_STREAM = 0x000D61AF;
MF_E_TRANSFORM_TYPE_NOT_SET = 0xC00D6D60;
MF_E_TRANSFORM_STREAM_CHANGE = 0xC00D6D61;
MF_E_TRANSFORM_INPUT_REMAINING = 0xC00D6D62;
MF_E_TRANSFORM_PROFILE_MISSING = 0xC00D6D63;
MF_E_TRANSFORM_PROFILE_INVALID_OR_CORRUPT = 0xC00D6D64;
MF_E_TRANSFORM_PROFILE_TRUNCATED = 0xC00D6D65;
MF_E_TRANSFORM_PROPERTY_PID_NOT_RECOGNIZED = 0xC00D6D66;
MF_E_TRANSFORM_PROPERTY_VARIANT_TYPE_WRONG = 0xC00D6D67;
MF_E_TRANSFORM_PROPERTY_NOT_WRITEABLE = 0xC00D6D68;
MF_E_TRANSFORM_PROPERTY_ARRAY_VALUE_WRONG_NUM_DIM = 0xC00D6D69;
MF_E_TRANSFORM_PROPERTY_VALUE_SIZE_WRONG = 0xC00D6D6A;
MF_E_TRANSFORM_PROPERTY_VALUE_OUT_OF_RANGE = 0xC00D6D6B;
MF_E_TRANSFORM_PROPERTY_VALUE_INCOMPATIBLE = 0xC00D6D6C;
MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_OUTPUT_MEDIATYPE = 0xC00D6D6D;
MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_INPUT_MEDIATYPE = 0xC00D6D6E;
MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_MEDIATYPE_COMBINATION = 0xC00D6D6F;
MF_E_TRANSFORM_CONFLICTS_WITH_OTHER_CURRENTLY_ENABLED_FEATURES = 0xC00D6D70;
MF_E_TRANSFORM_NEED_MORE_INPUT = 0xC00D6D72;
MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_SPKR_CONFIG = 0xC00D6D73;
MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING = 0xC00D6D74;
MF_S_TRANSFORM_DO_NOT_PROPAGATE_EVENT = 0x000D6D75;
MF_E_UNSUPPORTED_D3D_TYPE = 0xC00D6D76;
MF_E_TRANSFORM_ASYNC_LOCKED = 0xC00D6D77;
MF_E_TRANSFORM_CANNOT_INITIALIZE_ACM_DRIVER = 0xC00D6D78;
MF_E_LICENSE_INCORRECT_RIGHTS = 0xC00D7148;
MF_E_LICENSE_OUTOFDATE = 0xC00D7149;
MF_E_LICENSE_REQUIRED = 0xC00D714A;
MF_E_DRM_HARDWARE_INCONSISTENT = 0xC00D714B;
MF_E_NO_CONTENT_PROTECTION_MANAGER = 0xC00D714C;
MF_E_LICENSE_RESTORE_NO_RIGHTS = 0xC00D714D;
MF_E_BACKUP_RESTRICTED_LICENSE = 0xC00D714E;
MF_E_LICENSE_RESTORE_NEEDS_INDIVIDUALIZATION = 0xC00D714F;
MF_S_PROTECTION_NOT_REQUIRED = 0x000D7150;
MF_E_COMPONENT_REVOKED = 0xC00D7151;
MF_E_TRUST_DISABLED = 0xC00D7152;
MF_E_WMDRMOTA_NO_ACTION = 0xC00D7153;
MF_E_WMDRMOTA_ACTION_ALREADY_SET = 0xC00D7154;
MF_E_WMDRMOTA_DRM_HEADER_NOT_AVAILABLE = 0xC00D7155;
MF_E_WMDRMOTA_DRM_ENCRYPTION_SCHEME_NOT_SUPPORTED = 0xC00D7156;
MF_E_WMDRMOTA_ACTION_MISMATCH = 0xC00D7157;
MF_E_WMDRMOTA_INVALID_POLICY = 0xC00D7158;
MF_E_POLICY_UNSUPPORTED = 0xC00D7159;
MF_E_OPL_NOT_SUPPORTED = 0xC00D715A;
MF_E_TOPOLOGY_VERIFICATION_FAILED = 0xC00D715B;
MF_E_SIGNATURE_VERIFICATION_FAILED = 0xC00D715C;
MF_E_DEBUGGING_NOT_ALLOWED = 0xC00D715D;
MF_E_CODE_EXPIRED = 0xC00D715E;
MF_E_GRL_VERSION_TOO_LOW = 0xC00D715F;
MF_E_GRL_RENEWAL_NOT_FOUND = 0xC00D7160;
MF_E_GRL_EXTENSIBLE_ENTRY_NOT_FOUND = 0xC00D7161;
MF_E_KERNEL_UNTRUSTED = 0xC00D7162;
MF_E_PEAUTH_UNTRUSTED = 0xC00D7163;
MF_E_NON_PE_PROCESS = 0xC00D7165;
MF_E_REBOOT_REQUIRED = 0xC00D7167;
MF_S_WAIT_FOR_POLICY_SET = 0x000D7168;
MF_S_VIDEO_DISABLED_WITH_UNKNOWN_SOFTWARE_OUTPUT = 0x000D7169;
MF_E_GRL_INVALID_FORMAT = 0xC00D716A;
MF_E_GRL_UNRECOGNIZED_FORMAT = 0xC00D716B;
MF_E_ALL_PROCESS_RESTART_REQUIRED = 0xC00D716C;
MF_E_PROCESS_RESTART_REQUIRED = 0xC00D716D;
MF_E_USERMODE_UNTRUSTED = 0xC00D716E;
MF_E_PEAUTH_SESSION_NOT_STARTED = 0xC00D716F;
MF_E_PEAUTH_PUBLICKEY_REVOKED = 0xC00D7171;
MF_E_GRL_ABSENT = 0xC00D7172;
MF_S_PE_TRUSTED = 0x000D7173;
MF_E_PE_UNTRUSTED = 0xC00D7174;
MF_E_PEAUTH_NOT_STARTED = 0xC00D7175;
MF_E_INCOMPATIBLE_SAMPLE_PROTECTION = 0xC00D7176;
MF_E_PE_SESSIONS_MAXED = 0xC00D7177;
MF_E_HIGH_SECURITY_LEVEL_CONTENT_NOT_ALLOWED = 0xC00D7178;
MF_E_TEST_SIGNED_COMPONENTS_NOT_ALLOWED = 0xC00D7179;
MF_E_ITA_UNSUPPORTED_ACTION = 0xC00D717A;
MF_E_ITA_ERROR_PARSING_SAP_PARAMETERS = 0xC00D717B;
MF_E_POLICY_MGR_ACTION_OUTOFBOUNDS = 0xC00D717C;
MF_E_BAD_OPL_STRUCTURE_FORMAT = 0xC00D717D;
MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_PROTECTION_GUID = 0xC00D717E;
MF_E_NO_PMP_HOST = 0xC00D717F;
MF_E_ITA_OPL_DATA_NOT_INITIALIZED = 0xC00D7180;
MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_OUTPUT = 0xC00D7181;
MF_E_ITA_UNRECOGNIZED_DIGITAL_VIDEO_OUTPUT = 0xC00D7182;
MF_E_RESOLUTION_REQUIRES_PMP_CREATION_CALLBACK = 0xC00D7183;
MF_E_INVALID_AKE_CHANNEL_PARAMETERS = 0xC00D7184;
MF_E_CONTENT_PROTECTION_SYSTEM_NOT_ENABLED = 0xC00D7185;
MF_E_UNSUPPORTED_CONTENT_PROTECTION_SYSTEM = 0xC00D7186;
MF_E_DRM_MIGRATION_NOT_SUPPORTED = 0xC00D7187;
MF_E_CLOCK_INVALID_CONTINUITY_KEY = 0xC00D9C40;
MF_E_CLOCK_NO_TIME_SOURCE = 0xC00D9C41;
MF_E_CLOCK_STATE_ALREADY_SET = 0xC00D9C42;
MF_E_CLOCK_NOT_SIMPLE = 0xC00D9C43;
MF_S_CLOCK_STOPPED = 0x000D9C44;
MF_E_NO_MORE_DROP_MODES = 0xC00DA028;
MF_E_NO_MORE_QUALITY_LEVELS = 0xC00DA029;
MF_E_DROPTIME_NOT_SUPPORTED = 0xC00DA02A;
MF_E_QUALITYKNOB_WAIT_LONGER = 0xC00DA02B;
MF_E_QM_INVALIDSTATE = 0xC00DA02C;
MF_E_TRANSCODE_NO_CONTAINERTYPE = 0xC00DA410;
MF_E_TRANSCODE_PROFILE_NO_MATCHING_STREAMS = 0xC00DA411;
MF_E_TRANSCODE_NO_MATCHING_ENCODER = 0xC00DA412;
MF_E_TRANSCODE_INVALID_PROFILE = 0xC00DA413;
MF_E_ALLOCATOR_NOT_INITIALIZED = 0xC00DA7F8;
MF_E_ALLOCATOR_NOT_COMMITED = 0xC00DA7F9;
MF_E_ALLOCATOR_ALREADY_COMMITED = 0xC00DA7FA;
MF_E_STREAM_ERROR = 0xC00DA7FB;
MF_E_INVALID_STREAM_STATE = 0xC00DA7FC;
MF_E_HW_STREAM_NOT_CONNECTED = 0xC00DA7FD;
MF_E_NO_CAPTURE_DEVICES_AVAILABLE = 0xC00DABE0;
MF_E_CAPTURE_SINK_OUTPUT_NOT_SET = 0xC00DABE1;
MF_E_CAPTURE_SINK_MIRROR_ERROR = 0xC00DABE2;
MF_E_CAPTURE_SINK_ROTATE_ERROR = 0xC00DABE3;
MF_E_CAPTURE_ENGINE_INVALID_OP = 0xC00DABE4;
MF_E_CAPTURE_ENGINE_ALL_EFFECTS_REMOVED = 0xC00DABE5;
MF_E_CAPTURE_SOURCE_NO_INDEPENDENT_PHOTO_STREAM_PRESENT = 0xC00DABE6;
MF_E_CAPTURE_SOURCE_NO_VIDEO_STREAM_PRESENT = 0xC00DABE7;
MF_E_CAPTURE_SOURCE_NO_AUDIO_STREAM_PRESENT = 0xC00DABE8;
}
return lib
|
local Concord = require("lib.concord")
local Cpml = require("lib.cpml")
local Mesh = Concord.component(function(e, mesh)
e.mesh = mesh
end)
local GetProperties, SetProperties = {}, {}
Mesh.__mt.__index = function(e, key)
return GetProperties[key] and GetProperties[key](e) or Mesh[key]
end
Mesh.__mt.__newindex = function(e, key, value)
if SetProperties[key] then
SetProperties[key](e, value)
else
rawset(e, key, value)
end
end
return Mesh
|
-- Copyright 2016 by Malte Skambath
--
-- This file may be distributed an/or modified
--
-- 1. under the LaTeX Project Public License and/or
-- 2. under the GNU Public License
--
-- See the file doc/generic/pgf/licenses/LICENSE for more information
-- @library
local evolving -- Library name
-- Load dependencies:
require "pgf.gd.trees.ChildSpec"
require "pgf.gd.trees.ReingoldTilford1981"
require "pgf.gd.layered"
-- Load declarations from:
require "pgf.gd.experimental.evolving.TimeSpec"
require "pgf.gd.experimental.evolving.Supergraph"
-- Load preprocessing/optimization phases from:
require "pgf.gd.experimental.evolving.SupergraphVertexSplitOptimization"
require "pgf.gd.experimental.evolving.GreedyTemporalCycleRemoval"
-- Load postprocessing/graph animation phases from:
require "pgf.gd.experimental.evolving.GraphAnimationCoordination"
-- Load algorithms from:
require "pgf.gd.experimental.evolving.Skambath2016"
|
Talk(0, "哇!这里这么多人,干什么这么热闹,可少不了小侠我.我说名门正派又怎么样,还不是一样赶尽杀绝,跟魔教又有什么两样,只不过藉口好听一点罢了.", "talkname0", 1);Talk(14, "都是你这个兔崽子,打伤了鹰王和我,", "talkname14", 0);
Talk(11, "还有我.", "talkname11", 0);
Talk(14, "害我们只剩下范右使应战,寡不敌众.....", "talkname14", 0);
Talk(0, "既然如此,我就帮你们打发这些人,当是陪罪好了.", "talkname0", 1);
Talk(70, "少侠非魔教人士,还请速速离去,以免受池鱼之殃.", "talkname70", 0);
Talk(0, "那好,大家都别打了,因为这中间着实有许多误会,让我好好说给你们听.", "talkname0", 1);
Talk(6, "现在年轻人都这么狂妄吗?你自以为是武林盟主吗!要我们听你说.", "talkname6", 0);
Talk(8, "你这小贼,跟魔教勾结,想要拖延时间,好施什么诡计么?先杀了你再说.", "talkname8", 0);
Talk(0, "我就知道要你们安安静静听我说是不太可能,那只有想办法让你们服气了.一起来吧,这样比较省事.", "talkname0", 1);
Talk(6, "好狂妄的口气.", "talkname6", 0);
Talk(70, "阿弥陀佛.", "talkname70", 0);
if TryBattle(12) == true then goto label0 end;
Dead();
do return end;
::label0::
--昆仑派
ModifyEvent(-2, 12, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-12
ModifyEvent(-2, 14, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-14
ModifyEvent(-2, 15, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-15
jyx2_ReplaceSceneObject("", "NPC/昆仑弟子12", "");
jyx2_ReplaceSceneObject("", "NPC/昆仑弟子14", "");
jyx2_ReplaceSceneObject("", "NPC/昆仑弟子15", "");
ModifyEvent(-2, 16, 0, 0, -1, -1, -1, 5434, 5434, 5434, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-16
ModifyEvent(-2, 17, 0, 0, -1, -1, -1, 5432, 5432, 5432, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-17
ModifyEvent(-2, 18, 0, 0, -1, -1, -1, 5434, 5434, 5434, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-18
jyx2_SwitchRoleAnimation("NPC/昆仑弟子16","Assets/BuildSource/AnimationControllers/Dead.controller");
jyx2_SwitchRoleAnimation("NPC/昆仑弟子17","Assets/BuildSource/AnimationControllers/Dead.controller");
jyx2_SwitchRoleAnimation("NPC/昆仑弟子18","Assets/BuildSource/AnimationControllers/Dead.controller");
--崆峒派
ModifyEvent(-2, 20, 0, 0, -1, -1, -1, 5428, 5428, 5428, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-20
jyx2_SwitchRoleAnimation("NPC/崆峒弟子20","Assets/BuildSource/AnimationControllers/Dead.controller");
ModifyEvent(-2, 21, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-21
ModifyEvent(-2, 22, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-22
ModifyEvent(-2, 23, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-23
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子21", "");
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子22", "");
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子23", "");
ModifyEvent(-2, 24, 0, 0, -1, -1, -1, 5428, 5428, 5428, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-24
jyx2_SwitchRoleAnimation("NPC/崆峒弟子24","Assets/BuildSource/AnimationControllers/Dead.controller");
ModifyEvent(-2, 25, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-25
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子25", "");
ModifyEvent(-2, 26, 0, 0, -1, -1, -1, 5430, 5430, 5430, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-26
jyx2_SwitchRoleAnimation("NPC/崆峒弟子26","Assets/BuildSource/AnimationControllers/Dead.controller");
ModifyEvent(-2, 27, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-27
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子27", "");
--华山派
ModifyEvent(-2, 29, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-29
ModifyEvent(-2, 32, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-32
ModifyEvent(-2, 33, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-33
ModifyEvent(-2, 34, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-34
ModifyEvent(-2, 35, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-35
jyx2_ReplaceSceneObject("", "NPC/华山弟子29", "");
jyx2_ReplaceSceneObject("", "NPC/华山弟子32", "");
jyx2_ReplaceSceneObject("", "NPC/华山弟子33", "");
jyx2_ReplaceSceneObject("", "NPC/华山弟子34", "");
jyx2_ReplaceSceneObject("", "NPC/华山弟子35", "");
--少林派
ModifyEvent(-2, 38, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-38
jyx2_ReplaceSceneObject("", "NPC/少林弟子38", "");
ModifyEvent(-2, 39, 0, 0, -1, -1, -1, 5446, 5446, 5446, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-39
jyx2_SwitchRoleAnimation("NPC/少林弟子39","Assets/BuildSource/AnimationControllers/Dead.controller");
ModifyEvent(-2, 40, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-40
jyx2_ReplaceSceneObject("", "NPC/少林弟子40", "");
ModifyEvent(-2, 41, 0, 0, -1, -1, -1, 5444, 5444, 5444, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-41
jyx2_SwitchRoleAnimation("NPC/少林弟子41","Assets/BuildSource/AnimationControllers/Dead.controller");
ModifyEvent(-2, 42, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-42
ModifyEvent(-2, 43, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-43
jyx2_ReplaceSceneObject("", "NPC/少林弟子42", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子43", "");
ModifyEvent(-2, 44, 0, 0, -1, -1, -1, 5444, 5444, 5444, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-44
jyx2_SwitchRoleAnimation("NPC/少林弟子44","Assets/BuildSource/AnimationControllers/Dead.controller");
ModifyEvent(-2, 45, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-45
jyx2_ReplaceSceneObject("", "NPC/少林弟子45", "");
ModifyEvent(-2, 46, 0, 0, -1, -1, -1, 5446, 5446, 5446, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-46
jyx2_SwitchRoleAnimation("NPC/少林弟子46","Assets/BuildSource/AnimationControllers/Dead.controller");
--峨嵋
ModifyEvent(-2, 48, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-48
ModifyEvent(-2, 51, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-51
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子48", "");
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子51", "");
ModifyEvent(-2, 52, 0, 0, -1, -1, -1, 5436, 5436, 5436, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-52
ModifyEvent(-2, 53, 0, 0, -1, -1, -1, 5438, 5438, 5438, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-53
jyx2_SwitchRoleAnimation("NPC/峨嵋弟子52","Assets/BuildSource/AnimationControllers/Dead.controller");
jyx2_SwitchRoleAnimation("NPC/峨嵋弟子53","Assets/BuildSource/AnimationControllers/Dead.controller");
ModifyEvent(-2, 54, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-54
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子54", "");
ModifyEvent(-2, 55, 0, 0, -1, -1, -1, 5436, 5436, 5436, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-55
jyx2_SwitchRoleAnimation("NPC/峨嵋弟子55","Assets/BuildSource/AnimationControllers/Dead.controller");
ModifyEvent(-2, 56, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-56
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子56", "");
--武当
ModifyEvent(-2, 58, 0, 0, -1, -1, -1, 5442, 5442, 5442, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-58
jyx2_SwitchRoleAnimation("NPC/武当弟子58","Assets/BuildSource/AnimationControllers/Dead.controller");
ModifyEvent(-2, 59, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-59
jyx2_ReplaceSceneObject("", "NPC/武当弟子59", "");
ModifyEvent(-2, 60, 0, 0, -1, -1, -1, 5440, 5440, 5440, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-60
jyx2_SwitchRoleAnimation("NPC/武当弟子60","Assets/BuildSource/AnimationControllers/Dead.controller");
ModifyEvent(-2, 61, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-61
jyx2_ReplaceSceneObject("", "NPC/武当弟子61", "");
ModifyEvent(-2, 62, 0, 0, -1, -1, -1, 5442, 5442, 5442, -2, -2, -2);--by fanyu|改变贴图,战斗胜利。场景11-62
jyx2_SwitchRoleAnimation("NPC/武当弟子62","Assets/BuildSource/AnimationControllers/Dead.controller");
ModifyEvent(-2, 63, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|战斗胜利,贴图消失。场景11-63
jyx2_ReplaceSceneObject("", "NPC/武当弟子63", "");
LightScence();
Talk(0, "如何?现在肯安静地听我说了吧.事情的经过是这样的...如此如此........这般这般........总之,一切的阴谋,都是成昆那奸贼所计划的.所以我说呢,你们两方还是握手言和吧,反正明教杀过六大派的人,六大派也杀过明教的人,大家半斤八两,差不了多少,就都罢手吧.", "talkname0", 1);
Talk(8, "话都是你在说的,是不是真的,我们怎么知道.", "talkname8", 0);
Talk(6, "哼!技不如人,说这么多做什么,走吧!", "talkname6", 0);
Talk(70, "阿弥陀佛,盼少侠以后多所规劝引导,总要使明教改邪归正,少做坏事.我们走吧.", "talkname70", 0);
DarkScence();
ModifyEvent(-2, 7, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu|贴图消失。场景11-以下都是
jyx2_ReplaceSceneObject("", "NPC/hetaichong", "");
ModifyEvent(-2, 8, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
jyx2_ReplaceSceneObject("", "NPC/tangwenliang", "");
ModifyEvent(-2, 9, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
jyx2_ReplaceSceneObject("", "NPC/xuanci", "");
ModifyEvent(-2, 10, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
jyx2_ReplaceSceneObject("", "NPC/miejue", "");
--昆仑
ModifyEvent(-2, 11, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 12, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 13, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 14, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 15, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 16, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 17, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 18, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 19, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
jyx2_ReplaceSceneObject("", "NPC/昆仑弟子11", "");
jyx2_ReplaceSceneObject("", "NPC/昆仑弟子12", "");
jyx2_ReplaceSceneObject("", "NPC/昆仑弟子13", "");
jyx2_ReplaceSceneObject("", "NPC/昆仑弟子14", "");
jyx2_ReplaceSceneObject("", "NPC/昆仑弟子15", "");
jyx2_ReplaceSceneObject("", "NPC/昆仑弟子16", "");
jyx2_ReplaceSceneObject("", "NPC/昆仑弟子17", "");
jyx2_ReplaceSceneObject("", "NPC/昆仑弟子18", "");
jyx2_ReplaceSceneObject("", "NPC/昆仑弟子19-死", "");
--崆峒
ModifyEvent(-2, 20, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 21, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 22, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 23, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 24, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 25, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 26, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 27, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 28, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子20", "");
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子21", "");
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子22", "");
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子23", "");
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子24", "");
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子25", "");
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子26", "");
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子27", "");
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子28-死", "");
--华山
ModifyEvent(-2, 29, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 30, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 31, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 32, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 33, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 34, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 35, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
jyx2_ReplaceSceneObject("", "NPC/华山弟子29", "");
jyx2_ReplaceSceneObject("", "NPC/华山弟子30", "");
jyx2_ReplaceSceneObject("", "NPC/华山弟子31", "");
jyx2_ReplaceSceneObject("", "NPC/华山弟子32", "");
jyx2_ReplaceSceneObject("", "NPC/华山弟子33", "");
jyx2_ReplaceSceneObject("", "NPC/华山弟子34", "");
jyx2_ReplaceSceneObject("", "NPC/华山弟子35", "");
--少林
ModifyEvent(-2, 36, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 37, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 38, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 39, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 40, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 41, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 42, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 43, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 44, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 45, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 46, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 47, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
jyx2_ReplaceSceneObject("", "NPC/少林弟子36", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子37", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子38", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子39", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子40", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子41", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子42", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子43", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子44", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子45", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子46", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子47-死", "");
--峨嵋
ModifyEvent(-2, 48, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 49, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 50, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 51, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 52, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 53, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 54, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 55, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 56, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 57, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子48", "");
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子49", "");
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子50", "");
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子51", "");
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子52", "");
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子53", "");
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子54", "");
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子55", "");
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子56", "");
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子57-死", "");
--武当
ModifyEvent(-2, 58, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 59, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 60, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 61, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 62, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 63, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 64, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
jyx2_ReplaceSceneObject("", "NPC/武当弟子58", "");
jyx2_ReplaceSceneObject("", "NPC/武当弟子59", "");
jyx2_ReplaceSceneObject("", "NPC/武当弟子60", "");
jyx2_ReplaceSceneObject("", "NPC/武当弟子61", "");
jyx2_ReplaceSceneObject("", "NPC/武当弟子62", "");
jyx2_ReplaceSceneObject("", "NPC/武当弟子63", "");
jyx2_ReplaceSceneObject("", "NPC/武当弟子64", "");
ModifyEvent(-2, 65, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 66, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 67, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 68, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 69, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 70, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
jyx2_ReplaceSceneObject("", "NPC/崆峒弟子65-死", "");
jyx2_ReplaceSceneObject("", "NPC/峨嵋弟子66-死", "");
jyx2_ReplaceSceneObject("", "NPC/武当弟子68-死", "");
jyx2_ReplaceSceneObject("", "NPC/少林弟子69-死", "");
--明教
ModifyEvent(-2, 79, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 80, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 81, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 82, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 83, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 84, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
jyx2_ReplaceSceneObject("", "NPC/明教弟子79", "");
jyx2_ReplaceSceneObject("", "NPC/明教弟子80", "");
jyx2_ReplaceSceneObject("", "NPC/明教弟子81", "");
jyx2_ReplaceSceneObject("", "NPC/明教弟子82", "");
jyx2_ReplaceSceneObject("", "NPC/明教弟子83", "");
jyx2_ReplaceSceneObject("", "NPC/明教弟子84", "");
ModifyEvent(-2, 96, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 97, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 98, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 99, 0, 0, -1, -1, 89, -1, -1, -1, -2, -2, -2);--by fanyu|启动脚本-89。场景11-99
ModifyEvent(-2, 3, 1, 1, 83, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-83改变对话。场景11-3
ModifyEvent(-2, 4, 1, 1, 84, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-84改变对话。场景11-4
ModifyEvent(-2, 5, 1, 1, 85, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-85改变对话。场景11-5
ModifyEvent(-2, 6, 1, 1, 88, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-88改变对话。场景11-6
ModifyEvent(-2, 77, 1, 1, 87, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-87改变对话。场景11-77
ModifyEvent(-2, 78, 1, 1, 87, -1, -1, -2, -2, -2, -2, -2, -2);--by fanyu|启动脚本-87改变对话。场景11-78
SetScencePosition2(29, 34);
jyx2_MovePlayer("placeholder","Level/Dynamic");
LightScence();
Talk(14, "小子,你还不赖嘛!", "talkname14", 0);
Talk(10, "蝠王,不可无礼.明教全教下上,叩谢少侠护教救命的大恩!", "talkname10", 0);
Talk(0, "快别这么说,仗义行侠,本就是我辈中人应当做的.况且,这次也因为我的鲁莽,害你们陷入苦战.", "talkname0", 1);
Talk(12, "那里,是我们没问清楚.", "talkname12", 0);
Talk(14, "你们也别这么客套了.这样吧,大家听我一言,我说呢,这位少侠武功盖世义薄云天,于本教有存亡续绝的大恩.咱们拥立他为本教第三十四任教主.由他来做教主,总比你来做教主好吧,杨左使,你说对不对啊.", "talkname14", 0);
Talk(11, "是啊!这位少侠来做我们教主,也比你韦一笑来做好的多.", "talkname11", 0);
Talk(14, "你....", "talkname14", 0);
Talk(10, "你们两个别在那里吵了,丢人现眼的.", "talkname10", 0);
Talk(0, "不,不,在下我虽然一直梦想能当个什么掌门教主的.但是我仍有要事在身,且跟你们是不同世界的人,所以你们还是另觅他人吧.", "talkname0", 1);
Talk(10, "少侠如果一直推却不肯,我们明教恐怕又要为此争闹不休,四分五裂,到时又会被其他门派围攻,导致灭亡了.", "talkname10", 0);
Talk(0, "我这里有封阳教主的遗书,上面提到要谢逊谢法王暂代教主之职.我想你们还是先找到他再说吧.", "talkname0", 1);
Talk(10, "哦!真是如此,来人啊!即刻通令下去,全力寻找谢法王.", "talkname10", 0);
Talk(0, "另外还有一件事拜托你们,你们明教中是否有一本叫”倚天屠龙记”的书?是否能借我一下.", "talkname0", 1);
Talk(10, "有的.阳教主曾对我提过,我们教中有一本奇书,是我明教镇教之宝,皆由历代教主相传而下.", "talkname10", 0);
Talk(0, "是吗?真的有.皇天不负苦心人,打了这么多场仗,终于让我找到了.", "talkname0", 1);
Talk(10, "可是,这本书因为阳教主的突然消失,其下落也无人知道了.", "talkname10", 0);
Talk(12, "少侠别担心,等我们找到谢法王,整顿好教务后,必当全力搜寻此书的下落.若有消息,定当告之少侠.", "talkname12", 0);
Talk(0, "好吧,也只有这样了.我有空也会帮你们找找谢前辈,在下这就告辞了.", "talkname0", 1);
Talk(10, "这里有块铁焰令,是我明教的信物.少侠在江湖上行走,若有什么困难需要我明教帮忙的时后,只须出示这块铁焰令,我明教全体教众一定全力相助.", "talkname10", 0);
AddItem(190, 1);
AddEthics(10);
AddRepute(15);
do return end;
|
--[[
Jogo Cobra
# Tentar a ideia de manter todo o corpo no corpo, ou seja, sem a separação da cabeça e corpo.
]]--
require "cobra"
require "comida"
function love.load(arg)
if arg[#arg] == "-debug" then require("mobdebug").start() end -- Debug para ZeroBrane Studio IDE Utilize; Argumento - arg esta disponivel global.
lgrafico.setBackgroundColor(rgbByte({60 ,179, 113}))
cascavel = cobra.novo()
maca = comida.novo()
end
function love.update(dt)
if not update then
return
end
cascavel:update(dt, maca)
end
function love.draw()
maca:draw()
cascavel:draw()
end
function love.keypressed(tecla, cod, repeticao)
if tecla == "f1" then
update = not update
elseif tecla == "f5" then
love.load(arg)
end
cascavel:controle(tecla)
end
function love.keyreleased(tecla, cod)
end
function love.mousepressed(x, y, botao, toque, repeticao)
end
function love.mousereleased(x, y, botao, toque, repeticao)
end
function love.mousemoved(x, y, dx, dy, toque)
end
function love.wheelmoved(x, y)
end
function love.mousefocus(foco)
end
function love.resize(c, l)
end
function love.focus(foco)
end
function love.quit()
end
--[[
function inicioContato(a, b, contato)
end
function fimContato(a, b, contato)
end
function preContato(a, b, contato)
end
--function posContato(a, b, contato, normalImpulso, tangenteImpulso, normalImpulso1, tangenteImpulso1)
function posContato(a, b, contato, normalImpulso, tangenteImpulso)
end
function love.touchpressed(id, x, y, dx, dy, pressao)
end
function love.touchreleased(id, x, y, dx, dy, pressao)
end
function love.touchmoved(id, x, y, dx, dy, pressao)
end
function love.displayrotated(indice, orientacao)
end
function love.textedited(texto, inicio, tamanho)
end
function love.textinput(texto)
end
function love.directorydropped(caminho)
end
function love.filedropped(arquivo)
end
function love.errorhandler(erro)
end
function love.lowmemory()
end
function love.threaderror(thread, erro)
end
function love.visible(visivel)-- Esta funcao CallBack não funciona, utilize visivel = love.window.isMinimized()
end
--]]
|
-- army.lua
Army = Object:extend()
function Army:new()
self.transform = Transform(0, 0, 1, 1)
self.troops = {}
-- spawn points
self.points = {}
self.points.top = Transform(
love.graphics.getWidth() / 2,
-32,
1,
1
).position
self.points.bottom = Transform(
love.graphics.getWidth() / 2,
love.graphics.getHeight() + 32,
1,
1
).position
self.points.left = Transform(
-32,
love.graphics.getHeight() / 2,
1,
1
).position
self.points.right = Transform(
love.graphics.getWidth() + 32,
love.graphics.getHeight() / 2,
1,
1
).position
-- difficulty
self.difficulty = 1 -- lower values are harder
self.timer = self.difficulty
self.speed = 128
self.speedup = 4
self.maxspeed = 512
end
function Army:update(deltaTime)
-- debug controls
if debug then
-- do debug stuff...
end
self.speed = math.min(self.speed + self.speedup * deltaTime, self.maxspeed)
-- update all enlisted troops
for key, troop in ipairs(self.troops) do
troop:update(deltaTime)
end
-- tick timers downward
self.timer = math.max(self.timer - deltaTime, 0)
if self.timer == 0 then
self:enlist(Spear, self:getRandomPoint())
self.timer = self.difficulty + (math.random() * self.difficulty / 2)
end
self:teardown()
end
function Army:draw(deltaTime)
for key, troop in ipairs(self.troops) do
troop:draw()
end
end
function Army:teardown()
for i = #self.troops, 1, -1 do
-- get a local instance of the troop
local troop = self.troops[i]
if troop.destroyed then
-- remove that troop
table.remove(self.troops, i)
end
end
end
function Army:enlist(kind, position)
local direction = 0
sounds.throw:play()
-- figure out where that troop should move towards
-- based on where it spawned
if position == self.points.top then
-- go down
direction = 180
elseif position == self.points.top then
-- go up
direction = 0
elseif position == self.points.left then
-- go right
direction = 90
elseif position == self.points.right then
-- go left
direction = 270
end
-- enlist that kind of troop
table.insert(
self.troops,
kind(
position.x,
position.y,
direction,
self.speed
)
)
end
function Army:getRandomPoint()
local points = {}
-- make a copy of the spawn points using numerical keys
for key, point in pairs(self.points) do
table.insert(
points,
point
)
end
-- return a random index
local selected = math.floor(math.random() * #points + 1)
return points[selected]
end
function Army:resetTimer()
end
|
--[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------
-- columnlistarea class
local newobject = loveframes.NewObject("columnlistarea", "loveframes_object_columnlistarea", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: intializes the element
--]]---------------------------------------------------------
function newobject:initialize(parent)
self.type = "columnlistarea"
self.display = "vertical"
self.parent = parent
self.width = 80
self.height = 25
self.clickx = 0
self.clicky = 0
self.offsety = 0
self.offsetx = 0
self.extrawidth = 0
self.extraheight = 0
self.rowcolorindex = 1
self.rowcolorindexmax = 2
self.buttonscrollamount = parent.buttonscrollamount
self.mousewheelscrollamount = parent.mousewheelscrollamount
self.bar = false
self.dtscrolling = parent.dtscrolling
self.internal = true
self.internals = {}
self.children = {}
-- apply template properties to the object
loveframes.templates.ApplyToObject(self)
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
local cwidth, cheight = self.parent:GetColumnSize()
local parent = self.parent
local base = loveframes.base
local update = self.Update
local internals = self.internals
local children = self.children
self:CheckHover()
-- move to parent if there is a parent
if parent ~= base then
self.x = parent.x + self.staticx
self.y = parent.y + self.staticy
end
for k, v in ipairs(internals) do
v:update(dt)
end
for k, v in ipairs(children) do
local col = loveframes.util.BoundingBox(self.x, v.x, self.y, v.y, self.width, v.width, self.height, v.height)
if col then
v:update(dt)
end
v:SetClickBounds(self.x, self.y, self.width, self.height)
v.y = (v.parent.y + v.staticy) - self.offsety + cheight
v.x = (v.parent.x + v.staticx) - self.offsetx
end
if update then
update(self, dt)
end
end
--[[---------------------------------------------------------
- func: draw()
- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()
local visible = self.visible
if not visible then
return
end
local x = self.x
local y = self.y
local width = self.width
local height = self.height
local stencilfunc = function() love.graphics.rectangle("fill", x, y, width, height) end
local loveversion = love._version
local skins = loveframes.skins.available
local skinindex = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = skins[selfskin] or skins[skinindex]
local drawfunc = skin.DrawColumnListArea or skins[defaultskin].DrawColumnListArea
local drawoverfunc = skin.DrawOverColumnListArea or skins[defaultskin].DrawOverColumnListArea
local draw = self.Draw
local drawcount = loveframes.drawcount
local internals = self.internals
local children = self.children
-- set the object's draw order
self:SetDrawOrder()
if draw then
draw(self)
else
drawfunc(self)
end
if loveversion == "0.8.0" then
local stencil = love.graphics.newStencil(stencilfunc)
love.graphics.setStencil(stencil)
else
love.graphics.setStencil(stencilfunc)
end
for k, v in ipairs(children) do
local col = loveframes.util.BoundingBox(self.x, v.x, self.y, v.y, self.width, v.width, self.height, v.height)
if col then
v:draw()
end
end
love.graphics.setStencil()
for k, v in ipairs(internals) do
v:draw()
end
if not draw then
skin.DrawOverColumnListArea(self)
end
end
--[[---------------------------------------------------------
- func: mousepressed(x, y, button)
- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function newobject:mousepressed(x, y, button)
local toplist = self:IsTopList()
local scrollamount = self.mousewheelscrollamount
local internals = self.internals
local children = self.children
if self.hover and button == "l" then
local baseparent = self:GetBaseParent()
if baseparent and baseparent.type == "frame" then
baseparent:MakeTop()
end
end
if self.bar and toplist then
local bar = self:GetScrollBar()
local dtscrolling = self.dtscrolling
if dtscrolling then
local dt = love.timer.getDelta()
if button == "wu" then
bar:Scroll(-scrollamount * dt)
elseif button == "wd" then
bar:Scroll(scrollamount * dt)
end
else
if button == "wu" then
bar:Scroll(-scrollamount)
elseif button == "wd" then
bar:Scroll(scrollamount)
end
end
end
for k, v in ipairs(internals) do
v:mousepressed(x, y, button)
end
for k, v in ipairs(children) do
v:mousepressed(x, y, button)
end
end
--[[---------------------------------------------------------
- func: mousereleased(x, y, button)
- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function newobject:mousereleased(x, y, button)
local internals = self.internals
local children = self.children
for k, v in ipairs(internals) do
v:mousereleased(x, y, button)
end
for k, v in ipairs(children) do
v:mousereleased(x, y, button)
end
end
--[[---------------------------------------------------------
- func: CalculateSize()
- desc: calculates the size of the object's children
--]]---------------------------------------------------------
function newobject:CalculateSize()
local columnheight = self.parent.columnheight
local numitems = #self.children
local height = self.height
local width = self.width
local itemheight = columnheight
local itemwidth = 0
local bar = self.bar
local children = self.children
for k, v in ipairs(children) do
itemheight = itemheight + v.height
end
self.itemheight = itemheight
if self.itemheight > height then
self.extraheight = self.itemheight - height
if not bar then
table.insert(self.internals, loveframes.objects["scrollbody"]:new(self, "vertical"))
self.bar = true
self:GetScrollBar().autoscroll = self.parent.autoscroll
end
else
if bar then
self.internals[1]:Remove()
self.bar = false
self.offsety = 0
end
end
end
--[[---------------------------------------------------------
- func: RedoLayout()
- desc: used to redo the layour of the object
--]]---------------------------------------------------------
function newobject:RedoLayout()
local children = self.children
local starty = 0
local startx = 0
local bar = self.bar
local display = self.display
if #children > 0 then
for k, v in ipairs(children) do
local height = v.height
v.staticx = startx
v.staticy = starty
if bar then
v:SetWidth(self.width - self.internals[1].width)
self.internals[1].staticx = self.width - self.internals[1].width
self.internals[1].height = self.height
else
v:SetWidth(self.width)
end
starty = starty + v.height
v.lastheight = v.height
end
end
end
--[[---------------------------------------------------------
- func: AddRow(data)
- desc: adds a row to the object
--]]---------------------------------------------------------
function newobject:AddRow(data)
local row = loveframes.objects["columnlistrow"]:new(self, data)
local colorindex = self.rowcolorindex
local colorindexmax = self.rowcolorindexmax
if colorindex == colorindexmax then
self.rowcolorindex = 1
else
self.rowcolorindex = colorindex + 1
end
table.insert(self.children, row)
self:CalculateSize()
self:RedoLayout()
self.parent:AdjustColumns()
end
--[[---------------------------------------------------------
- func: GetScrollBar()
- desc: gets the object's scroll bar
--]]---------------------------------------------------------
function newobject:GetScrollBar()
local internals = self.internals
if self.bar then
local scrollbody = internals[1]
local scrollarea = scrollbody.internals[1]
local scrollbar = scrollarea.internals[1]
return scrollbar
else
return false
end
end
--[[---------------------------------------------------------
- func: Sort()
- desc: sorts the object's children
--]]---------------------------------------------------------
function newobject:Sort(column, desc)
self.rowcolorindex = 1
local colorindexmax = self.rowcolorindexmax
local children = self.children
table.sort(children, function(a, b)
if desc then
return (tostring(a.columndata[column]) or a.columndata[column]) < (tostring(b.columndata[column]) or b.columndata[column])
else
return (tostring(a.columndata[column]) or a.columndata[column]) > (tostring(b.columndata[column]) or b.columndata[column])
end
end)
for k, v in ipairs(children) do
local colorindex = self.rowcolorindex
v.colorindex = colorindex
if colorindex == colorindexmax then
self.rowcolorindex = 1
else
self.rowcolorindex = colorindex + 1
end
end
self:CalculateSize()
self:RedoLayout()
end
--[[---------------------------------------------------------
- func: Clear()
- desc: removes all items from the object's list
--]]---------------------------------------------------------
function newobject:Clear()
self.children = {}
self:CalculateSize()
self:RedoLayout()
self.parent:AdjustColumns()
end
|
-- conf.lua
--
-- @about Describes the configuration of the game.
-- @brief Config function called before any other function.
-- @param t Table holding configuration settings.
function love.conf(t)
-- misc
t.version = "11.2" -- LÖVE version this game was made for
t.console = false
t.gammacorrect = false
-- audio
t.audio.mixwithsysem = true
-- window
t.window.title = "Game Basics"
t.window.icon = "assets/logo.png"
t.window.width = 800
t.window.height = 600
t.window.borderless = false
t.window.resizable = false
t.window.fullscreen = false
t.window.fullscreentype = "desktop"
t.window.vsync = 1
t.window.msaa = 0
t.window.depth = 0
t.window.display = 1
t.window.x = nil
t.window.y = nil
-- modules
t.modules.joystick = false
t.modules.touch = false
t.modules.video = false
end
|
local status_ok, lightspeed = pcall(require, "lightspeed")
if not status_ok then
vim.notify("lightspeed not found")
return
end
lightspeed.setup({
ignore_case = false,
exit_after_idle_msecs = { unlabeled = 1000, labeled = nil },
--- s/x ---
jump_to_unique_chars = { safety_timeout = 400 },
match_only_the_start_of_same_char_seqs = true,
force_beacons_into_match_width = false,
-- Display characters in a custom way in the highlighted matches.
substitute_chars = { ['\r'] = '¬', },
-- Leaving the appropriate list empty effectively disables "smart" mode,
-- and forces auto-jump to be on or off.
safe_labels = {
"s", "f", "n", "u", "t", "/", "F", "L",
"N", "H", "G", "M", "U", "T", "?", "Z"
},
labels = {
"s", "f", "n",
"j", "k", "l", "o", "d", "w", "e", "h", "m", "v", "g",
"u", "t", "c", ".", "z",
"/", "F", "L", "N", "H", "G", "M", "U", "T", "?", "Z"
},
-- These keys are captured directly by the plugin at runtime.
special_keys = {
next_match_group = '<space>',
prev_match_group = '<tab>',
},
--- f/t ---
limit_ft_matches = 4,
repeat_ft_with_target_char = false,
})
|
-- Attempt to map the monadic DSL style to Lua.
--
-- The basic idea is to implement a "pure" DSL that represents a
-- dataflow network. I've used two approaches for this in the past: a
-- Monadic DSL in Haskell, and an Erlang implementation with an effect
-- handler. For Lua it seems the simplest approach is to duplicate
-- the effect handler approach on top of actor.lua tasks.
-- See erl_tools/src/dsl.erl
local dsl = {}
return dsl
|
-- Convert degrees to radians.
local function radians(d)
return math.pi / 180 * d
end
-- Convert radians to degrees.
local function degrees(r)
return 180 / math.pi * r
end
-- Module exports.
return {
radians = radians,
degrees = degrees
}
|
regularization = {}
function regularization.applyregularization(rbm)
if rbm.sparsity > 0 then
-- rbm.db:add(-rbm.sparsity) -- db is bias of visible layer
rbm.dc:add(-rbm.sparsity) -- dc is bias of hidden layer
-- rbm.dd:add(-rbm.sparsity) -- dd is bias of "label" layer
end
if rbm.L1 > 0 then
rbm.dW:add( -torch.sign(rbm.dW):mul(rbm.L1) )
if rbm.toprbm then
rbm.dU:add( -torch.sign(rbm.dU):mul(rbm.L1) )
end
end
if rbm.L2 > 0 then
rbm.dW:add( -torch.mul(rbm.dW,rbm.L2 ) )
if rbm.toprbm then
rbm.dU:add( -torch.mul(rbm.dU,rbm.L2 ) )
end
end
end
function regularization.dropout(rbm)
-- Create dropout mask for hidden units
if rbm.dropout > 0 then
rbm.dropout_mask = torch.lt( torch.rand(1,rbm.n_hidden),rbm.dropout ):typeAs(rbm.W)
end
end
|
object_tangible_furniture_all_frn_all_lamp_tbl_s02 = object_tangible_furniture_all_shared_frn_all_lamp_tbl_s02:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_all_frn_all_lamp_tbl_s02, "object/tangible/furniture/all/frn_all_lamp_tbl_s02.iff")
|
--[[
This file is part of halimede. It is subject to the licence terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/pallene/halimede/master/COPYRIGHT. No part of halimede, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
Copyright © 2015 The developers of halimede. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/pallene/halimede/master/COPYRIGHT.
]]--
local halimede = require('halimede')
local assert = halimede.assert
assert.globalTypeIsFunctionOrCall('pairs', 'setmetatable', 'getmetatable')
local function moduleclass(...)
local newClass = halimede.class(...)
local moduleClass = module
for key, value in pairs(newClass) do
moduleClass[key] = value
end
setmetatable(moduleClass, getmetatable(newClass))
return moduleClass
end
halimede.moduleclass = moduleclass
|
-- Copyright (C) 2018 The Dota IMBA Development Team
--
-- 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.
--
-- Editors:
--
-- Author - d2imba
-- Date Created - 15.08.2015 <-- Shits' ancient yo
-- Date Updated - 05.03.2020 (AltiV)
-- Converted to Lua by zimberzimber
-----------------------------------------------------------------------------------------------------------
-- Item Definition
-----------------------------------------------------------------------------------------------------------
if item_imba_octarine_core == nil then item_imba_octarine_core = class({}) end
LinkLuaModifier( "modifier_imba_octarine_core_basic", "components/items/item_octarine_core.lua", LUA_MODIFIER_MOTION_NONE ) -- Item stats
function item_imba_octarine_core:GetAbilityTextureName()
return "custom/imba_octarine_core"
end
function item_imba_octarine_core:GetIntrinsicModifierName()
return "modifier_imba_octarine_core_basic" end
function item_imba_octarine_core:OnSpellStart()
-- Play sound only to the caster
self:GetCaster():EmitSound("Item.DropGemWorld")
if self:GetCaster():GetModifierStackCount("modifier_imba_octarine_core_basic", self:GetCaster()) == 1 then
for _, mod in pairs(self:GetParent():FindAllModifiersByName(self:GetIntrinsicModifierName())) do
mod:SetStackCount(2)
end
else
for _, mod in pairs(self:GetParent():FindAllModifiersByName(self:GetIntrinsicModifierName())) do
mod:SetStackCount(1)
end
end
-- Ignore the item's cooldown
self:EndCooldown()
end
function item_imba_octarine_core:GetAbilityTextureName()
if self:GetCaster():GetModifierStackCount("modifier_imba_octarine_core_basic", self:GetCaster()) == 1 then
return "custom/imba_octarine_core_off"
else
return "custom/imba_octarine_core"
end
end
-----------------------------------------------------------------------------------------------------------
-- Basic modifier definition
-----------------------------------------------------------------------------------------------------------
if modifier_imba_octarine_core_basic == nil then modifier_imba_octarine_core_basic = class({}) end
function modifier_imba_octarine_core_basic:IsHidden() return true end
function modifier_imba_octarine_core_basic:IsPurgable() return false end
function modifier_imba_octarine_core_basic:RemoveOnDeath() return false end
function modifier_imba_octarine_core_basic:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
function modifier_imba_octarine_core_basic:OnCreated()
if IsServer() then
if not self:GetAbility() then self:Destroy() end
end
if not IsServer() then return end
self:SetStackCount(2)
-- Use Secondary Charges system to make CDR not stack with multiple Octarine Cores
for _, mod in pairs(self:GetParent():FindAllModifiersByName(self:GetName())) do
mod:GetAbility():SetSecondaryCharges(_)
end
end
function modifier_imba_octarine_core_basic:OnDestroy()
if not IsServer() then return end
for _, mod in pairs(self:GetParent():FindAllModifiersByName(self:GetName())) do
mod:GetAbility():SetSecondaryCharges(_)
end
end
function modifier_imba_octarine_core_basic:DeclareFunctions()
return {
MODIFIER_PROPERTY_MANA_BONUS,
MODIFIER_PROPERTY_HEALTH_BONUS,
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_EVENT_ON_TAKEDAMAGE,
MODIFIER_PROPERTY_COOLDOWN_PERCENTAGE,
MODIFIER_EVENT_ON_SPENT_MANA,
}
end
function modifier_imba_octarine_core_basic:GetModifierManaBonus()
if self:GetAbility() then
return self:GetAbility():GetSpecialValueFor("bonus_mana")
end
end
function modifier_imba_octarine_core_basic:GetModifierHealthBonus()
if self:GetAbility() then
return self:GetAbility():GetSpecialValueFor("bonus_health")
end
end
function modifier_imba_octarine_core_basic:GetModifierBonusStats_Intellect()
if self:GetAbility() then
return self:GetAbility():GetSpecialValueFor("bonus_intelligence")
end
end
--- Enum DamageCategory_t
-- DOTA_DAMAGE_CATEGORY_ATTACK = 1
-- DOTA_DAMAGE_CATEGORY_SPELL = 0
function modifier_imba_octarine_core_basic:OnTakeDamage( keys )
if keys.attacker == self:GetParent() and not keys.unit:IsBuilding() and not keys.unit:IsOther() then
-- Spell lifesteal handler
if self:GetParent():FindAllModifiersByName(self:GetName())[1] == self and keys.damage_category == DOTA_DAMAGE_CATEGORY_SPELL and keys.inflictor and bit.band(keys.damage_flags, DOTA_DAMAGE_FLAG_NO_SPELL_LIFESTEAL) ~= DOTA_DAMAGE_FLAG_NO_SPELL_LIFESTEAL then
-- Particle effect
self.lifesteal_pfx = ParticleManager:CreateParticle("particles/items3_fx/octarine_core_lifesteal.vpcf", PATTACH_ABSORIGIN_FOLLOW, keys.attacker)
ParticleManager:SetParticleControl(self.lifesteal_pfx, 0, keys.attacker:GetAbsOrigin())
ParticleManager:ReleaseParticleIndex(self.lifesteal_pfx)
-- "However, when attacking illusions, the heal is not affected by the illusion's changed incoming damage values."
-- This is EXTREMELY rough because I am not aware of any functions that can explicitly give you the incoming/outgoing damage of an illusion, or to give you the "displayed" damage when you're hitting illusions, which show numbers as if you were hitting a non-illusion.
if keys.unit:IsIllusion() then
if keys.damage_type == DAMAGE_TYPE_PHYSICAL and keys.unit.GetPhysicalArmorValue and GetReductionFromArmor then
keys.damage = keys.original_damage * (1 - GetReductionFromArmor(keys.unit:GetPhysicalArmorValue(false)))
elseif keys.damage_type == DAMAGE_TYPE_MAGICAL and keys.unit.GetMagicalArmorValue then
keys.damage = keys.original_damage * (1 - GetReductionFromArmor(keys.unit:GetMagicalArmorValue()))
elseif keys.damage_type == DAMAGE_TYPE_PURE then
keys.damage = keys.original_damage
end
end
if keys.unit:IsCreep() then
keys.attacker:Heal(math.max(keys.damage, 0) * self:GetAbility():GetSpecialValueFor("creep_lifesteal") * 0.01, keys.attacker)
else
keys.attacker:Heal(math.max(keys.damage, 0) * self:GetAbility():GetSpecialValueFor("hero_lifesteal") * 0.01, keys.attacker)
end
end
end
end
function modifier_imba_octarine_core_basic:GetModifierPercentageCooldown()
if self:GetAbility() and self:GetAbility():GetSecondaryCharges() == 1 then
return self:GetAbility():GetSpecialValueFor("bonus_cooldown")
end
end
function modifier_imba_octarine_core_basic:OnSpentMana( keys )
if self:GetAbility() and keys.unit == self:GetParent() and keys.unit:FindAllModifiersByName(self:GetName())[1] == self and self:GetStackCount() == 2 and self:GetAbility():IsCooldownReady() and keys.cost > 0 then -- [ 1 = disabled | 2 = enabled ]
self:GetAbility():UseResources(false, false, true)
-- Blast geometry
local blast_duration = 0.75 * 0.75
local blast_speed = self:GetAbility():GetSpecialValueFor("blast_radius") / blast_duration
-- Calculate damage
local damage = keys.cost * self:GetAbility():GetSpecialValueFor("blast_damage") * 0.01
-- Fire particle
local blast_pfx = ParticleManager:CreateParticle("particles/item/octarine_core/octarine_core_active.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetParent())
ParticleManager:SetParticleControl(blast_pfx, 1, Vector(100, 0, blast_speed))
ParticleManager:ReleaseParticleIndex(blast_pfx)
-- Fire sound
self:GetParent():EmitSound("Hero_Zuus.StaticField")
-- Damage units inside the blast radius if they haven't been affected already
for _, target in pairs(FindUnitsInRadius(self:GetParent():GetTeamNumber(), self:GetParent():GetAbsOrigin(), nil, self:GetAbility():GetSpecialValueFor("blast_radius"), DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do
-- Apply damage
ApplyDamage({attacker = self:GetParent(), victim = target, ability = self:GetAbility(), damage = damage, damage_type = DAMAGE_TYPE_MAGICAL})
-- Fire particle
local hit_pfx = ParticleManager:CreateParticle("particles/item/octarine_core/octarine_core_hit.vpcf", PATTACH_ABSORIGIN_FOLLOW, target)
ParticleManager:SetParticleControl(hit_pfx, 0, target:GetAbsOrigin())
ParticleManager:ReleaseParticleIndex(hit_pfx)
-- Print overhead message
SendOverheadEventMessage(nil, OVERHEAD_ALERT_BONUS_SPELL_DAMAGE, target, damage, nil)
end
end
end
|
------------------------------------------------------------------------
-- ContentLoss
------------------------------------------------------------------------
local ContentLoss, parent = torch.class('nn.ContentLoss', 'nn.Module')
function ContentLoss:__init(strength, target, normalize)
parent.__init(self)
self.strength = strength
self.target = target
self.normalize = normalize or false
self.loss = 0
self.crit = nn.MSECriterion()
end
function ContentLoss:updateOutput(input)
if input:nElement() == self.target:nElement() then
self.loss = self.crit:forward(input, self.target) * self.strength
else
-- print(input:size())
-- print(self.target:size())
-- print('WARNING: Skipping content loss')
end
self.output = input
return self.output
end
function ContentLoss:updateGradInput(input, gradOutput)
if input:nElement() == self.target:nElement() then
self.gradInput = self.crit:backward(input, self.target)
end
if self.normalize then
self.gradInput:div(torch.norm(self.gradInput, 1) + 1e-8)
end
self.gradInput:mul(self.strength)
self.gradInput:add(gradOutput)
return self.gradInput
end
function ContentLoss:update(other)
self.strength = other.strength
self.target = other.target
self.normalize = other.normalize
self.loss = other.loss
self.crit = other.crit
end
|
require("custom.utils")
local map = require("core.utils").map
vim.cmd("nnoremap <silent> <leader> :WhichKey '<Space>'<CR>")
map("n", "<leader>cc", ":Telescope <CR>")
map("n", "<leader>q", ":wqa <CR>")
map("n", "<leader>1", ":BufferLineGoToBuffer 1<CR>")
map("n", "<leader>2", ":BufferLineGoToBuffer 2<CR>")
map("n", "<leader>3", ":BufferLineGoToBuffer 3<CR>")
map("n", "<leader>4", ":BufferLineGoToBuffer 4<CR>")
map("n", "<leader>5", ":BufferLineGoToBuffer 5<CR>")
map("n", "<leader>6", ":BufferLineGoToBuffer 6<CR>")
map("n", "<leader>7", ":BufferLineGoToBuffer 7<CR>")
map("n", "<leader>8", ":BufferLineGoToBuffer 8<CR>")
map("n", "<leader>9", ":BufferLineGoToBuffer 9<CR>")
map("n", "<leader>mr", ":lua AsyncRunCode()<CR>")
map("n", "<leader>mc", ":lua SwitchConcealLevel()<CR>")
map("n", "<A-i>", ":lua require('FTerm').toggle()<CR>")
map("t", "<A-i>", "<C-\\><C-n>:lua require('FTerm').toggle()<CR>")
map("n", "<leader>tw", ":lua __fterm_wolfram()<CR>")
map("n", "<leader>tt", ":lua __fterm_btop()<CR>")
map("n", "<leader>tj", ":lua __fterm_julia()<CR>")
map("n", "<leader>tp", ":lua __fterm_python()<CR>")
-- Git diff keymap
map("n", "<leader>gdf", ":lua ToggleDiffView(false)<CR>")
map("n", "<leader>gdd", ":lua ToggleDiffView(true)<CR>")
map("n", "<leader>gdc", ":DiffviewClose<CR>")
-- MARP keymap
vim.cmd('au FileType markdown map <silent> <leader>mp :lua ToggleMarkdownPreview()<CR>')
vim.cmd [[
nmap ; <Plug>(eft-repeat)
xmap ; <Plug>(eft-repeat)
omap ; <Plug>(eft-repeat)
nmap f <Plug>(eft-f)
xmap f <Plug>(eft-f)
omap f <Plug>(eft-f)
nmap F <Plug>(eft-F)
xmap F <Plug>(eft-F)
omap F <Plug>(eft-F)
nmap t <Plug>(eft-t)
xmap t <Plug>(eft-t)
omap t <Plug>(eft-t)
nmap T <Plug>(eft-T)
xmap T <Plug>(eft-T)
omap T <Plug>(eft-T)
]]
vim.cmd [[
nmap j <Plug>(accelerated_jk_gj)
nmap k <Plug>(accelerated_jk_gk)
]]
|
-----------------------------------
-- Area: Lower Jeuno (245)
-- NPC: Mertaire
-- Starts and Finishes Quest: The Old Monument (start only), A Minstrel in Despair, Painful Memory (BARD AF1)
-- !pos -17 0 -61 245
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/keyitems")
require("scripts/globals/quests")
local ID = require("scripts/zones/Lower_Jeuno/IDs")
-----------------------------------
local POETIC_PARCHMENT = 634
function onTrade(player,npc,trade)
local theOldMonument = player:getQuestStatus(JEUNO,tpz.quest.id.jeuno.THE_OLD_MONUMENT)
local aMinstrelInDespair = player:getQuestStatus(JEUNO,tpz.quest.id.jeuno.A_MINSTREL_IN_DESPAIR)
-- A MINSTREL IN DESPAIR (poetic parchment)
if trade:hasItemQty(POETIC_PARCHMENT,1) and trade:getItemCount() == 1 and theOldMonument == QUEST_COMPLETED and aMinstrelInDespair == QUEST_AVAILABLE then
player:startEvent(101)
end
end
function onTrigger(player,npc)
local theOldMonument = player:getQuestStatus(JEUNO,tpz.quest.id.jeuno.THE_OLD_MONUMENT)
local painfulMemory = player:getQuestStatus(JEUNO,tpz.quest.id.jeuno.PAINFUL_MEMORY)
local theRequiem = player:getQuestStatus(JEUNO,tpz.quest.id.jeuno.THE_REQUIEM)
local circleOfTime = player:getQuestStatus(JEUNO,tpz.quest.id.jeuno.THE_CIRCLE_OF_TIME)
local job = player:getMainJob()
local level = player:getMainLvl()
-- THE OLD MONUMENT
if theOldMonument == QUEST_AVAILABLE and level >= ADVANCED_JOB_LEVEL then
player:startEvent(102)
-- PAINFUL MEMORY (Bard AF1)
elseif painfulMemory == QUEST_AVAILABLE and job == tpz.job.BRD and level >= AF1_QUEST_LEVEL then
if player:getCharVar("PainfulMemoryCS") == 0 then
player:startEvent(138) -- Long dialog for "Painful Memory"
else
player:startEvent(137) -- Short dialog for "Painful Memory"
end
elseif painfulMemory == QUEST_ACCEPTED then
player:startEvent(136) -- During Quest "Painful Memory"
-- CIRCLE OF TIME (Bard AF3)
elseif theRequiem == QUEST_COMPLETED and circleOfTime == QUEST_AVAILABLE and job == tpz.job.BRD and level >= AF3_QUEST_LEVEL then
player:startEvent(139) -- Start "The Circle of Time"
elseif circleOfTime == QUEST_ACCEPTED then
player:messageSpecial(ID.text.MERTAIRE_RING)
-- DEFAULT DIALOG
elseif painfulMemory == QUEST_COMPLETED then
player:startEvent(135) -- Standard dialog after completed "Painful Memory"
else
player:messageSpecial(ID.text.MERTAIRE_DEFAULT)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
-- THE OLD MONUMENT
if csid == 102 then
player:setCharVar("TheOldMonument_Event",1)
-- A MINSTREL IN DESPAIR
elseif csid == 101 then
player:addGil(GIL_RATE*2100)
player:messageSpecial(ID.text.GIL_OBTAINED, GIL_RATE*2100)
player:tradeComplete()
player:completeQuest(JEUNO,tpz.quest.id.jeuno.A_MINSTREL_IN_DESPAIR)
player:addFame(JEUNO, 30)
-- Placing this here allows the player to get additional poetic
-- parchments should they drop them until this quest is complete
player:setCharVar("TheOldMonument_Event",0)
-- PAINFUL MEMORY (Bard AF1)
elseif csid == 138 and option == 0 then
player:setCharVar("PainfulMemoryCS",1) -- player declined quest
elseif (csid == 137 or csid == 138) and option == 1 then
player:addQuest(JEUNO,tpz.quest.id.jeuno.PAINFUL_MEMORY)
player:setCharVar("PainfulMemoryCS",0)
player:addKeyItem(tpz.ki.MERTAIRES_BRACELET)
player:messageSpecial(ID.text.KEYITEM_OBTAINED,tpz.ki.MERTAIRES_BRACELET)
-- CIRCLE OF TIME (Bard AF3)
elseif csid == 139 then
player:addQuest(JEUNO,tpz.quest.id.jeuno.THE_CIRCLE_OF_TIME)
player:setCharVar("circleTime",1)
end
end
|
-- This is the v1.1
if CLIENT then
surface.CreateFont("Default_font", {
font = "Roboto",
extended = false,
size = 16
})
surface.CreateFont("NameWeapon_font", {
font = "Roboto",
extended = false,
size = 12
})
end
print("[SSHUD] Loading of cl_hud.lua completed.")
local HUDDisable = {
["DarkRP_HUD"] = true,
["CHudBattery"] = true,
["CHudHealth"] = true,
["CHudAmmo"] = true,
["CHudSecondaryAmmo"] = true
}
hook.Add("HUDShouldDraw", "HideHUD", function(name)
if HUDDisable[name] then return false end
end)
local function Base()
local ply = LocalPlayer()
local health = LocalPlayer():Health()
local armor = LocalPlayer():Armor()
local hunger = math.ceil(LocalPlayer():getDarkRPVar("Energy") or 0)
if not ply:Alive() then return end
if health < 1 then
health = -1
elseif health > 100 then
health = 100
end
if armor < 1 then
armor = 0
elseif armor > 99 then
armor = 100
end
if hunger < 1 then
hunger = -1
elseif hunger > 99 then
hunger = 103
end
if (GAMEMODE.Config.hungerspeed) then
surface.SetDrawColor(255, 255, 255, 255)
draw.RoundedBox(3, ScrW() * 0.004, ScrH() - 108, 109, 23, Color(20, 20, 20, 220))
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 106, 104, 19, Color(48, 48, 47, 170))
draw.DrawText(DarkRP.formatMoney(ply:getDarkRPVar("money")), "Default_font", 60, ScrH() - 105, Color(255, 255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
draw.RoundedBox(3, ScrW() * 0.004, ScrH() - 82, 109, 24, Color(20, 20, 20, 220))
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 80, 104, 20, Color(48, 48, 47, 170))
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 80, health * 1.10 - 6, 20, Color(255, 0, 0))
draw.RoundedBox(3, ScrW() * 0.004, ScrH() - 55, 109, 24, Color(20, 20, 20, 220))
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 53, 104, 20, Color(48, 48, 47, 170))
if armor < 1 then
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 53, armor, 20, Color(41, 11, 214))
elseif armor > 1 then
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 53, armor + 3, 20, Color(41, 11, 214))
end
draw.RoundedBox(3, ScrW() * 0.004, ScrH() - 28, 109, 24, Color(20, 20, 20, 220))
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 26, 104, 20, Color(48, 48, 47, 170))
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 26, hunger, 20, Color(224, 177, 20))
draw.RoundedBox(3, ScrW() - 120, ScrH() - 28, 109, 24, Color(20, 20, 20, 220))
draw.RoundedBox(3, ScrW() - 118, ScrH() - 26, 104.5, 20, Color(20, 20, 20, 170))
draw.RoundedBox(3, ScrW() - 120, ScrH() - 55, 109, 24, Color(20, 20, 20, 220))
draw.RoundedBox(3, ScrW() - 118, ScrH() - 53, 104.5, 20, Color(20, 20, 20, 170))
if (ply:GetActiveWeapon():GetPrintName() ~= nil) then
draw.SimpleText(ply:GetActiveWeapon():GetPrintName(), "NameWeapon_font", ScrW() - 110, ScrH() - 49, Color(255, 255, 255))
end
if (ply:GetActiveWeapon():Clip1() ~= -1) then
draw.SimpleText(ply:GetActiveWeapon():Clip1() .. "/" .. ply:GetAmmoCount(ply:GetActiveWeapon():GetPrimaryAmmoType()), "NameWeapon_font", ScrW() - 110, ScrH() - 22, Color(255, 255, 255, 255), 0, 0)
else
draw.SimpleText(ply:GetAmmoCount(ply:GetActiveWeapon():GetPrimaryAmmoType()), "NameWeapon_font", ScrW() - 110, ScrH() - 22, Color(255, 255, 255, 255), 0, 0)
end
if (ply:GetAmmoCount(ply:GetActiveWeapon():GetSecondaryAmmoType()) > 0) then
draw.SimpleText(ply:GetAmmoCount(ply:GetActiveWeapon():GetSecondaryAmmoType()), "NameWeapon_font", ScrW() - 110, ScrH() - 22, Color(255, 255, 255, 255), 0, 0)
end
else
surface.SetDrawColor(255, 255, 255, 255)
draw.RoundedBox(3, ScrW() * 0.004, ScrH() - 87, 110, 24, Color(20, 20, 20, 220))
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 85, 106, 20, Color(48, 48, 47, 170))
draw.DrawText(DarkRP.formatMoney(ply:getDarkRPVar("money")), "Default_font", 58, ScrH() - 84, Color(255, 255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
draw.RoundedBox(3, ScrW() * 0.004, ScrH() - 60, 109, 24, Color(20, 20, 20, 220))
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 58, 106, 20, Color(48, 48, 47, 170))
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 58, health * 1.10 - 5, 20, Color(255, 0, 0))
draw.RoundedBox(3, ScrW() * 0.004, ScrH() - 33, 109, 24, Color(20, 20, 20, 220))
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 31, 106, 20, Color(48, 48, 47, 170))
if armor < 1 then
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 31, armor, 20, Color(41, 11, 214))
elseif armor > 1 then
draw.RoundedBox(3, ScrW() * 0.0057, ScrH() - 31, armor + 4, 20, Color(41, 11, 214))
end
draw.RoundedBox(3, ScrW() - 120, ScrH() - 55, 109, 24, Color(20, 20, 20, 220))
draw.RoundedBox(3, ScrW() - 118, ScrH() - 53, 104.5, 20, Color(20, 20, 20, 170))
if (ply:GetActiveWeapon():GetPrintName() ~= nil) then
draw.SimpleText(ply:GetActiveWeapon():GetPrintName(), "NameWeapon_font", ScrW() - 110, ScrH() - 49, Color(255, 255, 255))
end
if (ply:GetActiveWeapon():Clip1() ~= -1) then
draw.SimpleText(ply:GetActiveWeapon():Clip1() .. "/" .. ply:GetAmmoCount(ply:GetActiveWeapon():GetPrimaryAmmoType()), "NameWeapon_font", ScrW() - 110, ScrH() - 22, Color(255, 255, 255, 255), 0, 0)
else
draw.SimpleText(ply:GetAmmoCount(ply:GetActiveWeapon():GetPrimaryAmmoType()), "NameWeapon_font", ScrW() - 110, ScrH() - 22, Color(255, 255, 255, 255), 0, 0)
end
if (ply:GetAmmoCount(ply:GetActiveWeapon():GetSecondaryAmmoType()) > 0) then
draw.SimpleText(ply:GetAmmoCount(ply:GetActiveWeapon():GetSecondaryAmmoType()), "NameWeapon_font", ScrW() - 110, ScrH() - 22, Color(255, 255, 255, 255), 0, 0)
end
end
end
hook.Add("HUDPaint", "DrawHUD", Base)
|
--
-- Addon _fiu_inventory.lua
-- Author marcob@marcob.org
-- StartDate 02/05/2017
--
local addon, cD = ...
function cD.scanInventories()
local itemBase = {}
-- scan Inventory Bags
local invBags = Inspect.Item.List(Utility.Item.Slot.Inventory())
for slotId, itemId in pairs(invBags) do
if itemId then
local item = Inspect.Item.Detail(itemId)
itemName = item.name
itemStack = item.stack
if itemBase[itemName] then
itemBase[itemName] = itemBase[itemName] + (item.stack or 1)
else
itemBase[itemName] = (item.stack or 1)
end
end
end
-- scan Questlog Bag
local invBags = Inspect.Item.List(Utility.Item.Slot.Quest())
for slotId, itemId in pairs(invBags) do
if itemId then
local item = Inspect.Item.Detail(itemId)
itemName = item.name
itemStack = item.stack
if itemBase[itemName] then
itemBase[itemName] = itemBase[itemName] + (item.stack or 1)
else
itemBase[itemName] = (item.stack or 1)
end
end
end
return itemBase
end
|
include("dualstick360/globals.lua")
include("dualstick360/bullet.lua")
include("dualstick360/utils.lua")
Player = {}
Player.__index = Player
--[[ Create a new Player object ]]
function Player.new()
local self = setmetatable({}, Player)
self.go = GameObjectManager:createGameObject("PlayerOne")
return self
end
--[[ Update the healthbar (global) ]]
function Player:healthbarupdate()
local hpLenght = (player.hp/PLAYER_HP)*HEALTH_BAR_LENGTH
player.hb.rc:setScale(Vec3(5, -hpLenght, 0.1))
end
--[[ Initialize the current Player object, constructs a rigid body, all objects that are part of the Player and sets its members. ]]
function Player:init() -- : inserts metatable at args called 'self'
-- variables for movement
self.movementDirection = Vec3(0, 0, 0)
self.moveKeyPressed = false
-- variables for shooting
self.bullets = {}
self.cursorDirection = Vec3(0, 0, 0)
self.timeSinceLastShot = 0
--variables for shield
self.shieldActive = false
-- variables for gamepad data
self.leftStickAngle = 0
self.rightStickAngle = 0
self.leftStickPush = 0
self.rightStickPush = 0
-- variables for gameplay
self.score = 0
self.hp = PLAYER_HP
-- physicscomponent
self.physComp = self.go:createPhysicsComponent()
local cinfo = RigidBodyCInfo()
cinfo.shape = PhysicsFactory:createSphere(PLAYER_SIZE)
cinfo.position = PLAYER_STARTPOSITION
cinfo.mass = PLAYER_MASS
cinfo.linearDamping = PLAYER_LINDAMP
cinfo.motionType = MotionType.Dynamic
cinfo.collisionFilterInfo = PLAYER_INFO
self.rb = self.physComp:createRigidBody(cinfo)
self.rb:setUserData(self)
--player shield 3 parts
--middle
self.shield = {}
self.shield.go = GameObjectManager:createGameObject("player_shield_mid")
self.shield.physComp = self.shield.go:createPhysicsComponent()
local cinfo = RigidBodyCInfo()
-- width length height
cinfo.shape = PhysicsFactory:createBox(Vec3(0.19* PLAYER_SIZE,0.93*PLAYER_SIZE,1.4* PLAYER_SIZE))
cinfo.position = Vec3(10, 0, 0)
cinfo.mass = 0.5
cinfo.restitution = PLAYER_SHIELDRESTITUTION
cinfo.motionType = MotionType.Keyframed
cinfo.collisionFilterInfo = PLAYERSHIELD_INFO
self.shield.rb = self.shield.physComp:createRigidBody(cinfo)
--right
self.shield_r = {}
self.shield_r.go = GameObjectManager:createGameObject("player_shield_r")
self.shield_r.physComp = self.shield_r.go:createPhysicsComponent()
local cinfo = RigidBodyCInfo()
-- width length height
cinfo.shape = PhysicsFactory:createBox(Vec3(0.19* PLAYER_SIZE,0.76 * PLAYER_SIZE,1.4* PLAYER_SIZE))
cinfo.position = Vec3(0, 0, 0)
cinfo.mass = 0.5
cinfo.restitution = PLAYER_SHIELDRESTITUTION
cinfo.motionType = MotionType.Keyframed
cinfo.collisionFilterInfo = PLAYERSHIELD_INFO
self.shield_r.rb = self.shield_r.physComp:createRigidBody(cinfo)
self.shield_r.go:setComponentStates(ComponentState.Inactive)
self.shield_r.rb:setRotation(Quaternion(Vec3(0,0,1),45))
--left
self.shield_l = {}
self.shield_l.go = GameObjectManager:createGameObject("player_shield_l")
self.shield_l.physComp = self.shield_l.go:createPhysicsComponent()
local cinfo = RigidBodyCInfo()
-- width length height
cinfo.shape = PhysicsFactory:createBox(Vec3(0.19* PLAYER_SIZE,0.76 * PLAYER_SIZE,1.4* PLAYER_SIZE))
cinfo.position = Vec3(0, 0, 0)
cinfo.mass = 0.5
cinfo.restitution = PLAYER_SHIELDRESTITUTION
cinfo.motionType = MotionType.Keyframed
cinfo.collisionFilterInfo = PLAYERSHIELD_INFO
self.shield_l.rb = self.shield_l.physComp:createRigidBody(cinfo)
self.shield_l.go:setComponentStates(ComponentState.Inactive)
self.shield_l.rb:setRotation(Quaternion(Vec3(0,0,1),-45))
-- init bullets
for i=1, PLAYER_BULLETLIMIT do
local b = Bullet.new(i)
b:init(i, true, false)
self.bullets[i] = b
end
-- health bar
hb = GameObjectManager:createGameObject("myHealthBar")
hb.rc = hb:createRenderComponent()
hb.rc:setPath("data/models/box.thModel")
hb.rc:setScale(Vec3(5, -(self.hp/PLAYER_HP)*HEALTH_BAR_LENGTH, 0.1))
hb:setPosition(Vec3((2/3)*CAMERA_Z-150,(4/15)*CAMERA_Z, (2/15)*CAMERA_Z))
hb:setRotation(Quaternion(Vec3(0,0,1),90))
self.hb = hb
end
--[[ Updates all members of the player.
Reads input from gamepad/keyboard and updates the Player position and cursor direction.
Also fires bullets and activates shield
]]
function Player:update(f)
-- gamepad movement controls (analog stick angle and push)
local leftStick = InputHandler:gamepad(0):leftStick()
local rightStick = InputHandler:gamepad(0):rightStick()
local rightTrigger = InputHandler:gamepad(0):rightTrigger()
self.leftStickAngle = (math.atan(leftStick.y, leftStick.x)/PI)*180 + 90
self.rightStickAngle = (math.atan(rightStick.y, rightStick.x)/PI)*180 + 90
self.leftStickPush = leftStick:length()
self.rightStickPush = rightStick:length()
if (self.leftStickAngle < 0) then
self.leftStickAngle = self.leftStickAngle + 360
end
if (self.rightStickAngle < 0) then
self.rightStickAngle = self.rightStickAngle + 360
end
-- DEBUG keyboard movement controls
if (InputHandler:isPressed(Key.W)) then
self.leftStickAngle = 180
self.leftStickPush = 1
elseif (InputHandler:isPressed(Key.S)) then
self.leftStickAngle = 0
self.leftStickPush = 1
elseif (InputHandler:isPressed(Key.A)) then
self.leftStickAngle = 270
self.leftStickPush = 1
elseif (InputHandler:isPressed(Key.D)) then
self.leftStickAngle = 90
self.leftStickPush = 1
end
-- move player
if (self.leftStickPush > PLAYER_MINIMUMPUSH) then
self.movementDirection = Vec3(math.sin((self.leftStickAngle/360)*2*PI), math.cos(self.leftStickAngle/360*2*PI), 0)
self.rb:applyLinearImpulse(self.movementDirection:mulScalar(PLAYER_MAXSPEED * self.leftStickPush))
end
-- DEBUG keyboard player cursor
self.keyboardKeyPressed = false
if (InputHandler:isPressed(Key.Up)) then
self.rightStickAngle = 180
self.keyboardKeyPressed = true
elseif (InputHandler:isPressed(Key.Down)) then
self.rightStickAngle = 0
self.keyboardKeyPressed = true
elseif (InputHandler:isPressed(Key.Left)) then
self.rightStickAngle = 270
self.keyboardKeyPressed = true
elseif (InputHandler:isPressed(Key.Right)) then
self.rightStickAngle = 90
self.keyboardKeyPressed = true
end
-- update shieldActive
if(rightTrigger > 0.9 or InputHandler:isPressed(Key.Space)) then
self.shieldActive = true
else
self.shieldActive = false
end
-- calc curserDirection
if (self.rightStickPush > PLAYER_MINIMUMPUSH or self.keyboardKeyPressed) then
self.cursorDirection = Vec3(math.sin((self.rightStickAngle/360)*2*PI), math.cos(self.rightStickAngle/360*2*PI), 0):normalized()
end
-- draw cursor
if ((self.rightStickPush > PLAYER_MINIMUMPUSH or self.keyboardKeyPressed) and self.shieldActive == false) then
DebugRenderer:drawArrow(self.rb:getPosition(), self.rb:getPosition() + self.cursorDirection:mulScalar(PLAYER_SIZE*2))
end
--update shield
if ((self.rightStickPush > PLAYER_MINIMUMPUSH or self.keyboardKeyPressed) and self.shieldActive) then
self.shield.go:setComponentStates(ComponentState.Active)
self.shield.rb:setPosition(self.rb:getPosition().x + self.cursorDirection.x*PLAYER_SHIELDDISTANCE,self.rb:getPosition().y + self.cursorDirection.y*PLAYER_SHIELDDISTANCE, 0)
local shieldrotation_deg = calcAngleBetween(Vec3(0,1,0),self.cursorDirection)
self.shield.rb:setRotation(Quaternion(Vec3(0,0,1),shieldrotation_deg))
self.shield_r.go:setComponentStates(ComponentState.Active)
q = Quaternion(Vec3(0.0, 0.0, 1.0), 45)
v = q:toMat3():mulVec3(self.cursorDirection)
self.shield_r.rb:setPosition(self.rb:getPosition().x + v.x*PLAYER_SHIELDDISTANCE_SIDE,self.rb:getPosition().y + v.y*PLAYER_SHIELDDISTANCE_SIDE, 0)
local shieldrotation_deg = calcAngleBetween(Vec3(0,1,0),self.cursorDirection)
self.shield_r.rb:setRotation(Quaternion(Vec3(0,0,1),shieldrotation_deg+45))
self.shield_l.go:setComponentStates(ComponentState.Active)
q = Quaternion(Vec3(0.0, 0.0, 1.0), -45)
v = q:toMat3():mulVec3(self.cursorDirection)
self.shield_l.rb:setPosition(self.rb:getPosition().x + v.x*PLAYER_SHIELDDISTANCE_SIDE,self.rb:getPosition().y + v.y*PLAYER_SHIELDDISTANCE_SIDE, 0)
local shieldrotation_deg = calcAngleBetween(Vec3(0,1,0),self.cursorDirection)
self.shield_l.rb:setRotation(Quaternion(Vec3(0,0,1),shieldrotation_deg-45))
else
self.shield.go:setComponentStates(ComponentState.Inactive)
self.shield_l.go:setComponentStates(ComponentState.Inactive)
self.shield_r.go:setComponentStates(ComponentState.Inactive)
end
-- shoot bullets
if ((self.rightStickPush > 0.5 or self.keyboardKeyPressed) and self.timeSinceLastShot > PLAYER_BULLETDELAY and self.shieldActive == false) then
for _, b in ipairs(self.bullets) do
if not (b.isActive) then
b:activateBullet(self.rb:getPosition() + self.cursorDirection:mulScalar(PLAYER_SIZE), self.cursorDirection, PLAYER_BULLETSPEED)
break
end
end
self.timeSinceLastShot = 0
end
-- enable delay between shots
if (self.timeSinceLastShot < PLAYER_BULLETDELAY) then
self.timeSinceLastShot = self.timeSinceLastShot + f
end
--keep on z axe
self.rb:setPosition(Vec3(self.rb:getPosition().x,self.rb:getPosition().y,0))
self.rb:setAngularVelocity(Vec3(0, 0, 0))
--gameplay printer
printGameplayText("HP: " .. self.hp)
printGameplayText("Score: " .. self.score)
-- debug printer
printText("self.leftstickAngle:" .. self.leftStickAngle)
printText("self.rightstickAngle:" .. self.rightStickAngle)
printText("self.leftStickPush:" .. self.leftStickPush)
printText("self.rightStickPush:" .. self.rightStickPush)
printText("rightTriggerValue: " .. rightTrigger)
end
|
function Buy(ply, price)
local pmoney = ply:GetValue("ZMoney")
if (pmoney and pmoney >= price) then
ply:SetValue("ZMoney", pmoney - price, true)
return true
end
end
Package.Export("Buy", Buy)
function AddMoney(ply, added)
local pmoney = ply:GetValue("ZMoney")
if pmoney then
if ACTIVE_POWERUPS.x2 then
added = added * 2
end
ply:SetValue("ZMoney", pmoney + added, true)
ply:SetValue("ZScore", ply:GetValue("ZScore") + added, false)
return true
end
end
Package.Export("AddMoney", AddMoney)
function InteractMapWeapon(weapon, char)
if weapon:IsValid() then
local m_weap_id = weapon:GetValue("MapWeaponID")
if m_weap_id then
local ply = char:GetPlayer()
if ply then
if not char:GetValue("PlayerDown") then
local price = MAP_WEAPONS[m_weap_id].price
local ammo_id = false
local charInvID = GetCharacterInventory(char)
if charInvID then
for i, v in ipairs(PlayersCharactersWeapons[charInvID].weapons) do
if v.weapon_name == MAP_WEAPONS[m_weap_id].weapon_name then
if not v.pap then
price = math.floor(MAP_WEAPONS[m_weap_id].price * Weapons_Ammo_Price_Percentage / 100)
else
price = Pack_a_punch_price
end
ammo_id = i
break
end
end
end
if Buy(ply, price) then
if not ammo_id then
AddCharacterWeapon(char, MAP_WEAPONS[m_weap_id].weapon_name, MAP_WEAPONS[m_weap_id].max_ammo, true)
else
PlayersCharactersWeapons[charInvID].weapons[ammo_id].ammo_bag = MAP_WEAPONS[m_weap_id].max_ammo
if PlayersCharactersWeapons[charInvID].weapons[ammo_id].weapon then
PlayersCharactersWeapons[charInvID].weapons[ammo_id].weapon:SetAmmoBag(MAP_WEAPONS[m_weap_id].max_ammo)
Events.CallRemote("UpdateAmmoText", ply)
end
end
end
end
end
return false
end
end
end
VZ_EVENT_SUBSCRIBE("Weapon", "Interact", InteractMapWeapon)
function BuyDoor(ply, door_id)
--print("BuyDoor", ply, door_id)
local map_door = GetMapDoorFromID(door_id)
if map_door then
local char = ply:GetControlledCharacter()
if char then
if not char:GetValue("PlayerDown") then
local required_rooms_good = true
for i, v in ipairs(MAP_DOORS[door_id].required_rooms) do
if not ROOMS_UNLOCKED[v] then
required_rooms_good = false
break
end
end
if required_rooms_good then
if Buy(ply, MAP_DOORS[door_id].price) then
map_door:Destroy()
for i, v in ipairs(MAP_DOORS[door_id].between_rooms) do
UnlockRoom(v)
end
Events.Call("VZ_DoorOpened", char, door_id)
end
end
end
end
end
end
VZ_EVENT_SUBSCRIBE("Events", "BuyDoor", BuyDoor)
VZ_EVENT_SUBSCRIBE("Events", "BuyMBOX", function(ply, mbox)
if (mbox and mbox:IsValid()) then
local mbox_can_buy = mbox:GetValue("CanBuyMysteryBox")
if mbox_can_buy then
if Active_MysteryBox_ID then
local char = ply:GetControlledCharacter()
if char then
if not char:GetValue("PlayerDown") then
if Buy(ply, Mystery_box_price) then
OpenActiveMysteryBox(char)
end
end
end
end
end
end
end)
function BuyPerk(ply, perk_sm)
if (perk_sm and perk_sm:IsValid()) then
local char = ply:GetControlledCharacter()
if char then
if not char:GetValue("PlayerDown") then
local perk_name = perk_sm:GetValue("MapPerk")
if perk_name then
local char_perks = char:GetValue("OwnedPerks")
if not char_perks[perk_name] then
if Buy(ply, PERKS_CONFIG[perk_name].price) then
GiveCharacterPerk(char, perk_name)
end
end
end
end
end
end
end
VZ_EVENT_SUBSCRIBE("Events", "BuyPerk", BuyPerk)
PAP_Upgrade_Data = nil
function ResetPAP()
if MAP_PAP_SM then
if PAP_Upgrade_Data then
if PAP_Upgrade_Data.up_timeout then
Timer.ClearTimeout(PAP_Upgrade_Data.up_timeout)
elseif PAP_Upgrade_Data.del_timeout then
Timer.ClearTimeout(PAP_Upgrade_Data.del_timeout)
PAP_Upgrade_Data.upgraded_weapon:Destroy()
end
end
PAP_Upgrade_Data = nil
MAP_PAP_SM:SetValue("CanBuyPackAPunch", true, true)
end
end
function UpgradeWeapon(ply, pap_sm)
if POWER_ON then
if (pap_sm and pap_sm:IsValid()) then
if pap_sm:GetValue("CanBuyPackAPunch") then
local char = ply:GetControlledCharacter()
if char then
if not char:GetValue("PlayerDown") then
local charInvID = GetCharacterInventory(char)
if charInvID then
local Inv = PlayersCharactersWeapons[charInvID]
if Inv.selected_slot then
local selected_weap
for i, v in ipairs(Inv.weapons) do
if (v.slot == Inv.selected_slot and v.weapon) then
if v.weapon:IsValid() then
if not v.pap then
selected_weap = v.weapon_name
end
end
break
end
end
if selected_weap then
if Buy(ply, Pack_a_punch_price) then
pap_sm:SetValue("CanBuyPackAPunch", false, true)
for i, v in ipairs(Inv.weapons) do
if (v.slot == Inv.selected_slot and v.weapon) then
v.destroying = true
v.weapon:Destroy()
v.weapon = nil
table.remove(PlayersCharactersWeapons[charInvID].weapons, i)
break
end
end
PAP_Upgrade_Data = {}
PAP_Upgrade_Data.up_timeout = Timer.SetTimeout(function()
PAP_Upgrade_Data.up_timeout = nil
PAP_Upgrade_Data.upgraded_weapon = NanosWorldWeapons[selected_weap](MAP_PACK_A_PUNCH.weapon_location, MAP_PACK_A_PUNCH.weapon_rotation)
PAP_Upgrade_Data.upgraded_weapon:SetCollision(CollisionType.NoCollision)
PAP_Upgrade_Data.upgraded_weapon:SetGravityEnabled(false)
PAP_Upgrade_Data.upgraded_weapon:SetMaterial(Pack_a_punch_weapon_material, Pack_a_punch_weapon_material_index)
PAP_Upgrade_Data.upgraded_weapon:SetValue("PAPWeaponForCharacterID", {char:GetID(), selected_weap}, false)
Events.BroadcastRemote("PAPReadySound")
PAP_Upgrade_Data.del_timeout = Timer.SetTimeout(function()
PAP_Upgrade_Data.upgraded_weapon:Destroy()
PAP_Upgrade_Data = nil
MAP_PAP_SM:SetValue("CanBuyPackAPunch", true, true)
end, Pack_a_punch_destroy_weapon_time_ms)
Events.Call("VZ_PAPUpgradedWeapon")
end, Pack_a_punch_upgrade_time_ms)
Events.BroadcastRemote("PAPUpgradeSound")
return true
end
end
end
end
end
end
end
end
end
end
VZ_EVENT_SUBSCRIBE("Events", "UpgradeWeap", UpgradeWeapon)
VZ_EVENT_SUBSCRIBE("Events", "BuyWunderfizz", function(ply, SM_Wunder)
if (SM_Wunder and SM_Wunder:IsValid()) then
local char = ply:GetControlledCharacter()
if char then
if not char:GetValue("PlayerDown") then
local can_buy_wunder = SM_Wunder:GetValue("CanBuyWunder")
if can_buy_wunder then
if Active_Wunderfizz_ID then
if table_count(char:GetValue("OwnedPerks")) < table_count(PERKS_CONFIG) then
if Buy(ply, Wonderfizz_Price) then
OpenActiveWunderfizz(char)
end
end
end
end
end
end
end
end)
VZ_EVENT_SUBSCRIBE("Events", "BuyTeleport", function(ply, teleporter)
if (teleporter and teleporter:IsValid()) then
if teleporter:GetValue("CanTeleport") then
local char = ply:GetControlledCharacter()
if char then
if not char:GetValue("PlayerDown") then
local teleporter_ID = teleporter:GetValue("TeleporterID")
if Buy(ply, MAP_TELEPORTERS[teleporter_ID].price) then
local teleport_table = {
ply,
}
local in_tbl = 1
local Destination_Spawns_Count = table_count(MAP_TELEPORTERS[teleporter_ID].teleport_to)
if Destination_Spawns_Count > 1 then
local players_in_radius = GetPlayersInRadius_ToTeleport(ply, MAP_TELEPORTERS[teleporter_ID].location, MAP_TELEPORTERS[teleporter_ID].distance_sq)
for k, v in pairs(players_in_radius) do
if in_tbl < Destination_Spawns_Count then
table.insert(teleport_table, v)
in_tbl = in_tbl + 1
end
end
elseif Destination_Spawns_Count == 0 then
Package.Error("vzombies : A teleporter doesn't have any destination, teleporter " .. tostring(teleporter_ID))
return
end
for i, v in ipairs(teleport_table) do
local char_to_tp = v:GetControlledCharacter()
char_to_tp:SetLocation(MAP_TELEPORTERS[teleporter_ID].teleport_to[i].location + Vector(0, 0, 100))
char_to_tp:SetRotation(MAP_TELEPORTERS[teleporter_ID].teleport_to[i].rotation)
v:SetCameraRotation(MAP_TELEPORTERS[teleporter_ID].teleport_to[i].rotation)
Events.CallRemote("PlayerTeleportedSound", v)
end
if MAP_TELEPORTERS[teleporter_ID].teleport_back_ms > 0 then
local TeleportBackCount = table_count(MAP_TELEPORTERS[teleporter_ID].teleport_back)
if TeleportBackCount ~= Destination_Spawns_Count then
Package.Error("vzombies : Missing back destinations (spawns) for the teleporter " .. tostring(teleporter_ID))
return
end
local teleport_back_timeout = Timer.SetTimeout(function()
if teleporter:IsValid() then
for i, v in ipairs(teleport_table) do
if v:IsValid() then
local char_to_tp = v:GetControlledCharacter()
if char_to_tp then
char_to_tp:SetLocation(MAP_TELEPORTERS[teleporter_ID].teleport_back[i].location + Vector(0, 0, 100))
char_to_tp:SetRotation(MAP_TELEPORTERS[teleporter_ID].teleport_back[i].rotation)
v:SetCameraRotation(MAP_TELEPORTERS[teleporter_ID].teleport_back[i].rotation)
Events.CallRemote("PlayerTeleportedSound", v)
end
end
end
end
end, MAP_TELEPORTERS[teleporter_ID].teleport_back_ms)
end
if MAP_TELEPORTERS[teleporter_ID].teleporter_cooldown_ms > 0 then
teleporter:SetValue("CanTeleport", false, true)
Timer.SetTimeout(function()
if teleporter:IsValid() then
teleporter:SetValue("CanTeleport", true, true)
end
end, MAP_TELEPORTERS[teleporter_ID].teleporter_cooldown_ms)
end
end
end
end
end
end
end)
if Prone_Perk_Config.enabled then
VZ_EVENT_SUBSCRIBE("Character", "StanceModeChanged", function(char, old_state, new_state)
local ply = char:GetPlayer()
if ply then
if not char:GetValue("PlayerDown") then
if new_state == StanceMode.Proning then
local char_loc = char:GetLocation()
local char_rot = char:GetRotation()
for k, v in pairs(StaticMesh.GetPairs()) do
if v:GetValue("ProneMoney") then
local perk_loc = v:GetLocation()
if char_loc:DistanceSquared(perk_loc) <= Prone_Perk_Config.Max_Distance_sq then
local perk_rot = v:GetRotation()
local rel_yaw = RelRot1(char_rot.Yaw, perk_rot.Yaw)
if (rel_yaw >= Prone_Perk_Config.Rel_Rot_Between[1] and rel_yaw <= Prone_Perk_Config.Rel_Rot_Between[2]) then
v:SetValue("ProneMoney", nil, false)
AddMoney(ply, Prone_Perk_Config.money)
end
end
end
end
end
end
end
end)
end
|
slot0 = class("GuildBossFormationShipCard")
slot0.Ctor = function (slot0, slot1)
slot0._go = slot1
tf(slot1).pivot = Vector2(0.5, 0)
tf(slot1).sizeDelta = Vector2(200, 300)
tf(slot1).localScale = Vector3(0.6, 0.6, 0.6)
end
slot0.RefreshPosition = function (slot0, slot1, slot2)
slot0.soltIndex = slot1
if slot2 then
slot0:UpdateLocalPosition()
end
end
slot0.UpdateLocalPosition = function (slot0)
slot0:SetLocalPosition(slot0._go.transform.parent:Find(slot0.soltIndex).localPosition)
end
slot0.SetLocalPosition = function (slot0, slot1)
slot0._go.transform.localPosition = slot1
end
slot0.GetLocalPosition = function (slot0)
return slot0._go.transform.localPosition
end
slot0.GetSoltIndex = function (slot0)
return slot0.soltIndex
end
slot0.Update = function (slot0, slot1, slot2)
slot0.shipId = slot1.id
slot0.teamType = slot1:getTeamType()
slot0:RefreshPosition(slot2, true)
end
slot0.Dispose = function (slot0)
ClearEventTrigger(GetOrAddComponent(slot0._go, "EventTriggerListener"))
PoolMgr.GetInstance():ReturnSpineChar(slot0._go.name, slot0._go)
end
return slot0
|
#!/usr/bin/env luajit
local unpack = unpack or require'table'.unpack
-- math.randomseed(123)
local rrt = require'rrt'
local grid = require'grid'
-- Go from 0,0 to 1,1
local interval_x = {-1, 1}
local interval_y = {-1, 1}
local planner = rrt.new({
intervals = {interval_x, interval_y}
}):set_system{
is_collision = function(self, s)
return self:distState(s, {0,0}) < 0.25
end
}
-- Go from 0,0 to 1,1
local start_xy = {-0.9, -0.9}
local goal_xy = {0.9, 0.9}
planner:plan(start_xy, goal_xy)
-- Periodically, check to find the best trajectory
local i = 0
local t0 = os.time()
repeat
local dt = os.difftime(os.time(), t0)
planner:iterate()
if i>1e3 and planner.goal.parent then
print(string.format("Iteration %d | Cost: %f",
i, planner.lowerBoundCost))
break
elseif i % 100 == 0 then
print(string.format("Iteration %d | Cost: %f",
i, planner.goal.parent and planner.lowerBoundCost or 0/0))
end
-- for _, vertex in ipairs(tree) do print(vertex.id, unpack(vertex)) end
until dt > 2
local path_xy, path_length = assert(planner:trace())
print("Path", path_length)
local grid_params = {
scale = planner.DISCRETIZATION_STEP,
xmin = interval_x[1], xmax = interval_x[2],
ymin = interval_y[1], ymax = interval_y[2],
datatype = 'double'
}
local costmap = grid.new(grid_params)
local function color_path(map, idx) map[idx] = 127 end
costmap:path(path_xy, color_path)
assert(costmap:save"/tmp/costmapRRT_path_default.pgm")
-- Test the dubins model for the car
local interval_x = {-10, 10}
local interval_y = {-10, 10}
local interval_a = {0, 2*math.pi}
local intervals = {interval_x, interval_y, interval_a}
local DISCRETIZATION_STEP = 0.1
local CIRCLE_RADIUS = 2
local circular_obstacles = {
{2, -2, CIRCLE_RADIUS},
{0, 0, CIRCLE_RADIUS},
{-2, 2, CIRCLE_RADIUS},
}
local grid_params = {
scale = DISCRETIZATION_STEP,
xmin = interval_x[1], xmax = interval_x[2],
ymin = interval_y[1], ymax = interval_y[2],
datatype = 'double'
}
local costmap = require'grid'.new(grid_params)
local function set_obs(map, idx)
map[idx] = 255
end
for _,c in ipairs(circular_obstacles) do
local xc, yc, rc = unpack(c)
costmap:circle({xc, yc}, rc, set_obs)
end
assert(costmap:save"/tmp/costmapRRT.pgm")
print("Planning the car route!")
local planner_car = assert(rrt.new{
intervals = intervals,
DISCRETIZATION_STEP = DISCRETIZATION_STEP,
})
local sys_dubins = assert(rrt.systems.dubins({
TURNING_RADIUS = 3,
circular_obstacles = circular_obstacles
}))
assert(planner_car:set_system(sys_dubins))
local start = {-7.5,-7.5, 0}
local goal = {7.5, 7.5, 0}
assert(planner_car:plan(start, goal))
-- Periodically, check to find the best trajectory
-- Should do this within a computational bound
local i = 0
local t0 = os.time()
repeat
local dt = os.difftime(os.time(), t0)
local ret, err = planner_car:iterate()
if not ret then print("Bad iteration", err) end
if i>1e3 and planner_car.goal.parent then
print(string.format("%d | Iteration %d | Cost: %f",
dt, i, planner_car.lowerBoundCost))
-- break
elseif i % 100 == 0 then
print(string.format("%d | Iteration %d | Cost: %f",
dt, i, planner_car.goal.parent and planner_car.lowerBoundCost or 0/0))
end
i = i + 1
until dt > 5
local path_xy, path_length = assert(planner_car:trace())
print("path_xy", path_xy)
for i, v in ipairs(path_xy) do
print(i, v)
end
print("Path length", path_length)
local function color_path(map, idx, i) map[idx] = 127 end
costmap:path(path_xy, color_path)
assert(costmap:save"/tmp/costmapRRT_path.pgm")
|
local composer = require( "composer" )
local scene = composer.newScene()
physics = require ("physics" )
local function gotoMenu()
composer.gotoScene("menu")
return true
end
function scene:create ( event )
local sceneGroup = self.view
local camerEngine = require ("ssk2.loadSSK")
_G.ssk.init()
display.setDefault("magTextureFilter", "nearest" )
--start physics
group = display.currentStage
physics.start()
physics.setGravity( 0, 0 )
physics.setAverageCollisionPositions(true)
physics.setVelocityIterations(8)
physics.setPositionIterations(8)
--menu / level loading
require("level1") -- level loader
require("movement") --myPlayer movement WASD
require("mouse") -- turn on mouse
require("animation") -- animated myPlayer
--require("AIstatic")
--require("wall") -- turn walls on /wall collistion on
--require("AIFollower") -- AI that follows you around
--require("mousetest") -- test the mouse X and Y coordinates
level = level + 1
print (level)
-- track camera ssk2
ssk.camera.tracking( camera, group, {centered =true} )
local tiled = require "com.ponywolf.ponytiled"
local mapData = require "Map1"
display.setDefault("background", 0.2)
myPlayer:addEventListener("tap" , gotoMenu)
end
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
return scene
|
local VisualAIPlan = class.class("VisualAIPlan")
local CoIter = require("mod.visual_ai.api.CoIter")
local utils = require("mod.visual_ai.internal.utils")
function VisualAIPlan:init()
self.blocks = {}
self.subplan_true = nil
self.subplan_false = nil
self.parent = nil
end
function VisualAIPlan:current_block()
return self.blocks[#self.blocks]
end
function VisualAIPlan:iter_blocks()
return fun.iter(self.blocks)
end
function VisualAIPlan:can_add_block()
local cur = self:current_block()
if cur == nil then
return true
end
if cur.proto.type == "action" or cur.proto.type == "special" then
if cur.proto.is_terminal then
return false, ("Plan ends in terminal action (%s)."):format(cur.proto._id)
end
end
if cur.proto.type == "condition" then
return false, ("Plan ends with a condition (%s)."):format(cur.proto._id)
end
return true
end
function VisualAIPlan:tile_size()
local width = #self.blocks
local height = 1
if self.subplan_true then
local w, h = self.subplan_true:tile_size()
width = width + w
height = h
end
if self.subplan_false then
local w, h = self.subplan_false:tile_size()
width = math.max(width, w)
height = height + h
end
return width, height
end
function VisualAIPlan:iter_tiles(x, y)
x = x or 0
y = y or 0
local f = function()
while true do
local i = 1
while self.blocks[i] do
coroutine.yield("block", x, y, self.blocks[i], self)
if i < #self.blocks then
coroutine.yield("line", x, y, { "right", x + 1, y }, self)
end
i = i + 1
x = x + 1
end
local last_block = self:current_block()
if last_block == nil then
-- empty plan
coroutine.yield("empty", x, y, "", self)
elseif last_block.proto.type == "condition" then
coroutine.yield("line", x-1, y, { "right", x, y }, self.subplan_true)
for _, state, cx, cy, block, plan in self.subplan_true:iter_tiles(x, y) do
coroutine.yield(state, cx, cy, block, plan)
end
local _, height = self.subplan_true:tile_size()
coroutine.yield("line", x - 1, y, { "down", x - 1, y + height }, self.subplan_false)
for _, state, cx, cy, block, plan in self.subplan_false:iter_tiles(x-1, y + height) do
coroutine.yield(state, cx, cy, block, plan)
end
elseif last_block.proto.type == "target" then
coroutine.yield("line", x-1, y, { "right", x, y }, self)
coroutine.yield("empty", x, y, "", self)
elseif last_block.proto.type == "action"
or last_block.proto.type == "special"
then
if not last_block.proto.is_terminal then
coroutine.yield("line", x-1, y, { "right", x, y }, self)
coroutine.yield("empty", x, y, "", self)
end
end
coroutine.yield(nil)
end
end
return CoIter.iter(f)
end
function VisualAIPlan:check_for_errors(x, y)
x = x or 0
y = y or 0
local errors = {}
for i, block in ipairs(self.blocks) do
x = x + 1
end
local last_block = self:current_block()
if last_block == nil then
errors[#errors+1] = { message = "Branch is missing a final block.", x = x, y = y }
elseif last_block.proto.type == "condition" then
assert(self.subplan_true ~= nil)
assert(self.subplan_false ~= nil)
table.append(errors, self.subplan_true:check_for_errors(x, y))
local _, height = self.subplan_true:tile_size()
table.append(errors, self.subplan_false:check_for_errors(x - 1, y + height))
elseif last_block.proto.type == "target" then
errors[#errors+1] = { message = "Target block is missing next block.", x = x - 1, y = y }
elseif last_block.proto.type == "action" or last_block.proto.type == "special" then
if not last_block.proto.is_terminal then
errors[#errors+1] = { message = "Non-terminal action is missing next block.", x = x - 1, y = y }
end
end
return errors
end
function VisualAIPlan:_insert_block(block)
assert(self:can_add_block())
assert(block._id)
assert(block.proto)
assert(block.vars)
self.blocks[#self.blocks+1] = block
return self.blocks[#self.blocks]
end
function VisualAIPlan:add_condition_block(block, subplan_true, subplan_false)
if block.proto.type ~= "condition" then
error("Block prototype must be 'condition'.")
end
local block = self:_insert_block(block)
if subplan_true then
-- BUG #118
-- class.assert_is_an(VisualAIPlan, subplan_true)
assert(subplan_true ~= subplan_false)
else
subplan_true = VisualAIPlan:new()
end
if subplan_false then
-- BUG #118
-- class.assert_is_an(VisualAIPlan, subplan_false)
else
subplan_false = VisualAIPlan:new()
end
subplan_true.parent = self
subplan_false.parent = self
self.subplan_true = subplan_true
self.subplan_false = subplan_false
return block
end
function VisualAIPlan:add_target_block(block)
if block.proto.type ~= "target" then
error("Block prototype must be 'target'.")
end
return self:_insert_block(block)
end
function VisualAIPlan:add_action_block(block)
if block.proto.type ~= "action" then
error("Block prototype must be 'action'.")
end
return self:_insert_block(block)
end
function VisualAIPlan:add_special_block(block)
if block.proto.type ~= "special" then
error("Block prototype must be 'special'.")
end
return self:_insert_block(block)
end
function VisualAIPlan:add_block(block)
local idx = table.index_of(self.blocks, block)
if idx ~= nil then
error(("Block '%s' already exists in this plan."):format(tostring(block)))
end
local proto = block.proto
if proto.type == "condition" then
return self:add_condition_block(block, nil, nil)
elseif proto.type == "target" then
return self:add_target_block(block)
elseif proto.type == "action" then
return self:add_action_block(block)
elseif proto.type == "special" then
return self:add_special_block(block)
else
error("unknown block type " .. tostring(proto.type))
end
end
function VisualAIPlan:replace_block(block, new_block)
local idx = table.index_of(self.blocks, block)
if idx == nil then
error(("No block '%s' in this plan."):format(tostring(block)))
end
local function snip_rest()
for i = idx, #self.blocks do
self.blocks[i] = nil
end
end
local proto = new_block.proto
local current = self:current_block()
if block == current and current.proto.type == "condition" and proto.type ~= "condition" then
self.subplan_true = nil
self.subplan_false = nil
end
if proto.type == "condition" then
if block.proto.type == "condition" then
self.blocks[idx] = new_block
else
snip_rest()
self:add_condition_block(new_block, nil, nil)
end
elseif proto.type == "target" then
self.blocks[idx] = new_block
elseif proto.type == "action" then
if proto.is_terminal then
snip_rest()
self:add_action_block(new_block)
else
self.blocks[idx] = new_block
end
elseif proto.type == "special" then
if proto.is_terminal then
snip_rest()
self:add_special_block(new_block)
else
self.blocks[idx] = new_block
end
else
error("unknown block type " .. tostring(proto.type))
end
return self.blocks[idx]
end
function VisualAIPlan:merge(other)
assert(self:can_add_block())
self.subplan_true = nil
self.subplan_false = nil
if other.subplan_true then
other.subplan_true.parent = self
self.subplan_true = other.subplan_true
end
if other.subplan_false then
other.subplan_false.parent = self
self.subplan_false = other.subplan_false
end
table.append(self.blocks, other.blocks)
end
function VisualAIPlan:split(idx)
assert(idx > 0 and idx <= #self.blocks)
local right = VisualAIPlan:new()
local len = #self.blocks
for i = idx, len do
local block = self.blocks[i]
if block.proto.type == "condition" then
assert(i == len)
right:add_condition_block(block, self.subplan_true, self.subplan_false)
else
right:add_block(block)
end
self.blocks[i] = nil
end
self.subplan_true = nil
self.subplan_false = nil
return right
end
function VisualAIPlan:insert_block_before(block, new_block, split_type)
local idx = table.index_of(self.blocks, block)
if idx == nil then
error(("No block '%s' in this plan."):format(tostring(block)))
end
local proto = new_block.proto
local function snip_rest()
for i = idx, #self.blocks do
self.blocks[i] = nil
end
end
if proto.type == "condition" then
local right = self:split(idx)
if split_type == "true_branch" then
self:add_condition_block(new_block, right, nil)
elseif split_type == "false_branch" then
self:add_condition_block(new_block, nil, right)
else
error("unknown split type " .. tostring(split_type))
end
elseif proto.type == "target" then
table.insert(self.blocks, idx, new_block)
elseif proto.type == "action" then
if proto.is_terminal then
snip_rest()
self:add_action_block(new_block)
else
table.insert(self.blocks, idx, new_block)
end
elseif proto.type == "special" then
if proto.is_terminal then
snip_rest()
self:add_special_block(new_block)
else
table.insert(self.blocks, idx, new_block)
end
else
error("unknown block type " .. tostring(proto.type))
end
return self.blocks[idx]
end
function VisualAIPlan:remove_block(block, merge_type)
local idx = table.index_of(self.blocks, block)
if idx == nil then
error(("No block '%s' in this plan."):format(tostring(block)))
end
local to_merge
if block.proto.type == "condition" then
-- This block must be at the end.
assert(idx == #self.blocks)
if merge_type == "true_branch" then
to_merge = self.subplan_true
elseif merge_type == "false_branch" then
to_merge = self.subplan_false
else
error("unknown merge type " .. tostring(merge_type))
end
self.subplan_true = nil
self.subplan_false = nil
end
table.remove(self.blocks, idx)
if to_merge then
self:merge(to_merge)
end
end
function VisualAIPlan:remove_block_and_rest(block)
local idx = table.index_of(self.blocks, block)
if idx == nil then
error(("No block '%s' in this plan."):format(tostring(block)))
end
if block.proto.type == "condition" then
-- This block must be at the end.
assert(idx == #self.blocks)
self.subplan_true = nil
self.subplan_false = nil
end
for i = idx, #self.blocks do
self.blocks[i] = nil
end
end
function VisualAIPlan:swap_branches(block)
local idx = table.index_of(self.blocks, block)
if idx == nil then
error(("No block '%s' in this plan."):format(tostring(block)))
end
if block.proto.type ~= "condition" then
return
end
local temp = self.subplan_true
self.subplan_true = self.subplan_false
self.subplan_false = temp
end
function VisualAIPlan:serialize()
self.parent = nil
for _, block in ipairs(self.blocks) do
block.proto = nil
end
if self.subplan_true then
self.subplan_true.parent = nil
end
if self.subplan_false then
self.subplan_false.parent = nil
end
end
function VisualAIPlan:deserialize()
for _, block in ipairs(self.blocks) do
-- TODO remove block if invalid, don't throw an error
block.proto = data["visual_ai.block"]:ensure(block._id)
assert(block.proto)
end
if self.subplan_true then
self.subplan_true.parent = self
end
if self.subplan_false then
self.subplan_false.parent = self
end
end
return VisualAIPlan
|
-- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
modifier_medusa_mana_shield_lua = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_medusa_mana_shield_lua:IsHidden()
return false
end
function modifier_medusa_mana_shield_lua:IsDebuff()
return false
end
function modifier_medusa_mana_shield_lua:IsPurgable()
return false
end
function modifier_medusa_mana_shield_lua:GetAttributes()
return MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_medusa_mana_shield_lua:OnCreated( kv )
-- references
self.damage_per_mana = self:GetAbility():GetSpecialValueFor( "damage_per_mana" )
self.absorb_pct = self:GetAbility():GetSpecialValueFor( "absorption_tooltip" )/100
if not IsServer() then return end
-- Play effects
local sound_cast = "Hero_Medusa.ManaShield.On"
EmitSoundOn( sound_cast, self:GetParent() )
end
function modifier_medusa_mana_shield_lua:OnRefresh( kv )
-- references
self.damage_per_mana = self:GetAbility():GetSpecialValueFor( "damage_per_mana" )
self.absorb_pct = self:GetAbility():GetSpecialValueFor( "absorption_tooltip" )
end
function modifier_medusa_mana_shield_lua:OnRemoved()
end
function modifier_medusa_mana_shield_lua:OnDestroy()
if not IsServer() then return end
-- Play effects
local sound_cast = "Hero_Medusa.ManaShield.Off"
EmitSoundOn( sound_cast, self:GetParent() )
end
--------------------------------------------------------------------------------
-- Modifier Effects
function modifier_medusa_mana_shield_lua:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_INCOMING_DAMAGE_PERCENTAGE,
}
return funcs
end
function modifier_medusa_mana_shield_lua:GetModifierIncomingDamage_Percentage( params )
local absorb = -100*self.absorb_pct
-- calculate mana spent
local damage_absorbed = params.damage * self.absorb_pct
local manacost = damage_absorbed/self.damage_per_mana
local mana = self:GetParent():GetMana()
-- if not enough mana, calculate damage blocked by remaining mana
if mana<manacost then
damage_absorbed = mana * self.damage_per_mana
absorb = -damage_absorbed/params.damage*100
manacost = mana
end
-- spend mana
self:GetParent():SpendMana( manacost, self:GetAbility() )
-- play effects
self:PlayEffects( damage_absorbed )
return absorb
end
--------------------------------------------------------------------------------
-- Graphics & Animations
function modifier_medusa_mana_shield_lua:GetEffectName()
return "particles/units/heroes/hero_medusa/medusa_mana_shield.vpcf"
end
function modifier_medusa_mana_shield_lua:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
function modifier_medusa_mana_shield_lua:PlayEffects( damage )
-- Get Resources
local particle_cast = "particles/units/heroes/hero_medusa/medusa_mana_shield_impact.vpcf"
local sound_cast = "Hero_Medusa.ManaShield.Proc"
-- Create Particle
local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_ABSORIGIN_FOLLOW, self:GetParent() )
ParticleManager:SetParticleControl( effect_cast, 1, Vector( damage, 0, 0 ) )
ParticleManager:ReleaseParticleIndex( effect_cast )
-- Create Sound
EmitSoundOn( sound_cast, self:GetParent() )
end
|
require 'torch'
require 'libsvmutil'
require 'svmsgd'
require 'liblinear'
require 'libsvm'
include('data.lua')
|
-- This script flips the squawk code between 1200 and 7000
-- to set the transponder for a VFR flight. As the VFR code
-- is 7000 in Europe, we can't simply do this:
create_positive_edge_trigger(13, "sim/cockpit/radios/transponder_code", 0, 1200);
-- Instead we use the flip command to set it to 1200 or 7000:
create_positive_edge_flip(14, "sim/cockpit/radios/transponder_code", 0, 1200, 7000);
-- The flip command compares the the value of the DataRef with it's first value given.
-- If this is equal, than the DataRef will be set to the second value given.
-- If not, it will be set to the first value.
--
-- So if the transponder is set to 2015, than it will be flipped to 1200. Another press onto
-- the button will than flip the transponder code to 7000.
--
-- Please keep in mind that the value after the DataRef's name is always the index.
-- The index must be 0 (zero), even if it is a non-array value.
--
-- Play around with this little script and take a look into the manual. There are more
-- button functions you can create. All functions starting with "create_" have to be called
-- only once. After that, they will work until the scripts are reloaded or Lua stops.
-- They are the old "Button2DataRef" plugin included and work faster than pure Lua code.
-- So if you can exchange a >>do_every_frame("if button(XYZ) ...<< construction with a
-- simple >>create_<< function call, choose the >>create_<< function to get maximum
-- execution speed (highest frame rate).
|
function f1(a: number, b: string)
if a > 100 then
return a
else
return b
end
end
let a = f1(100, 'abc')
let b: number = f1(100, 'abc')
|
/*=============================================================================
Expression-Advanced TextEditor
Author: Oskar
Credits: Andreas "Syranide" Svensson for making the E2 editor
=============================================================================*/
local math_max = math.max
local math_min = math.min
local math_floor = math.floor
local math_ceil = math.ceil
local string_find = string.find
local string_rep = string.rep
local string_sub = string.sub
local string_gsub = string.gsub
local string_Explode = string.Explode
local string_len = string.len
local string_gmatch = string.gmatch
local string_match = string.match
local table_remove = table.remove
local table_insert = table.insert
local table_concat = table.concat
local table_Count = table.Count
local table_KeysFromValue = table.KeysFromValue
local surface_SetFont = surface.SetFont
local surface_DrawRect = surface.DrawRect
local surface_DrawText = surface.DrawText
local surface_GetTextSize = surface.GetTextSize
local surface_SetDrawColor = surface.SetDrawColor
local surface_SetTextColor = surface.SetTextColor
local surface_SetTextPos = surface.SetTextPos
local draw_SimpleText = draw.SimpleText
local draw_WordBox = draw.WordBox
local input_IsKeyDown = input.IsKeyDown
local input_IsMouseDown = input.IsMouseDown
local BookmarkMaterial = Material( "diagona-icons/152.png" )
local ParamPairs = {
["{"] = { "{", "}", true },
["["] = { "[", "]", true },
["("] = { "(", ")", true },
["}"] = { "}", "{", false },
["]"] = { "]", "[", false },
[")"] = { ")", "(", false },
}
local PANEL = { }
function PANEL:Init( )
self:SetCursor( "beam" )
self.Rows = { "" }
self.Undo = { }
self.Redo = { }
self.PaintRows = { }
self.FoldButtons = { }
self.FoldData = { }
self.FoldedRows = { }
self.Bookmarks = { }
self.ActiveBookmarks = { }
self.Insert = false
self.Blink = RealTime( )
self.BookmarkWidth = 16
self.LineNumberWidth = 2
self.FoldingWidth = 16
self.CaretRow = 0
self.LongestRow = 0
self.TextEntry = self:Add( "TextEntry" )
self.TextEntry:SetMultiline( true )
self.TextEntry:SetSize( 0, 0 )
self.TextEntry:SetFocusTopLevel( true )
self.TextEntry.m_bDisableTabbing = true // OH GOD YES!!!!! NO MORE HACKS!!!
self.TextEntry.OnTextChanged = function( ) self:_OnTextChanged( ) end
self.TextEntry.OnKeyCodeTyped = function( _, code ) self:_OnKeyCodeTyped( code ) end
self.Caret = Vector2( 1, 1 )
self.Start = Vector2( 1, 1 )
self.Scroll = Vector2( 1, 1 )
self.Size = Vector2( 1, 1 )
self.ScrollBar = self:Add( "DVScrollBar" )
self.ScrollBar:SetUp( 1, 1 )
self.ScrollBar.btnUp.DoClick = function ( self ) self:GetParent( ):AddScroll( -4 ) end
self.ScrollBar.btnDown.DoClick = function ( self ) self:GetParent( ):AddScroll( 4 ) end
function self.ScrollBar:AddScroll( dlta )
local OldScroll = self:GetScroll( )
self:SetScroll( self:GetScroll( ) + dlta )
return OldScroll == self:GetScroll( )
end
function self.ScrollBar:OnMouseWheeled( dlta )
if ( !self:IsVisible() ) then return false end
return self:AddScroll( dlta * -4 )
end
self.hScrollBar = self:Add( "EA_HScrollBar")
self.hScrollBar:SetUp( 1, 1 )
surface_SetFont( "Fixedsys" )
self.FontWidth, self.FontHeight = surface_GetTextSize( " " )
end
function PANEL:RequestFocus( )
self.TextEntry:RequestFocus( )
end
function PANEL:OnGetFocus( )
self.TextEntry:RequestFocus( )
end
/*---------------------------------------------------------------------------
Cursor functions
---------------------------------------------------------------------------*/
local function GetFoldingOffset( self, Row ) do return 0 end
local offset = 0
local pos = 1
while pos < Row or self.FoldedRows[pos] do
if self.FoldedRows[pos] then
offset = offset + 1
Row = Row + 1
end
pos = pos + 1
end
return offset
end
function PANEL:CursorToCaret( )
local x, y = self:CursorPos( )
x = x - ( self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth )
if x < 0 then x = 0 end
if y < 0 then y = 0 end
local line = math_floor( y / self.FontHeight )
line = line + GetFoldingOffset( self, line + self.Scroll.x )
local char = math_floor( x / self.FontWidth + 0.5 )
line = line + self.Scroll.x
char = char + self.Scroll.y
if line > #self.Rows then line = #self.Rows end
local length = #self.Rows[line]
if char > length + 1 then char = length + 1 end
return Vector2( line, char )
end
function PANEL:SetCaret( caret )
self.Caret = self:CopyPosition( caret )
self.Start = self:CopyPosition( caret )
self:ScrollCaret( )
end
function PANEL:CopyPosition( caret )
return caret:Clone( )
end
function PANEL:MovePosition( caret, offset )
local caret = self:CopyPosition( caret )
if offset > 0 then
while true do
local length = #self.Rows[caret.x] - caret.y + 2
if offset < length then
caret.y = caret.y + offset
break
elseif caret.x == #self.Rows then
caret.y = caret.y + length - 1
break
else
offset = offset - length
caret.x = caret.x + 1
caret.y = 1
end
end
elseif offset < 0 then
offset = -offset
while true do
if offset < caret.y then
caret.y = caret.y - offset
break
elseif caret.x == 1 then
caret.y = 1
break
else
offset = offset - caret.y
caret.x = caret.x - 1
caret.y = #self.Rows[caret.x] + 1
end
end
end
return caret
end
function PANEL:ScrollCaret( )
if self.Caret.x - self.Scroll.x < 1 then
self.Scroll.x = self.Caret.x - 1
if self.Scroll.x < 1 then self.Scroll.x = 1 end
end
if self.Caret.x - self.Scroll.x > self.Size.x - 1 then
self.Scroll.x = self.Caret.x - self.Size.x + 1
if self.Scroll.x < 1 then self.Scroll.x = 1 end
end
if self.Caret.y - self.Scroll.y < 4 then
self.Scroll.y = self.Caret.y - 4
if self.Scroll.y < 1 then self.Scroll.y = 1 end
end
if self.Caret.y - 1 - self.Scroll.y > self.Size.y - 4 then
self.Scroll.y = self.Caret.y - 1 - self.Size.y + 4
if self.Scroll.y < 1 then self.Scroll.y = 1 end
end
self.ScrollBar:SetScroll( self.Scroll.x - 1 )
self.hScrollBar:SetScroll( self.Scroll.y - 1 )
end
/*---------------------------------------------------------------------------
Selection stuff
---------------------------------------------------------------------------*/
function PANEL:HasSelection( )
return self.Caret != self.Start
end
function PANEL:Selection( )
return { Vector2( self.Start( ) ), Vector2( self.Caret( ) ) }
end
function PANEL:GetSelection( )
return self:GetArea( self:Selection( ) )
end
function PANEL:SetSelection( text )
self:SetCaret( self:SetArea( self:Selection( ), text ) )
end
function PANEL:MakeSelection( selection )
local start, stop = selection[1], selection[2]
if start.x < stop.x or ( start.x == stop.x and start.y < stop.y ) then
return start, stop
else
return stop, start
end
end
function PANEL:GetArea( selection )
local start, stop = self:MakeSelection( selection )
if start.x == stop.x then
if self.Insert and start.y == stop.y then
selection[2].y = selection[2].y + 1
return string_sub( self.Rows[start.x], start.y, start.y )
else
return string_sub( self.Rows[start.x], start.y, stop.y - 1 )
end
else
local text = string_sub( self.Rows[start.x], start.y )
for i = start.x + 1, stop.x - 1 do
text = text .. "\n" .. self.Rows[i]
end
return text .. "\n" .. string_sub( self.Rows[stop.x], 1, stop.y - 1 )
end
end
function PANEL:SetArea( selection, text, isundo, isredo, before, after )
local buffer = self:GetArea( selection )
local start, stop = self:MakeSelection( selection )
if start != stop then
// clear selection
self.Rows[start.x] = string_sub( self.Rows[start.x], 1, start.y - 1 ) .. string_sub( self.Rows[stop.x], stop.y )
for i = start.x + 1, stop.x do
table_remove( self.Rows, start.x + 1 )
end
end
if !text or text == "" then
self.ScrollBar:SetUp( self.Size.x, #self.Rows + ( math_floor( self:GetTall( ) / self.FontHeight ) - 2 ) - table_Count( table_KeysFromValue( self.FoldedRows, true ) ))
self:CalculateHScroll( )
self.PaintRows = { }
self:OnTextChanged( )
if isredo then
self.Undo[#self.Undo + 1] = { { self:CopyPosition( start ), self:CopyPosition( start ) },
buffer, after, before }
return before
elseif isundo then
self.Redo[#self.Redo + 1] = { { self:CopyPosition( start ), self:CopyPosition( start ) },
buffer, after, before }
return before
else
self.Redo = { }
self.Undo[#self.Undo + 1] = { { self:CopyPosition( start ), self:CopyPosition( start ) },
buffer, self:CopyPosition( selection[1] ), self:CopyPosition( start ) }
return start
end
end
// insert text
local rows = string_Explode( "\n", text )
local remainder = string_sub( self.Rows[start.x], start.y )
self.Rows[start.x] = string_sub( self.Rows[start.x], 1, start.y - 1 ) .. rows[1]
for i = 2, #rows do
table_insert( self.Rows, start.x + i - 1, rows[i] )
end
local stop = Vector2( start.x + #rows - 1, #( self.Rows[start.x + #rows - 1] ) + 1 )
self.Rows[stop.x] = self.Rows[stop.x] .. remainder
self.ScrollBar:SetUp( self.Size.x, #self.Rows + ( math_floor( self:GetTall( ) / self.FontHeight ) - 2 ) - table_Count( table_KeysFromValue( self.FoldedRows, true ) ))
self:CalculateHScroll( )
self.PaintRows = { }
self:OnTextChanged( )
if isredo then
self.Undo[#self.Undo + 1] = { { self:CopyPosition( start ), self:CopyPosition( stop ) },
buffer, after, before }
return before
elseif isundo then
self.Redo[#self.Redo + 1] = { { self:CopyPosition( start ), self:CopyPosition( stop ) },
buffer, after, before }
return before
else
self.Redo = { }
self.Undo[#self.Undo + 1] = { { self:CopyPosition( start ), self:CopyPosition( stop ) },
buffer, self:CopyPosition( selection[1] ), self:CopyPosition( stop ) }
return stop
end
end
function PANEL:SelectAll( )
self.Caret = Vector2( #self.Rows, #self.Rows[#self.Rows] + 1 )
self.Start = Vector2( 1, 1 )
self:ScrollCaret( )
end
function PANEL:Indent( Shift )
local oldSelection = { self:MakeSelection( self:Selection( ) ) }
local Scroll = self.Scroll:Clone( )
local Start, End = oldSelection[1]:Clone( ), oldSelection[2]:Clone( )
Start.y = 1
if End.y ~= 1 then
End.x = End.x + 1
End.y = 1
end
self.Start = Start:Clone( )
self.Caret = End:Clone( )
if self.Caret.y == 1 then
self.Caret = self:MovePosition( self.Caret, -1 )
end
if Shift then // Unindent
local Temp = string_gsub( self:GetSelection( ), "\n ? ? ? ?", "\n" )
self:SetSelection( string_match( Temp, "^ ? ? ? ?(.*)$") )
else // Indent
self:SetSelection( " " .. string_gsub( self:GetSelection( ), "\n", "\n " ) )
end
//TODO: SublimeText like indenting.
self.Start = Start:Clone( )
self.Caret = End:Clone( )
self.Scroll = Scroll:Clone( )
self:ScrollCaret( )
end
function PANEL:CanUndo( )
return #self.Undo > 0
end
function PANEL:DoUndo( )
if #self.Undo > 0 then
local undo = self.Undo[#self.Undo]
self.Undo[#self.Undo] = nil
self:SetCaret( self:SetArea( undo[1], undo[2], true, false, undo[3], undo[4] ) )
end
end
function PANEL:CanRedo( )
return #self.Redo > 0
end
function PANEL:DoRedo( )
if #self.Redo > 0 then
local redo = self.Redo[#self.Redo]
self.Redo[#self.Redo] = nil
self:SetCaret( self:SetArea( redo[1], redo[2], false, true, redo[3], redo[4] ) )
end
end
function PANEL:wordLeft( caret )
local row = self.Rows[caret.x] or ""
if caret.y == 1 then
if caret.x == 1 then return caret end
caret = Vector2( caret.x-1, #self.Rows[caret.x-1] )
row = self.Rows[caret.x]
end
local pos = row:sub( 1, caret.y - 1 ):match( "[^%w]+()[%w ]+[^%w ]*$" )
caret.y = pos or 1
return caret
end
function PANEL:wordRight( caret )
local row = self.Rows[caret.x] or ""
if caret.y > #row then
if caret.x == #self.Rows then return caret end
caret = Vector2( caret.x + 1, 1 )
row = self.Rows[caret.x]
if row:sub( 1, 1 ) ~= " " then return caret end
end
local pos = row:match( "[^%w ]+()[%w ]", caret.y )
caret.y = pos or ( #row + 1 )
return caret
end
function PANEL:wordStart( caret )
local line = self.Rows[caret.x]
for startpos, endpos in string_gmatch( line, "()[a-zA-Z0-9_]+()" ) do
if startpos <= caret.y and endpos >= caret.y then
return Vector2( caret.x, startpos )
end
end
return Vector2( caret.x, 1 )
end
function PANEL:wordEnd( caret )
local line = self.Rows[caret.x]
for startpos, endpos in string_gmatch( line, "()[a-zA-Z0-9_]+()" ) do
if startpos <= caret.y and endpos >= caret.y then
return Vector2( caret.x, endpos )
end
end
return Vector2( caret.x, caret.y )
end
/*---------------------------------------------------------------------------
TextEntry hooks
---------------------------------------------------------------------------*/
local AutoParam = {
["{"] = "}",
["["] = "]",
["("] = ")",
["\""] = "\"",
["'"] = "'",
}
local SpecialCase = {
["}"] = true,
["]"] = true,
[")"] = true,
["\""] = true,
["'"] = true,
}
function PANEL:_OnKeyCodeTyped( code )
self.Blink = RealTime( )
local alt = input_IsKeyDown( KEY_LALT ) or input_IsKeyDown( KEY_RALT )
if alt then return end
local shift = input_IsKeyDown( KEY_LSHIFT ) or input_IsKeyDown( KEY_RSHIFT )
local control = input_IsKeyDown( KEY_LCONTROL ) or input_IsKeyDown( KEY_RCONTROL )
-- allow ctrl-ins and shift-del ( shift-ins, like ctrl-v, is handled by vgui )
if not shift and control and code == KEY_INSERT then
shift, control, code = true, false, KEY_C
elseif shift and not control and code == KEY_DELETE then
shift, control, code = false, true, KEY_X
end
if control then
if code == KEY_A then
self:SelectAll( )
elseif code == KEY_Z then
self:DoUndo( )
elseif code == KEY_Y then
self:DoRedo( )
elseif code == KEY_X then
if self:HasSelection( ) then
local clipboard = self:GetSelection( )
clipboard = string_gsub( clipboard, "\n", "\r\n" )
SetClipboardText( clipboard )
self:SetSelection( )
end
elseif code == KEY_C then
if self:HasSelection( ) then
local clipboard = self:GetSelection( )
clipboard = string_gsub( clipboard, "\n", "\r\n" )
SetClipboardText( clipboard )
end
elseif code == KEY_Q then
self:GetParent( ):GetParent( ):Close( )
elseif code == KEY_T then
self:GetParent( ):GetParent( ):NewTab( )
elseif code == KEY_W then
self:GetParent( ):GetParent( ):CloseTab( )
elseif code == KEY_S then // Save
if shift then // ctrl+shift+s
self:GetParent( ):GetParent( ):SaveFile( true, true )
else // ctrl+s
self:GetParent( ):GetParent( ):SaveFile( true )
end
elseif code == KEY_UP then
if shift then
if self:HasSelection( ) then
local start, stop = self:MakeSelection( self:Selection( ) )
if start.x > 1 then
local data = table_remove( self.Rows, start.x - 1 )
table_insert( self.Rows, stop.x, data )
self.Start:Add( -1, 0 )
self.Caret:Add( -1, 0 )
self.PaintRows = { }
self:ScrollCaret( )
end
elseif self.Caret.x > 1 then
local data = table_remove( self.Rows, self.Caret.x )
self:SetCaret( self.Caret:Add( -1, 0 ) )
table_insert( self.Rows, self.Caret.x, data )
self.PaintRows = { }
end
else
self.Scroll.x = self.Scroll.x - 1
if self.Scroll.x < 1 then self.Scroll.x = 1 end
self.ScrollBar:SetScroll( self.Scroll.x -1 )
end
elseif code == KEY_DOWN then
if shift then
if self:HasSelection( ) then
local start, stop = self:MakeSelection( self:Selection( ) )
if stop.x < #self.Rows then
local data = table_remove( self.Rows, stop.x + 1 )
table_insert( self.Rows, start.x, data )
self.Start:Add( 1, 0 )
self.Caret:Add( 1, 0 )
self.PaintRows = { }
self:ScrollCaret( )
end
elseif self.Caret.x < #self.Rows then
local data = table_remove( self.Rows, self.Caret.x )
self:SetCaret( self.Caret:Add( 1, 0 ) )
table_insert( self.Rows, self.Caret.x, data )
self.PaintRows = { }
end
else
self.Scroll.x = self.Scroll.x + 1
self.ScrollBar:SetScroll( self.Scroll.x -1 )
end
elseif code == KEY_LEFT then
if self:HasSelection( ) and not shift then
self.Start = self:CopyPosition( self.Caret )
else
self.Caret = self:wordLeft( self.Caret )
end
self:ScrollCaret( )
if not shift then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == KEY_RIGHT then
if self:HasSelection( ) and !shift then
self.Start = self:CopyPosition( self.Caret )
else
self.Caret = self:wordRight( self.Caret )
end
self:ScrollCaret( )
if !shift then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == KEY_HOME then
self.Caret = Vector2( 1, 1 )
self:ScrollCaret( )
if !shift then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == KEY_END then
self.Caret = Vector2( #self.Rows, 1 )
self:ScrollCaret( )
if !shift then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == KEY_D then
-- Save current selection
local old_start = self:CopyPosition( self.Start )
local old_end = self:CopyPosition( self.Caret )
local old_scroll = self:CopyPosition( self.Scroll )
local str = self:GetSelection( )
if ( str != "" ) then -- If you have a selection
self:SetSelection( str:rep( 2 ) ) -- Repeat it
else -- If you don't
-- Select the current line
self.Start = Vector2( self.Start.x, 1 )
self.Caret = Vector2( self.Start.x, #self.Rows[self.Start.x]+1 )
-- Get the text
local str = self:GetSelection( )
-- Repeat it
self:SetSelection( str .. "\n" .. str )
end
-- Restore selection
self.Caret = old_end
self.Start = old_start
self.Scroll = old_scroll
self:ScrollCaret( )
elseif code == KEY_SPACE then
self:GetParent( ):GetParent( ):DoValidate( true )
elseif code == KEY_B then // TODO: Fix F-Keys and move bookmarks to F2
local Start, End = self:MakeSelection( self:Selection( ) )
if shift then
local pos = Start.x
while pos <= #self.Rows do
if pos >= #self.Rows then pos = 0 end
pos = pos + 1
if pos == Start.x then break end
if self.ActiveBookmarks[pos] then
self.Start = self.ActiveBookmarks[pos][1]
self.Caret = self.ActiveBookmarks[pos][2]
self:ScrollCaret( )
break
end
end
else
self.Bookmarks[Start.x]:DoClick( )
end
end
else
if code == KEY_ENTER then
local Line = self.Rows[self.Caret.x]
local Count = string_len( string_match( string_sub( Line, 1, self.Caret.y - 1 ), "^%s*" ) )
if string_match( "{" .. Line .. "}", "^%b{}.*$" ) then
if string_match( string_sub( Line, 1, self.Caret.y - 1 ), "{$" ) and string_match( string_sub( Line, self.Caret.y, -1 ), "^}" ) then
local Caret = self:SetArea( self:Selection( ), "\n" .. string_rep( " ", math_floor( Count / 4 ) + 1 ) .. "\n" .. string_rep( " ", math_floor( Count / 4 ) ) )
Caret.y = 1
Caret = self:MovePosition( Caret, -1 )
self:SetCaret( Caret )
-- elseif string_match( string_sub( Line, 1, self.Caret.y - 1 ), "{") then
elseif string_match( "{" .. string_sub( Line, 1, self.Caret.y - 1 ) .. "}", "^%b{}.*$" ) then
self:SetSelection( "\n" .. string_rep( " ", math_floor( Count / 4 ) ) )
else
self:SetSelection( "\n" .. string_rep( " ", math_floor( Count / 4 ) ) .. " " )
end
else
if string_match( string_sub( Line, 1, self.Caret.y - 1 ), "{") then
self:SetSelection( "\n" .. string_rep( " ", math_floor( Count / 4 ) ) .. " " )
else
self:SetSelection( "\n" .. string_rep( " ", math_floor( Count / 4 ) ) )
end
end
elseif code == KEY_INSERT then
self.Insert = !self.Insert
elseif code == KEY_UP then
if self.Caret.x > 1 then
self.Caret.x = self.Caret.x - 1
local length = #( self.Rows[self.Caret.x] )
if self.Caret.y > length + 1 then
self.Caret.y = length + 1
end
end
self:ScrollCaret( )
if !shift then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == KEY_DOWN then
if self.Caret.x < #self.Rows then
self.Caret.x = self.Caret.x + 1
local length = #( self.Rows[self.Caret.x] )
if self.Caret.y > length + 1 then
self.Caret.y = length + 1
end
end
self:ScrollCaret( )
if !shift then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == KEY_LEFT then
self.Caret = self:MovePosition( self.Caret, -1 )
self:ScrollCaret( )
if !shift then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == KEY_RIGHT then
self.Caret = self:MovePosition( self.Caret, 1 )
self:ScrollCaret( )
if !shift then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == KEY_BACKSPACE then
if self:HasSelection( ) then
self:SetSelection( )
else
local buffer = self:GetArea( { self.Caret, Vector2( self.Caret.x, 1 ) } )
if self.Caret.y % 4 == 1 and #buffer > 0 and string_rep( " ", #buffer ) == buffer then
self:SetCaret( self:SetArea( { self.Caret, self:MovePosition( self.Caret, -4 ) } ) )
elseif #buffer > 0 and AutoParam[self.Rows[self.Caret.x][self.Caret.y-1]] and AutoParam[self.Rows[self.Caret.x][self.Caret.y-1]] == self.Rows[self.Caret.x][self.Caret.y] then
self.Caret.y = self.Caret.y + 1
self:SetCaret( self:SetArea( { self.Caret, self:MovePosition( self.Caret, -2 ) } ) )
else
self:SetCaret( self:SetArea( { self.Caret, self:MovePosition( self.Caret, -1 ) } ) )
end
end
elseif code == KEY_DELETE then
if self:HasSelection( ) then
self:SetSelection( )
else
local buffer = self:GetArea( { Vector2( self.Caret.x, self.Caret.y + 4 ), Vector2( self.Caret.x, 1 ) } )
if self.Caret.y % 4 == 1 and string_rep( " ", #( buffer ) ) == buffer and #( self.Rows[self.Caret.x] ) >= self.Caret.y + 4 - 1 then
self:SetCaret( self:SetArea( { self.Caret, self:MovePosition( self.Caret, 4 ) } ) )
else
self:SetCaret( self:SetArea( { self.Caret, self:MovePosition( self.Caret, 1 ) } ) )
end
end
elseif code == KEY_PAGEUP then --
self.Caret.x = math_max( self.Caret.x - math_ceil( self.Size.x / 2 ), 1 )
self.Caret.y = math_min( self.Caret.y, #self.Rows[self.Caret.x] + 1 )
self.Scroll.x = math_max( self.Scroll.x - math_ceil( self.Size.x / 2 ), 1 )
self:ScrollCaret( )
if !shift then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == KEY_PAGEDOWN then
self.Caret.x = math_min( self.Caret.x + math_ceil( self.Size.x / 2 ), #self.Rows )
self.Caret.y = self.Caret.x == #self.Rows and 1 or math_min( self.Caret.y, #self.Rows[self.Caret.x] + 1 )
self.Scroll.x = self.Scroll.x + math_ceil( self.Size.x / 2 )
self:ScrollCaret( )
if !shift then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == KEY_HOME then
local row = self.Rows[self.Caret.x]
local first_char = string_find( row, "%S" ) or string_len( row ) + 1
self.Caret.y = self.Caret.y == first_char and 1 or first_char
self:ScrollCaret( )
if !shift then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == KEY_END then
self.Caret.y = #self.Rows[self.Caret.x] + 1
self:ScrollCaret( )
if !shift then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == KEY_F2 then // F-Keys is broken atm! D:
print( ":D" )
// TODO: ?
end
end
if code == KEY_TAB or ( control and ( code == KEY_I or code == KEY_O ) ) then
if code == KEY_O then shift = not shift end
if code == KEY_TAB and control then shift = not shift end
if self:HasSelection( ) then
self:Indent( shift )
else
if (shift and code ~= KEY_O) or code == KEY_I then
local newpos = self.Caret.y - 4
if newpos < 1 then newpos = 1 end
self.Start:Set( self.Caret.x, newpos )
if string_find( self:GetSelection( ), "%S" ) then
local Caret = self.Caret:Clone( )
self.Start:Set( self.Start.x, 1 )
self.Caret:Set( Caret.x, #self.Rows[Caret.x] + 1 )
local text = string_match( self.Rows[Caret.x], "^ ? ? ? ?(.*)$" )
local oldLength = #self.Rows[Caret.x]
self:SetSelection( text )
self.Caret = self:MovePosition( Caret, #text - oldLength )
self.Start = self.Caret:Clone( )
else
self:SetSelection( "" )
end
else
if code == KEY_O then
local Caret = self.Caret:Clone( )
self.Start:Set( self.Start.x, 1 )
self.Caret:Set( Caret.x, #self.Rows[Caret.x] + 1 )
self:Indent( )
self.Caret = Caret:Add( 0, 4 )
self.Start = self.Caret:Clone( )
else
self:SetSelection( string_rep( " ", ( self.Caret.y + 2 ) % 4 + 1 ) )
end
end
end
end
if control and self.OnShortcut then self:OnShortcut( code ) end
end
function PANEL:_OnTextChanged( )
local ctrlv = false
local text = self.TextEntry:GetValue( )
self.TextEntry:SetText( "" )
if ( input_IsKeyDown( KEY_LCONTROL ) or input_IsKeyDown( KEY_RCONTROL ) ) and not ( input_IsKeyDown( KEY_LALT ) or input_IsKeyDown( KEY_RALT ) ) then
-- ctrl+[shift+]key
if input_IsKeyDown( KEY_V ) then
-- ctrl+[shift+]V
ctrlv = true
else
-- ctrl+[shift+]key with key ~= V
return
end
end
if text == "" then return end
if not ctrlv then
if text == "\n" then return end
end
local bSelection = self:HasSelection( )
if bSelection then
local selection = self:Selection( )
local selectionText = self:GetArea( selection )
if #text == 1 and AutoParam[text] then
self:SetSelection( text .. selectionText .. AutoParam[text] )
self.Start = selection[1]:Add( 0, 1 )
self.Caret = selection[2]:Add( 0, 1 )
self:ScrollCaret( )
else
self:SetSelection( text )
end
elseif #text == 1 and AutoParam[text] then
if
self.Rows[self.Caret.x][self.Caret.y] == " " or
self.Rows[self.Caret.x][self.Caret.y] == "" or
self.Rows[self.Caret.x][self.Caret.y] == AutoParam[text]
then
self:SetSelection( text .. AutoParam[text] )
self:SetCaret( self:MovePosition( self.Caret, -1 ) )
elseif SpecialCase[text] and self.Rows[self.Caret.x][self.Caret.y] == text then
self:SetCaret( self:MovePosition( self.Caret, 1 ) )
else
self:SetSelection( text )
end
elseif #text == 1 and SpecialCase[text] and self.Rows[self.Caret.x][self.Caret.y] == text then
self:SetCaret( self:MovePosition( self.Caret, 1 ) )
else
self:SetSelection( text )
end
self:ScrollCaret( )
end
/*---------------------------------------------------------------------------
Mouse stuff
---------------------------------------------------------------------------*/
function PANEL:OnMousePressed( code )
if self.MouseDown then return end
if code == MOUSE_LEFT then
local cursor = self:CursorToCaret( )
if self.LastClick and CurTime( ) - self.LastClick < 0.6 and ( self.Caret == cursor or self.LastCursor == cursor ) then
if self.temp then
self.temp = nil
self.Start = Vector2( cursor.x, 1 )
self.Caret = Vector2( cursor.x, #self.Rows[cursor.x] + 1 )
else
self.temp = true
self.Start = self:wordStart( cursor )
self.Caret = self:wordEnd( cursor )
end
self.LastClick = CurTime( )
self.LastCursor = cursor
self:RequestFocus( )
self.Blink = RealTime( )
return
end
self.temp = nil
self.LastClick = CurTime( )
self.LastCursor = cursor
self:RequestFocus( )
self.Blink = RealTime( )
self.MouseDown = MOUSE_LEFT
self.Caret = self:CursorToCaret( )
if !input_IsKeyDown( KEY_LSHIFT ) and !input_IsKeyDown( KEY_RSHIFT ) then
self.Start = self:CopyPosition( self.Caret )
end
elseif code == MOUSE_RIGHT then
self.MouseDown = MOUSE_RIGHT
self:MouseCapture( true )
end
end
function PANEL:OnMouseReleased( code )
if code == MOUSE_LEFT and self.MouseDown == code then
self.MouseDown = nil
self.Caret = self:CursorToCaret( )
elseif code == MOUSE_RIGHT and self.MouseDown == code then
self.MouseDown = nil
self:MouseCapture( false )
if vgui.GetHoveredPanel( ) == self then
local Menu = DermaMenu( )
if self:HasSelection() then
Menu:AddOption( "Copy", function( )
local clipboard = self:GetSelection( )
clipboard = string_gsub( clipboard, "\n", "\r\n" )
SetClipboardText( clipboard )
end )
Menu:AddOption( "Cut", function( )
local clipboard = self:GetSelection( )
clipboard = string_gsub( clipboard, "\n", "\r\n" )
SetClipboardText( clipboard )
self:SetSelection( )
end )
end
Menu:AddOption( "Paste", function( )
self.TextEntry:Paste( )
end )
Menu:AddSpacer( )
Menu:AddOption( "Select All", function( )
self:SelectAll( )
end )
Menu:Open( )
end
end
end
function PANEL:OnMouseWheeled( delta )
self.Scroll:Add( - 4 * delta, 0 )
if self.Scroll.x < 1 then self.Scroll.x = 1 end
if self.Scroll.x > #self.Rows then self.Scroll.x = #self.Rows end
self.ScrollBar:SetScroll( self.Scroll.x - 1 )
end
/*---------------------------------------------------------------------------
Paint stuff
---------------------------------------------------------------------------*/
local function ParseIndents( Rows, exit )
local foldData = { }
local level = 0
for line = 1, #Rows do
if line == exit then break end
local text = Rows[line]
foldData[line] = 0 //level
for nStart, sType, nEnd in string.gmatch( text, "()([{}])()") do
level = level + ( sType == "{" and 1 or -1 )
end
end
return foldData
end
local function FindValidLines( Rows )
local Out = { }
local MultilineComment = false
local Row, Char = 1, 0
while Row < #Rows do
local Line = Rows[Row]
while Char < #Line do
Char = Char + 1
local Text = Line[Char]
if MultilineComment then
if Text == "/" and Line[Char-1] == "*" then
if Out[Row] then
Out[Row] = Out[Row] or { 0, 0 }
Out[Row][2] = Char
else
Out[Row] = { 1, Char }
end
MultilineComment = false
continue
else
Out[Row] = Out[Row] or false
continue
end
end
if Text == "/" then
if Line[Char+1] == "/" then // SingleLine comment
Out[Row] = { Char, #Line + 1 }
break
elseif Line[Char+1] == "*" then // MultiLine Comment
MultilineComment = true
Out[Row] = { Char, #Line + 1 }
continue
end
end
end
if not Out[Row] and Out[Row] ~= false then
Out[Row] = true
end
Char = 0
Row = Row + 1
end
return Out
end
local function FindMatchingParam( Rows, Row, Char )
if !Rows[Row] then return false end
local Param, EnterParam, ExitParam = ParamPairs[Rows[Row][Char]]
if not Param then
Char = Char - 1
Param = ParamPairs[Rows[Row][Char]]
end
if not Param then return false end
EnterParam = Param[1]
ExitParam = Param[2]
local line, pos, level = Row, Char, 0
local ValidLines = FindValidLines( Rows )
if type( ValidLines[line] ) == "table" and ValidLines[line][1] <= pos and ValidLines[line][2] >= pos then return false end
if Param[3] then -- Look forward
while line < #Rows do
while pos < #Rows[line] do
pos = pos + 1
local Text = Rows[line][pos]
if not ValidLines[line] then break end
if type( ValidLines[line] ) == "table" and ValidLines[line][1] <= pos and ValidLines[line][2] >= pos then continue end
if Text == EnterParam then
level = level + 1
elseif Text == ExitParam then
if level > 0 then
level = level - 1
else
return { Vector2( Row, Char ), Vector2( line, pos ) }
end
end
end
pos = 0
line = line + 1
end
else -- Look backwards
while line > 0 do
while pos > 0 do
pos = pos - 1
local Text = Rows[line][pos]
if not ValidLines[line] then break end
if type( ValidLines[line] ) == "table" and ValidLines[line][1] <= pos and ValidLines[line][2] >= pos then continue end
if Text == EnterParam then
level = level + 1
elseif Text == ExitParam then
if level > 0 then
level = level - 1
else
return { Vector2( line, pos ), Vector2( Row, Char ) }
end
end
end
line = line - 1
pos = #(Rows[line] or "") + 1
end
end
return false
end
function PANEL:Paint( w, h )
self.LineNumberWidth = 6 + self.FontWidth * string_len( tostring( math_min( self.Scroll.x, #self.Rows - self.Size.x + 1 ) + self.Size.x - 1 ) )
if !input_IsMouseDown( MOUSE_LEFT ) and self.MouseDown == MOUSE_LEFT then
self:OnMouseReleased( MOUSE_LEFT )
end
self.PaintRows = self.PaintRows or { }
if self.MouseDown and self.MouseDown == MOUSE_LEFT then
self.Caret = self:CursorToCaret( )
end
local offset = table_Count( table_KeysFromValue( self.FoldedRows, true ) )
local n = #self.Rows + ( math_floor( self:GetTall( ) / self.FontHeight ) - 2 ) - offset
// Disabled
/*if self.CanvasSize ~= n and false then
self.ScrollBar:SetUp( self.Size.x, n )
self:CalculateHScroll( )
-- self.ScrollBar:InvalidateLayout( true )
self.CanvasSize = n
end */
self.Scroll.x = math_floor( self.ScrollBar:GetScroll( ) + 1 )
self.Scroll.y = math_floor( self.hScrollBar:GetScroll( ) + 1 )
self:DrawText( w, h )
self:PaintTextOverlay( )
/*local str = "Length: " .. #self:GetCode( ) .. " Lines: " .. #self.Rows .. " Row: " .. self.Caret.x .. " Col: " .. self.Caret.y
if ( self:HasSelection( ) ) then str = str .. " Sel: " .. #self:GetSelection( ) end
surface_SetFont( "Trebuchet18" )
local w,h = surface_GetTextSize( str )
local _w, _h = self:GetSize( )
draw_WordBox( 4, _w - w - 10 - ( self.ScrollBar.Enabled and 16 or 0 ), _h - h - 10, str, "Trebuchet18", Color( 0,0,0,100 ), Color( 255,255,255,255 ) )*/
end
function PANEL:PaintTextOverlay( )
if self.TextEntry:HasFocus( ) and self.Caret.x - self.Scroll.x >= 0 and self.Caret.x < self.Scroll.x + self.Size.x + 1 then
local width, height = self.FontWidth, self.FontHeight
if ( RealTime( ) - self.Blink ) % 0.8 < 0.4 then
surface_SetDrawColor( 240, 240, 240, 255 )
if self.Insert then
surface_DrawRect( ( self.Caret.y - self.Scroll.y ) * width + self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth, ( self.CaretRow + 1 ) * height, width, 1 )
else
surface_DrawRect( ( self.Caret.y - self.Scroll.y ) * width + self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth, self.CaretRow * height, 1, height )
end
end
end
end
local C_white = Color( 255, 255, 255 )
local C_gray = Color( 160, 160, 160 )
function PANEL:DrawText( w, h )
surface_SetFont( "Fixedsys" )
surface_SetDrawColor( 32, 32, 32, 255 )
surface_DrawRect( 0, 0, self.BookmarkWidth, self:GetTall( ) )
surface_DrawRect( self.BookmarkWidth, 0, self.LineNumberWidth, self:GetTall( ) )
surface_DrawRect( self.BookmarkWidth + self.LineNumberWidth, 0, self.FoldingWidth, self:GetTall( ) )
surface_SetDrawColor( 0, 0, 0, 255 )
surface_DrawRect( self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth, 0, self:GetWide( ) - ( self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth ), self:GetTall( ) )
self.Params = FindMatchingParam( self.Rows, self.Caret.x, self.Caret.y )
self.FoldData = ParseIndents( self.Rows )
for i = 1, #self.Rows do
if self.FoldButtons[i] and ValidPanel( self.FoldButtons[i] ) then
self.FoldButtons[i]:SetVisible( false )
end
end
for i = 1, #self.Rows do
if self.Bookmarks[i] and ValidPanel( self.Bookmarks[i] ) then
self.Bookmarks[i]:SetVisible( false )
end
end
local line = self.Scroll.x - 1
line = line + GetFoldingOffset( self, line + self.Scroll.x - 1 )
while self.FoldedRows[line+1] do
line = line + 1
end
local painted = 0
local hideLevel = 0
while painted < self.Size.x + 2 do
line = line + 1
if hideLevel == 0 then
if self.FoldButtons[line] then
local btn = self.FoldButtons[line]
if !btn.Expanded then
hideLevel = self.FoldData[line + 1]
end
end
self:PaintRowUnderlay( line, painted )
self:PaintRow( line, painted )
painted = painted + 1
self.FoldedRows[line] = false
elseif !self.FoldData[line] or self.FoldData[line] < hideLevel then
hideLevel = 0
line = line - 1
self.FoldedRows[line] = true
else
self.FoldedRows[line] = true
end
end
-- for i = self.Scroll.x, self.Scroll.x + self.Size.x + 1 do
-- self:PaintRow( i )
-- end
end
function PANEL:PaintRowUnderlay( Row, LinePos )
if Row > #self.Rows then return end
if Row == self.Caret.x and self.TextEntry:HasFocus( ) then
surface_SetDrawColor( 48, 48, 48, 255 )
surface_DrawRect( self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth, ( LinePos ) * self.FontHeight, self:GetWide( ) - ( self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth ) , self.FontHeight )
self.CaretRow = LinePos
end
if self:HasSelection( ) then
local start, stop = self:MakeSelection( self:Selection( ) )
local line, char = start.x, start.y
local endline, endchar = stop.x, stop.y
char = char - self.Scroll.y
endchar = endchar - self.Scroll.y
if char < 0 then char = 0 end
if endchar < 0 then endchar = 0 end
local length = self.Rows[Row]:len( ) - self.Scroll.y + 1
surface_SetDrawColor( 0, 0, 160, 255 )
if Row == line and line == endline then
surface_DrawRect(
char * self.FontWidth + self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth,
( LinePos ) * self.FontHeight,
self.FontWidth * ( endchar - char ),
self.FontHeight
)
elseif Row == line then
surface_DrawRect(
char * self.FontWidth + self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth,
( LinePos ) * self.FontHeight,
self.FontWidth * math_min( self.Size.y - char + 2, length - char + 1 ),
self.FontHeight
)
elseif Row == endline then
surface_DrawRect(
self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth,
( LinePos ) * self.FontHeight,
self.FontWidth * endchar,
self.FontHeight
)
elseif Row > line and Row < endline then
surface_DrawRect(
self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth,
( LinePos ) * self.FontHeight,
self.FontWidth * math_min( self.Size.y + 2, length + 1 ),
self.FontHeight
)
end
elseif self.Params then
if self.Params[1].x == Row then
surface_SetDrawColor( 160, 160, 160, 255 )
surface_DrawRect( ( self.Params[1].y - self.Scroll.y ) * self.FontWidth + self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth, (LinePos+1) * self.FontHeight, self.FontWidth, 1 )
end
if self.Params[2].x == Row then
surface_SetDrawColor( 160, 160, 160, 255 )
surface_DrawRect( ( self.Params[2].y - self.Scroll.y ) * self.FontWidth + self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth, (LinePos+1) * self.FontHeight, self.FontWidth, 1 )
end
end
end
function PANEL:PaintRow( Row, LinePos )
if Row > #self.Rows then return end
if Row < #self.Rows and self.FoldData[Row] < self.FoldData[Row+1] then
if !self.FoldButtons[Row] or !ValidPanel( self.FoldButtons[Row] ) then
local btn = self:Add( "EA_ImageButton" )
btn:SetPos( self.BookmarkWidth + self.LineNumberWidth, ( LinePos ) * self.FontHeight )
btn:SetIconCentered( true )
btn:SetIconFading( false )
btn.Expanded = true
btn:SetMaterial( Material( "oskar/minus.png" ) )
local paint = btn.Paint
btn.Paint = function( _, w, h )
surface.SetDrawColor = function()
surface_SetDrawColor( 150, 150, 150, 255 )
if btn.Hovered then surface_SetDrawColor( 200, 200, 200, 255 ) end
end
paint( btn, w, h )
surface.SetDrawColor = surface_SetDrawColor
end
btn.DoClick = function( )
if btn.Expanded then
btn:SetMaterial( Material( "oskar/plus.png" ) )
btn.Expanded = false
else
btn:SetMaterial( Material( "oskar/minus.png" ) )
btn.Expanded = true
end
end
self.FoldButtons[Row] = btn
else
self.FoldButtons[Row]:SetVisible( true )
self.FoldButtons[Row]:SetPos( self.BookmarkWidth + self.LineNumberWidth, ( LinePos ) * self.FontHeight )
end
end
if Row <= #self.Rows then
if not self.Bookmarks[Row] or not ValidPanel( self.Bookmarks[Row] ) then
local btn = self:Add( "EA_ImageButton" )
btn:SetIconCentered( true )
btn:SetIconFading( false )
btn.bActive = false
btn:SetMaterial( BookmarkMaterial )
local paint = btn.Paint
btn.Paint = function( _, w, h )
if not btn.bActive then return end
paint( btn, w, h )
end
btn.DoClick = function( )
btn.bActive = not btn.bActive
if btn.bActive then
self.ActiveBookmarks[Row] = { self:MakeSelection( self:Selection( ) ) }
else
self.ActiveBookmarks[Row] = nil
end
end
self.Bookmarks[Row] = btn
end
self.Bookmarks[Row]:SetVisible( true )
self.Bookmarks[Row]:SetPos( 2, ( LinePos ) * self.FontHeight )
end
draw_SimpleText( tostring( Row ), "Fixedsys", self.BookmarkWidth + self.LineNumberWidth - 3, self.FontHeight * ( LinePos ), C_white, TEXT_ALIGN_RIGHT )
local offset = math_max( self.Scroll.y, 1 )
if !self.PaintRows[Row] then
self.PaintRows[Row] = self:SyntaxColorLine( Row )
end
local offset = -self.Scroll.y + 1
for i, cell in ipairs( self.PaintRows[Row] ) do
if offset < 0 then
if cell[1]:len( ) > -offset then
line = cell[1]:sub( 1 - offset )
offset = line:len( )
draw_SimpleText( line .. " ", "Fixedsys", self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth, ( LinePos ) * self.FontHeight, cell[2] )
else
offset = offset + cell[1]:len( )
end
else
draw_SimpleText( cell[1] .. " ", "Fixedsys", offset * self.FontWidth + self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth, ( LinePos ) * self.FontHeight, cell[2] )
offset = offset + cell[1]:len( )
end
end
end
function PANEL:SyntaxColorLine( Row )
return { { self.Rows[Row], C_white } }
end
/*---------------------------------------------------------------------------
Text setters / getters
---------------------------------------------------------------------------*/
function PANEL:SetCode( Text )
self.ScrollBar:SetScroll( 0 )
self.hScrollBar:SetScroll( 0 )
self.Rows = string_Explode( "\n", Text )
self.Caret = Vector2( 1, 1 )
self.Start = Vector2( 1, 1 )
self.Scroll = Vector2( 1, 1 )
self.Undo = { }
self.Redo = { }
self.PaintRows = { }
self.ScrollBar:SetUp( self.Size.x, #self.Rows + ( math_floor( self:GetTall( ) / self.FontHeight ) - 2 ) - table_Count( table_KeysFromValue( self.FoldedRows, true ) ))
self:CalculateHScroll( )
end
function PANEL:GetCode( )
local code = string_gsub( table_concat( self.Rows, "\n" ), "\r", "" )
return code
end
function PANEL:OnTextChanged( )
// Override
end
/*---------------------------------------------------------------------------
PerformLayout
---------------------------------------------------------------------------*/
function PANEL:CalculateHScroll( )
self.LongestRow = 0
for i = 1, #self.Rows do
self.LongestRow = math.max( self.LongestRow, #self.Rows[i] )
end
self.hScrollBar:SetUp( self.Size.y, self.LongestRow )
end
function PANEL:PerformLayout( )
local NumberPadding = self.BookmarkWidth + self.LineNumberWidth + self.FoldingWidth
self.ScrollBar:SetSize( 16, self:GetTall( ) )
self.ScrollBar:SetPos( self:GetWide( ) - self.ScrollBar:GetWide( ), 0 )
self.hScrollBar:SetSize( self:GetWide( ) - NumberPadding - self.ScrollBar:GetWide( ), 16 )
self.hScrollBar:SetPos( NumberPadding, self:GetTall( ) - 16 )
self.Size.x = math_floor( self:GetTall( ) / self.FontHeight ) - 1
self.Size.y = math_floor( ( self:GetWide( ) - NumberPadding - self.ScrollBar:GetWide( ) ) / self.FontWidth ) - 1
self.ScrollBar:SetUp( self.Size.x, #self.Rows + ( math_floor( self:GetTall( ) / self.FontHeight ) - 2 ) )
self:CalculateHScroll( )
end
vgui.Register( "EA_Editor", PANEL, "EditablePanel" )
|
--[[
TheNexusAvenger
Visual indicator for the end of aiming.
--]]
local BEACON_SPEED_MULTIPLIER = 2
local Workspace = game:GetService("Workspace")
local NexusVRCharacterModel = require(script.Parent.Parent.Parent.Parent)
local NexusObject = NexusVRCharacterModel:GetResource("NexusInstance.NexusObject")
local Beacon = NexusObject:Extend()
Beacon:SetClassName("Beacon")
--[[
Creates a beacon.
--]]
function Beacon:__new()
self:InitializeSuper()
--Create the parts.
self.Sphere = Instance.new("Part")
self.Sphere.Transparency = 1
self.Sphere.Material = "Neon"
self.Sphere.Anchored = true
self.Sphere.CanCollide = false
self.Sphere.Size = Vector3.new(0.5,0.5,0.5)
self.Sphere.Shape = "Ball"
self.Sphere.TopSurface = "Smooth"
self.Sphere.BottomSurface = "Smooth"
self.Sphere.Parent = Workspace.CurrentCamera
self.ConstantRing = Instance.new("ImageHandleAdornment")
self.ConstantRing.Adornee = self.Sphere
self.ConstantRing.Size = Vector2.new(2,2)
self.ConstantRing.Image = "rbxasset://textures/ui/VR/VRPointerDiscBlue.png"
self.ConstantRing.Visible = false
self.ConstantRing.Parent = self.Sphere
self.MovingRing = Instance.new("ImageHandleAdornment")
self.MovingRing.Adornee = self.Sphere
self.MovingRing.Size = Vector2.new(2,2)
self.MovingRing.Image = "rbxasset://textures/ui/VR/VRPointerDiscBlue.png"
self.MovingRing.Visible = false
self.MovingRing.Parent = self.Sphere
end
--[[
Updates the beacon at a given CFrame.
--]]
function Beacon:Update(CenterCFrame,HoverPart)
--Calculate the size for the current time.
local Height = 0.4 + (-math.cos(tick() * 2 * BEACON_SPEED_MULTIPLIER)/8)
local BeaconSize = 2 * ((tick() * BEACON_SPEED_MULTIPLIER) % math.pi)/math.pi
--Update the size and position of the beacon.
self.Sphere.CFrame = CenterCFrame * CFrame.new(0,Height,0)
self.ConstantRing.CFrame = CFrame.new(0,-Height,0) * CFrame.Angles(math.pi/2,0,0)
self.MovingRing.CFrame = CFrame.new(0,-Height,0) * CFrame.Angles(math.pi/2,0,0)
self.MovingRing.Transparency = BeaconSize/2
self.MovingRing.Size = Vector2.new(BeaconSize,BeaconSize)
--Update the beacon color.
local BeaconColor = Color3.new(0,170/255,0)
if HoverPart then
local VRBeaconColor = HoverPart:FindFirstChild("VRBeaconColor")
if VRBeaconColor then
BeaconColor = VRBeaconColor.Value
elseif (HoverPart:IsA("Seat") or HoverPart:IsA("VehicleSeat")) and not HoverPart.Disabled then
BeaconColor = Color3.new(0,170/255,255/255)
end
end
self.Sphere.Color = BeaconColor
--Show the beacon.
self.Sphere.Transparency = 0
self.ConstantRing.Visible = true
self.MovingRing.Visible = true
end
--[[
Hides the beacon.
--]]
function Beacon:Hide()
--Hide the beacon.
self.Sphere.Transparency = 1
self.ConstantRing.Visible = false
self.MovingRing.Visible = false
end
--[[
Destroys the beacon.
--]]
function Beacon:Destroy()
self.Sphere:Destroy()
end
return Beacon
|
function FG_DrawBackgroundBlur( panel, starttime, blur )
local matBlurScreen = Material( "pp/blurscreen" )
local Fraction = 1
if ( starttime ) then
Fraction = math.Clamp( (SysTime() - starttime) / 1, 0, 1 )
end
local x, y = panel:LocalToScreen( 0, 0 )
DisableClipping( true )
surface.SetMaterial( matBlurScreen )
surface.SetDrawColor( 255, 255, 255, 255 )
for i=0.33, 1, 0.33 do
matBlurScreen:SetFloat( "$blur", Fraction * 5 * i )
matBlurScreen:Recompute()
if ( render ) then render.UpdateScreenEffectTexture() end -- Todo: Make this available to menu Lua
surface.DrawTexturedRect( x * -1, y * -1, ScrW(), ScrH() )
end
surface.SetDrawColor( 10, 10, 10, blur * Fraction )
surface.DrawRect( x * -1, y * -1, ScrW(), ScrH() )
DisableClipping( false )
end
|
require("config")
require("module")
require("common")
require("cameraTracker")
package.path=package.path..";../Samples/FlexibleBody/lua/?.lua" --;"..package.path
require("test/IguanaIKSolverLua")
require("RigidBodyWin/subRoutines/CollisionChecker")
useGraph=true
background="terrain"
--background="plane"
showHighMesh=false
showTargetMesh=false
matchPose=true
performIK=true
drawSphere=true
--[[
아래 부분의 코드가 구현에 해당한다. 윗부분을 바꿔서 다른 시나리오를 수행할 수 있다.
]]--
scenario="original_scale"
--option="explicit"
option="implicit"
--option="semi-implicit"
usePenaltyMethod=true
useEventRecoder=false
if useEventRecoder then
startMode="save" -- "load" or "save"
end
Timeline=LUAclass(LuaAnimationObject)
function Timeline:__init(label, totalTime)
self.totalTime=totalTime
RE.renderer():addFrameMoveObject(self)
self:attachTimer(1/30, totalTime)
RE.motionPanel():motionWin():addSkin(self)
end
function start()
rootnode =RE.ogreRootSceneNode()
bgnode=RE.createChildSceneNode(rootnode , "BackgroundNode")
if scenario=="original_scale" then
scale_factor=1
-- 50kg, 80 mm (메시가 크고 코드 전반적으로 스케일을 고치기 워려워서..)
if useEventRecoder then
RE.viewpoint():setFOVy(45.000004)
RE.viewpoint():setZoom(1.000001)
RE.viewpoint().vpos:set(400.811377, 193.491147, 485.733366)
RE.viewpoint().vat:set(61.462009, -103.110592, 22.623585)
RE.viewpoint():update()
if not drawSphere then
win:trcWin_setDrawSphere(false)
end
else
RE.viewpoint():setClipDistances(0.5, 1000)
RE.viewpoint():setFOVy(45.000002)
RE.viewpoint().vpos:assign(vector3(54.725145, 3.286307, 74.032226))
RE.viewpoint().vat:assign(vector3(1.288031, 0.837722, 0.142416))
RE.viewpoint():update()
end
-- 10000mm/s^2 = -10 m/s^2
gravity=-10000
-- 120
if usePenaltyMethod then
win.simulationFrameRate=1200 -- 밑에 penalty gains를 두배 늘리고 simulationFrameRate를 두배 늘리면 품질이 좀더 나아지지만, 너무 느려서 일단 이렇게.
else
win.simulationFrameRate=120
end
win.renderingFrameRate=60
stiffness=100000
legStiffness=stiffness*2
springDamp=1000
if false then
stiffness=10000
legStiffness=stiffness*2
springDamp=100
end
dynamicFrictionCoef=0.5
penaltyStiffness=1000000
penaltyDampness=10000
--dynamicFrictionCoef=10 -- this doesn't seem correct but..
world:setParameter("mass", 50)
world:setParameter("bendingConstraints1", 4)
world:setParameter("stiffness", stiffness)
world:setParameter("bendingStiffness", stiffness*0.5)
integrateM=1
--#define INTEGRATE_EXPLICIT 0
--#define INTEGRATE_IMPLICIT 1
--#define INTEGRATE_SEMI_IMPLICIT 2
world:setParameter("integrateMethod",integrateM)
world:setParameter("springDamp",springDamp)
world:setParameter("kDF", dynamicFrictionCoef) -- dynamic friction coefficient
world:setParameter("kDFvelThr", 0.01)
world:setParameter("drawContactForce", 1)
world:setParameter("debugDrawWorld",0)
world:setParameter("drawSimulatedMesh",1)
world:setGravity(vector3(0, gravity, 0))
if background=="terrain" then
initialPosition=vector3(0,30,0)
else
initialPosition=vector3(0,30,0)
end
if background=="terrain" then
world:createTerrain("../Resource/crowdEditingScripts/terrain/heightmap1_256_256_2bytes.raw", vector3(-200,0, -200), 256, 256, 800, 800, 30)
else
world:createFloor(-15, vector3(400, 30, 400))
end
if useGraph == true then
win:setTRCwinTerrain();
local w=win.mTRCwin:findWidget("Synthesis")
w:checkButtonValue(1)
win.mTRCwin:callCallbackFunction(w)
if showTargetMesh == false then
win:setSkeletonVisible(false)
else
win:setSkeletonVisible(true)
end
end
-- debug.debug()
win:createTargetMesh(0, scale_factor, initialPosition);
local maxV=vector3(-1e5, -1e5, -1e5)
local minV=vector3(1e5, 1e5, 1e5)
for i=0, win:targetMesh():numVertex()-1 do
local v= win:targetMesh():getVertex(i)
maxV.x=math.max(v.x, maxV.x)
maxV.y=math.max(v.y, maxV.y)
maxV.z=math.max(v.z, maxV.z)
minV.x=math.min(v.x, minV.x)
minV.y=math.min(v.y, minV.y)
minV.z=math.min(v.z, minV.z)
end
print(maxV-minV)
world:createSoftBody(win:targetMesh())
--if integrateM~=1 then
--world:setParameter("contactMethod",SimulatorImplicit.PENALTY_METHOD)
world:setParameter("contactMethod",SimulatorImplicit.LCP_METHOD)
if(usePenaltyMethod) then
world:setParameter("contactMethod",SimulatorImplicit.PENALTY_METHOD)
world:setParameter("penaltyStiffness", penaltyStiffness)
world:setParameter("penaltyDampness", penaltyDampness)
world:setParameter("penaltyMuScale", 2)
end
--else
--world:setParameter("contactMethod",SimulatorImplicit.LCP_METHOD_FRICTIONLESS)
--world:setParameter("contactMethod",SimulatorImplicit.LCP_METHOD)
-- world:setParameter("contactMethod",SimulatorImplicit.BARAFF98)
-- world:setParameter("penaltyStiffness", 10000)
--end
local resourcePath="../src/lua/"
world:adjustSoftBodyParam("dynamicFrictionCoef", resourcePath.."iguanaAll.selection", dynamicFrictionCoef*0)
--world:adjustSoftBodyParam("dynamicFrictionCoef", resourcePath.."iguanaTail.selection", 0)
world:adjustSoftBodyParam("dynamicFrictionCoef", resourcePath.."leftFoot.selection", dynamicFrictionCoef)
world:adjustSoftBodyParam("dynamicFrictionCoef", resourcePath.."rightFoot.selection", dynamicFrictionCoef)
world:adjustSoftBodyParam("dynamicFrictionCoef", resourcePath.."leftHand.selection", dynamicFrictionCoef)
world:adjustSoftBodyParam("dynamicFrictionCoef", resourcePath.."rightHand.selection", dynamicFrictionCoef)
world:adjustSoftBodyParam("stiffness", resourcePath.."leftFoot.selection", legStiffness)
world:adjustSoftBodyParam("stiffness", resourcePath.."rightFoot.selection", legStiffness)
world:adjustSoftBodyParam("stiffness", resourcePath.."leftHand.selection", legStiffness)
world:adjustSoftBodyParam("stiffness", resourcePath.."rightHand.selection", legStiffness)
mTerrain=TerrainWrapper ()
mIKsolver=IguanaIKSolverLUA(win:trcWin_motion():skeleton(), mTerrain)
noParam=vector3N ()
end
end
function ctor()
local wi=this:widgetIndex("scriptfn");
this:removeWidgets(wi+1);
this:create("Button", "test", "test")
this:updateLayout()
--mTimeline=Timeline("Timeline", 100000)
--RE.motionPanel():motionWin():playFrom(0)
if useEventRecoder then
--mEventReceiver=EVR() -- also rename EVRecoder:_onFrameChanged to EVR:_onFrameChanged
mEventReceiver=EVRecoder("none", "_testCollAvoid.dat")
if not drawSphere then
mEventReceiver.drawCursor=true
end
end
end
function callStart()
RE.viewpoint():setFOVy(44.999999)
if(world:isWorldValid()) then
if win:isTRCwin_synthesizing() then
win.mTRCwin:findWidget("Synthesis"):checkButtonValue(false)
win.mTRCwin:callCallbackFunction(w)
end
else
win:start()
prevDrawn=0
prevExactTime=0
start()
if useEventRecoder and mEventReceiver.mode=="none" then
mEventReceiver:changeMode(startMode)
end
end
end
function onCallback(w, userData)
--win:_onCallback(w, userData)
if w:id()=='Start' then
callStart()
elseif w:id()=='test' then
g_forces={
--CT.ivec(5),
CT.ivec(76),
vector3N(1),
0}
-- 1000000Nmm/s^2 = -1000 Nm/s^2
g_forces[2](0):assign(vector3(200000,0, -200000))
end
end
if not useEventRecoder then
EVRecoder={}
end
function EVRecoder:_frameMove(fElapsedTime)
if false then
return win:_frameMove(fElapsedTime)
end
local mSimulator=world
if not mSimulator:isWorldValid() then return 0 end
local nSubStep=math.round(win.simulationFrameRate/win.renderingFrameRate)
local step=1.0/win.simulationFrameRate
local mTargetMesh=win:targetMesh()
if mTargetMesh:numVertex()>0 then
if win:isTRCwin_synthesizing() then
win:trcWin_singleFrame();
for i=0, nSubStep-1 do
local exactTime=sop.clampMap(i,0,nSubStep, prevDrawn, win:trcWin_lastDrawn());
--print(exactTime);
if(win:trcWin_hasTerrain()) then
updateTargetMeshTRCwin(win:trcWin_terrainMotion(), prevExactTime, exactTime);
else
updateTargetMeshTRCwin(win:trcWin_motion(), prevExactTime, exactTime);
end
if g_forces then
world:addExternalForce(g_forces[1], g_forces[2])
g_forces[3]=g_forces[3]+1
end
win:stepSimulation(step);
prevExactTime=exactTime;
end
prevDrawn=win:trcWin_lastDrawn();
if g_forces then
local mSimulatedMesh=world.mSimulatedMesh;
local pos=mSimulatedMesh:getVertex(g_forces[1](0))
local f=g_forces[2](0)*0.001*0.05
dbg.draw('Arrow', pos-f, pos, "force", 4)
if g_forces[3]>win.simulationFrameRate*0.1 then
-- 0.2s
g_forces=nil
end
else
dbg.erase('Arrow', 'force')
end
end
end
world:renderme()
end
function dtor()
dbg.finalize()
end
function updateTargetMeshTRCwin(mot, prevTime, time)
local prevPose=Pose()
local pose=Pose();
mot:samplePose(prevPose, prevTime);
mot:samplePose(pose, time);
-- retrieve example mesh to mTargetMesh.
local mMeshAnimation=win.mMeshAnimation
local mTargetMesh=win:targetMesh()
local mPrevTargetMesh=win:prevTargetMesh()
mMeshAnimation:setPose(prevPose);
mMeshAnimation:retrieveAnimatedMesh(mPrevTargetMesh);
mMeshAnimation:setPose(pose);
mMeshAnimation:retrieveAnimatedMesh(mTargetMesh);
if(matchPose) then
-- 타겟메쉬의 이전 프레임과 simulatedMesh의 마지막 프레임을 맞추어준다.
local metric=math.KovarMetric ()
local mSimulatedMesh=world.mSimulatedMesh;
local nv=mSimulatedMesh:numVertex();
local simulated=vectorn(nv*3)
local captured=vectorn(nv*3)
for i=0, nv-1 do
simulated:setVec3(i*3, mSimulatedMesh:getVertex(i));
end
for i=0, nv-1 do
captured:setVec3(i*3, win:prevTargetMesh():getVertex(i));
end
metric:calcDistance(simulated, captured);
--dbg.namedDraw('Traj', simulated:matView(3), 'curr', 'blueCircle', 3, 'QuadListZ')
--dbg.namedDraw('Traj', captured:matView(3), 'goal', 'redCircle', 3, 'QuadListZ')
win:trcWin_transformSynthesized(metric.transfB);
if(performIK) then
pose:setRootTransformation(pose:rootTransformation()*transf(metric.transfB));
local DEBUG_DRAW=false
if DEBUG_DRAW then
-- debug skin
if not SKIN then
SKIN=RE.createSkin(win:trcWin_motion():skeleton())
end
end
mIKsolver:IKsolve(pose, noParam)
if DEBUG_DRAW then
SKIN:setPose(pose, win:trcWin_motion():skeleton())
end
-- update targetMesh to reveal IK result.
mMeshAnimation:setPose(pose);
mMeshAnimation:retrieveAnimatedMesh(mTargetMesh);
end
end
world:changeSoftBodyRestLength(mTargetMesh);
end
function EVRecoder:_onFrameChanged(win, iframe)
end
function EVRecoder:_handleRendererEvent(ev, button, x,y)
print(ev, button)
if ev=="KEYDOWN" or ev=="KEYUP" then
local ascii=tonumber(button)
if not ascii then
ascii=string.byte(button)
end
--print(ascii)
return win:trcWin_handleRendererEvent(ev, ascii, -1, -1);
else
return win:trcWin_handleRendererEvent(ev, button,x, y);
end
--return 0
end
TerrainWrapper = LUAclass()
function TerrainWrapper :__init()
end
function TerrainWrapper:getTerrainHeight2(pos)
return win:getTerrainHeight(pos)
end
if not useEventRecoder then
function handleRendererEvent(ev, button, x,y)
return EVRecoder:_handleRendererEvent(ev, button, x, y)
end
function frameMove(fElapsedTime)
return EVRecoder:_frameMove(fElapsedTime)
end
end
|
----------------------------------------------------------
-- Load RayUI Environment
----------------------------------------------------------
RayUI:LoadEnv("UnitFrames")
local _, ns = ...
local oUF = RayUF or oUF
local utf8sub = function(string, i, dots)
local bytes = string:len()
if (bytes <= i) then
return string
else
local len, pos = 0, 1
while(pos <= bytes) do
len = len + 1
local c = string:byte(pos)
if c > 240 then
pos = pos + 4
elseif c > 225 then
pos = pos + 3
elseif c > 192 then
pos = pos + 2
else
pos = pos + 1
end
if (len == i) then break end
end
if (len == i and pos <= bytes) then
return string:sub(1, pos - 1)..(dots and "..." or "")
else
return string
end
end
end
local function hex(r, g, b)
if not r then return "|cffFFFFFF" end
if(type(r) == "table") then
if(r.r) then r, g, b = r.r, r.g, r.b else r, g, b = unpack(r) end
end
return ("|cff%02x%02x%02x"):format(r * 255, g * 255, b * 255)
end
oUF.Tags.Methods["RayUF:lvl"] = function(u)
local level = UnitLevel(u)
local typ = UnitClassification(u)
local diffColor = level > 0 and GetQuestDifficultyColor(level) or QuestDifficultyColors["impossible"]
if level <= 0 then
level = "??"
end
if typ=="rareelite" then
return hex(diffColor)..level.."r+|r"
elseif typ=="elite" then
return hex(diffColor)..level.."+|r"
elseif typ=="rare" then
return hex(diffColor)..level.."r|r"
else
return hex(diffColor)..level.."|r"
end
end
oUF.Tags.Methods["RayUF:hp"] = function(u)
local color
if UnitIsPlayer(u) then
local _, class = UnitClass(u)
color = oUF.colors.class[class]
elseif UnitIsTapDenied(u) then
color = oUF.colors.tapped
elseif UnitIsEnemy(u, "player") then
color = oUF.colors.reaction[1]
else
color = oUF.colors.reaction[UnitReaction(u, "player") or 5]
end
local min, max = UnitHealth(u), UnitHealthMax(u)
-- return R:ShortValue(min).." | "..math.floor(min/max*100+.5).."%"
return format("|cff%02x%02x%02x%s|r", color[1] * 255, color[2] * 255, color[3] * 255, R:ShortValue(min).." | "..math.floor(min/max*100+.5).."%")
end
oUF.Tags.Events["RayUF:hp"] = "UNIT_HEALTH"
oUF.Tags.Methods["RayUF:pp"] = function(u)
local _, str = UnitPowerType(u)
local power = UnitPower(u)
if str and power > 0 then
local min, max = UnitPower(u), UnitPowerMax(u)
return hex(oUF.colors.power[str])..R:ShortValue(min).." | "..math.floor(min/max*100+.5).."%".."|r"
end
end
oUF.Tags.Events["RayUF:pp"] = "UNIT_POWER_UPDATE"
oUF.Tags.Methods["RayUF:color"] = function(u, r)
local _, class = UnitClass(u)
local reaction = UnitReaction(u, "player")
if UnitIsTapDenied(u) then
return hex(oUF.colors.tapped)
elseif (UnitIsPlayer(u)) then
return hex(oUF.colors.class[class])
elseif reaction then
return hex(oUF.colors.reaction[reaction])
else
return hex(1, 1, 1)
end
end
oUF.Tags.Events["RayUF:color"] = "UNIT_HEALTH_FREQUENT UNIT_MAXHEALTH UNIT_CONNECTION PLAYER_FLAGS_CHANGED"
oUF.Tags.Methods["RayUF:name"] = function(u, r)
local name = UnitName(r or u)
return name
end
oUF.Tags.Events["RayUF:name"] = "UNIT_NAME_UPDATE"
oUF.Tags.Methods["RayUF:info"] = function(u)
if UnitIsDead(u) then
return oUF.Tags.Methods["RayUF:lvl"](u).."|cffCFCFCF "..DEAD.."|r"
elseif UnitIsGhost(u) then
return oUF.Tags.Methods["RayUF:lvl"](u).."|cffCFCFCF "..L["灵魂"].."|r"
elseif not UnitIsConnected(u) then
return oUF.Tags.Methods["RayUF:lvl"](u).."|cffCFCFCF "..L["离线"].."|r"
else
return oUF.Tags.Methods["RayUF:lvl"](u)
end
end
oUF.Tags.Events["RayUF:info"] = "UNIT_HEALTH"
oUF.Tags.Methods["RayUF:altpower"] = function(u)
local cur = UnitPower(u, ALTERNATE_POWER_INDEX)
local max = UnitPowerMax(u, ALTERNATE_POWER_INDEX)
local per = 0
if max ~= 0 then
per = floor(cur/max*100)
end
return format("%d", per > 0 and per or 0).."%"
end
oUF.Tags.Events["RayUF:altpower"] = "UNIT_POWER_UPDATE UNIT_MAXPOWER"
|
local nest = require('nest')
-- register groups name via which-key and apply via nest
local register_groups = function(maps)
for _, map in pairs(maps) do
nest.applyKeymaps(map)
end
end
local escapes = {
{ mode = "i", { "jk", "<Esc>" } },
{ mode = "t", { "jk", "<C-\\><C-N>" } },
}
local leader = {
prefix = "<leader>",
{ "l", "<cmd>luaf%<cr>" },
{ "q", "<cmd>Format<cr>" },
}
-- Easy align
local align = {
{ options = { noremap = false }, {
{ mode = "n", { "ga", "<Plug>(EasyAlign)" } },
{ mode = "v", { "ga", "<Plug>(EasyAlign)" } },
}}
}
local telescope = {
name = "telescope",
prefix = "<leader>t",
{ "t", "<cmd>Telescope<cr>" },
{ "f", "<cmd>Telescope fd<cr>" },
{ "s", "<cmd>Telescope file_browser<cr>" },
{ "b", "<cmd>Telescope buffers<cr>" },
{ "g", "<cmd>Telescope live_grep<cr>" },
{ "h", "<cmd>Telescope command_history<cr>" },
{ "r", "<cmd>Telescope oldfiles<cr>" },
}
register_groups({
escapes,
leader,
telescope,
align
})
|
function start (song)
print("Song: " .. song .. " @ " .. bpm .. " downscroll: " .. downscroll)
followDadXOffset = -75
end
local defaultHudX = 0
local defaultHudY = 0
local defaultWindowX = 0
local defaultWindowY = 0
local lastStep = 0
local floatShit = 0
local dadMidpointX = 0
local dadMidpointY = 0
function update (elapsed)
local currentBeat = (songPos / 1000)*(bpm/60)
if cameraShake then
shakeCam(0.01, 0.01)
shakeHUD(0.01, 0.01)
end
if laughShake then
shakeCam(0.005, 0.01)
end
end
function beatHit (beat)
end
function stepHit (step)
--leaving this here to test stuff
if curStep == 1 then
end
if curStep >= 432 and curStep < 448 then
setDefaultCamZoom(1.1)
end
if curStep == 440 then
laughShake = true
flashCam(125, 125, 125, 2)
end
if curStep == 448 then
laughShake = false
cameraShake = true
setDefaultCamZoom(0.9)
end
if curStep == 704 then
cameraShake = false
end
end
function dadNoteHit()
if curStep >= 444 and curStep < 448 then
-- addCamZoom(0.2)
--addHudZoom(0.2)
end
end
|
local errorinfo_list = {
[1] = "技能还在冷却中",
[2] = "能量不足",
[3] = "血量不足",
[4] = "没有目标",
[5] = "封印状态下无法使用该技能",
[6] = "没有阵亡队友",
[7] = "技能释放失败",
[8] = "只有队长可以进行此操作",
[9] = "全员自动中,无法进行此操作",
}
function showErrorInfo(id)
root.view.battle.Canvas.ErrorInfo:SetActive(true);
root.view.battle.Canvas.ErrorInfo.Text[UnityEngine.UI.Text].text = errorinfo_list[id];
end
function EVENT.RAW_BATTLE_EVENT(_, event, ...)
if event == "SHOW_ERROR_INFO" then
if root.speedUp then return end
local info = ...
showErrorInfo(info.id)
end
end
|
function OnAlarm(timer)
--local pickupEntity = timer:getEntity()
timer.currentTrigger:setEnabled(true)
local app = Phyre.PApplication.GetApplicationForScript()
local controller = timer:getEntity():getComponentType(Phyre.PQuarryComponent):getEntity():getComponent(Phyre.PPhysicsCharacterControllerComponent)
if controller then
app:resetPlayerStatus(controller)
end
timer:reset()
end
|
require("neoscroll").setup({
mappings = { "<C-u>", "<C-d>", "zt", "zz", "zb" },
})
|
-- Places a node within a 3x3x3 around the main node
local make_ore = function (pos, elapsed)
local meta = minetest.get_meta(pos)
--oreveins.tools.log("make_ore "..minetest.serialize(oreveins._internal.oreos[meta:get_string("id")]))
local ore = oreveins._internal.oreos[meta:get_string("id")]["nodes"][math.random(#oreveins._internal.oreos[meta:get_string("id")]["nodes"])]
local size = meta:get_int("size")
meta:set_int("time", 0) -- Reset internal time
local pos_add = vector.add(pos, vector.new(size, size, size))
local pos_sub = vector.subtract(pos, vector.new(size, size, size))
local air_nodes = minetest.find_nodes_in_area(pos_add, pos_sub, {"air"}, true)
if air_nodes == nil then return true end -- It's empty so let's treat it like we've already placed a node.
air_nodes = air_nodes["air"]
--oreveins.tools.log("find_nodes_in_area found "..minetest.serialize(air_nodes))
if air_nodes == nil then return true end -- Prevents after our change from blowing up
if #air_nodes == 0 then return true end -- Ensure we don't blow up when itterating over nil/empty table
if air_nodes == {} then return true end -- The quest to prevent blow up
-- Iterate over all positions finding a position which is air/empty
for indx, sec in pairs(air_nodes) do
local node = minetest.get_node_or_nil(sec)
local name = "nil"
if node ~= nil then
name = node.name
end
if oreveins.log_debug then
oreveins.tools.log(""..tostring(indx).." "..minetest.pos_to_string(sec, 1).." "..name)
end
if name == "air" then
if oreveins.log_debug then
oreveins.tools.log("I built a "..ore.." here.")
end
if ore ~= "technic:mineral_uranium" then
minetest.swap_node(sec, {name = ore})
else
minetest.swap_node(sec, {name = "oreveins:uranium_ore"})
end
return true
end
end
return true -- Keep the nodetimer going
end
-- Now we use all this to make our machine
local grouping = nil
local sounding = nil
if oreveins.GAMEMODE == "MCL2" or oreveins.GAMEMODE == "MCL5" then
local mcl_sounds = rawget(_G, "mcl_sounds") or oreveins.tools.error("Failed obtaining mcl_sounds")
grouping = {handy=1, axey=1, pickaxey=1, shovely=1}
sounding = mcl_sounds.node_sound_metal_defaults()
elseif oreveins.GAMEMODE == "MTG" then
local default = rawget(_G, "default") or oreveins.tools.error("Failed obtaining default for sounds")
grouping = {oddly_breakable_by_hand = 1}
sounding = default.node_sound_metal_defaults()
else
grouping = {oddly_breakable_by_hand = 1, handy=1, axey=1, pickaxey=1, shovely=1}
end
-- Registers a node which passively produces ores (Returns if successful)
oreveins.make_orevein = function (id, use_id_as_name)
if oreveins._internal.oreos[id] == nil then
oreveins.tools.log("Invalid node "..itemstring.." for creating orevein.")
return false
end
local itemstring = oreveins._internal.oreos[id]["nodes"][1]
local itemstring_split = oreveins.tools.split(itemstring, ":")
local from_mod = itemstring_split[1]
local item = itemstring_split[2]
local item_split = oreveins.tools.split(item, "_")
local name = "ore"
name = item_split[ #item_split ]
if use_id_as_name ~= nil then
name = id
end
name = oreveins.tools.firstToUpper(name)
local texts = ItemStack(itemstring.." 1"):get_definition().tiles[1] or oreveins.tools.error("Failed obtaining texture of "..itemstring)
minetest.register_node("oreveins:"..id, {
short_description = name.." Vein",
description = name.." Vein\n"
.."Produces: "..tostring(#oreveins._internal.oreos[id]["nodes"]).." nodes\n"
.."Size: "..tostring(oreveins._internal.oreos[id]["size"]).." cubed\n"
.."Speed: "..tostring(oreveins._internal.oreos[id]["speed"]).." seconds",
_doc_items_long_desc = oreveins.S("Oreveins produce ores over a period of time, this allows the world to remain more or less untouched, since oreveins produce an unlimited amount"),
_doc_items_usagehelp = oreveins.S("Place a node on the ground, place a orevein on top of that block then remove that block (under the orevein), wait till it produces. keep nodes away from the orevein to allow placeing ores there"),
_doc_items_hidden=false,
tiles = {
texts.."^oreveins_overlay.png"
},
groups = grouping,
-- Ah MCL uses extra stuff
_mcl_blast_resistance = 2,
_mcl_hardness = 2,
sounds = sounding,
paramtype2 = "facedir",
light_source = 1,
drop = "oreveins:"..item,
on_construct = function (pos)
local meta = minetest.get_meta(pos)
meta:set_string("id", id)
meta:set_string("product", itemstring)
meta:set_int("max_time", oreveins._internal.oreos[id]["speed"])
meta:set_int("time", 0)
meta:set_int("size", oreveins._internal.oreos[id]["size"])
meta:set_int("upgrade_size", 0)
meta:set_int("upgrade_speed", 0)
meta:set_int("breakable", 1)
meta:set_string("infotext", name.." Vein ("..tostring(maxtime)..")")
end,
after_place_node = function (pos, placer, itemstack)
local meta = minetest.get_meta(pos)
local timer = minetest.get_node_timer(pos)
timer:start(1)
end,
after_dig_node = function(pos, oldnode, oldnodemeta, digger)
if oldnode == nil then return nil end
if oldnodemeta == nil then return nil end
local size_ups = oldnodemeta.upgrade_size or 0
local speed_ups = oldnodemeta.upgrade_speed or 0
local p_inv = minetest.get_inventory({type="player", name=digger:get_player_name()})
local up_size = ItemStack("oreveins:upgrade_size") or 0
local up_speed = ItemStack("oreveins:upgrade_speed") or 0
for i=0,size_ups,1 do
if p_inv:room_for_item("main", up_size) then
p_inv:add_item("main", up_size)
else
break
end
end
for i=0,speed_ups,1 do
if p_inv:room_for_item("main", up_speed) then
p_inv:add_item("main", up_speed)
else
break
end
end
end,
can_dig = function(pos, player)
local meta = minetest.get_meta(pos)
return meta:get_int("breakable") == 1
end,
on_timer = function (pos, elapsed)
local meta = minetest.get_meta(pos)
meta:set_string("infotext", name.." Vein ("..tostring(meta:get_int("max_time")-meta:get_int("time"))..")")
if(meta:get_int("time")+1 > meta:get_int("max_time")) then
return make_ore(pos, elapsed)
end
meta:set_int("time", meta:get_int("time")+1)
return true
end
})
if oreveins.ir ~= nil and oreveins.blacklist_replication then
oreveins.ir.bl_add("oreveins:"..id)
end
--[[if oreveins.craftable then
minetest.register_craft({
output = "oreveins:"..item.." 1",
recipe = {
{itemstring, itemstring, itemstring},
{itemstring, itemstring, itemstring},
{itemstring, itemstring, itemstring}
}
})
end]]
minetest.register_craft({
type = "fuel",
recipe = "oreveins:"..item,
burntime = 600 -- 10 minutes
})
return true
end
-- Calls make_orevein for each vein id in _internals
oreveins.make_veins = function()
local oreos = oreveins._internal.oreos
local mades = 0
--oreveins.tools.log(minetest.serialize(oreos))
for idx, cookie in pairs(oreos) do
--oreveins.tools.log("I want a "..idx)
if idx ~= "orepack" then
oreveins.make_orevein(idx, false)
mades = mades + 1
else
oreveins.make_orevein(idx, true)
mades = mades + 1
end
end
oreveins.tools.log("Made "..tostring(mades).." oreveins.")
end
local upgrade_it = function(itemstack, placer, pointed)
--oreveins.tools.log("GET: We don't know, "..placer:get_player_name()..", "..minetest.serialize(pointed))
if pointed == nil then
oreveins.tools.log("Pointed is nil!")
return itemstack
end
if pointed.x == nil or pointed.y == nil or pointed.z == nil then
oreveins.tools.log("Pointed contains nil!")
return itemstack
end
local pmeta = minetest.get_meta(pointed)
local speed = pmeta:get_int("speed") or 0
local size = pmeta:get_int("size") or 0
if itemstack.name == "oreveins:upgrade_size" and size < oreveins.max_size then
pmeta:set_int("size", size+1)
pmeta:set_int("upgrade_size", pmeta:get_int("upgrade_size")+1)
oreveins.tools.log("Upgraded "..minetest.pos_to_string(pointed).." size to "..tostring(size+1))
elseif itemstack.name == "oreveins:upgrade_speed" and speed > oreveins.min_speed then
pmeta:set_int("speed", speed-1)
pmeta:set_int("upgrade_speed", pmeta:get_int("upgrade_speed")+1)
oreveins.tools.log("Upgraded "..minetest.pos_to_string(pointed).." speed to "..tostring(speed-1))
else
oreveins.tools.log("Can't Upgrade "..minetest.pos_to_string(pointed).." size is "..tostring(size).." speed is "..tostring(speed))
return nil
end
itemstack:take_item()
return itemstack
end
minetest.register_craftitem("oreveins:upgrade_size", {
short_description = "Size Upgrade",
description = "Use this on a vein to cause it to increase size.",
inventory_image = "oreveins_upgrade_size.png",
groups = {oreveins_upgrade=1, upgrade_size=1},
on_place = function(is, p, po)
return upgrade_it(is, p, po)
end,
on_use = function(is, p, po)
return upgrade_it(is, p, po)
end
})
minetest.register_craftitem("oreveins:upgrade_speed", {
short_description = "Speed Upgrade",
description = "Use this on a vein to cause it to spawn ores faster.",
inventory_image = "oreveins_upgrade_speed.png",
groups = {oreveins_upgrade=1, upgrade_speed=1},
on_place = function(is, p, po)
return upgrade_it(is, p, po)
end,
on_use = function(is, p, po)
return upgrade_it(is, p, po)
end
})
minetest.register_craftitem("oreveins:ic_card", {
description = "IC Card",
inventory_image = "oreveins_ic_card.png",
groups = {oreveins_ic=1}
})
minetest.register_craftitem("oreveins:driver", {
description = "Driver",
inventory_image = "oreveins_driver.png",
groups = {oreveins_driver=1}
})
local iron = "default:steel_ingot"
local gold = "default:gold_ingot"
local diamond = "default:diamond"
local mese = "default:mese_crystal"
local driver = "oreveins:driver"
local ic_card = "oreveins:ic_card"
if oreveins.GAMEMODE == "MCL2" or oreveins.GAMEMODE == "MCL5" then
iron = "mcl_core:iron_ingot"
gold = "mcl_core:gold_ingot"
diamond = "mcl_core:diamond"
mese = "mesecons:redstone"
end
if oreveins.craftable then
minetest.register_craft({
output = ic_card,
recipe = {
{iron, gold, iron},
{iron, mese, iron},
{iron, gold, iron}
},
})
minetest.register_craft({
output = driver,
recipe = {
{iron, diamond, iron},
{iron, mese, iron},
{iron, gold, iron}
},
})
minetest.register_craft({
output = "oreveins:upgrade_size",
recipe = {
{iron, driver, iron},
{iron, ic_card, iron},
{iron, gold, iron}
},
})
minetest.register_craft({
output = "oreveins:upgrade_speed",
recipe = {
{iron, ic_card, iron},
{iron, ic_card, iron},
{iron, gold, iron}
},
})
end
|
-- Taken from bb template
if PointsManager == nil then
Debug.EnabledModules['points:*'] = false
DebugPrint ( 'Creating new PointsManager object.' )
PointsManager = class({})
end
local WinnerEvent = Event()
local ScoreChangedEvent = Event()
local LimitChangedEvent = Event()
PointsManager.onWinner = WinnerEvent.listen
PointsManager.onScoreChanged = ScoreChangedEvent.listen
PointsManager.onLimitChanged = LimitChangedEvent.listen
function PointsManager:Init ()
DebugPrint ( 'Initializing.' )
self.hasGameEnded = false
self.extend_counter = 0
local scoreLimit = NORMAL_KILL_LIMIT
local scoreLimitIncrease = KILL_LIMIT_INCREASE
if HeroSelection.is10v10 then
scoreLimit = TEN_V_TEN_KILL_LIMIT
--scoreLimitIncrease = scoreLimitIncrease/2
end
scoreLimit = 10 + (scoreLimit + scoreLimitIncrease) * PlayerResource:SafeGetTeamPlayerCount()
CustomNetTables:SetTableValue( 'team_scores', 'limit', { value = scoreLimit, name = 'normal' } )
CustomNetTables:SetTableValue( 'team_scores', 'score', {
goodguys = 0,
badguys = 0,
})
GameEvents:OnHeroKilled(function (keys)
-- increment points
if not keys.killer or not keys.killed then
return
end
if keys.killer:GetTeam() ~= keys.killed:GetTeam() and not keys.killed:IsReincarnating() and not keys.killed:IsTempestDouble() and keys.killed:GetTeam() ~= DOTA_TEAM_NEUTRALS then
self:AddPoints(keys.killer:GetTeam())
end
end)
GameEvents:OnPlayerAbandon(function (keys)
-- Reduce the score limit when player abandons but only if game time is after MIN_MATCH_TIME
if HudTimer and HudTimer:GetGameTime() > MIN_MATCH_TIME then
PointsManager:RefreshLimit()
end
end)
GameEvents:OnPlayerReconnect(function (keys)
-- Try to refresh the score limit to the correct value if player reconnected
Timers:CreateTimer(1, function()
PointsManager:RefreshLimit()
end)
end)
-- Register chat commands
ChatCommand:LinkDevCommand("-addpoints", Dynamic_Wrap(PointsManager, "AddPointsCommand"), self)
ChatCommand:LinkDevCommand("-add_enemy_points", Dynamic_Wrap(PointsManager, "AddEnemyPointsCommand"), self)
ChatCommand:LinkDevCommand("-kill_limit", Dynamic_Wrap(PointsManager, "SetLimitCommand"), self)
-- Find fountains
local fountains = Entities:FindAllByClassname("ent_dota_fountain")
local radiant_fountain
local dire_fountain
for _, entity in pairs(fountains) do
if entity:GetTeamNumber() == DOTA_TEAM_GOODGUYS then
radiant_fountain = entity
elseif entity:GetTeamNumber() == DOTA_TEAM_BADGUYS then
dire_fountain = entity
end
end
-- Find fountain triggers
local radiant_fountain_t = Entities:FindByName(nil, "fountain_good_trigger")
local dire_fountain_t = Entities:FindByName(nil, "fountain_bad_trigger")
-- Find radiant shrine location(s)
local radiant_shrine
if radiant_fountain_t then
local radiant_fountain_bounds = radiant_fountain_t:GetBounds()
local radiant_fountain_origin = radiant_fountain_t:GetAbsOrigin()
radiant_shrine = Vector(radiant_fountain_bounds.Maxs.x + radiant_fountain_origin.x + 400, 0, 512)
else
radiant_shrine = Vector(-5200, 0, 512)
end
-- Find dire shrine location(s)
local dire_shrine
if dire_fountain_t then
local dire_fountain_bounds = dire_fountain_t:GetBounds()
local dire_fountain_origin = dire_fountain_t:GetAbsOrigin()
dire_shrine = Vector(dire_fountain_bounds.Mins.x + dire_fountain_origin.x - 400, 0, 512)
else
dire_shrine = Vector(5200, 0, 512)
end
-- Create shrines in front of the fountains
local coreDude = CreateUnitByName("npc_dota_core_guy", radiant_shrine, true, radiant_fountain, radiant_fountain, DOTA_TEAM_GOODGUYS)
coreDude = CreateUnitByName("npc_dota_core_guy", dire_shrine, true, dire_fountain, dire_fountain, DOTA_TEAM_BADGUYS)
--coreDude = CreateUnitByName("npc_dota_core_guy_2", Vector(-5200, -200, 512), true, nil, nil, DOTA_TEAM_GOODGUYS)
--coreDude = CreateUnitByName("npc_dota_core_guy_2", Vector(5200, 200, 512), true, nil, nil, DOTA_TEAM_BADGUYS)
end
function PointsManager:GetState ()
return {
limit = self:GetLimit(),
goodScore = self:GetPoints(DOTA_TEAM_GOODGUYS),
badScore = self:GetPoints(DOTA_TEAM_BADGUYS),
extend_counter = self.extend_counter
}
end
function PointsManager:LoadState (state)
self:SetLimit(state.limit)
self:SetPoints(DOTA_TEAM_GOODGUYS, state.goodScore)
self:SetPoints(DOTA_TEAM_BADGUYS, state.badScore)
self.extend_counter = state.extend_counter
end
function PointsManager:CheckWinCondition(teamID, points)
if self.hasGameEnded then
return
end
local limit = CustomNetTables:GetTableValue('team_scores', 'limit').value
if points >= limit then
WinnerEvent.broadcast(teamID)
end
end
function PointsManager:SetWinner(teamID)
-- actually need to implement lose win logic for teams
Music:FinishMatch(teamID)
GAME_WINNER_TEAM = teamID
Bottlepass:SendWinner(teamID)
GAME_TIME_ELAPSED = GameRules:GetDOTATime(false, false)
GameRules:SetGameWinner(teamID)
self.hasGameEnded = true
end
function PointsManager:SetPoints(teamID, amount)
local score = CustomNetTables:GetTableValue('team_scores', 'score')
if teamID == DOTA_TEAM_GOODGUYS then
score.goodguys = amount
elseif teamID == DOTA_TEAM_BADGUYS then
score.badguys = amount
end
CustomNetTables:SetTableValue('team_scores', 'score', score)
ScoreChangedEvent.broadcast()
self:CheckWinCondition(teamID, amount)
end
function PointsManager:AddPoints(teamID, amount)
amount = amount or 1
local score = CustomNetTables:GetTableValue('team_scores', 'score')
if teamID == DOTA_TEAM_GOODGUYS then
amount = score.goodguys + amount
elseif teamID == DOTA_TEAM_BADGUYS then
amount = score.badguys + amount
end
PointsManager:SetPoints(teamID, amount)
end
function PointsManager:GetPoints(teamID)
local score = CustomNetTables:GetTableValue('team_scores', 'score')
if not score then
return 0
end
if teamID == DOTA_TEAM_GOODGUYS then
return score.goodguys
elseif teamID == DOTA_TEAM_BADGUYS then
return score.badguys
end
end
function PointsManager:GetGameLength()
return CustomNetTables:GetTableValue('team_scores', 'limit').name
end
function PointsManager:GetLimit()
return CustomNetTables:GetTableValue('team_scores', 'limit').value
end
function PointsManager:SetLimit(killLimit)
CustomNetTables:SetTableValue('team_scores', 'limit', {value = killLimit, name = self:GetGameLength() })
LimitChangedEvent.broadcast(true)
end
function PointsManager:IncreaseLimit(limit_increase)
local extend_amount = 0
if not limit_increase then
extend_amount = PlayerResource:SafeGetTeamPlayerCount() * KILL_LIMIT_INCREASE
else
extend_amount = limit_increase
end
self.extend_counter = self.extend_counter + 1
PointsManager:SetLimit(PointsManager:GetLimit() + extend_amount)
Notifications:TopToAll({text="#duel_final_duel_objective_extended", duration=5.0, replacement_map={extend_amount=extend_amount}})
end
function PointsManager:AddEnemyPointsCommand(keys)
local text = string.lower(keys.text)
local splitted = split(text, " ")
local hero = PlayerResource:GetSelectedHeroEntity(keys.playerid)
local teamID = hero:GetTeamNumber()
if hero:GetTeamNumber() == DOTA_TEAM_GOODGUYS then
teamID = DOTA_TEAM_BADGUYS
else
teamID = DOTA_TEAM_GOODGUYS
end
local pointsToAdd = tonumber(splitted[2]) or 1
self:AddPoints(teamID, pointsToAdd)
end
function PointsManager:AddPointsCommand(keys)
local text = string.lower(keys.text)
local splitted = split(text, " ")
local hero = PlayerResource:GetSelectedHeroEntity(keys.playerid)
local teamID = hero:GetTeamNumber()
local pointsToAdd = tonumber(splitted[2]) or 1
self:AddPoints(teamID, pointsToAdd)
end
function PointsManager:SetLimitCommand(keys)
local text = string.lower(keys.text)
local splitted = split(text, " ")
if splitted[2] and tonumber(splitted[2]) then
self:SetLimit(tonumber(splitted[2]))
else
GameRules:SendCustomMessage("Usage is -kill_limit X, where X is the kill limit to set", 0, 0)
end
end
function PointsManager:RefreshLimit()
-- Current limit:
local limit = self:GetLimit()
local maxPoints = math.max(self:GetPoints(DOTA_TEAM_GOODGUYS), self:GetPoints(DOTA_TEAM_BADGUYS))
local base_limit = NORMAL_KILL_LIMIT
if HeroSelection.is10v10 then
base_limit = TEN_V_TEN_KILL_LIMIT
end
-- Expected score limit with changed number of players connected:
-- Expected behavior: Disconnects should reduce player_count and reconnects should increase player_count.
local newLimit = 10 + (base_limit + (self.extend_counter + 1) * KILL_LIMIT_INCREASE) * PlayerResource:SafeGetTeamPlayerCount()
if newLimit < limit then
local limitChange = limit - newLimit -- this used to be constant 10 and not dependent on number of players
newLimit = math.min(limit, math.max(maxPoints + limitChange, limit - limitChange))
end
self:SetLimit(newLimit)
end
|
--[[
ExtendedExportFilter.lua
--]]
local ExtendedExportFilter, dbg, dbgf = ExportFilter:newClass{ className='ExtendedExportFilter', register=true }
--- Constructor for extending class.
--
function ExtendedExportFilter:newClass( t )
return ExportFilter.newClass( self, t )
end
--- Constructor for new instance.
--
function ExtendedExportFilter:new( t )
local o = ExportFilter.new( self, t ) -- note: new export filter class (18/Nov/2013 23:10) requires parameter table (with filter-context or export-settings) and initializes filter id, name, & title.
return o
end
--- This optional function adds the observers for our required fields metachoice and metavalue so we can change
-- the dialog depending if they have been populated.
--
function ExtendedExportFilter:startDialogMethod()
self:logV( "start dialog method has not been overridden." )
end
-- reminder: this won't be called unless derived class provided an end-dialog function - if so, the method should be provided too.
function ExtendedExportFilter:endDialogMethod()
app:error( "end dialog method has not been overridden." )
end
--- This function will create the section displayed on the export dialog
-- when this filter is added to the export session.
--
function ExtendedExportFilter:sectionForFilterInDialogMethod()-- vf, props )
app:error( "do override this" )
end
--- Should render photo method.
function ExtendedExportFilter:shouldRenderPhotoMethod( photo )
return true -- in case extended class does not override
end
--- Post process rendered photos (overrides base class).
--
-- @usage reminder: videos are not considered rendered photos (won't be seen by this method).
--
function ExtendedExportFilter:postProcessRenderedPhotosMethod()
app:error( "o" ) -- ya gotta do this one yerself.
end
--- Called from update-filter-status method, to ensure main filter.
--
-- @usage preferrably called in edb when LR-export-filters.. changes, since that catches it at earliest point,
-- <br> on the down side, if multiple filters are present, you have to set through the prompt multiple times. - oh well, user shouldn't make that mistake more than once or twice..
--
function ExtendedExportFilter:requireMainFilterInDialog()
local props = self.exportSettings or error( "no es" )
local s, m = self:requireFilterInDialog( "com.robcole.Exportant.Main" )
if s then
assert( str:is( props.pluginManagerPreset, "plugin manager preset" ), "no plugin manager preset" )
return true
else
if not str:is( props.pluginManagerPreset ) then
props.pluginManagerPreset = 'Default'
end
return false
end
-- never reaches here
end
-- call in post-process photos method, to be sure.
function ExtendedExportFilter:requireMainFilterInPost()
local s, m = self:requireFilterInPost( "com.robcole.Exportant.Main" )
if s then
return true
else
self:logW( m ) -- fully descriptive error message.
local s, m = self:cancelExport()
if s then
self:log( "Export canceled." )
else
self:logW( m )
end
return false
end
-- never reaches here.
end
--- This function will check the status of the Export Dialog to determine
-- if all required fields have been populated.
--
function ExtendedExportFilter:updateFilterStatusMethod( name, value )
self:logV( "update filter method has not been overridden." )
end
-- Initialize photo, video, & union arrays, plus candidates & union-cache.
--
-- Note: cache-params should include file-format in raw-ids array.
--
-- I confess, this is a method born from laziness ;-}.
--
function ExtendedExportFilter:initPhotos( params )
local rendInfo = self:peruseRenditions( params )
if rendInfo then -- always (normally) the case
return rendInfo.photos, rendInfo.videos, rendInfo.union, rendInfo.candidates, rendInfo.unionCache
else
return {}, {}, {}, {}, lrMeta:createCache{} -- happens sometimes in anomalous situations.
end
end
function ExtendedExportFilter:getSectionTitle()
return str:fmtx( "^1 - ^2", app:getAppName(), self.title )
end
-- method calling "boot-strap" functions:
function ExtendedExportFilter.startDialog( propertyTable)
app:error( "Start dialog must be overridden." ) -- since for filter assurance class must be specified explicitly.
end
--- This function will create the section displayed on the export dialog
-- when this filter is added to the export session.
--
function ExtendedExportFilter.sectionForFilterInDialog( vf, propertyTable )
app:error( "do override" )
end
--[[ *** save for possible future resurrection:
function ExtendedExportFilter.endDialog( propertyTable)
app:error( "End dialog must be overridden." ) -- since for filter assurance class must be specified explicitly.
-- actually, there is no need for this method, but for debugging and to hold space for future..
end
--]]
--- This function obtains access to the photos and removes entries that don't match the metadata filter.
--
-- @usage called *before* post-process-rendered-photos function (no cached metadata).
-- @usage base class has no say (need not be called).
--
function ExtendedExportFilter.shouldRenderPhoto( exportSettings, photo )
app:error( "do override" )
end
--- Post process rendered photos.
--
function ExtendedExportFilter.postProcessRenderedPhotos( functionContext, filterContext )
app:error( "O" )
end
-- Note: there are not base class export settings.
ExtendedExportFilter:inherit( ExportFilter ) -- inherit *non-overridden* members.
return ExtendedExportFilter
|
local PLUGIN = PLUGIN
--[[PLUGIN.itemDrops = {
drop = {
{items = {"food_ruchkasamodrochka8"}, chance = 55, class = "npc_mutant_boar"},
{items = {"food_ruchkasamodrochka7"}, chance = 55, class = "npc_bloods"},
{items = {"food_ruchkasamodrochka2"}, chance = 55, class = "npc_zombies"},
{items = {"food_ruchkasamodrochka9"}, chance = 55, class = "npc_plot"},
{items = {"food_ruchkasamodrochka"}, chance = 55, class = "npc_stalker_burer"},
{items = {"food_ruchkasamodrochka4"}, chance = 55, class = "npc_mutant_pseudodog"},
{items = {"food_ruchkasamodrochka5"}, chance = 55, class = "npc_rat"},
{items = {"food_ruchkasamodrochka3"}, chance = 55, class = "npc_blinddog"},
}
}
if (SERVER) then
function PLUGIN:OnNPCKilled(entity, attacker)
if (!IsValid(entity)) then
return
end
if (!IsValid(attacker) and !attacker:IsPlayer()) then
return
end
for k, v in ipairs(self.itemDrops.drop) do
if (entity:GetClass() == v.class) then
if (100 * math.random() > v.chance) then
break
end
nut.item.spawn(table.Random(v.items), entity:GetPos() + Vector(0, 0, 15))
break
end
end
end
end]]
|
ENT.Type = "anim"
ENT.Base = "base_entity"
ENT.PrintName = "Thrown smoke grenade"
ENT.Author = "Spy"
ENT.Information = "Thrown smoke grenade"
ENT.Spawnable = false
ENT.AdminSpawnable = false
|
class "RenderTargetBinding"
RenderTargetBinding.MODE_IN = 0
RenderTargetBinding.MODE_OUT = 1
RenderTargetBinding.MODE_COLOR = 2
RenderTargetBinding.MODE_DEPTH = 3
function RenderTargetBinding:__getvar(name)
if name == "id" then
return Polycode.RenderTargetBinding_get_id(self.__ptr)
elseif name == "name" then
return Polycode.RenderTargetBinding_get_name(self.__ptr)
elseif name == "mode" then
return Polycode.RenderTargetBinding_get_mode(self.__ptr)
end
end
function RenderTargetBinding:__setvar(name,value)
if name == "id" then
Polycode.RenderTargetBinding_set_id(self.__ptr, value)
return true
elseif name == "name" then
Polycode.RenderTargetBinding_set_name(self.__ptr, value)
return true
elseif name == "mode" then
Polycode.RenderTargetBinding_set_mode(self.__ptr, value)
return true
end
return false
end
function RenderTargetBinding:__delete()
if self then Polycode.delete_RenderTargetBinding(self.__ptr) end
end
|
require('prototypes.custom-input')
require('prototypes.gui-style')
require('prototypes.item')
|
ele.register_tool("elepower_wireless:wireless_porter", {
description = "Wireless Porter",
inventory_image = "elewireless_wireless_porter.png",
on_use = function (itemstack, player, pointed_thing)
local meta = itemstack:get_meta()
local storage = ele.tools.get_tool_property(itemstack, "storage")
local pos = minetest.string_to_pos(meta:get_string("receiver"))
if not pos or pos == "" then return itemstack end
local node = minetest.get_node_or_nil(pos)
local plname = player:get_player_name()
if not node or not ele.helpers.get_item_group(node.name, "matter_receiver") then
minetest.chat_send_player(plname, "Destination Receiver is missing or unloaded!")
return itemstack
end
local nmeta = minetest.get_meta(pos)
local nstorage = ele.helpers.get_node_property(nmeta, pos, "storage")
local nusage = ele.helpers.get_node_property(nmeta, pos, "usage")
local top = vector.add(pos, {x = 0, y = 1, z = 0})
local topnode = minetest.get_node_or_nil(top)
if topnode and topnode.name ~= "air" then
minetest.chat_send_player(plname, "Destination is obstructed!")
return itemstack
end
if not (nstorage >= nusage and storage >= nusage) then
minetest.chat_send_player(plname, "Not enough power to commit teleport!")
return itemstack
end
-- Teleport player
player:set_pos(top)
-- TODO: Sound
nmeta:set_int("storage", nstorage - nusage)
-- Add wear
meta:set_int("storage", storage - nusage)
itemstack = ele.tools.update_tool_wear(itemstack)
return itemstack
end,
on_place = function(itemstack, placer, pointed_thing)
if not placer or placer:get_player_name() == "" then return itemstack end
local player = placer:get_player_name()
if minetest.is_protected(pos, player) then
minetest.chat_send_player(player, "You are not allowed to teleport here!")
return itemstack
end
local meta = itemstack:get_meta()
local pos = pointed_thing.under
local node = minetest.get_node_or_nil(pos)
if not node or not ele.helpers.get_item_group(node.name, "matter_receiver") then return itemstack end
local strpos = minetest.pos_to_string(pos)
local curpos = minetest.string_to_pos(meta:get_string("receiver"))
if (curpos and curpos ~= "") and curpos == pos then
minetest.chat_send_player(player, "Wireless Porter is already bound to this location!")
return itemstack
end
meta:set_string("receiver", strpos)
minetest.chat_send_player(player, ("Wireless Porter bound to %s!"):format(strpos))
return itemstack
end,
ele_capacity = 1000,
})
|
local glue = require'glue'
local pp = require'pp'
local fs = require'fs'
assert(fs.chdir(fs.exedir()..'/../../tests'))
local function tostr(s)
return pp.format(s)
end
local function _test(t1, t2, prefix, level)
if type(t1)=='table' and type(t2)=='table' then
--for k,v in pairs(t1) do print('>t1',k,v) end
--for k,v in pairs(t2) do print('>t2',k,v) end
for k,v in pairs(t1) do
_test(t2[k], v, prefix .. '.' .. tostr(k), level + 1)
end
for k,v in pairs(t2) do
_test(t1[k], v, prefix .. '.' .. tostr(k), level + 1)
end
else
if (t1 == t1 and t1 ~= t2) or (t1 ~= t1 and t2 == t2) then
error(tostr(t1) .. " ~= " .. tostr(t2) ..
" [" .. prefix .. "]", level)
end
end
end
function test(t1, t2)
return _test(t1, t2, 't', 3)
end
function testmatch(s, pat)
if not s:match(pat) then
error("'" .. s .. "'" .. " not matching '" .. pat .. "'", 2)
end
end
function ptest(t1,t2)
print(t1)
test(t1,t2,nil,3)
end
local time
local last_time
function timediff()
time = time or require'time'
local time = time.clock()
local d = last_time and (time - last_time) or 0
last_time = time
return d
end
function dir(d)
local f = io.popen('ls -1 '..d)
return glue.collect(f:lines())
end
|
noise_sprite_offset = 120
terrain_1 = {} -- spike mountains
terrain_2 = {} -- level mountains
terrain_1_start = 64
terrain_2_start = 86
terrain_height = 64
terrain_unit = terrain_height / 15
base_map_offset_x = 120
base_map_offset_y = 16
base = {}
base_parts = { 45, 46, 61, 62, 63 }
spaceship_parts = { 13, 11, 43 } -- top, middle, bottom
spaceship_x = 86
spaceship_y = 70
spaceship_animation_ticks = 0
explosion_colors = {8, 9, 10}
smoke_colors = {7,6,5}
function generate_planet_terrain()
for y=0,7 do
for x=0,7 do
index = (y * 8) + x
true_x = noise_sprite_offset + x
terrain_1[index] = sget(true_x, y)
end
end
for y=0,7 do
for x=0,7 do
index = (y * 8) + x
true_x = noise_sprite_offset + x
terrain_2[index] = sget(true_x, y + 8)
end
end
for y=0,7 do
for x=0,7 do
index = (y * 8) + x
true_x = base_map_offset_x + x
true_y = base_map_offset_y + y
base[index] = { x, y, sget(true_x, true_y) }
end
end
end
function update_planet(stage_ticks)
if (stage == 4) then
if (stage_ticks == 30) then
sfx(2, 1)
for p=0,3 do
for ring=1,3 do
for a=0,360, 8 do
r = a * 3.14159 / 180
velocity = vector_scale({sin(r), cos(r)}, ring * (rnd(0.9) + 0.1))
position = {spaceship_x + 8, spaceship_y + 8 + (p * 16)}
color = explosion_colors[ring]
add_particle(position, velocity, color, 2 + rnd(1))
end
end
end
end
if (stage_ticks == 120) then
return_to_menu()
end
end
if (stage == 5) then
if (stage_ticks >= 30 and stage_ticks < 60) then
sfx(2, 1)
offset = min(((127 / 30) * (stage_ticks - 30)), 128)
thruster_y = (spaceship_y + 48) - offset
for loop = 0, 1 do
for x=0,13 do
position = {spaceship_x + x, thruster_y - rnd(0.5)}
velocity = {0, 0.5 + rnd(0.5)}
color = smoke_colors[ceil(rnd(#smoke_colors))]
add_particle(position, velocity, color, 0.2 + rnd(0.6))
end
end
end
if (stage_ticks == 90) then
return_to_menu()
end
end
end
function draw_planet(stage_ticks)
rectfill(0, 0, 127, 127, 8)
rectfill(0, terrain_2_start, 127, 127, 4)
for x = 0,63 do
height = terrain_unit * terrain_1[x]
rectfill(x * 2, terrain_1_start, (x * 2) + 1, terrain_1_start - height, 9)
end
rectfill(0, terrain_1_start, 127, terrain_2_start, 9)
for x = 0,63 do
height = terrain_unit * terrain_2[x]
rectfill(x * 2, terrain_2_start, (x * 2) + 1, terrain_2_start - height, 10)
end
for i = 0,63 do
x = base[i][1]
y = base[i][2]
part = base[i][3]
if (part != 0) then
spr(base_parts[part], x * 8, (y * 8) + (terrain_2_start - 4))
end
end
if (stage == 5) then
draw_particles()
offset = 0
if (stage_ticks > 30) then
offset = min(((127 / 30) * (stage_ticks - 30)), 128)
end
spr(spaceship_parts[1], spaceship_x, spaceship_y - offset, 2, 2)
spr(spaceship_parts[2], spaceship_x, (spaceship_y + 16) - offset, 2, 2)
spr(spaceship_parts[3], spaceship_x, (spaceship_y + 32) - offset, 2, 2)
end
if (stage == 4) then
if (stage_ticks <= 40) then
spr(spaceship_parts[1], spaceship_x, spaceship_y, 2, 2)
spr(spaceship_parts[2], spaceship_x, spaceship_y + 16, 2, 2)
spr(spaceship_parts[3], spaceship_x, spaceship_y + 32, 2, 2)
end
draw_particles()
end
if (stage == 2) then
spr(spaceship_parts[1], spaceship_x, spaceship_y, 2, 2)
spr(spaceship_parts[2], spaceship_x, spaceship_y + 16, 2, 2)
spr(spaceship_parts[3], spaceship_x, spaceship_y + 32, 2, 2)
end
if (stage == 2 and stage_ticks > 60) then
offset = max((127 - (127 / 30) * (stage_ticks - 60)), 64)
draw_astro(1, 16, offset, 64, 64)
end
end
|
#!/usr/local/bin/lua
print("Hello, World")
sum = 0
num = 1
while num <= 100 do
sum = sum + num
num = num + 1
end
print("sum =",sum)
local age = io.read()
if age == 40 and sex =="Male" then
print("男人四十一枝花")
elseif age > 60 and sex ~="Female" then
print("old man without country!")
elseif age < 20 then
io.write("too young, too naive!\n")
else
print("Your age is "..age)
end
|
local tablex = require('tablex')
local sf = string.format
local til = tablex.is_list
local type = type
local has_lspconfig, _ = pcall(require, 'lspconfig')
if not has_lspconfig then
print('‼ Tried loading lspconfig for omnisharp ... unsuccessfully.')
return has_lspconfig
end
--- Recursively flatten a table.
---
--- @param acc table Accumulator of flattened keys
--- @param sep string Separator to use for keys
--- @param key string Current key
--- @param value any Current value
--- @return table _ flattened table
local function flatten (acc, sep, key, value)
if type(value) ~= 'table' then
acc[key] = value
return acc
end
if til(value) then
for i = 1, #value do
flatten(
acc,
':',
sf('%s%s%s', key, sep, i - 1),
value[i]
)
end
return acc
end
for k, v in pairs(value) do
flatten(
acc,
':',
sf('%s%s%s', key, sep, k),
v
)
end
return acc
end
--- OmniSharp's settings as a table
---
--- Using a function's return value as a temporary
--- variable to avoid the table lingering around the
--- memory after its use, when the garbage collector
--- sweeps for unreferenced objects.
---
--- @return table _ OmniSharp settings table
local function omnisharp_settings ()
return {
useModernNet = true,
formattingOptions = {
enableEditorConfigSupport = true,
indentBlock = true,
indentBraces = false,
indentSwitchCaseSection = true,
indentSwitchCaseSectionWhenBlock = true,
indentSwitchSection = true,
indentationSize = 3,
labelPositioning = 'oneLess',
newLine = '\n',
newLineForCatch = true,
newLineForClausesInQuery = true,
newLineForElse = false,
newLineForFinally = true,
newLineForMembersInAnonymousTypes = true,
newLineForMembersInObjectInit = true,
newLinesForBracesInAccessors = true,
newLinesForBracesInAnonymousMethods = false,
newLinesForBracesInAnonymousTypes = false,
newLinesForBracesInControlBlocks = false,
newLinesForBracesInLambdaExpressionBody = false,
newLinesForBracesInMethods = true,
newLinesForBracesInObjectCollectionArrayInitializers = true,
newLinesForBracesInProperties = true,
newLinesForBracesInTypes = true,
organizeImports = true,
spaceAfterCast = true,
spaceAfterColonInBaseTypeDeclaration = true,
spaceAfterComma = true,
spaceAfterControlFlowStatementKeyword = true,
spaceAfterDot = false,
spaceAfterMethodCallName = false,
spaceAfterSemicolonsInForStatement = true,
spaceBeforeColonInBaseTypeDeclaration = true,
spaceBeforeComma = false,
spaceBeforeDot = false,
spaceBeforeOpenSquareBracket = false,
spaceBeforeSemicolonsInForStatement = false,
spaceBetweenEmptyMethodCallParentheses = false,
spaceBetweenEmptyMethodDeclarationParentheses = false,
spaceBetweenEmptySquareBrackets = false,
spaceWithinCastParentheses = false,
spaceWithinExpressionParentheses = false,
spaceWithinMethodCallParentheses = false,
spaceWithinMethodDeclarationParenthesis = false,
spaceWithinOtherParentheses = false,
spaceWithinSquareBrackets = true,
spacesIgnoreAroundVariableDeclaration = false,
spacingAfterMethodDeclarationName = true,
spacingAroundBinaryOperator = 'single',
tabSize = 3,
useTabs = false,
wrappingKeepStatementsOnSingleLine = true,
wrappingPreserveSingleLine = true,
},
roslynExtensionsOptions = {
documentAnalysisTimeoutMs = 10000,
enableAnalyzersSupport = true,
enableDecompilationSupport = true,
enableImportCompletion = true,
},
}
end
--- Make the full environment to pass to OmniSharp.
---
--- @return table _ Flattened environment table for OmniSharp.
local function make_environment()
local settings = flatten({}, '_', 'OMNISHARP', omnisharp_settings())
local home_env = {
OMNISHARPHOME = vim.fn.expand('$XDG_DATA_HOME') .. '/omnisharp'
}
return tablex.deep_extend('keep', settings, home_env)
end
return {
cmd = {
'dotnet',
sf(
'%s/lsp_servers/omnisharp/omnisharp/OmniSharp.dll',
vim.fn.stdpath('data')
),
'--languageserver',
'--hostPID', tostring(vim.fn.getpid())
},
filetypes = {
'cs',
'vb'
},
cmd_env = make_environment()
}
|
-----------------------------------
-- Ability: Elemental Siphon
-- Drains MP from your summoned spirit.
-- Obtained: Summoner level 50
-- Recast Time: 5:00
-- Duration: Instant
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/pets")
require("scripts/globals/magic")
require("scripts/globals/utils")
require("scripts/globals/msg")
-----------------------------------
function onAbilityCheck(player,target,ability)
local pet = player:getPetID()
if (pet >= 0 and pet <= 7) then -- spirits
return 0,0
else
return tpz.msg.basic.UNABLE_TO_USE_JA,0
end
end
function onUseAbility(player,target,ability)
local spiritEle = player:getPetID() + 1 -- get the spirit's ID, then make it line up with element value for the day order.
-- pet order: fire, ice, air, earth, thunder, water, light, dark
-- day order: fire, earth, water, wind, ice, thunder, light, dark
if (spiritEle == 2) then
spiritEle = 5
elseif (spiritEle == 3) then
spiritEle = 4
elseif (spiritEle == 4) then
spiritEle = 2
elseif (spiritEle == 5) then
spiritEle = 6
elseif (spiritEle == 6) then
spiritEle = 3
end
local pEquipMods = player:getMod(tpz.mod.ENHANCES_ELEMENTAL_SIPHON)
local basePower = player:getSkillLevel(tpz.skill.SUMMONING_MAGIC) + pEquipMods - 50
if (basePower < 0) then
basePower = 0
end
local weatherDayBonus = 1
local dayElement = VanadielDayElement()
local weather = player:getWeather()
-- Day bonus/penalty
if (dayElement == tpz.magic.dayStrong[spiritEle]) then
weatherDayBonus = weatherDayBonus + 0.1
elseif (dayElement == tpz.magic.dayWeak[spiritEle]) then
weatherDayBonus = weatherDayBonus - 0.1
end
-- Weather bonus/penalty
if (weather == tpz.magic.singleWeatherStrong[spiritEle]) then
weatherDayBonus = weatherDayBonus + 0.1
elseif (weather == tpz.magic.singleWeatherWeak[spiritEle]) then
weatherDayBonus = weatherDayBonus - 0.1
elseif (weather == tpz.magic.doubleWeatherStrong[spiritEle]) then
weatherDayBonus = weatherDayBonus + 0.25
elseif (weather == tpz.magic.doubleWeatherWeak[spiritEle]) then
weatherDayBonus = weatherDayBonus - 0.25
end
local power = math.floor(basePower * weatherDayBonus)
local spirit = player:getPet()
power = utils.clamp(power, 0, spirit:getMP()) -- cap MP drained at spirit's MP
power = utils.clamp(power, 0, player:getMaxMP() - player:getMP()) -- cap MP drained at the max MP - current MP
spirit:delMP(power)
return player:addMP(power)
end
|
local MINIMUM_PLAYERS = 1
local MAXIMUM_PLAYERS = 8
function givePositionFeedback(playerPosition)
-- Checking if the player's position is a valid number
if playerPosition >= MINIMUM_PLAYERS and playerPosition <= MAXIMUM_PLAYERS then
-- Getting correct message based on player's position
if playerPosition <= 3 then
print("Well done! You are in spot " .. playerPosition .. "!")
elseif playerPosition <= 5 then
print("You are almost there!")
else
print("You are not in the top three yet! Keep going!")
end
else
-- The position of the player is not valid
warn("Incorrect player position [" .. playerPosition .. "]!")
end
end
givePositionFeedback(math.random(1, 8))
givePositionFeedback(math.random(1, 8))
|
package.path = "../?.lua;"..package.path;
require("p5")
local gestureCommands = {
[1] = "GID_BEGIN";
[2] = "GID_END";
[3] = "GID_ZOOM";
[4] = "GID_PAN";
[5] = "GID_ROTATE";
[6] = "GID_TWOFINGERTAP";
[7] = "GID_PRESSANDTAP";
--"GID_ROLLOVER";
}
function setup()
--print("touchOn: ", touchOn())
end
function draw()
background(0xff, 0x20, 0x20, 126)
end
function gestureEvent(event)
print("gestureEvent: ", event.ID, gestureCommands[event.ID])
end
go({width = 640, height = 480, frameRate=10})
|
--------------------------------
--- DUPLICATOR
--------------------------------
local Duplicator = {}
MR.Duplicator = Duplicator
local dup = {
-- Force to stop the current loading to begin a new one
forceStop = false,
-- Get the recreated table format version
recreateTableSaveFormat,
-- Controls the timer from RecreateTable
recreateTimerIncrement = 0,
-- The save identifier if a save is being loaded
-- Index: [1] = server, [player ent index + 1] = player, [999] = invalid player (avoid script errors)
-- running[Index] = load name or ""
running = {},
-- Status of the loading
processed = {
-- Default count control
default = {
total = 0, -- total materials
current = 0, -- current material
errors = {} -- simple string list (material names) of errors
},
-- Index: [1] = MR.SV.Ply:GetFakeHostPly(), [player ent index + 1] = player, [999] = invalid player (avoid script errors)
-- processed.list[Index] = { copy of the default count control }
list = {}
},
-- Default ducplicator speeds (mr_delay)
speed = {
Normal = "0.035",
Fast = "0.01",
Slow = "0.1"
},
-- Tables exchanged between scopes to synchronize materials
modificationChunks = {}
}
-- Networking
net.Receive("Duplicator:SetRunning", function(_, ply)
Duplicator:SetRunning(ply or LocalPlayer(), net.ReadString(), net.ReadBool())
end)
-- Networking
net.Receive("Duplicator:GetAntiDyssyncChunks", function(_, ply)
local len = net.ReadUInt(16)
Duplicator:GetAntiDyssyncChunks(ply or LocalPlayer(), net.ReadData(len), net.ReadString(), net.ReadString(), net.ReadString(), net.ReadTable())
end)
net.Receive("Duplicator:InitProcessedList", function()
if SERVER then return end
Duplicator:InitProcessedList(LocalPlayer(), net.ReadInt(8))
end)
function Duplicator:Init()
-- Init fallback lists (to avoid script errors)
dup.running[999] = {}
dup.processed.list[999] = table.Copy(dup.processed.default)
-- Check every minute for dyssynchrony
--[[
-- TODO: Improve anti dyssync
if SERVER then
timer.Create("MR_AntiDyssynchrony", 60, 0, function()
MR.SV.Duplicator:FindDyssynchrony()
end)
end
]]
end
function Duplicator:InitProcessedList(ply, forceIndex)
dup.processed.list[forceIndex or Duplicator:GetControlIndex(ply)] = table.Copy(dup.processed.default)
if SERVER and MR.Ply:IsValid(ply) then
net.Start("Duplicator:InitProcessedList")
net.WriteInt(Duplicator:GetControlIndex(ply), 8)
net.Send(ply)
end
end
function Duplicator:GetControlIndex(ply)
return SERVER and ply == MR.SV.Ply:GetFakeHostPly() and 1 or MR.Ply:IsValid(ply) and ply:EntIndex() + 1 or 999
end
function Duplicator:AddModificationChunks(ply, chunk, lastPart)
local plyIndex = Duplicator:GetControlIndex(ply)
if not dup.modificationChunks[plyIndex] or istable(dup.modificationChunks[plyIndex]) then
dup.modificationChunks[plyIndex] = ""
end
dup.modificationChunks[plyIndex] = dup.modificationChunks[plyIndex] .. chunk
if lastPart then
dup.modificationChunks[plyIndex] = util.JSONToTable(util.Decompress(dup.modificationChunks[plyIndex]))
end
end
function Duplicator:GeModificationChunksTab(ply)
local tab = dup.modificationChunks[Duplicator:GetControlIndex(ply)]
return tab and istable(tab) and tab
end
-- Set the old material
function Duplicator:IsProgressBarEnabled()
return GetConVar("internal_mr_progress_bar"):GetString() == "1" and true
end
-- Check if the duplicator is stopping
function Duplicator:IsStopping()
return dup.forceStop
end
-- Set duplicator stopping state
function Duplicator:SetStopping(value)
dup.forceStop = value
end
-- Check if the duplicator is running
-- Must return the name of the loading or nil
function Duplicator:IsRunning(ply)
return dup.running[Duplicator:GetControlIndex(ply)]
end
function Duplicator:SetRunning(ply, loadName, isBroadcasted)
local index = Duplicator:GetControlIndex(ply)
if index == 999 then return end
if SERVER then
net.Start("Duplicator:SetRunning")
net.WriteString(loadName or "")
net.WriteBool(isBroadcasted)
if isBroadcasted then
net.Broadcast()
else
net.Send(ply)
end
end
dup.running[index] = loadName ~= "" and loadName
end
function Duplicator:GetTotal(ply)
return dup.processed.list[Duplicator:GetControlIndex(ply)].total
end
function Duplicator:SetTotal(ply, value)
local index = Duplicator:GetControlIndex(ply)
if index == 999 then return end
dup.processed.list[index].total = value
end
function Duplicator:GetCurrent(ply)
return dup.processed.list[Duplicator:GetControlIndex(ply)].current
end
function Duplicator:SetCurrent(ply, value)
local index = Duplicator:GetControlIndex(ply)
if index == 999 then return end
dup.processed.list[index].current = value
end
function Duplicator:IncrementCurrent(ply)
local index = Duplicator:GetControlIndex(ply)
if index == 999 then return end
dup.processed.list[index].current = dup.processed.list[index].current + 1
end
function Duplicator:GetErrorsCurrent(ply)
return #dup.processed.list[Duplicator:GetControlIndex(ply)].errors
end
function Duplicator:GetErrorsList(ply)
return dup.processed.list[Duplicator:GetControlIndex(ply)].errors
end
function Duplicator:InsertErrorsList(ply, value)
local index = Duplicator:GetControlIndex(ply)
if index == 999 then return end
table.insert(dup.processed.list[index].errors, value)
end
function Duplicator:EmptyErrorsList(ply, value)
local index = Duplicator:GetControlIndex(ply)
if index == 999 then return end
table.Empty(dup.processed.list[index].errors)
end
function Duplicator:GetSpeedProfile(field)
return dup.speed[field]
end
function Duplicator:GetSpeeds()
return dup.speed
end
-- Load a GMod save
local function RecreateTable(ply, ent, savedTable)
if SERVER then
-- Get the save version
if savedTable.savingFormat then
recreateTableSaveFormat = savedTable.savingFormat
-- Auto disable it
timer.Simple(0.2, function()
recreateTableSaveFormat = nil
end)
end
-- Increment timer name
dup.recreateTimerIncrement = dup.recreateTimerIncrement + 1
-- Start with the saving format, then send the rest
timer.Simple(savedTable.savingFormat and 0 or 0.01, function()
-- Remove some disabled elements (because duplicator allways gets these tables full of trash)
MR.DataList:CleanDisabled(savedTable.map or savedTable.displacements or nil)
-- Index the format version
savedTable.savingFormat = recreateTableSaveFormat
MR.SV.Duplicator:RecreateTable(ply, ent, savedTable)
end)
end
end
duplicator.RegisterEntityModifier("MapRetexturizer_Models", RecreateTable)
duplicator.RegisterEntityModifier("MapRetexturizer_Decals", RecreateTable)
duplicator.RegisterEntityModifier("MapRetexturizer_Maps", RecreateTable)
duplicator.RegisterEntityModifier("MapRetexturizer_Displacements", RecreateTable)
duplicator.RegisterEntityModifier("MapRetexturizer_Skybox", RecreateTable)
duplicator.RegisterEntityModifier("MapRetexturizer_version", RecreateTable)
-- Send the anti dyssynchrony table (compressed string chunks)
function Duplicator:SendAntiDyssyncChunks(sendTab, scope, lib, callback, args)
if sendTab and istable(sendTab) and MR.DataList:GetTotalModificantions(sendTab.applied or sendTab) > 0 then
local curTable = util.Compress(util.TableToJSON(sendTab))
local chunks = {}
local totalSize = string.len(curTable)
local chunkSize = 15000 -- 15KB
for i = 1, math.ceil(totalSize / chunkSize), 1 do
local startByte = chunkSize * (i - 1) + 1
local remaining = totalSize - (startByte - 1)
local endByte = remaining < chunkSize and (startByte - 1) + remaining or chunkSize * i
table.insert(chunks, string.sub(curTable, startByte, endByte))
end
for k,v in ipairs(chunks) do
timer.Create("MR_SendChunks" .. k, k * 0.1, 1, function()
net.Start("Duplicator:GetAntiDyssyncChunks")
net.WriteUInt(#v, 16)
net.WriteData(v, #v)
if k == #chunks then
net.WriteString(scope)
net.WriteString(lib)
net.WriteString(callback)
net.WriteTable(args and istable(args) and args or {})
end
if SERVER then
net.Broadcast()
else
net.SendToServer()
end
end)
end
end
end
-- Get anti dyssynchrony table
function Duplicator:GetAntiDyssyncChunks(ply, chunk, scope, lib, callback, args)
if Duplicator:IsRunning(ply) then return end
local lastPart = scope and true
Duplicator:AddModificationChunks(ply, chunk, lastPart)
if lastPart then
local serverModifications = Duplicator:GeModificationChunksTab(ply)
if scope == "SH" then
MR[lib][callback](MR[lib][callback], ply, serverModifications, args and unpack(args))
else
MR[scope][lib][callback](MR[scope][lib][callback], ply, serverModifications, args and unpack(args))
end
end
end
-- Find any dyssynchrony between the current modifications and the modifications of a selected table
function Duplicator:FindDyssynchrony(checkTable, isCurrent)
local differences = MR.DataList:GetDifferences(checkTable, isCurrent)
if differences and table.Count(differences.current) > 0 then
differences.current.savingFormat = MR.Save:GetCurrentVersion()
else
differences = nil
end
return differences
end
|
object_building_kashyyyk_poi_kash_rryatt_lvl2_far_tree_a1 = object_building_kashyyyk_shared_poi_kash_rryatt_lvl2_far_tree_a1:new {
}
ObjectTemplates:addTemplate(object_building_kashyyyk_poi_kash_rryatt_lvl2_far_tree_a1, "object/building/kashyyyk/poi_kash_rryatt_lvl2_far_tree_a1.iff")
|
Particle = require("entities.core.particle")
WalkingDust = class("Particle", Particle)
WalkingDust.spritesheet = SpriteSheet:new("sprites/dust2.png", 32, 32)
function WalkingDust:initialize()
Particle.initialize(self)
self.scale = 1
self.velx = 0
self.vely = 0
self.lifetime = 0.5
end
function WalkingDust:setVelocity(velx, vely)
self.velx = velx
self.vely = vely
end
function WalkingDust:setScale(scale)
self.scale = scale
end
function WalkingDust:update(dt)
Particle.update(self, dt)
self.x = self.x + self.velx * dt
self.y = self.y + self.vely * dt
end
function WalkingDust:draw()
love.graphics.scale(self.scale)
love.graphics.setColor(141, 143, 166)
self.spritesheet:draw(math.floor((0.5 - self.lifetime)/0.5*5)%5, 0, -16, -16)
end
return WalkingDust
|
function appInclude()
includedirs {
"$(SolutionDir)",
"$(SolutionDir)ThirdParty",
}
end
function appResourceFiles()
files {
"./Assets/Icon/Resource.rc",
"./Applications/Resource.h"
}
end
workspace "Rockcat"
location "./"
configurations { "Debug", "Release" }
objdir "$(SolutionDir)Out/Intermediate"
targetdir "$(SolutionDir)Out/Intermediate/$(Platform)/$(Configuration)/$(ProjectName)"
characterset "Unicode"
platforms "x64"
targetname "$(ProjectName)"
warnings "Extra"
dpiawareness "High"
systemversion "latest"
symbolspath "$(IntDir)$(TargetName).pdb"
debugdir "$(SolutionDir)Out"
--flags { "MultiProcessorCompile", "NoIncrementalLink" }
flags { "MultiProcessorCompile", }
filter { "configurations:Debug" }
cppdialect "C++17"
symbols "On"
optimize "Debug"
defines { "_DEBUG", "_UNICODE", "UNICODE", "CONFIGURATION=\"_Debug\"" }
filter { "configurations:Release" }
optimize "Speed"
defines { "NDEBUG", "_UNICODE", "UNICODE", "CONFIGURATION=\"\"" }
filter { "platforms:Win64" }
system "Windows"
architecture "x64"
filter {}
group "Fort"
project "Gear"
kind "StaticLib"
language "C++"
location "./Out/Intermediate/VCProjects"
files "./Gear/**"
includedirs {
"$(SolutionDir)",
"$(SolutionDir)ThirdParty/cereal/include"
}
--[[
project "Learner"
kind "ConsoleApp"
language "C++"
location "./Projects"
files "./Fort/Learner/**"
includedirs { "$(SolutionDir)" }
links { "Gear" }
targetdir "$(SolutionDir)Out"
]]
group "Colorful"
project "IRenderer"
kind "StaticLib"
language "C++"
location "./Out/Intermediate/VCProjects"
files "./Colorful/Gfx/**"
removefiles "./Colorful/Gfx/ImGui/**"
includedirs {
"$(SolutionDir)",
"$(SolutionDir)ThirdParty",
"$(SolutionDir)ThirdParty/cereal/include",
"$(SolutionDir)ThirdParty/glslang",
"$(SolutionDir)ThirdParty/KTX-Software/include",
"$(SolutionDir)ThirdParty/assimp/build/include",
"$(SolutionDir)ThirdParty/assimp/include",
}
defines { "DYNAMIC_LIB", "STB_IMAGE_IMPLEMENTATION", "KHRONOS_STATIC", "LIBKTX" }
libdirs {
"$(SolutionDir)ThirdParty/dxc/lib/x64"
}
links {
"glslang",
"spirv-cross",
"libktx",
"dxcompiler",
"d3dcompiler",
"assimp"
}
postbuildcommands {
"{COPY} $(SolutionDir)ThirdParty/dxc/bin/x64/*.dll $(SolutionDir)Out"
}
project "VulkanRenderer"
kind "SharedLib"
language "C++"
location "./Out/Intermediate/VCProjects"
targetname "$(ProjectName)_$(Configuration)"
targetdir "$(SolutionDir)Out"
files "./Colorful/Vulkan/**"
includedirs {
"$(SolutionDir)",
"$(SolutionDir)ThirdParty/Vulkan-Headers/include",
"$(SolutionDir)ThirdParty/cereal/include"
}
defines { "DYNAMIC_LIB" }
--implibname "$(SolutionDir)Out/Intermediate/$(Configuration)/$(ProjectName)"
links {
"Gear",
"IRenderer",
"glslang",
"spirv-cross",
"libktx",
"dxcompiler",
"d3dcompiler",
"assimp",
}
--[[
project "D3D11Renderer"
kind "SharedLib"
language "C++"
location "./Projects"
files {
"./Colorful/D3D/D3D11/**",
"./Colorful/D3D/DXGI_Interface.h",
"./Colorful/D3D/DXGI_Interface.cpp",
}
includedirs { "$(SolutionDir)" }
defines { "DYNAMIC_LIB" }
implibname "$(SolutionDir)Out/Intermediate/$(Configuration)/$(ProjectName)"
links {
"Gear",
"d3d11",
"dxgi",
"IRenderer"
}
project "D3D12Renderer"
kind "SharedLib"
language "C++"
location "./Projects"
files {
"./Colorful/D3D/D3D12/**",
"./Colorful/D3D/DXGI_Interface.h",
"./Colorful/D3D/DXGI_Interface.cpp",
}
includedirs { "$(SolutionDir)" }
defines { "DYNAMIC_LIB" }
implibname "$(SolutionDir)Out/Intermediate/$(Configuration)/$(ProjectName)"
links {
"Gear",
"d3d12",
"dxgi",
"IRenderer"
}
project "SoftwareRenderer"
kind "SharedLib"
language "C++"
location "./Projects"
files "./Colorful/Software/**"
includedirs { "$(SolutionDir)" }
defines { "DYNAMIC_LIB" }
implibname "$(SolutionDir)Out/Intermediate/$(Configuration)/$(ProjectName)"
links {
"Gear",
"IRenderer"
}
project "ImGuiRenderer"
kind "StaticLib"
language "C++"
location "./Projects/"
files "./Colorful/Gfx/ImGui/**"
includedirs { "$(SolutionDir)" }
]]
group "ThirdParty"
project "glslang"
kind "StaticLib"
language "C++"
location "./Out/Intermediate/VCProjects"
files {
"./ThirdParty/glslang/**.h",
"./ThirdParty/glslang/**.cpp",
}
includedirs {
"$(SolutionDir)ThirdParty/glslang",
"$(SolutionDir)ThirdParty/glslang/build",
}
removefiles {
"./ThirdParty/glslang/gtests/**",
"./ThirdParty/glslang/ndk_test/**",
"./ThirdParty/glslang/Test/**",
"./ThirdParty/glslang/glslang/OSDependent/Unix/**",
"./ThirdParty/glslang/glslang/OSDependent/Web/**",
"./ThirdParty/glslang/glslang/OSDependent/Windows/**",
"./ThirdParty/glslang/OGLCompilersDLL/**",
"./ThirdParty/glslang/StandAlone/StandAlone.cpp",
"./ThirdParty/glslang/StandAlone/spirv-remap.cpp",
}
disablewarnings { "4702", "4458", "4456", "4127", "4457", "4244", "4100", "4189", "4389", "4701" }
filter { "configurations:Debug" }
defines {
"WIN32",
"_WINDOWS",
"ENABLE_HLSL",
"GLSLANG_OSINCLUDE_WIN32",
"ENABLE_OPT=0"
}
filter { "configurations:Release" }
defines {
"WIN32",
"_WINDOWS",
"NDEBUG",
"ENABLE_HLSL",
"GLSLANG_OSINCLUDE_WIN32",
"ENABLE_OPT=0"
}
project "libktx"
kind "StaticLib"
language "C++"
location "./Out/Intermediate/VCProjects"
files {
"./ThirdParty/KTX-Software/other_include/KHR/**",
"./ThirdParty/KTX-Software/include/**",
"./ThirdParty/KTX-Software/lib/**.h",
"./ThirdParty/KTX-Software/lib/**.c",
"./ThirdParty/KTX-Software/lib/**.inl",
"./ThirdParty/KTX-Software/lib/basisu/zstd/**",
}
removefiles {
"./ThirdParty/KTX-Software/lib/basisu/zstd/zstddeclib.c",
"./ThirdParty/KTX-Software/lib/dfdutils/vulkan/vulkan_core.h",
"./ThirdParty/KTX-Software/lib/dfdutils/endswap.c",
"./ThirdParty/KTX-Software/lib/dfdutils/testbidirectionalmapping.c",
"./ThirdParty/KTX-Software/lib/dfdutils/createdfdtest.c",
"./ThirdParty/KTX-Software/lib/gl_funclist.inl",
"./ThirdParty/KTX-Software/lib/gl_funcs.c",
"./ThirdParty/KTX-Software/lib/gl_funcs.h",
"./ThirdParty/KTX-Software/lib/vk_funclist.inl",
"./ThirdParty/KTX-Software/lib/vk_funcs.h",
"./ThirdParty/KTX-Software/lib/vk_funcs.c",
"./ThirdParty/KTX-Software/lib/vk_format_check.c",
"./ThirdParty/KTX-Software/lib/vk_format_enum.h",
"./ThirdParty/KTX-Software/lib/vk_format_str.c",
"./ThirdParty/KTX-Software/lib/vkloader.c",
"./ThirdParty/KTX-Software/lib/writer1.c",
"./ThirdParty/KTX-Software/lib/writer2.c",
}
includedirs {
"$(SolutionDir)",
"$(SolutionDir)ThirdParty/KTX-Software/include",
"$(SolutionDir)ThirdParty/KTX-Software/other_include",
"$(SolutionDir)ThirdParty/KTX-Software/utils",
"$(SolutionDir)ThirdParty/KTX-Software/lib/basisu/zstd",
}
filter {
defines {
"KHRONOS_STATIC",
"LIBKTX"
}
}
disablewarnings { "4389", "4706", "4100", "4127", "4189", "4701", "4702", "4101", "4456" }
project "ImGui"
kind "StaticLib"
language "C++"
location "./Out/Intermediate/VCProjects"
files {
"./ThirdParty/ImGUI/**.h",
"./ThirdParty/ImGUI/**.cpp"
}
removefiles {
"./ThirdParty/ImGUI/examples/**",
"./ThirdParty/ImGUI/misc/fonts/**",
"./ThirdParty/ImGUI/misc/freetype/**",
"./ThirdParty/ImGUI/backends/**"
}
includedirs {
"$(SolutionDir)ThirdParty/ImGUI"
}
project "spirv-cross"
kind "StaticLib"
language "C++"
location "./Out/Intermediate/VCProjects"
files {
"./ThirdParty/SPIRV-Cross/**.h",
"./ThirdParty/SPIRV-Cross/**.hpp",
"./ThirdParty/SPIRV-Cross/**.cpp",
}
removefiles {
"./ThirdParty/SPIRV-Cross/samples/**",
"./ThirdParty/SPIRV-Cross/main.cpp",
"./ThirdParty/SPIRV-Cross/tests-other/**",
"./ThirdParty/SPIRV-Cross/spirv_cross_c.h",
"./ThirdParty/SPIRV-Cross/spirv_cross_c.cpp",
}
includedirs { "$(SolutionDir)ThirdParty/SPIRV-Cross" }
vpaths {
["core"] = {
"./ThirdParty/SPIRV-Cross/GLSL.std.450.h",
"./ThirdParty/SPIRV-Cross/spirv.hpp",
"./ThirdParty/SPIRV-Cross/spirv_cfg.hpp",
"./ThirdParty/SPIRV-Cross/spirv_common.hpp",
"./ThirdParty/SPIRV-Cross/spirv_cross.hpp",
"./ThirdParty/SPIRV-Cross/spirv_cross_containers.hpp",
"./ThirdParty/SPIRV-Cross/spirv_cross_error_handling.hpp",
"./ThirdParty/SPIRV-Cross/spirv_cross_parsed_ir.hpp",
"./ThirdParty/SPIRV-Cross/spirv_cfg.cpp",
"./ThirdParty/SPIRV-Cross/spirv_cross.cpp",
"./ThirdParty/SPIRV-Cross/spirv_cross_parsed_ir.cpp",
"./ThirdParty/SPIRV-Cross/spirv_parser.hpp",
"./ThirdParty/SPIRV-Cross/spirv_parser.cpp",
},
["hlsl"] = {
"./ThirdParty/SPIRV-Cross/spirv_hlsl.hpp",
"./ThirdParty/SPIRV-Cross/spirv_hlsl.cpp",
},
["glsl"] = {
"./ThirdParty/SPIRV-Cross/spirv_glsl.hpp",
"./ThirdParty/SPIRV-Cross/spirv_glsl.cpp",
},
["reflect"] = {
"./ThirdParty/SPIRV-Cross/spirv_reflect.hpp",
"./ThirdParty/SPIRV-Cross/spirv_reflect.cpp",
},
["util"] = {
"./ThirdParty/SPIRV-Cross/spirv_cross_util.hpp",
"./ThirdParty/SPIRV-Cross/spirv_cross_util.cpp"
},
["msl"] = {
"./ThirdParty/SPIRV-Cross/spirv_msl.hpp",
"./ThirdParty/SPIRV-Cross/spirv_msl.cpp"
},
["cpp"] = {
"./ThirdParty/SPIRV-Cross/spirv_cpp.hpp",
"./ThirdParty/SPIRV-Cross/spirv_cpp.cpp",
},
["include"] = {
"./ThirdParty/SPIRV-Cross/include/**",
"./ThirdParty/SPIRV-Cross/cmake/**",
"./ThirdParty/SPIRV-Cross/spirv.h"
}
}
disablewarnings { "4065", "4702", "4706", '4996' }
project "assimp"
kind "SharedLib"
location "./Out/Intermediate/VCProjects"
targetdir "$(SolutionDir)Out"
targetname "$(ProjectName)_$(Configuration)"
buildoptions { "/bigobj" }
disablewarnings { "4819", "4189", "4131", "4996", "4127", "4244" }
--implibname "$(SolutionDir)Out/Intermediate/$(Configuration)/$(ProjectName)"
files {
"./ThirdParty/assimp/**.h",
"./ThirdParty/assimp/**.cpp",
"./ThirdParty/assimp/**.hpp",
"./ThirdParty/assimp/**.c",
"./ThirdParty/assimp/**.cc",
}
removefiles {
"./ThirdParty/assimp/contrib/zlib/contrib/inflate86/**",
"./ThirdParty/assimp/code/AssetLib/IFC/IFCReaderGen_4.h",
"./ThirdParty/assimp/code/AssetLib/IFC/IFCReaderGen_4.cpp",
"./ThirdParty/assimp/contrib/zlib/contrib/**",
"./ThirdParty/assimp/test/**",
"./ThirdParty/assimp/tools/**",
"./ThirdParty/assimp/contrib/gtest/**",
"./ThirdParty/assimp/build/CMakeFiles/**",
"./ThirdParty/assimp/include/port/AndroidJNI/**",
"./ThirdParty/assimp/port/**",
"./ThirdParty/assimp/code/AMF/**",
"./ThirdParty/assimp/samples/**",
"./ThirdParty/assimp/contrib/zip/test/**",
"./ThirdParty/assimp/contrib/draco/**"
}
includedirs {
"$(SolutionDir)ThirdParty/assimp/build/include",
"$(SolutionDir)ThirdParty/assimp/build",
"$(SolutionDir)ThirdParty/assimp/include",
"$(SolutionDir)ThirdParty/assimp/code",
"$(SolutionDir)ThirdParty/assimp",
"$(SolutionDir)ThirdParty/assimp/contrib/zlib",
"$(SolutionDir)ThirdParty/assimp/build/contrib/zlib",
"$(SolutionDir)ThirdParty/assimp/contrib/rapidjson/include",
"$(SolutionDir)ThirdParty/assimp/contrib/",
"$(SolutionDir)ThirdParty/assimp/contrib/pugixml/src",
"$(SolutionDir)ThirdParty/assimp/contrib/unzip",
"$(SolutionDir)ThirdParty/assimp/contrib/irrXML",
"$(SolutionDir)ThirdParty/assimp/contrib/openddlparser/include"
}
filter { "configurations:Debug" }
defines {
"WIN32",
"_WINDOWS",
"_DEBUG",
"WIN32_LEAN_AND_MEAN",
"UNICODE",
"_UNICODE",
"ASSIMP_BUILD_NO_C4D_IMPORTER",
"MINIZ_USE_UNALIGNED_LOADS_AND_STORES=0",
"ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC=1",
"RAPIDJSON_HAS_STDSTRING=1",
"RAPIDJSON_NOMEMBERITERATORCLASS",
"ASSIMP_BUILD_DLL_EXPORT",
"_SCL_SECURE_NO_WARNINGS",
"_CRT_SECURE_NO_WARNINGS",
"OPENDDLPARSER_BUILD",
"assimp_EXPORTS",
}
filter { "configurations:Release" }
defines {
"WIN32",
"_WINDOWS",
"NDEBUG",
"WIN32_LEAN_AND_MEAN",
"UNICODE",
"_UNICODE",
"ASSIMP_BUILD_NO_C4D_IMPORTER",
"MINIZ_USE_UNALIGNED_LOADS_AND_STORES=0",
"ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC=1",
"RAPIDJSON_HAS_STDSTRING=1",
"RAPIDJSON_NOMEMBERITERATORCLASS",
"ASSIMP_BUILD_DLL_EXPORT",
"_SCL_SECURE_NO_WARNINGS",
"_CRT_SECURE_NO_WARNINGS",
"OPENDDLPARSER_BUILD",
"assimp_EXPORTS",
}
group "Applications"
project "RenderTest"
kind "WindowedApp"
language "C++"
location "./Out/Intermediate/VCProjects"
targetname "$(ProjectName)_$(Configuration)"
files {
"./Applications/Colorful/RenderTest/**",
}
appResourceFiles()
includedirs {
"$(SolutionDir)",
"$(SolutionDir)ThirdParty/cereal/include"
}
targetdir "$(SolutionDir)Out"
links { "Gear", "IRenderer", "VulkanRenderer" }
vpaths {
["Resource"] = {
"./Assets/Icon/Resource.rc",
"./Applications/Resource.h"
},
[""] = {
"./Applications/Colorful/RenderTest/**"
}
}
|
-- Called when chat message sent
function ChatControl(args)
-- Set the weather
if args.text:sub(0,8) == "/weather" then
-- Grab the weather value
local wea = args.text:sub(10,args.text:len())
-- Check weather words
if wea == "sunny" then
DefaultWorld:SetWeatherSeverity(0)
Chat:Broadcast(args.player:GetName() .. " set weather to sunny", colorCommand)
return false
end
if wea == "rain" then
DefaultWorld:SetWeatherSeverity(1)
Chat:Broadcast(args.player:GetName() .. " set weather to rain", colorCommand)
return false
end
if wea == "storm" then
DefaultWorld:SetWeatherSeverity(2)
Chat:Broadcast(args.player:GetName() .. " set weather to storm", colorCommand)
return false
end
wea = tonumber(wea)
if wea < 0 or wea > 2 then
args.player:SendChatMessage("Weather value must be [0-2]", colorError)
return false
end
DefaultWorld:SetWeatherSeverity(wea)
Chat:Broadcast(args.player:GetName() .. " set weather to " .. tostring(wea), colorCommand)
return false
end
end
Events:Subscribe("PlayerChat", ChatControl)
|
C_Club = {}
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.AcceptInvitation)
---@param clubId string
function C_Club.AcceptInvitation(clubId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.AddClubStreamChatChannel)
---@param clubId string
---@param streamId string
function C_Club.AddClubStreamChatChannel(clubId, streamId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.AdvanceStreamViewMarker)
---@param clubId string
---@param streamId string
function C_Club.AdvanceStreamViewMarker(clubId, streamId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.AssignMemberRole)
---@param clubId string
---@param memberId number
---@param roleId ClubRoleIdentifier
function C_Club.AssignMemberRole(clubId, memberId, roleId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.CanResolvePlayerLocationFromClubMessageData)
---@param clubId string
---@param streamId string
---@param epoch number
---@param position number
---@return boolean canResolve
function C_Club.CanResolvePlayerLocationFromClubMessageData(clubId, streamId, epoch, position) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.ClearAutoAdvanceStreamViewMarker)
function C_Club.ClearAutoAdvanceStreamViewMarker() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.ClearClubPresenceSubscription)
function C_Club.ClearClubPresenceSubscription() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.CompareBattleNetDisplayName)
---@param clubId string
---@param lhsMemberId number
---@param rhsMemberId number
---@return number comparison
function C_Club.CompareBattleNetDisplayName(clubId, lhsMemberId, rhsMemberId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.CreateClub)
---@param name string
---@param shortName? string
---@param description string
---@param clubType ClubType
---@param avatarId number
function C_Club.CreateClub(name, shortName, description, clubType, avatarId) end
---Check the canCreateStream privilege.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.CreateStream)
---@param clubId string
---@param name string
---@param subject string
---@param leadersAndModeratorsOnly boolean
function C_Club.CreateStream(clubId, name, subject, leadersAndModeratorsOnly) end
---Check canCreateTicket privilege.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.CreateTicket)
---@param clubId string
---@param allowedRedeemCount? number
---@param duration? number
---@param defaultStreamId? string
function C_Club.CreateTicket(clubId, allowedRedeemCount, duration, defaultStreamId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.DeclineInvitation)
---@param clubId string
function C_Club.DeclineInvitation(clubId) end
---Check the canDestroy privilege.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.DestroyClub)
---@param clubId string
function C_Club.DestroyClub(clubId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.DestroyMessage)
---@param clubId string
---@param streamId string
---@param messageId ClubMessageIdentifier
function C_Club.DestroyMessage(clubId, streamId, messageId) end
---Check canDestroyStream privilege.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.DestroyStream)
---@param clubId string
---@param streamId string
function C_Club.DestroyStream(clubId, streamId) end
---Check canDestroyTicket privilege.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.DestroyTicket)
---@param clubId string
---@param ticketId string
function C_Club.DestroyTicket(clubId, ticketId) end
---nil arguments will not change existing club data
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.EditClub)
---@param clubId string
---@param name? string
---@param shortName? string
---@param description? string
---@param avatarId? number
---@param broadcast? string
function C_Club.EditClub(clubId, name, shortName, description, avatarId, broadcast) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.EditMessage)
---@param clubId string
---@param streamId string
---@param messageId ClubMessageIdentifier
---@param message string
function C_Club.EditMessage(clubId, streamId, messageId, message) end
---Check the canSetStreamName, canSetStreamSubject, canSetStreamAccess privileges. nil arguments will not change existing stream data.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.EditStream)
---@param clubId string
---@param streamId string
---@param name? string
---@param subject? string
---@param leadersAndModeratorsOnly? boolean
function C_Club.EditStream(clubId, streamId, name, subject, leadersAndModeratorsOnly) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.Flush)
function C_Club.Flush() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.FocusCommunityStreams)
function C_Club.FocusCommunityStreams() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.FocusStream)
---@param clubId string
---@param streamId string
---@return boolean focused
function C_Club.FocusStream(clubId, streamId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetAssignableRoles)
---@param clubId string
---@param memberId number
---@return ClubRoleIdentifier[] assignableRoles
function C_Club.GetAssignableRoles(clubId, memberId) end
---listen for AVATAR_LIST_UPDATED event. This can happen if we haven't downloaded the battle.net avatar list yet
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetAvatarIdList)
---@param clubType ClubType
---@return number[]? avatarIds
function C_Club.GetAvatarIdList(clubType) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetClubCapacity)
---@return number capacity
function C_Club.GetClubCapacity() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetClubInfo)
---@param clubId string
---@return ClubInfo? info
function C_Club.GetClubInfo(clubId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetClubLimits)
---@param clubType ClubType
---@return ClubLimits clubLimits
function C_Club.GetClubLimits(clubType) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetClubMembers)
---@param clubId string
---@param streamId? string
---@return number[] members
function C_Club.GetClubMembers(clubId, streamId) end
---The privileges for the logged in user for this club
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetClubPrivileges)
---@param clubId string
---@return ClubPrivilegeInfo privilegeInfo
function C_Club.GetClubPrivileges(clubId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetClubStreamNotificationSettings)
---@param clubId string
---@return ClubStreamNotificationSetting[] settings
function C_Club.GetClubStreamNotificationSettings(clubId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetCommunityNameResultText)
---@param result ValidateNameResult
---@return string? errorCode
function C_Club.GetCommunityNameResultText(result) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetGuildClubId)
---@return string? guildClubId
function C_Club.GetGuildClubId() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetInfoFromLastCommunityChatLine)
---@return ClubMessageInfo messageInfo
---@return string clubId
---@return string streamId
---@return ClubType clubType
function C_Club.GetInfoFromLastCommunityChatLine() end
---Returns a list of players that you can send a request to a Battle.net club. Returns an empty list for Character based clubs
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetInvitationCandidates)
---@param filter? string
---@param maxResults? number
---@param cursorPosition? number
---@param allowFullMatch? boolean
---@param clubId string
---@return ClubInvitationCandidateInfo[] candidates
function C_Club.GetInvitationCandidates(filter, maxResults, cursorPosition, allowFullMatch, clubId) end
---Get info about a specific club the active player has been invited to.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetInvitationInfo)
---@param clubId string
---@return ClubSelfInvitationInfo? invitation
function C_Club.GetInvitationInfo(clubId) end
---Get the pending invitations for this club. Call RequestInvitationsForClub() to retrieve invitations from server.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetInvitationsForClub)
---@param clubId string
---@return ClubInvitationInfo[] invitations
function C_Club.GetInvitationsForClub(clubId) end
---These are the clubs the active player has been invited to.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetInvitationsForSelf)
---@return ClubSelfInvitationInfo[] invitations
function C_Club.GetInvitationsForSelf() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetLastTicketResponse)
---@param ticket string
---@return ClubErrorType error
---@return ClubInfo? info
---@return boolean showError
function C_Club.GetLastTicketResponse(ticket) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetMemberInfo)
---@param clubId string
---@param memberId number
---@return ClubMemberInfo? info
function C_Club.GetMemberInfo(clubId, memberId) end
---Info for the logged in user for this club
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetMemberInfoForSelf)
---@param clubId string
---@return ClubMemberInfo? info
function C_Club.GetMemberInfoForSelf(clubId) end
---Get info about a particular message.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetMessageInfo)
---@param clubId string
---@param streamId string
---@param messageId ClubMessageIdentifier
---@return ClubMessageInfo? message
function C_Club.GetMessageInfo(clubId, streamId, messageId) end
---Get the ranges of the messages currently downloaded.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetMessageRanges)
---@param clubId string
---@param streamId string
---@return ClubMessageRange[] ranges
function C_Club.GetMessageRanges(clubId, streamId) end
---Get downloaded messages before (and including) the specified messageId limited by count. These are filtered by ignored players
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetMessagesBefore)
---@param clubId string
---@param streamId string
---@param newest ClubMessageIdentifier
---@param count number
---@return ClubMessageInfo[] messages
function C_Club.GetMessagesBefore(clubId, streamId, newest, count) end
---Get downloaded messages in the given range. These are filtered by ignored players
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetMessagesInRange)
---@param clubId string
---@param streamId string
---@param oldest ClubMessageIdentifier
---@param newest ClubMessageIdentifier
---@return ClubMessageInfo[] messages
function C_Club.GetMessagesInRange(clubId, streamId, oldest, newest) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetStreamInfo)
---@param clubId string
---@param streamId string
---@return ClubStreamInfo? streamInfo
function C_Club.GetStreamInfo(clubId, streamId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetStreamViewMarker)
---@param clubId string
---@param streamId string
---@return number? lastReadTime
function C_Club.GetStreamViewMarker(clubId, streamId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetStreams)
---@param clubId string
---@return ClubStreamInfo[] streams
function C_Club.GetStreams(clubId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetSubscribedClubs)
---@return ClubInfo[] clubs
function C_Club.GetSubscribedClubs() end
---Get the existing tickets for this club. Call RequestTickets() to retrieve tickets from server.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.GetTickets)
---@param clubId string
---@return ClubTicketInfo[] tickets
function C_Club.GetTickets(clubId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.IsAccountMuted)
---@param clubId string
---@return boolean accountMuted
function C_Club.IsAccountMuted(clubId) end
---Returns whether the given message is the first message in the stream, taking into account ignored messages
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.IsBeginningOfStream)
---@param clubId string
---@param streamId string
---@param messageId ClubMessageIdentifier
---@return boolean isBeginningOfStream
function C_Club.IsBeginningOfStream(clubId, streamId, messageId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.IsEnabled)
---@return boolean clubsEnabled
function C_Club.IsEnabled() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.IsRestricted)
---@return ClubRestrictionReason restrictionReason
function C_Club.IsRestricted() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.IsSubscribedToStream)
---@param clubId string
---@param streamId string
---@return boolean subscribed
function C_Club.IsSubscribedToStream(clubId, streamId) end
---Check kickableRoleIds privilege.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.KickMember)
---@param clubId string
---@param memberId number
function C_Club.KickMember(clubId, memberId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.LeaveClub)
---@param clubId string
function C_Club.LeaveClub(clubId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.RedeemTicket)
---@param ticketId string
function C_Club.RedeemTicket(ticketId) end
---Request invitations for this club from server. Check canGetInvitation privilege.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.RequestInvitationsForClub)
---@param clubId string
function C_Club.RequestInvitationsForClub(clubId) end
---Call this when the user scrolls near the top of the message view, and more need to be displayed. The history will be downloaded backwards (newest to oldest).
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.RequestMoreMessagesBefore)
---@param clubId string
---@param streamId string
---@param messageId? ClubMessageIdentifier
---@param count? number
---@return boolean alreadyHasMessages
function C_Club.RequestMoreMessagesBefore(clubId, streamId, messageId, count) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.RequestTicket)
---@param ticketId string
function C_Club.RequestTicket(ticketId) end
---Request tickets from server. Check canGetTicket privilege.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.RequestTickets)
---@param clubId string
function C_Club.RequestTickets(clubId) end
---Check canRevokeOwnInvitation or canRevokeOtherInvitation
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.RevokeInvitation)
---@param clubId string
---@param memberId number
function C_Club.RevokeInvitation(clubId, memberId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.SendBattleTagFriendRequest)
---@param guildClubId string
---@param memberId number
function C_Club.SendBattleTagFriendRequest(guildClubId, memberId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.SendCharacterInvitation)
---@param clubId string
---@param character string
function C_Club.SendCharacterInvitation(clubId, character) end
---Check the canSendInvitation privilege.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.SendInvitation)
---@param clubId string
---@param memberId number
function C_Club.SendInvitation(clubId, memberId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.SendMessage)
---@param clubId string
---@param streamId string
---@param message string
function C_Club.SendMessage(clubId, streamId, message) end
---Only one stream can be set for auto-advance at a time. Focused streams will have their view times advanced automatically.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.SetAutoAdvanceStreamViewMarker)
---@param clubId string
---@param streamId string
function C_Club.SetAutoAdvanceStreamViewMarker(clubId, streamId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.SetAvatarTexture)
---@param texture table
---@param avatarId number
---@param clubType ClubType
function C_Club.SetAvatarTexture(texture, avatarId, clubType) end
---Check the canSetOwnMemberNote and canSetOtherMemberNote privileges.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.SetClubMemberNote)
---@param clubId string
---@param memberId number
---@param note string
function C_Club.SetClubMemberNote(clubId, memberId, note) end
---You can only be subscribed to 0 or 1 clubs for presence. Subscribing to a new club automatically unsuscribes you to existing subscription.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.SetClubPresenceSubscription)
---@param clubId string
function C_Club.SetClubPresenceSubscription(clubId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.SetClubStreamNotificationSettings)
---@param clubId string
---@param settings ClubStreamNotificationSetting[]
function C_Club.SetClubStreamNotificationSettings(clubId, settings) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.SetFavorite)
---@param clubId string
---@param isFavorite boolean
function C_Club.SetFavorite(clubId, isFavorite) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.SetSocialQueueingEnabled)
---@param clubId string
---@param enabled boolean
function C_Club.SetSocialQueueingEnabled(clubId, enabled) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.ShouldAllowClubType)
---@param clubType ClubType
---@return boolean clubTypeIsAllowed
function C_Club.ShouldAllowClubType(clubType) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.UnfocusAllStreams)
---@param unsubscribe boolean
function C_Club.UnfocusAllStreams(unsubscribe) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.UnfocusStream)
---@param clubId string
---@param streamId string
function C_Club.UnfocusStream(clubId, streamId) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_Club.ValidateText)
---@param clubType ClubType
---@param text string
---@param clubFieldType ClubFieldType
---@return ValidateNameResult result
function C_Club.ValidateText(clubType, text, clubFieldType) end
---@class ClubInfo
---@field clubId string
---@field name string
---@field shortName string|nil
---@field description string
---@field broadcast string
---@field clubType ClubType
---@field avatarId number
---@field memberCount number|nil
---@field favoriteTimeStamp number|nil
---@field joinTime number|nil
---@field socialQueueingEnabled boolean|nil
---@class ClubInvitationCandidateInfo
---@field memberId number
---@field name string
---@field priority number
---@field status ClubInvitationCandidateStatus
---@class ClubInvitationInfo
---@field invitationId string
---@field isMyInvitation boolean
---@field invitee ClubMemberInfo
---@class ClubLimits
---@field maximumNumberOfStreams number
---@class ClubMemberInfo
---@field isSelf boolean
---@field memberId number
---@field name string|nil
---@field role ClubRoleIdentifier|nil
---@field presence ClubMemberPresence
---@field clubType ClubType|nil
---@field guid string|nil
---@field bnetAccountId number|nil
---@field memberNote string|nil
---@field officerNote string|nil
---@field classID number|nil
---@field race number|nil
---@field level number|nil
---@field zone string|nil
---@field achievementPoints number|nil
---@field profession1ID number|nil
---@field profession1Rank number|nil
---@field profession1Name string|nil
---@field profession2ID number|nil
---@field profession2Rank number|nil
---@field profession2Name string|nil
---@field lastOnlineYear number|nil
---@field lastOnlineMonth number|nil
---@field lastOnlineDay number|nil
---@field lastOnlineHour number|nil
---@field guildRank string|nil
---@field guildRankOrder number|nil
---@field isRemoteChat boolean|nil
---@field overallDungeonScore number|nil
---@class ClubMessageIdentifier
---@field epoch number
---@field position number
---@class ClubMessageInfo
---@field messageId ClubMessageIdentifier
---@field content string
---@field author ClubMemberInfo
---@field destroyer ClubMemberInfo|nil
---@field destroyed boolean
---@field edited boolean
---@class ClubMessageRange
---@field oldestMessageId ClubMessageIdentifier
---@field newestMessageId ClubMessageIdentifier
---@class ClubPrivilegeInfo
---@field canDestroy boolean
---@field canSetAttribute boolean
---@field canSetName boolean
---@field canSetDescription boolean
---@field canSetAvatar boolean
---@field canSetBroadcast boolean
---@field canSetPrivacyLevel boolean
---@field canSetOwnMemberAttribute boolean
---@field canSetOtherMemberAttribute boolean
---@field canSetOwnMemberNote boolean
---@field canSetOtherMemberNote boolean
---@field canSetOwnVoiceState boolean
---@field canSetOwnPresenceLevel boolean
---@field canUseVoice boolean
---@field canVoiceMuteMemberForAll boolean
---@field canGetInvitation boolean
---@field canSendInvitation boolean
---@field canSendGuestInvitation boolean
---@field canRevokeOwnInvitation boolean
---@field canRevokeOtherInvitation boolean
---@field canGetBan boolean
---@field canGetSuggestion boolean
---@field canSuggestMember boolean
---@field canGetTicket boolean
---@field canCreateTicket boolean
---@field canDestroyTicket boolean
---@field canAddBan boolean
---@field canRemoveBan boolean
---@field canCreateStream boolean
---@field canDestroyStream boolean
---@field canSetStreamPosition boolean
---@field canSetStreamAttribute boolean
---@field canSetStreamName boolean
---@field canSetStreamSubject boolean
---@field canSetStreamAccess boolean
---@field canSetStreamVoiceLevel boolean
---@field canCreateMessage boolean
---@field canDestroyOwnMessage boolean
---@field canDestroyOtherMessage boolean
---@field canEditOwnMessage boolean
---@field canPinMessage boolean
---@field kickableRoleIds number[]
---@class ClubSelfInvitationInfo
---@field invitationId string
---@field club ClubInfo
---@field inviter ClubMemberInfo
---@field leaders ClubMemberInfo[]
---@class ClubStreamInfo
---@field streamId string
---@field name string
---@field subject string
---@field leadersAndModeratorsOnly boolean
---@field streamType ClubStreamType
---@field creationTime number
---@class ClubStreamNotificationSetting
---@field streamId string
---@field filter ClubStreamNotificationFilter
---@class ClubTicketInfo
---@field ticketId string
---@field allowedRedeemCount number
---@field currentRedeemCount number
---@field creationTime number
---@field expirationTime number
---@field defaultStreamId string|nil
---@field creator ClubMemberInfo
|
------------------------------------------------------------------------------
-- MultiBox class
------------------------------------------------------------------------------
local ctrl = {
nick = "multibox",
parent = iup.BOX,
subdir = "elem",
creation = "-",
funcname = "MultiBox",
callback = {}
}
function ctrl.createElement(class, param)
return iup.MultiBox()
end
iup.RegisterWidget(ctrl)
iup.SetClass(ctrl, "iupWidget")
|
local localization =
{
--- Settings menu entries ---
ATT_STR_GENERAL = "Allgemein",
ATT_STR_SHOW_WINDOW_ON_MAIL = "Zeige Fenster im Postfach",
ATT_STR_SHOW_WINDOW_ON_GUILDSTORE = "Zeige Fenster im Gildenladen",
ATT_STR_SHOW_WINDOW_ON_CRAFTINGSTATION = "Zeige Fenster an Handwerksstation",
ATT_STR_SHOW_NOTIFICATIONS = "Zeige Ankündigungen",
ATT_STR_SHOW_NOTIFICATIONS_DURING_COMBAT = "Zeige Ankündigungen während des Kampfes",
ATT_STR_HIGHLIGHT_OWN_NAME_BY_COLOR = "Eigenen Namen farblich hervorheben",
ATT_STR_HIGHLIGHT_OWN_GUILDNAMES_BY_CHAT_COLOR = "Eigene Gildennamen farblich hervorheben",
ATT_STR_COLOR = "Farbe",
ATT_STR_EXTENDED = "Erweitert",
ATT_STR_SCAN_DURING_COMBAT = "Suche nach Ereignissen während des Kampfes",
ATT_STR_SCAN_LONG_INTERVAL = "Intervall 1 (Sekunden)",
ATT_STR_SCAN_SHORT_INTERVAL = "Intervall 2 (Millisekunden)",
ATT_STR_DONATE = "Spenden",
ATT_STR_DONATE_TOOLTIP = "Du magst dieses Addon und möchtest gerne deine Unterstützung ausdrücken? Dann sende eine Spende an @Aldanga :-)",
ATT_STR_GUILDSTATUS_TEXT = "Update-Status",
ATT_STR_GUILDSTATUS_TOOLTIP_LINE1 = "Gilde benötigt Aktualisierung",
ATT_STR_GUILDSTATUS_TOOLTIP_LINE2 = "Gilde aktualisiert gerade",
ATT_STR_GUILDSTATUS_TOOLTIP_LINE3 = "Gilde ist aktuell",
ATT_STR_BUTTON_CLOSE_TOOLTIP = "Schließe Fenster",
ATT_STR_BUTTON_DRAWTIER_TOOLTIP = "Zeige Fenster über oder unter anderen UI Elementen",
ATT_STR_KEYBIND_TOGGLE_MAIN_WINDOW = "Zeige oder verstecke Hauptfenster",
}
ZO_ShallowTableCopy(localization, ArkadiusTradeTools.Localization)
|
local combat = Combat()
combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_HEALING)
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE)
combat:setParameter(COMBAT_PARAM_AGGRESSIVE, 0)
combat:setParameter(COMBAT_PARAM_DISPEL, CONDITION_PARALYZE)
function onGetFormulaValues(player, level, maglevel)
return 4, 7
end
combat:setCallback(CALLBACK_PARAM_LEVELMAGICVALUE, "onGetFormulaValues")
function onCastSpell(creature, var)
return combat:execute(creature, var)
end
|
--[[
File: game.lua
Author: Daniel "lytedev" Flanagan
Website: http://dmf.me
The gamestate in charge of managinplayer... well... the game.
]]--
local Game = Gamestate.new()
local pairs = pairs
function Game:init()
self.pixelFont = love.graphics.newFont("assets/fonts/pf_tempesta_seven_condensed.ttf", 8)
world = love.physics.newWorld(0, 0, true)
love.graphics.setBackgroundColor(17, 17, 17, 255)
self.camera = Camera()
self.camera:zoomTo(2)
self.camera:lookAt(0, 0)
gameCamera = self.camera
self:restart()
end
function Game:restart()
gameobjects = {}
towers = {}
enemies = {}
world = love.physics.newWorld(0, 0, true)
world:setCallbacks(beginContact, endContact, preSolve, postSolve)
self.player = Player(0, 200)
player = self.player
Tower(40, 200)
Tower(-40, 200)
self:addEnemy(math.random(), math.random())
self.timer = Timer.new()
self.timer:addPeriodic(2, function()
self:addEnemy(math.random(), math.random())
end)
end
function beginContact(a, b, coll)
end
function endContact(a, b, coll)
end
function preSolve(a, b, coll)
end
function postSolve(a, b, coll)
end
function Game:addEnemy(x, y)
local x = x or 0
local y = y or 0
Enemy(x, y)
end
function Game:update(dt)
if love.keyboard.isDown("escape") then
love.event.quit()
end
if love.keyboard.isDown("r") then
self:restart()
end
addDebugText(love.timer.getFPS())
addDebugText(self.player.cooldown)
self.timer:update(dt)
world:update(dt)
local movement = vector(0, 0)
if love.keyboard.isDown("a", "left") then
movement.x = movement.x - 1
end
if love.keyboard.isDown("w", "up") then
movement.y = movement.y - 1
end
if love.keyboard.isDown("d", "right") then
movement.x = movement.x + 1
end
if love.keyboard.isDown("s", "down") then
movement.y = movement.y + 1
end
if love.mouse.isDown("l") then
self.player:dropTower()
end
if love.mouse.isDown("r") then
self.player:deleteTower()
end
movement:normalize_inplace()
movement = movement * (self.player.speed)
self.player:applyForce(movement.x, movement.y)
for k, v in pairs(gameobjects) do
v:update(dt)
end
px, py = self.player:getPosition()
self.camera:lookAt(px, py)
end
function Game:draw()
self.camera:attach()
for k, v in pairs(towers) do
v:drawAuras()
end
for k, v in pairs(gameobjects) do
love.graphics.setColor(255, 255, 255, 255)
v:draw()
end
for k, v in pairs(towers) do
v:drawAttack()
end
player:drawDropPoint()
love.graphics.setColor(255, 0, 0, 255)
-- love.graphics.rectangle('line', -25, -25, 50, 50)
self.camera:detach()
love.graphics.setColor(255, 255, 255, 255)
love.graphics.setFont(self.pixelFont)
drawDebugText()
end
return Game
|
package("memorymapping")
set_homepage("https://github.com/NimbusKit/memorymapping")
set_description("fmemopen port library")
set_urls("https://github.com/NimbusKit/memorymapping.git")
add_versions("2014.12.21", "79ce0ddd0de4b11e4944625eb866290368f867c0")
on_install("android", "macosx", "iphoneos", function (package)
io.writefile("xmake.lua", [[
add_rules("mode.debug", "mode.release")
target("fmemopen")
set_kind("$(kind)")
add_files("src/*.c")
add_headerfiles("src/*.h")
]])
local configs = {}
if package:config("shared") then
configs.kind = "shared"
elseif package:config("pic") ~= false then
configs.cxflags = "-fPIC"
end
import("package.tools.xmake").install(package, configs)
end)
on_test(function (package)
assert(package:has_cfuncs("fmemopen", {includes = {"stdio.h", "fmemopen.h"}}))
end)
|
--[[
Collection of functions to detect if a line hits a shape
Special thanks to Rayco "XeNMaX" Hernandez García for his BIG help.
]]
local ZERO_TOLERANCE = 0.000001
Vector3D = {
new = function(self, _x, _y, _z)
local newVector = { x = _x or 0.0, y = _y or 0.0, z = _z or 0.0 }
return setmetatable(newVector, { __index = Vector3D })
end,
Copy = function(self)
return Vector3D:new(self.x, self.y, self.z)
end,
Normalize = function(self)
local mod = self:Module()
self.x = self.x / mod
self.y = self.y / mod
self.z = self.z / mod
end,
Dot = function(self, V)
return self.x * V.x + self.y * V.y + self.z * V.z
end,
Module = function(self)
return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
end,
AddV = function(self, V)
return Vector3D:new(self.x + V.x, self.y + V.y, self.z + V.z)
end,
SubV = function(self, V)
return Vector3D:new(self.x - V.x, self.y - V.y, self.z - V.z)
end,
CrossV = function(self, V)
return Vector3D:new(self.y * V.z - self.z * V.y,
self.z * V.x - self.x * V.z,
self.x * V.y - self.y * V.z)
end,
Mul = function(self, n)
return Vector3D:new(self.x * n, self.y * n, self.z * n)
end,
Div = function(self, n)
return Vector3D:new(self.x / n, self.y / n, self.z / n)
end,
}
collisionTest = { }
collisionTest.Rectangle = function(lineStart, lineEnd, rectangleCenter, sizeX, sizeY )
-- check if line intersects rectangle around element
local ratio = rectangleCenter.z / lineEnd.z
lineEnd.x = rectangleCenter.x * lineEnd.x
lineEnd.y = rectangleCenter.y * lineEnd.y
lineEnd.z = rectangleCenter.z
if lineEnd.x < (rectangleCenter.x + sizeX/2) and lineEnd.x > (rectangleCenter.x - sizeX/2) then
if lineEnd.y < (rectangleCenter.y + sizeY/2) and lineEnd.y > (rectangleCenter.y - sizeY/2) then
return lineEnd
end
end
end
collisionTest.Sphere = function(lineStart, lineEnd, sphereCenter, sphereRadius)
-- check if line intersects sphere around element
local vec = Vector3D:new(lineEnd.x - lineStart.x, lineEnd.y - lineStart.y, lineEnd.z - lineStart.z)
local A = vec.x^2 + vec.y^2 + vec.z^2
local B = ( (lineStart.x - sphereCenter.x) * vec.x + (lineStart.y - sphereCenter.y) * vec.y + (lineStart.z - sphereCenter.z) * vec.z ) * 2
local C = ( (lineStart.x - sphereCenter.x)^2 + (lineStart.y - sphereCenter.y)^2 + (lineStart.z - sphereCenter.z)^2 ) - sphereRadius^2
local delta = B^2 - 4*A*C
if (delta >= 0) then
delta = math.sqrt(delta)
local t = (-B - delta) / (2*A)
if (t > 0) then
return Vector3D:new(lineStart.x + vec.x * t, lineStart.y + vec.y * t, lineStart.z + vec.z * t)
end
end
end
collisionTest.Cylinder = function(lineStart, lineEnd, cylCenter, cylRadius, cylHeight)
local kU = Vector3D:new(1, 0, 0)
local kV = Vector3D:new(0, 1, 0)
local kW = Vector3D:new(0, 0, 1)
local rkDir = lineEnd:SubV(lineStart)
rkDir:Normalize()
local afT = { 0.0, 0.0 }
local fHalfHeight = cylHeight * 0.5
local fRSqr = cylRadius * cylRadius
local kDiff = lineStart:SubV(cylCenter)
local kP = Vector3D:new(kU:Dot(kDiff), kV:Dot(kDiff), kW:Dot(kDiff))
local fDz = kW:Dot(rkDir)
if (math.abs(fDz) >= 1.0 - ZERO_TOLERANCE) then
local fRadialSqrDist = fRSqr - kP.x * kP.x - kP.y * kP.y
if (fRadialSqrDist < 0.0) then
return nil
end
if (fDz > 0.0) then
afT[1] = -kP.z - fHalfHeight
if afT[1] < 0 then return nil end
return lineStart:AddV(rkDir:Mul(afT[1]))
else
afT[1] = kP.z - fHalfHeight
if afT[1] < 0 then return nil end
return lineStart:AddV(rkDir:Mul(afT[1]))
end
end
local kD = Vector3D:new(kU:Dot(rkDir), kV:Dot(rkDir), fDz)
local fA0, fA1, fA2, fDiscr, fRoot, fInv, fT
if (math.abs(kD.z) <= ZERO_TOLERANCE) then
if (math.abs(kP.z) > fHalfHeight) then
return nil
end
fA0 = kP.x * kP.x + kP.y * kP.y - fRSqr
fA1 = kP.x * kD.x + kP.y * kD.y
fA2 = kD.x * kD.x + kD.y * kD.y
fDiscr = fA1 * fA1 - fA0 * fA2
if (fDiscr < 0.0) then
return nil
elseif (fDiscr > ZERO_TOLERANCE) then
fRoot = math.sqrt(fDiscr)
fInv = 1.0 / fA2
afT[1] = (-fA1 - fRoot) * fInv
if afT[1] < 0 then return nil end
return lineStart:AddV(rkDir:Mul(afT[1]))
else
afT[1] = -fA1 / fA2
if afT[1] < 0 then return nil end
return lineStart:AddV(rkDir:Mul(afT[1]))
end
end
local iQuantity = 0
fInv = 1.0 / kD.z
local fT0 = (-fHalfHeight - kP.z) * fInv
local fXTmp = kP.x + fT0 * kD.x
local fYTmp = kP.y + fT0 * kD.y
if (fXTmp * fXTmp + fYTmp * fYTmp <= fRSqr) then
iQuantity = iQuantity + 1
afT[iQuantity] = fT0
end
local fT1 = (fHalfHeight - kP.z) * fInv
fXTmp = kP.x + fT1 * kD.x
fYTmp = kP.y + fT1 * kD.y
if (fXTmp * fXTmp + fYTmp * fYTmp <= fRSqr) then
iQuantity = iQuantity + 1
afT[iQuantity] = fT1
end
if (iQuantity == 2) then
if (afT[1] > afT[2]) then
local fSave = afT[1]
afT[1] = afT[2]
afT[2] = fSave
end
if afT[1] < 0 then return nil end
return lineStart:AddV(rkDir:Mul(afT[1]))
end
fA0 = kP.x * kP.x + kP.y * kP.y - fRSqr
fA1 = kP.x * kD.x + kP.y * kD.y
fA2 = kD.x * kD.x + kD.y * kD.y
fDiscr = fA1 * fA1 - fA0 * fA2
if (fDiscr < 0.0) then
return nil
elseif (fDiscr > ZERO_TOLERANCE) then
fRoot = math.sqrt(fDiscr)
fInv = 1.0 / fA2
fT = (-fA1 - fRoot) * fInv
if (fT0 <= fT1) then
if (fT0 <= fT and fT <= fT1) then
iQuantity = iQuantity + 1
afT[iQuantity] = fT
end
else
if (fT1 <= fT and fT <= fT0) then
iQuantity = iQuantity + 1
afT[iQuantity] = fT
end
end
if (iQuantity == 2) then
if (afT[1] > afT[2]) then
local fSave = afT[1]
afT[1] = afT[2]
afT[2] = fSave
end
if afT[1] < 0 then return nil end
return lineStart:AddV(rkDir:Mul(afT[1]))
end
fT = (-fA1 + fRoot) * fInv
if (fT0 <= fT1) then
if (fT0 <= fT and fT <= fT1) then
iQuantity = iQuantity + 1
afT[iQuantity] = fT
end
else
if (fT1 <= fT and fT <= fT0) then
iQuantity = iQuantity + 1
afT[iQuantity] = fT
end
end
else
fT = -fA1 / fA2
if (fT0 <= fT1) then
if (fT0 <= fT and fT <= fT1) then
iQuantity = iQuantity + 1
afT[iQuantity] = fT
end
else
if (fT1 <= fT and fT <= fT0) then
iQuantity = iQuantity + 1
afT[iQuantity] = fT
end
end
end
if (iQuantity == 2) then
if (afT[1] > afT[2]) then
local fSave = afT[1]
afT[1] = afT[2]
afT[2] = fSave
end
if afT[1] < 0 then return nil end
return lineStart:AddV(rkDir:Mul(afT[1]))
elseif (iQuantity == 1) then
if afT[1] < 0 then return nil end
return lineStart:AddV(rkDir:Mul(afT[1]))
end
return nil
end
|
local Decay = Class(function(self, inst)
self.inst = inst
self.maxhealth = 100
self.decayrate = 1
self.currenthealth = self.maxhealth
end)
function Decay:DoDelta(amount)
local oldhealth = self.currenthealth
self.currenthealth = self.currenthealth + amount
if self.currenthealth <= 0 then
if oldhealth > 0 then
self.inst:PushEvent("spentfuel")
end
self.currenthealth = 0
end
if self.currenthealth > self.maxhealth then
self.inst:PushEvent("addfuel")
end
--print ("Decay: Fuel: ", self.currenthealth, "State:",self.inst.sg.currentstate.name)
end
local function delta(health, amount, pause, num)
while true do
if not health.paused then
health:DoDelta(amount)
if num then
num = num - self.decayrate
if num <= 0 then
return
end
end
end
Sleep(pause)
end
end
function Decay:SetTimeDelta(amount, pause, num)
--print ("SetTimeDelta", amount, pause, num)
if self.deltatask then
KillThread(self.deltatask)
end
-- Only set the timer if we are going to need an update
if pause >0 then
self.deltatask = StartThread(function() delta(self, amount, pause, num) self.deltatask = nil end, self.inst.GUID)
end
end
return Decay
|
local treesitter = require'nvim-treesitter.configs'
local function init()
treesitter.setup{
ensure_installed = {
'bash',
'css',
'go',
'graphql',
'html',
'json',
'lua',
'python',
'rust',
'tsx',
'typescript',
'yaml',
},
highlight = {
enable = true
}
}
end
return {
init = init
}
|
local IInput = require("api.gui.IInput")
local IUiLayer = require("api.gui.IUiLayer")
local InputHandler = require("api.gui.InputHandler")
local UiTheme = require("api.gui.UiTheme")
local UiWindow = require("api.gui.UiWindow")
local Draw = require("api.Draw")
local ColorEditorMenuList = require("mod.extra_config_options.api.gui.ColorEditorMenuList")
local Ui = require("api.Ui")
local Gui = require("api.Gui")
local ColorEditorMenu = class.class("ColorEditorMenu", IUiLayer)
ColorEditorMenu:delegate("input", IInput)
function ColorEditorMenu:init(color)
self.list = ColorEditorMenuList:new(color)
local key_hints = self:make_key_hints()
self.win = UiWindow:new("extra_config_options:ui.menu.color_editor.title", true, key_hints)
self.input = InputHandler:new()
self.input:forward_to(self.list)
self.input:bind_keys(self:make_keymap())
end
function ColorEditorMenu:make_keymap()
return {}
end
function ColorEditorMenu:make_key_hints()
return self.list:make_key_hints()
end
function ColorEditorMenu:on_query()
Gui.play_sound("base.pop2")
end
function ColorEditorMenu:relayout()
self.width = 360
self.height = 190
self.x, self.y = Ui.params_centered(self.width, self.height)
self.t = UiTheme.load(self)
self.win:relayout(self.x, self.y, self.width, self.height)
self.list:relayout(self.x + 26, self.y + 46, self.width, self.height)
end
function ColorEditorMenu:draw()
self.win:draw()
self.list:draw()
Draw.set_color(self.t.base.text_color)
Draw.line_rect(self.x + 243, self.y + 45, 82, 82)
Draw.set_color(self.list.color)
Draw.filled_rect(self.x + 244, self.y + 46, 80, 80)
end
function ColorEditorMenu:update(dt)
self.win:update(dt)
local color, canceled = self.list:update(dt)
if color then
return color
end
end
return ColorEditorMenu
|
local _, ns = ...
local B, C, L, DB, P = unpack(ns)
P.Changelog = [[
v1.4.1
[鼠标提示] 地下城信息显示超时颜色
[易用性] 添加刻希亚稀有逃跑的荒蚺助手
v1.4.0
[主要] 更新支持9.1
[美化] 更新部分插件美化
[鼠标提示] PvE进度信息添加新版本数据,地下城信息由副本次数更新为暴雪副本评分和最高层数
[易用性] 添加暂离界面
[易用性] 修复复制幻化
[易用性] 移除顿号转斜杠
v1.3.11
[美化] 修复WeakAurasOptions报错
v1.3.10
[报错] 修复一个加载错误
v1.3.9
[美化] 兼容旧版MeetingStone
v1.3.8
[美化] 更新Immersion美化
[美化] 更新MeetingStone美化
v1.3.7
[美化] 添加Auctionator美化
[鼠标提示] PvE进度信息支持自定义成就
[其他] 预组建队伍职责美化支持集合石插件
v1.3.6
[美化] 移除和新增部分材质
[美化] 添加其他风格职责图标
[鼠标提示] PvE进度信息只统计9.0大秘境次数
[易用性] 移除商人界面装备等级显示、移除试衣间增强
v1.3.5
[聊天] 修复聊天框隐藏
v1.3.4
[聊天] 添加聊天框隐藏
[美化] 添加Extended Vendor UI美化
[易用性] 添加选项隐藏未学天赋提醒
[易用性] 添加商人界面装备等级显示
v1.3.3
[单位框体] 修复姓名版字体颜色错误
v1.3.2
[单位框体] 修复白色姓名文本和职责图标在团队框体未生效的问题
v1.3.1
[鼠标提示] 修复对比成就时可能出现的报错
v1.3.0
|cffFF1414重写控制台|r,部分选项需要重新设置
[动作条] 重写全局渐隐
[单位框体] 添加单位框体渐隐
[鼠标提示] 添加PvE进度信息 (ElvUI_WindTools)
[易用性] 添加一键复制幻化 (CopyMog)
v1.2.8
[美化] 美化兼容DungeonTools
[美化] 更新Immersion美化
[其他] 添加双击专精图标快速切换专精功能
[天赋管理] 添加天赋管理功能
[拾取管理] |cffFF1414重置|r拾取配置文件,修复某些情况副本显示不完整的问题; 移除默认专精选项
v1.2.7
[任务] 添加暗影国度世界任务助手
[美化] 添加WorldQuestTab美化
[其他] 添加鼠标提示坐骑来源
[其他] 添加拾取专精管理, 支持团队副本和大秘境。命令:/lsm 或者冒险手册界面打开
v1.2.6
[材质] 材质替换支持LibSharedMedia
[材质] 添加WindMedia材质包
[材质] 添加Lyn风格职责图标
[战斗] 切换动作条时刷新终结技高亮
[美化] 更新MeetingStone美化
v1.2.5
[战斗] 添加终结技高亮
[美化] 添加Myslot美化
[美化] 更新AceGUI美化
v1.2.4
|cffFF1414重置配置文件|r,需要重新进行设置
[聊天] 添加超链接图标
[聊天] 修复离队玩家仍会显示小队编号的问题
[美化] 更新WeakAurasOptions美化
[美化] 添加RareScanner美化
[全局渐隐] 拖动法术时自动显示动作条
[全局渐隐] 修复可能造成的污染
v1.2.3
[全局渐隐] 修复动作条背景无法点击穿透的问题
v1.2.2
添加全局渐隐,支持NDui动作条/头像
添加聊天姓名染色
添加聊天小队编号
美化兼容MeetingStonePlus
v1.2.1
修复部分插件美化
v1.2.0
更新支持9.0
]]
|
iron = {}
iron.blocks = {}
function iron:load()
iron.spr = love.graphics.newImage("/assets/iron.png")
iron:new(0, 15, 31, 1)
iron:new(-15, 0, 1, 31)
iron:new(15, 0, 1, 31)
iron:new(0, -15, 31, 1)
-- Starting block
iron:new(0,3, 4, 2)
iron:new(10,-5, 2, 10)
iron:new(7, 10, 3, 2)
iron:new(-9, 10, 3, 4)
iron:new(-9, -10, 1, 4)
iron:new(-11, -3, 1, 6)
end
function iron:new(x, y, w, h)
x = x * 16
y = y * 16
w = w * 16
h = h * 16
local structure = {}
structure.body = love.physics.newBody(world.world, x, y)
structure.shape = love.physics.newRectangleShape(w, h)
structure.fixture = love.physics.newFixture(structure.body, structure.shape)
structure.y = y
structure.x = x
structure.w = w
structure.h = h
structure.fixture:setUserData("iron")
table.insert(self.blocks, structure)
end
function iron:update(dt)
end
function iron:draw()
-- Tiling solid blocks:
for i in ipairs(self.blocks) do
-- *Start calculates the top right corner of the box
local xStart = self.blocks[i].x - (self.blocks[i].w / 2)
local yStart = self.blocks[i].y - (self.blocks[i].h / 2)
-- These will be used to iterate through the width and height in increments of 16
local widthRemaining = self.blocks[i].w
-- We'll subtract 16 from widthRemaining until it's 0
while widthRemaining > 0 do
local xVal = xStart + self.blocks[i].w - widthRemaining
local heightRemaining = self.blocks[i].h
while heightRemaining > 0 do
local yVal = yStart + self.blocks[i].h - heightRemaining
love.graphics.draw(self.spr, xVal, yVal, 0, 1, 1)
heightRemaining = heightRemaining - 16
end
widthRemaining = widthRemaining - 16
end
love.graphics.draw(self.spr, xStart, yStart, 0, 1, 1)
end
end
|
local World = {}
World.__index = World
local beginContact = function(a, b, coll)
if (a:getUserData() == "MainCharacter" and b:getUserData() == "Ground") or (a:getUserData() == "Ground" and b:getUserData() == "MainCharacter") then
gameDirector:getMainCharacter().inGround = true
end
local bulletFixture = a:getUserData() == "Bullet" and a or b:getUserData() == "Bullet" and b or nil
if bulletFixture then
gameDirector:removeBullet(nil, bulletFixture)
end
end
function World:new()
love.physics.setMeter(64)
world = love.physics.newWorld(0, 9.81 * 128)
world:setCallbacks(beginContact)
return setmetatable({world = world}, World)
end
function World:update(dt)
self.world:update(dt)
end
return World
|
--[[
This Lua script is to override timestamp with integer/float epoch time.
https://github.com/fluent/fluent-bit/issues/662
sample input is
[XXXXX.XXXXX, {"KEY_OF_TIMESTAMP"=>1530239065.807368, "data"=>"sample"}]
expected output is
[1530239065.807368040, {"KEY_OF_TIMESTAMP"=>1530239065.807368, "data"=>"sample"}]
sample configuration:
[FILTER]
Name lua
Match *.*
script override_time.lua
call override_time
]]
function override_time(tag, timestamp, record)
-- modify KEY_OF_TIMESTAMP properly.
return 1, record["KEY_OF_TIMESTAMP"], record
end
|
------------------------------------------
--- G6HotFix 的加载,用于加载整个Lua系统
------------------------------------------
--
-- G6采用Require来加载Lua文件,以提供HotFix支持,
-- 所以在加载其他Lua文件之前,要先将HotFix加载
--
-- Load HotFix
print("Load HotFix...");
local hotfix_func,err = UELoadLuaFile("G6Hotfix.lua");
if (hotfix_func) and type(hotfix_func) == "function" then
package.loaded["g6hotfix"] = hotfix_func();
_G.G6HotFix = package.loaded["g6hotfix"];
else
print("Require HotFix Fail " .. tostring(err));
end
-- _G.G6HotFix = require "G6Core.Misc.G6Hotfix"
print("Load HotFix --->");
--
-- 所有之后的Lua文件使用的是hotfix的require了
--
--- 重新加载某个文件
---@param filepath string
function ReloadFile(filepath)
if nil == filepath then
return
end
_G.G6HotFix.ReloadFile(filepath)
end
--- 重新加载所有文件
function ReloadAll()
_G.G6HotFix.ClearLoadedModule()
end
--- 打印表内容
---@overload fun(tbl: table):string
---@param TableToPrint table
---@param MaxIntent number
---@return string
function _G.TableToString (TableToPrint, MaxIntent)
local HandlerdTable = {}
local function ItretePrintTable(TP, Indent)
if not Indent then Indent = 0 end
if type(TP) ~= "table" then return tostring(TP) end
if(Indent > MaxIntent) then return tostring(TP) end
if HandlerdTable[TP] then
return "";
end
HandlerdTable[TP] = true
local StrToPrint = string.rep(" ", Indent) .. "{\r\n"
Indent = Indent + 2
for k, v in pairs(TP) do
StrToPrint = StrToPrint .. string.rep(" ", Indent)
if (type(k) == "number") then
StrToPrint = StrToPrint .. "[" .. k .. "] = "
elseif (type(k) == "string") then
StrToPrint = StrToPrint .. k .. "= "
else
StrToPrint = StrToPrint .. tostring(k) .. " = "
end
if (type(v) == "number") then
StrToPrint = StrToPrint .. v .. ",\r\n"
elseif (type(v) == "string") then
StrToPrint = StrToPrint .. "\"" .. v .. "\",\r\n"
elseif (type(v) == "table") then
StrToPrint = StrToPrint .. tostring(v) .. ItretePrintTable(v, Indent + 2) .. ",\r\n"
else
StrToPrint = StrToPrint .. "\"" .. tostring(v) .. "\",\r\n"
end
end
StrToPrint = StrToPrint .. string.rep(" ", Indent-2) .. "}"
return StrToPrint
end
if MaxIntent == nil then
MaxIntent = 64
end
return ItretePrintTable(TableToPrint)
end
--- hotfix所有修改的文件
--- @param bNotPrintHotfixFile boolean @是否需要打印日志
function HotFix(bNotPrintHotfixFile)
_G.G6HotFix.HotFixModifyFile(bNotPrintHotfixFile)
end
ReloadAll()
print("PRINT G6ENV : ", TableToString(G6ENV) )
|
local Behavior = CreateAIBehavior("InVehicleTranquilized", "Dumb",
{
Exclusive = 1,
Constructor = function(self,entity,data)
AI.ModifySmartObjectStates(entity.id,"Busy");
entity:InsertSubpipe( AIGOALPIPE_HIGHPRIORITY, "cv_tranquilized", nil, -190 );
entity:TriggerEvent(AIEVENT_SLEEP);
AI.SetIgnorant(entity.id,1);
end,
Destructor = function(self,entity)
AI.ModifySmartObjectStates(entity.id,"-Busy");
entity:CancelSubpipe( -190 );
AI.SetIgnorant(entity.id,0);
end,
---------------------------------------------
-- being waken up from fall & play
-- FALL_AND_PLAY_WAKEUP = function(self, entity, sender, data)
-- entity:SelectPipe(0,"cv_tranquilized_wakeup");
-- end,
---------------------------------------------
OnSeenByEnemy = function( self, entity, sender )
end,
---------------------------------------------
OnQueryUseObject = function ( self, entity, sender, extraData )
end,
---------------------------------------------
OnEnemySeen = function( self, entity, fDistance )
end,
---------------------------------------------
OnTargetDead = function( self, entity )
end,
--------------------------------------------------
OnBulletHit = function( self, entity, sender,data )
end,
---------------------------------------------
OnSomethingSeen = function( self, entity )
end,
---------------------------------------------
OnThreateningSeen = function( self, entity )
end,
--------------------------------------------------
OnNoHidingPlace = function( self, entity, sender,data )
end,
---------------------------------------------
OnBackOffFailed = function(self,entity,sender)
end,
---------------------------------------------
GET_ALERTED = function( self, entity )
end,
---------------------------------------------
DRAW_GUN = function( self, entity )
end,
---------------------------------------------
OnEnemyMemory = function( self, entity )
-- called when the enemy can no longer see its foe, but remembers where it saw it last
end,
---------------------------------------------
OnInterestingSoundHeard = function( self, entity )
end,
---------------------------------------------
OnThreateningSoundHeard = function( self, entity, fDistance )
end,
--------------------------------------------------
OnCoverRequested = function ( self, entity, sender)
-- called when the enemy is damaged
end,
---------------------------------------------
OnDamage = function ( self, entity, sender)
end,
---------------------------------------------
OnEnemyDamage = function ( self, entity, sender,data)
end,
---------------------------------------------
OnReload = function( self, entity )
end,
--------------------------------------------------
OnBulletRain = function ( self, entity, sender,data)
end,
--------------------------------------------------
OnObjectSeen = function( self, entity, fDistance, signalData )
end,
---------------------------------------------
OnCloseContact = function(self,entity,sender)
end,
---------------------------------------------
OnPathFound = function(self,entity,sender)
end,
---------------------------------------------
OnNoTarget = function(self,entity,sender)
end,
--------------------------------------------------
-- CUSTOM SIGNALS
--------------------------------------------------
--------------------------------------------------
OnSomebodyDied = function( self, entity, sender)
end,
--------------------------------------------------
OnGroupMemberDiedNearest = function ( self, entity, sender,data)
end,
--------------------------------------------------
INVESTIGATE_TARGET = function (self, entity, sender)
end,
---------------------------------------------
-- GROUP SIGNALS
--------------------------------------------------
HEADS_UP_GUYS = function (self, entity, sender)
end,
---------------------------------------------
INCOMING_FIRE = function (self, entity, sender)
end,
---------------------------------------------
OnHideSpotReached = function ( self, entity, sender,data)
end,
-------------------------------------------------
})
|
require("telescope").setup {
defaults = {
mappings = {
i = {
["<C-k>"] = "move_selection_previous",
["<C-j>"] = "move_selection_next",
},
n = {
["<C-k>"] = "move_selection_previous",
["<C-j>"] = "move_selection_next",
},
},
prompt_prefix = "❯ ",
selection_caret = "› ",
},
}
|
local wezterm = require'wezterm'
local fennel = require'fennel'
--watch_path = wezterm.config_dir .. "config.fnl"
local value = wezterm.config_dir .. "/config.fnl"
--print("string" .. value)
wezterm.add_to_config_reload_watch_list(value)
fennel.path = (wezterm.config_dir .. "/?.fnl;" .. fennel.path)
--package.path = (wezterm.config_dir .. "/?.lua;" .. package.path)
table.insert(package.loaders or package.searchers, fennel.searcher)
return require('config')
|
bgNPC:SetStateAction('zombie', 'danger', {
update = function(actor)
local enemy = actor:GetNearEnemy()
if not IsValid(enemy) then return end
local npc = actor:GetNPC()
local data = actor:GetStateData()
data.delay = data.delay or 0
if enemy:IsPlayer() and enemy:InVehicle() then
enemy = enemy:GetVehicle()
end
if data.delay < CurTime() then
if npc:GetPos():DistToSqr(enemy:GetPos()) > 160000 then
actor:WalkToTarget(enemy, 'run')
end
data.delay = CurTime() + 3
end
end,
not_stop = function(actor, state, data, new_state, new_data)
return actor:EnemiesCount() > 0 and not actor:HasStateGroup(new_state, 'danger')
end
})
|
-- credit to atom0s for help with decompiling
-- Decompiled using luadec 2.2 rev: for Lua 5.1 from https://github.com/viruscamp/luadec
return {
{
CondList = {
{
API = "参与天数",
CompCount = 1,
Desc = "Play Bakugo's Challenge for 1 days.",
Id = 1,
Rewards = {
{ 1001001, 10000 },
{ 1013107, 1 },
{ 1001008, 1000 },
},
Title = "First-Timer",
},
{
API = "参与天数",
CompCount = 3,
Desc = "Play Bakugo's Challenge for 3 days.",
Id = 2,
Rewards = {
{ 1001001, 20000 },
{ 1013107, 2 },
{ 1001009, 1000 },
},
Title = "Persistent Jumper",
},
{
API = "参与天数",
CompCount = 5,
Desc = "Play Bakugo's Challenge for 5 days.",
Id = 3,
Rewards = {
{ 1001001, 30000 },
{ 1001013, 1 },
{ 1001010, 1000 },
},
Title = "Pro Jumper",
},
{
API = "累计柱子",
CompCount = 50,
Desc = "Jump over a total of 50 pillars.",
Id = 4,
Rewards = {
{ 1001001, 10000 },
{ 1025001, 1 },
{ 1001008, 1000 },
},
Title = "Rookie Jumper",
},
{
API = "累计柱子",
CompCount = 100,
Desc = "Jump over a total of 100 pillars.",
Id = 5,
Rewards = {
{ 1001001, 20000 },
{ 1025001, 2 },
{ 1001009, 1000 },
},
Title = "Adept Jumper",
},
{
API = "累计柱子",
CompCount = 200,
Desc = "Jump over a total of 200 pillars.",
Id = 6,
Rewards = {
{ 1001001, 30000 },
{ 1025001, 3 },
{ 1001010, 1000 },
},
Title = "Like a Sparrow",
},
{
API = "累计柱子",
CompCount = 300,
Desc = "Jump over a total of 300 pillars.",
Id = 7,
Rewards = {
{ 1001001, 40000 },
{ 1001013, 1 },
{ 1001008, 1000 },
},
Title = "Master Jumper",
},
},
DailyRewards = {
{ 1001002, 20 },
},
EggRewards = {
{ 1001013, 1 },
},
ID = 1,
ScoreRewards = {
{
Rewards = {
{ 1001001, 5000 },
},
Score = 50,
},
{
Rewards = {
{ 1025001, 1 },
},
Score = 100,
},
{
Rewards = {
{ 1021005, 1 },
},
Score = 200,
},
},
Sort = 36,
__maketime = 1618578319,
__md5 = "1e2fa2dbe15a2218f97c41a1a9290f0b",
__version = 2,
},
ConstInfo = {
ActIntro = "Participate in Bakugo's Jumping Challenge to earn handsome rewards.",
BounsFloorAmount = 10,
BounsScore = 20,
DayTimes = 3,
DefineRemainTime = 300,
EggRange = { 10, 20 },
FristFloorLength = 340,
GSpeed = 1200,
IsShowJudgeLine = false,
JudgeSizeOffset = -10,
LengthProgTime = 1.5,
MaxLength = 600,
MaxNextX = 600,
MaxWidth = 300,
MinLength = 100,
MinNextX = 260,
MinWidth = 100,
NormalScore = 1,
PerfectComboBouns = 1,
PerfectComboBounsLimit = 4,
PerfectRange = 20,
PerfectScore = 3,
RuleIntro = "#s24#h48Event Rules#r#s20[Gameplay Introduction]:#r#w10#c5c5c5cOnce the mini-game starts, tap the screen to make Bakugo jump.#r#w10#h40The more pillars he jumps over, the better rewards you get.#n#r[Scoring]: #c5c5c5c#r#w10Normal Jump +1pt#r#w10Perfect Jump +3pts#r#w10Perfect Jump Combo +1 Extra (Up to 4 times)#r#w10#h40Every 10 pillars jumped over +20 pts#r#s20#n[Easter Egg Rewards]:#r#c5c5c5c#w10A special pillar has a chance to appear after you jump over 10 pillars in a single game.#r#w10Jump over the special pillar to get an easter egg reward (Valid only once during each event).#r#w10#h40#r#s20#nScore Rewards:#r#w10#c5c5c5cYou can get these daily rewards by reaching the target score.",
TimeSpeedList = {
{ 11, 110 },
{ 27, 120 },
{ 50, 130 },
{ 68, 140 },
{ 107, 150 },
},
VSpeed = -600,
},
}
|
--------------------------------------------------------------------------------
-- Control panel handler
--------------------------------------------------------------------------------
local HTTP_Return = {
"HTTP/1.1 302 OK",
"Location: /\n"
}
--------------------------------------------------------------------------------
-- Control panel code
--------------------------------------------------------------------------------
local physicsMode = {
[1] = "Inertial",
[3] = "Non-inertial",
[4] = "Disabled",
}
Net.HTTPServer.Handlers["/"] = function(request)
local server_info = ""
if Net.Server.Host then
local uptime = math.floor(curtime())
server_info = server_info..
string.format("<strong>Server uptime:</strong> %d:%02d:%02d:%02d<br />",
uptime / (24*60*60),
(uptime / (60*60)) % 24,
(uptime / (60)) % 60,
(uptime) % 60)
local mjd = DedicatedServerAPI.GetMJD()
local date = os.date("%c", 86400.0 * (mjd + 2400000.5 - 2440587.5)) or "error"
server_info = server_info.."<strong>Server date:</strong> "..date.." ("..mjd..") <br />"
local delta = math.abs(DedicatedServerAPI.GetTrueMJD() - DedicatedServerAPI.GetMJD())*86400.0
server_info = server_info..
string.format("<strong>Date delta:</strong> %d:%02d:%02d:%02d.%03d<br />",
delta / (24*60*60),
(delta / (60*60)) % 24,
(delta / (60)) % 60,
(delta) % 60,
(delta * 1000) % 1000)
server_info = server_info.."<strong>Clients:</strong>"
-- if #Net.Server.Clients > 0 then
server_info = server_info.."<ul>"
for k,v in pairs(Net.Server.Clients) do
server_info = server_info.."<li>"..k.." "..tostring(v).."</li>"
end
server_info = server_info.."</ul>"
-- else
-- server_info = server_info.."<br />None<br />"
-- end
server_info = server_info..[[<strong>Vessels:</strong>
<table id="nicetable"><thead>
<tr>
<th scope="col"><strong>ID</strong></th>
<th scope="col"><strong>smA (km)</strong></th>
<th scope="col"><strong>e</strong></th>
<th scope="col"><strong>i (deg)</strong></th>
<th scope="col"><strong>MnA (deg)</strong></th>
<th scope="col"><strong>AgP (deg)</strong></th>
<th scope="col"><strong>AsN (deg)</strong></th>
<th scope="col"><strong>Period (min)</strong></th>
<th scope="col"><strong>Orbits</strong></th>
<th scope="col"><strong>Lat (deg)</strong></th>
<th scope="col"><strong>Lon (deg)</strong></th>
<th scope="col"><strong>Alt (m)</strong></th>
<th scope="col"><strong>Mass (kg)</strong></th>
<th scope="col"><strong>Physics</strong></th>
</tr>
</thead>
<tbody>]]
for idx=0,VesselAPI.GetCount()-1 do
local exists = VesselAPI.GetParameter(idx,0)
local status = ""
if exists == 0 then status = " class=\"decayed\"" end
local mass_sym = "%.0f"
if VesselAPI.GetParameter(idx,13) > 1000e3 then mass_sym = "%.3E" end
local alt_sym = "%.0f"
if VesselAPI.GetParameter(idx,16) > 120000e3 then alt_sym = "%.3E" end
if VesselAPI.GetParameter(idx,2) > 1000000 then
server_info = server_info..string.format(
"<tr"..status..">"..
"<td>%05d</td>"..
"<td>---</td>"..
"<td>---</td>"..
"<td>---</td>"..
"<td>---</td>"..
"<td>---</td>"..
"<td>---</td>"..
"<td>---</td>"..
"<td>---</td>"..
"<td>%.3f</td>"..
"<td>%.3f</td>"..
"<td>"..alt_sym.."</td>"..
"<td>"..mass_sym.."</td>"..
"<td>%s</td>"..
"</tr>",
VesselAPI.GetParameter(idx,2),
VesselAPI.GetParameter(idx,14),
VesselAPI.GetParameter(idx,15),
VesselAPI.GetParameter(idx,16),
VesselAPI.GetParameter(idx,13),
physicsMode[VesselAPI.GetParameter(idx,4)] or "Unknown")
else
server_info = server_info..string.format(
"<tr"..status..">"..
"<td>%05d</td>"..
"<td>%.1f</td>"..
"<td>%.5f</td>"..
"<td>%.3f</td>"..
"<td>%.3f</td>"..
"<td>%.3f</td>"..
"<td>%.3f</td>"..
"<td>%.2f</td>"..
"<td>%.2f</td>"..
"<td>%.3f</td>"..
"<td>%.3f</td>"..
"<td>"..alt_sym.."</td>"..
"<td>"..mass_sym.."</td>"..
"<td>%s</td>"..
"</tr>",
VesselAPI.GetParameter(idx,2),
-- VesselAPI.GetParameter(idx,50)*1e-3,
-- VesselAPI.GetParameter(idx,51)*1e-3,
-- VesselAPI.GetParameter(idx,52)*1e-3,
VesselAPI.GetParameter(idx,120)*1e-3,
VesselAPI.GetParameter(idx,121),
math.deg(VesselAPI.GetParameter(idx,122)),
math.deg(VesselAPI.GetParameter(idx,123)),
math.deg(VesselAPI.GetParameter(idx,124)),
math.deg(VesselAPI.GetParameter(idx,125)),
VesselAPI.GetParameter(idx,127)/60,
VesselAPI.GetParameter(idx,132),
VesselAPI.GetParameter(idx,14),
VesselAPI.GetParameter(idx,15),
VesselAPI.GetParameter(idx,16),
VesselAPI.GetParameter(idx,13),
physicsMode[VesselAPI.GetParameter(idx,4)] or "Unknown")
end
end
server_info = server_info.."</tbody></table>"
end
return [[
<html>
<head>
<title>VSFL Control Panel</title>
<link rel="stylesheet" type="text/css" media="screen" href="http://vsfl.wireos.com/wp-content/themes/k2/style.css" />
</head>
<body>
<div id="page">
<div class="wrapper">
<div class="primary">
<div class="post entry-content">
<h2>VSFL Control Panel</h2>
<h3>Server information</h3>
<p>]].. server_info ..[[</p>
<h3>Server software management</h3>
<p>
<form method="post" action="/reload/http">
<input type="submit" value="Reload HTTP handlers" />
</form>
<form method="post" action="/reload/network">
<input type="submit" value="Reload networking code" />
</form>
<form method="post" action="/reload/vsfl">
<input type="submit" value="Reload VSFL code" />
</form>
</p>
</div>
</div>
</div>
</div>
</body>
</html>
]]
end
--------------------------------------------------------------------------------
-- Reloads handlers
--------------------------------------------------------------------------------
Net.HTTPServer.Handlers["/reload/http"] = function(request)
Net.HTTPServer.InitializeHandlers()
return HTTP_Return
end
Net.HTTPServer.Handlers["/reload/network"] = function(request)
print("X-Space: Reloading networking code\n")
if Net.Server and Net.Server.Stop then Net.Server.Stop() end
Include(PluginsFolder.."lua/network.lua")
InternalCallbacks.OnDedicatedServer()
return HTTP_Return
end
Net.HTTPServer.Handlers["/reload/vsfl"] = function(request)
print("X-Space: Reloading VSFL related code\n")
Include(PluginsFolder.."lua/vsfl.lua")
return HTTP_Return
end
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local datetime = require "util.datetime";
local jid_split = require "util.jid".split;
local offline_messages = module:open_store("offline", "archive");
module:add_feature("msgoffline");
module:hook("message/offline/handle", function(event)
local origin, stanza = event.origin, event.stanza;
local to = stanza.attr.to;
local node;
if to then
node = jid_split(to)
else
node = origin.username;
end
return offline_messages:append(node, nil, stanza, os.time(), "");
end, -1);
module:hook("message/offline/broadcast", function(event)
local origin = event.origin;
local node, host = origin.username, origin.host;
local data = offline_messages:find(node);
if not data then return true; end
for _, stanza, when in data do
stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = host, stamp = datetime.datetime(when)}):up(); -- XEP-0203
origin.send(stanza);
end
offline_messages:delete(node);
return true;
end, -1);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.