content stringlengths 5 1.05M |
|---|
mq = require('mq')
require 'ImGui'
local FailSafe = function()
--mq.delay(1)
end
local openGUI = true
local shouldDrawGUI = true
local dotGUI = function()
openGUI, shouldDrawGUI = ImGui.Begin('DoTs', openGUI)
local checkDebuff = function (buffName)
if (mq.TLO.Target.Buff(buffName).ID()) then
local buffTimer = mq.TLO.Target.Buff(buffName).Duration.TotalSeconds()
local buffCaster = mq.TLO.Target.Buff(buffName).Caster()
ImGui.Text(buffName..' - '..buffCaster..' - '..buffTimer)
end
end
local checkSpecDebuff = function (className, buffName, altName)
if (mq.TLO.Me.Class.ShortName() == className) then
if (mq.TLO.Target.Buff(buffName).ID()) then
local buffTimer = mq.TLO.Target.Buff(buffName).Duration.TotalSeconds()
local buffCaster = mq.TLO.Target.Buff(buffName).Caster()
ImGui.Text(altName..' - '..buffCaster..' - '..buffTimer)
end
end
end
local debuffsTakenUp = 0
if shouldDrawGUI then
if (mq.TLO.Target.ID()) then
checkDebuff('Funeral Dirge')
checkDebuff('T`Vyl\'s Resolve')
checkDebuff('Mana Burn')
checkSpecDebuff('SHD', 'Bloodletting Coalition', 'Coalition')
checkSpecDebuff('BRD', 'Coalition of Sticks and Stones', 'Coalition')
checkSpecDebuff('ROG', 'Pinpoint Shortcomings', 'Pinpoint Defects')
if (mq.TLO.Target.Slowed.ID()) then ImGui.Text('Slowed! '..mq.TLO.Target.Slowed()) end
local freeBuffs = 94 - mq.TLO.Target.BuffCount()
if (mq.TLO.Target.Type() == 'NPC') then ImGui.Text('Buffs Free '..freeBuffs) end
end
ImGui.End()
end
end
local targetGUI = function()
openGUI, shouldDrawGUI = ImGui.Begin('Target', openGUI)
if shouldDrawGUI then
local pctHPs = mq.TLO.Target.PctHPs()
if not pctHPs then pctHPs = 0 end
local ratioHPs = pctHPs / 100
local pctAggro = mq.TLO.Target.PctAggro()
if not pctAggro then pctAggro = 0 end
local tLevel = mq.TLO.Target.Level()
if not tLevel then tLevel = 0 end
local tType = mq.TLO.Target.Type()
if not tType then tType = 'none' end
local myName = mq.TLO.Target.CleanName()
if not myName then myName = 'None' end
if (mq.TLO.Target.Type() == 'NPC') then
ImGui.PushStyleColor(ImGuiCol.PlotHistogram, ratioHPs, 0, 1 - ratioHPs, 1)
ImGui.PushStyleColor(ImGuiCol.Text, 1, 1, 1, 1)
else
ImGui.PushStyleColor(ImGuiCol.PlotHistogram, 1- ratioHPs, ratioHPs, 0.6, 1)
ImGui.PushStyleColor(ImGuiCol.Text, 0.4, 0.4, 0.4, 1)
end
ImGui.ProgressBar(ratioHPs, -1, -1, tLevel..' '..myName..': '..pctHPs..'%'..'Aggro: '..pctAggro..'%')
ImGui.PopStyleColor(2)
ImGui.End()
end
end
local hpGUI = function()
WindowFlags = ImGuiWindowFlags.NoTitleBar
openGUI, shouldDrawGUI = ImGui.Begin('HP', openGUI, WindowFlags)
if shouldDrawGUI then
local pctHPs = mq.TLO.Me.PctHPs()
if not pctHPs then pctHPs = 0 end
local ratioHPs = pctHPs / 100
local attacking = ' '
local myName = mq.TLO.Me.CleanName()
if (mq.TLO.Me.AmIGroupLeader()) then myName = '*L*'..myName end
if (mq.TLO.Group.GroupSize()) then
if (mq.TLO.Group.MainAssist() == mq.TLO.Me()) then myName = '*MA*'..myName end
if (mq.TLO.Group.MainTank() == mq.TLO.Me()) then myName = '*MT*'..myName end
if (mq.TLO.Group.MasterLooter() == mq.TLO.Me()) then myName = '*ML*'..myName end
end
ImGui.PushStyleColor(ImGuiCol.PlotHistogram, 1- ratioHPs, ratioHPs, 0.6, 1)
ImGui.PushStyleColor(ImGuiCol.Text, 0.4, 0.4, 0.4, 1)
if mq.TLO.Me.Combat() then
attacking = ' (A)'
else
attacking = ' '
end
ImGui.ProgressBar(ratioHPs, -1, -0, myName..': '..pctHPs..'%'..attacking)
ImGui.PopStyleColor(2)
if (ImGui.IsItemClicked()) then
mq.TLO.Me.DoTarget()
end
DiscTimer()
local myClass = mq.TLO.Me.Class.ShortName()
if (myClass == 'SHD' or myClass == 'PAL' or myClass == 'WAR') then
CheckTankBuffs(myClass)
end
CheckClassBuffs()
-- General
CheckBuff('Kromrif Focusing')
CheckSpecBuffYes(mq.TLO.Me.Class.ShortName(), 'Glyph of Destruction', 'Destruction Glyph')
ImGui.Text('Buffs Free: '..mq.TLO.Me.FreeBuffSlots())
ImGui.End()
end
end
function CheckTankBuffs(myClass)
if (myClass == 'SHD') then
CheckSpecBuff('SHD', 'Shining Aegis', 'Shining Aegis')
CheckSpecSongYes('SHD', 'Lich Sting', 'SK Epic')
CheckSpecSongYes('SHD', 'Group Armor of the Inquisitor', 'Group Armor')
CheckSpecBuffYes('SHD', 'Glyph of Dragon Scales', 'Dragon Glyph')
end
if (myClass == 'PAL') then
CheckSpecBuff('PAL', 'Shining Aegis', 'Shining Aegis')
CheckSpecSongYes('PAL', 'Lich Sting', 'SK Epic')
CheckSpecBuffYes('PAL', 'Glyph of Dragon Scales', 'Dragon Glyph')
CheckSpecSongYes('PAL', 'Group Armor of the Inquisitor', 'Group Armor')
end
if (myClass == 'WAR') then
CheckSpecSongYes('WAR', 'Group Armor of the Inquisitor', 'Group Armor')
CheckSpecSongYes('WAR', 'Lich Sting', 'SK Epic')
CheckSpecBuff('WAR', 'Shining Aegis', 'Shining Aegis')
CheckSpecBuffYes('WAR', 'Glyph of Dragon Scales', 'Dragon Glyph')
end
end
function CheckClassBuffs()
-- SK Buffs
CheckSpecBuff('SHD', 'Cadcane\'s Skin', 'Cadcane\'s Skin')
CheckSpecBuff('SHD', 'Stormwall Stance', 'Stormwall Stance')
CheckSpecBuff('SHD', 'Confluent Disruption', 'Confluent Disruption')
CheckSpecBuff('SHD', 'Shroud of the Restless', 'SK Unity')
-- PAL Buffs
CheckSpecBuff('PAL', 'Stormwall Stance', 'Stormwall Stance')
-- BRD Buffs
CheckSpecBuff('BRD', 'Symphony of Battle', 'Symphony of Battle')
CheckSpecSongYes('BRD', 'Ruaabri\'s Fury', 'Ruaabris Fury')
CheckSpecSongYes('BRD', 'Dichotomic Fury', 'BST Dicho')
CheckSpecSongYes('BRD', 'Dissident Fury', 'BST Dicho')
CheckSpecSongYes('BRD', 'Composite Fury', 'BST Dicho')
CheckSpecSongYes('BRD', 'Quick Time', 'QT')
CheckSpecSongYes('BRD', 'Prophet\'s Gift of the Ruchu', 'Shaman Epic')
end
local groupGUI = function()
local WindowFlags = ImGuiWindowFlags.NoBackground
--if (not mq.TLO.Group.GroupSize()) then WindowFlags = ImGuiWindowFlags.NoBackground end
openGUI, shouldDrawGUI = ImGui.Begin('Group', openGUI, WindowFlags)
if shouldDrawGUI then
local groupSize = mq.TLO.Group.GroupSize()
if not groupSize then groupSize = 0 end
if (groupSize > 0) then
for i=1,groupSize
do
local memName = mq.TLO.Group.Member(i).Name()
PushGroupHP(i)
end
end
ImGui.End()
end
end
local manaGUI = function()
local WindowFlags = ImGuiWindowFlags.NoBackground + ImGuiWindowFlags.NoTitleBar
openGUI, shouldDrawGUI = ImGui.Begin('MP', openGUI, WindowFlags)
if shouldDrawGUI then
local pctMPs = mq.TLO.Me.PctMana()
if not pctMPs then pctMPs = 0 end
local ratioMPs = pctMPs / 100
local myName = mq.TLO.Me.CleanName()
ImGui.PushStyleColor(ImGuiCol.PlotHistogram, 1 - ratioMPs, ratioMPs, 1, 1)
ImGui.PushStyleColor(ImGuiCol.Text, 0.5, 0.5, 0.5, 1)
ImGui.ProgressBar(ratioMPs, -1, -1, pctMPs..'%')
ImGui.PopStyleColor(2)
ImGui.End()
end
end
local endGUI = function()
local WindowFlags = ImGuiWindowFlags.NoBackground + ImGuiWindowFlags.NoTitleBar
openGUI, shouldDrawGUI = ImGui.Begin('Endurance', openGUI, WindowFlags)
if shouldDrawGUI then
local pctHPs = mq.TLO.Me.PctHPs()
if not pctHPs then pctHPs = 0 end
local pctMPs = mq.TLO.Me.PctMana()
if not pctMPs then pctMPs = 0 end
local pctEnd = mq.TLO.Me.PctEndurance()
if not pctEnd then pctEnd = 0 end
local ratioHPs = pctHPs / 100
local ratioMPs = pctMPs / 100
local ratioEnd = pctEnd / 100
local myName = mq.TLO.Me.CleanName()
ImGui.PushStyleColor(ImGuiCol.PlotHistogram, ratioEnd, 1, 0.4, 1)
ImGui.PushStyleColor(ImGuiCol.Text, 0.5, 0.5, 0.5, 1)
ImGui.ProgressBar(ratioEnd, -1, -1, pctEnd..'%')
ImGui.PopStyleColor(2)
ImGui.End()
end
end
function PushGroupHP(groupNum)
local gMemName = mq.TLO.Group.Member(groupNum).Name()
local pctHPs = mq.TLO.Group.Member(groupNum).Spawn.PctHPs()
local pctMPs = mq.TLO.Group.Member(groupNum).Spawn.PctMana()
local pctEnd = mq.TLO.Group.Member(groupNum).Spawn.PctEndurance()
if not pctHPs then pctHPs = 0 end
if not pctMPs then pctMPs = 0 end
if not pctEnd then pctEnd = 0 end
if (mq.TLO.Group.Member(groupNum).Present()) then
local ratioHPs = pctHPs / 100
local ratioMPs = pctMPs / 100
local ratioEnd = pctEnd / 100
ImGui.Columns(3)
PushHP(ratioHPs, pctHPs, gMemName)
GroupContextMenu(gMemName)
ImGui.NextColumn()
PushMP(ratioMPs, pctMPs, gMemName)
ImGui.NextColumn()
PushEnd(ratioEnd, pctEnd, gMemName)
ImGui.Columns(1)
else
if not gMemName then return end
PushHP(0, gMemName, 'Not In Zone')
GroupContextMenu(gMemName)
end
end
function GroupContextMenu(gMemName)
if ImGui.BeginPopupContextItem() then
if ImGui.BeginMenu('Set Leader') then
if ImGui.MenuItem(gMemName) then
mq.cmd.docommand('/makeleader '..gMemName)
end
ImGui.EndMenu()
end
if ImGui.BeginMenu('Set Assist') then
if ImGui.MenuItem(gMemName) then
mq.cmd.docommand('/group set '..gMemName..' 2')
end
ImGui.EndMenu()
end
if ImGui.BeginMenu('Set Tank') then
if ImGui.MenuItem(gMemName) then
mq.cmd.docommand('/group set '..gMemName..' 1')
end
ImGui.EndMenu()
end
if ImGui.BeginMenu('Set Puller') then
if ImGui.MenuItem(gMemName) then
mq.cmd.docommand('/group set '..gMemName..' 3')
end
ImGui.EndMenu()
end
if ImGui.BeginMenu('Set Mark NPC') then
if ImGui.MenuItem(gMemName) then
mq.cmd.docommand('/group set '..gMemName..' 4')
end
ImGui.EndMenu()
end
if ImGui.BeginMenu('Set Master Looter') then
if ImGui.MenuItem(gMemName) then
mq.cmd.docommand('/group set '..gMemName..' 5')
end
ImGui.EndMenu()
end
ImGui.EndPopup()
end
end
function PushHP(ratioHPs, pctHPs, gMemName)
local gDisplayName = gMemName
--if (mq.TLO.Group.MainAssist() == gMemName) then gDisplayName = '*MA*'..gDisplayName end
--if (mq.TLO.Group.MainTank() == gMemName) then gDisplayName = '*MT*'..gDisplayName end
--if (mq.TLO.Group.MasterLooter() == gMemName) then gDisplayName = '*ML*'..gDisplayName end
ImGui.PushStyleColor(ImGuiCol.PlotHistogram, 1- ratioHPs, ratioHPs, 0.6, 1)
ImGui.PushStyleColor(ImGuiCol.Text, 0.4, 0.4, 0.4, 1)
ImGui.ProgressBar(ratioHPs, -1, -0, gDisplayName..': '..pctHPs..'%')
ImGui.PopStyleColor(2)
if (ImGui.IsItemClicked()) then
mq.TLO.Group.Member(gMemName).Spawn.DoTarget()
end
end
function PushMP(ratioMPs, pctMPs, gMemName)
ImGui.PushStyleColor(ImGuiCol.PlotHistogram, 1 - ratioMPs, ratioMPs, 1, 1)
ImGui.PushStyleColor(ImGuiCol.Text, 0.5, 0.5, 0.5, 1)
ImGui.ProgressBar(ratioMPs, -0.5, -0, pctMPs..'%')
ImGui.PopStyleColor(2)
if (ImGui.IsItemClicked()) then
mq.TLO.Group.Member(gMemName).Spawn.DoTarget()
end
end
function PushEnd(ratioEnd, pctEnd, gMemName)
ImGui.PushStyleColor(ImGuiCol.PlotHistogram, ratioEnd, 1, 0.4, 1)
ImGui.PushStyleColor(ImGuiCol.Text, 0.5, 0.5, 0.5, 1)
ImGui.ProgressBar(ratioEnd, -1, 0, pctEnd..'%')
ImGui.PopStyleColor(2)
if (ImGui.IsItemClicked()) then
mq.TLO.Group.Member(gMemName).Spawn.DoTarget()
end
end
function DiscTimer()
if (mq.TLO.Me.ActiveDisc.ID()) then
local discName = mq.TLO.Me.ActiveDisc.Name()
ImGui.ProgressBar(1, -1, 15, discName)
if (ImGui.IsItemClicked()) then
mq.cmd.stopdisc()
end
end
end
function CheckBuff(buffName)
if (not mq.TLO.Me.Buff(buffName).ID()) then
ImGui.Text('Need - '..buffName)
end
end
CheckSpecBuff = function (className, buffName, buffText)
if (mq.TLO.Me.Class.ShortName() == className) then
if (not mq.TLO.Me.Buff(buffName).ID()) then
ImGui.Text('Need - '..buffText)
end
end
end
CheckSpecBuffYes = function (className, buffName, buffText)
if (mq.TLO.Me.Class.ShortName() == className) then
if (mq.TLO.Me.Buff(buffName).ID()) then
ImGui.Text('Have - '..buffText)
end
end
end
CheckSpecSongYes = function (className, buffName, buffText)
if (mq.TLO.Me.Class.ShortName() == className) then
if (mq.TLO.Me.Song(buffName).ID()) then
ImGui.Text('Have - '..buffText)
end
end
end
local startGUI = function ()
if ImGui.TreeNode("Checkboxes") then
local changed1, newVal1 = ImGui.Checkbox("Debuffs GUI", startDebuffs)
if changed1 then startDebuffs = newVal1 end
local changed2, newVal2 = ImGui.Checkbox("Target GUI", startTarget)
if changed2 then startTarget = newVal2 end
local changed3, newVal3 = ImGui.Checkbox("HP GUI", startHP)
if changed3 then startHP = newVal3 end
local changed4, newVal4 = ImGui.Checkbox("Group GUI", startGroup)
if changed4 then startGroup = newVal4 end
local changed5, newVal5 = ImGui.Checkbox("Mana GUI", startMana)
if changed5 then startMana = newVal5 end
local changed6, newVal6 = ImGui.Checkbox("Endurance GUI", startEnd)
if changed6 then startEnd = newVal6 end
end
end
mq.imgui.init('dotGUI', dotGUI)
mq.imgui.init('targetGUI', targetGUI)
mq.imgui.init('hpGUI', hpGUI)
mq.imgui.init('groupGUI', groupGUI)
mq.imgui.init('manaGUI', manaGUI)
mq.imgui.init('endGUI', endGUI)
--mq.imgui.init('startGUI', startGUI)
local terminate = false
while not terminate do
FailSafe()
mq.delay(100) -- equivalent to '1s'
end |
--- LÖVE file release.
-- @module scripts.love
-- @usage love(project)
local Script = require "love-release.script"
local s = {}
function s.script(project)
local script = Script:new(project)
script:createLoveFile()
end
setmetatable(s, { __call = function(_, project) return s.script(project) end })
return s
|
--- midi devices
-- @module midi
-- @alias Midi
require 'norns'
local Midi = {}
Midi.devices = {}
Midi.list = {}
Midi.vport = {}
for i=1,4 do
Midi.vport[i] = {
name = "none",
callbacks = {},
index = 0,
send = function() end,
attached = false
}
end
Midi.__index = Midi
--- constructor
-- @tparam integer id : arbitrary numeric identifier
-- @tparam string name : name
-- @tparam userdata dev : opaque pointer to device
function Midi.new(id, name, dev)
local d = setmetatable({}, Midi)
d.id = id
-- append duplicate device names
--while tab.contains(Midi.list,name) do
--name = name .. "+"
--end
d.name = name
d.dev = dev -- opaque pointer
d.event = nil -- event callback
d.remove = nil -- device unplug callback
d.ports = {} -- list of virtual ports this device is attached to
-- autofill next postiion
local connected = {}
for i=1,4 do table.insert(connected, Midi.vport[i].name) end
if not tab.contains(connected, name) then
for i=1,4 do
if Midi.vport[i].name == "none" then
Midi.vport[i].name = name
break
end
end
end
return d
end
--- static callback when any midi device is added;
-- user scripts can redefine
-- @param dev : a Midi table
function Midi.add(dev) end
--- static callback when any midi device is removed;
-- user scripts can redefine
-- @param dev : a Midi table
function Midi.remove(dev) end
--- call add() for currently available devices
-- when scripts are restarted
function Midi.reconnect()
for id,dev in pairs(Midi.devices) do
if Midi.add ~= nil then Midi.add(dev) end
end
end
--- send midi event to device
-- @param array
function Midi:send(data)
if data.type then
--print("msg")
local d = Midi.to_data(data)
if d then midi_send(self.dev, d) end
else
--print("data")
midi_send(self.dev, data)
end
end
--- create device, returns object with handler and send
function Midi.connect(n)
local n = n or 1
if n>4 then n=4 end
Midi.vport[n].index = Midi.vport[n].index + 1
local d = {
index = Midi.vport[n].index,
port = n,
event = function(data)
print("midi input")
end,
attached = function() return Midi.vport[n].attached end,
send = function(data) Midi.vport[n].send(data) end,
disconnect = function(self)
self.send = function() print("not connected") end
Midi.vport[self.port].callbacks[self.index] = nil
self.index = nil
self.port = nil
end,
reconnect = function(self, p)
p = p or 1
if self.index then
Midi.vport[self.port].callbacks[self.index] = nil
end
self.send = function(data) Midi.vport[p].send(data) end
self.attached = function() return Midi.vport[p].attached end
Midi.vport[p].index = Midi.vport[p].index + 1
self.index = Midi.vport[p].index
self.port = p
Midi.vport[p].callbacks[self.index] = function(data) self.event(data) end
end
}
Midi.vport[n].callbacks[d.index] = function(data) d.event(data) end
-- midi send helper functions
d.note_on = function(note, vel, ch)
d.send{type="note_on", note=note, vel=vel, ch=ch or 1}
end
d.note_off = function(note, vel, ch)
d.send{type="note_off", note=note, vel=vel or 100, ch=ch or 1}
end
d.cc = function(cc, val, ch)
d.send{type="cc", cc=cc, val=val, ch=ch or 1}
end
d.pitchbend = function(val, ch)
d.send{type="pitchbend", val=val, ch=ch or 1}
end
d.key_pressure = function(note, val, ch)
d.send{type="key_pressure", note=note, val=val, ch=ch or 1}
end
d.channel_pressure = function(val, ch)
d.send{type="channel_pressure", val=val, ch=ch or 1}
end
d.start = function()
d.send{type="start"}
end
d.stop = function()
d.send{type="stop"}
end
d.continue = function()
d.send{type="continue"}
--d.send{0xfb}
end
d.clock = function()
d.send{type="clock"}
end
d.song_position = function(lsb, msb)
d.send{type="song_position", lsb=lsb, msb=msb}
end
d.song_select = function(val)
d.send{type="song_select", val=val}
end
return d
end
--- clear handlers
function Midi.cleanup()
for i=1,4 do
Midi.vport[i].callbacks = {}
Midi.vport[i].index = 0
end
end
-- utility
-- function table for msg-to-data conversion
local to_data = {
-- FIXME: should all subfields have default values (ie note/vel?)
note_on = function(msg)
return {0x90 + (msg.ch or 1) - 1, msg.note, msg.vel or 100}
end,
note_off = function(msg)
return {0x80 + (msg.ch or 1) - 1, msg.note, msg.vel or 100}
end,
cc = function(msg)
return {0xb0 + (msg.ch or 1) - 1, msg.cc, msg.val}
end,
pitchbend = function(msg)
return {0xe0 + (msg.ch or 1) - 1, msg.val & 0x7f, (msg.val >> 7) & 0x7f}
end,
key_pressure = function(msg)
return {0xa0 + (msg.ch or 1) - 1, msg.note, msg.val}
end,
channel_pressure = function(msg)
return {0xd0 + (msg.ch or 1) - 1, msg.val}
end,
start = function(msg)
return {0xfa}
end,
stop = function(msg)
return {0xfc}
end,
continue = function(msg)
return {0xfb}
end,
clock = function(msg)
return {0xf8}
end,
song_position = function(msg)
return {0xf2, msg.lsb, msg.msb}
end,
song_select = function(msg)
return {0xf3, msg.val}
end
}
--- convert msg to data (midi bytes)
function Midi.to_data(msg)
if msg.type then
return to_data[msg.type](msg)
else return nil end
end
--- convert data (midi bytes) to msg
function Midi.to_msg(data)
local msg = {}
-- note on
if data[1] & 0xf0 == 0x90 then
msg = {
note = data[2],
vel = data[3],
ch = data[1] - 0x90 + 1
}
if data[3] > 0 then
msg.type = "note_on"
elseif data[3] == 0 then -- if velocity is zero then send note off
msg.type = "note_off"
end
-- note off
elseif data[1] & 0xf0 == 0x80 then
msg = {
type = "note_off",
note = data[2],
vel = data[3],
ch = data[1] - 0x80 + 1
}
-- cc
elseif data[1] & 0xf0 == 0xb0 then
msg = {
type = "cc",
cc = data[2],
val = data[3],
ch = data[1] - 0xb0 + 1
}
-- pitchbend
elseif data[1] & 0xf0 == 0xe0 then
msg = {
type = "pitchbend",
val = data[2] + (data[3] << 7),
ch = data[1] - 0xe0 + 1
}
-- key pressure
elseif data[1] & 0xf0 == 0xa0 then
msg = {
type = "key_pressure",
note = data[2],
val = data[3],
ch = data[1] - 0xa0 + 1
}
-- channel pressure
elseif data[1] & 0xf0 == 0xd0 then
msg = {
type = "channel_pressure",
val = data[2],
ch = data[1] - 0xd0 + 1
}
-- start
elseif data[1] == 0xfa then
msg.type = "start"
-- stop
elseif data[1] == 0xfc then
msg.type = "stop"
-- continue
elseif data[1] == 0xfb then
msg.type = "continue"
-- clock
elseif data[1] == 0xf8 then
msg.type = "clock"
-- song position pointer
elseif data[1] == 0xf2 then
msg = {
type = "song_position",
lsb = data[2],
msb = data[3]
}
-- song select
elseif data[1] == 0xf3 then
msg = {
type = "song_select",
val = data[2]
}
-- active sensing (should probably ignore)
elseif data[1] == 0xfe then
-- do nothing
-- everything else
else
msg = {
type = "other",
}
end
return msg
end
function Midi.update_devices()
-- build list of available devices
Midi.list = {}
for _,device in pairs(Midi.devices) do
table.insert(Midi.list, device.name)
device.ports = {}
end
-- connect available devices to vports
for i=1,4 do
Midi.vport[i].attached = false
Midi.vport[i].send = function(data) end
for _,device in pairs(Midi.devices) do
if device.name == Midi.vport[i].name then
Midi.vport[i].send = function(data) device:send(data) end
Midi.vport[i].attached = true
table.insert(device.ports, i)
end
end
end
end
--- norns functions
--- add a device
norns.midi.add = function(id, name, dev)
print("midi added:", name)
local d = Midi.new(id, name, dev)
Midi.devices[id] = d
Midi.update_devices()
if Midi.add ~= nil then Midi.add(d) end
end
--- remove a device
norns.midi.remove = function(id)
if Midi.devices[id] then
print("midi removed:", Midi.devices[id].name)
if Midi.devices[id].remove then
Midi.devices[id].remove()
end
end
Midi.devices[id] = nil
Midi.update_devices()
end
--- handle a midi event
norns.midi.event = function(id, data)
-- iterate through port table
local d = Midi.devices[id]
if d ~= nil then
if d.event ~= nil then
d.event(data)
end
for _,n in pairs(d.ports) do
for _,event in pairs(Midi.vport[n].callbacks) do
--print("vport " .. n)
event(data)
end
end
end
-- hack = send all midi to menu for param-cc-map
norns.menu_midi_event(data)
end
return Midi
]]-- |
local vector_meta = global_metatable("vector")
local quat_meta = global_metatable("quaternion")
function IsVector(v)
return type(v) == "table" and type(v[1]) == "number" and type(v[2]) == "number" and type(v[3]) == "number" and not v[4]
end
function MakeVector(v)
return setmetatable(v, vector_meta)
end
function Vector(x, y, z)
if IsVector(x) then x, y, z = x[1], x[2], x[3] end
return MakeVector {x or 0, y or 0, z or 0}
end
function vector_meta:__unserialize(data)
local x, y, z = data:match("([-0-9.]*);([-0-9.]*);([-0-9.]*)")
self[1] = tonumber(x)
self[2] = tonumber(y)
self[3] = tonumber(z)
return self
end
function vector_meta:__serialize()
return table.concat(self, ";")
end
VEC_ZERO = Vector()
VEC_FORWARD = Vector(0, 0, 1)
VEC_UP = Vector(0, 1, 0)
VEC_LEFT = Vector(1, 0, 0)
function vector_meta:Clone()
return MakeVector {self[1], self[2], self[3]}
end
local VecStr = VecStr
function vector_meta:__tostring()
return VecStr(self)
end
function vector_meta:__unm()
return MakeVector {-self[1], -self[2], -self[3]}
end
function vector_meta:Add(o)
if IsVector(o) then
self[1] = self[1] + o[1]
self[2] = self[2] + o[2]
self[3] = self[3] + o[3]
else
self[1] = self[1] + o
self[2] = self[2] + o
self[3] = self[3] + o
end
return self
end
function vector_meta.__add(a, b)
if not IsVector(a) then a, b = b, a end
if IsTransformation(b) then
return Transformation(vector_meta.Add(vector_meta.Clone(a), b.pos), quat_meta.Clone(b.rot))
end
return vector_meta.Add(vector_meta.Clone(a), b)
end
function vector_meta:Sub(o)
if IsVector(o) then
self[1] = self[1] - o[1]
self[2] = self[2] - o[2]
self[3] = self[3] - o[3]
else
self[1] = self[1] - o
self[2] = self[2] - o
self[3] = self[3] - o
end
return self
end
function vector_meta.__sub(a, b)
if not IsVector(a) then a, b = b, a end
return vector_meta.Sub(vector_meta.Clone(a), b)
end
function vector_meta:Mul(o)
if IsVector(o) then
self[1] = self[1] * o[1]
self[2] = self[2] * o[2]
self[3] = self[3] * o[3]
elseif IsQuaternion(o) then
-- v2 = v + 2 * r X (s * v + r X v) / quat_meta.LengthSquare(self)
--local s, r = o[4], Vector(o[1], o[2], o[3])
--self:Add(2 * s * r:Cross(self) + 2 * r:Cross(r:Cross(self)))
local x1, y1, z1 = self[1], self[2], self[3]
local x2, y2, z2, s = o[1], o[2], o[3], o[4]
local x3 = y2*z1 - z2*y1
local y3 = z2*x1 - x2*z1
local z3 = x2*y1 - y2*x1
self[1] = x1 + (x3 * s + y2*z3 - z2*y3) * 2
self[2] = y1 + (y3 * s + z2*x3 - x2*z3) * 2
self[3] = z1 + (z3 * s + x2*y3 - y2*x3) * 2
else
self[1] = self[1] * o
self[2] = self[2] * o
self[3] = self[3] * o
end
return self
end
function vector_meta.__mul(a, b)
if not IsVector(a) then a, b = b, a end
return vector_meta.Mul(vector_meta.Clone(a), b)
end
function vector_meta:Div(o)
self[1] = self[1] / o
self[2] = self[2] / o
self[3] = self[3] / o
return self
end
function vector_meta.__div(a, b)
return vector_meta.Div(vector_meta.Clone(a), b)
end
function vector_meta:Mod(o)
self[1] = self[1] % o
self[2] = self[2] % o
self[3] = self[3] % o
return self
end
function vector_meta.__mod(a, b)
return vector_meta.Mod(vector_meta.Clone(a), b)
end
function vector_meta:Pow(o)
self[1] = self[1] ^ o
self[2] = self[2] ^ o
self[3] = self[3] ^ o
return self
end
function vector_meta.__pow(a, b)
return vector_meta.Pow(vector_meta.Clone(a), b)
end
function vector_meta.__eq(a, b)
return a[1] == b[1] and a[2] == b[2] and a[3] == b[3]
end
function vector_meta.__lt(a, b)
return a[1] < b[1] or (a[1] == b[1] and (
a[2] < b[2] or (a[2] == b[2] and (
a[3] < b[3] ))))
end
function vector_meta.__le(a, b)
return a[1] < b[1] or (a[1] == b[1] and (
a[2] < b[2] or (a[2] == b[2] and (
a[3] <= b[3] ))))
end
local VecDot = VecDot
function vector_meta:Dot(b)
return MakeVector(VecDot(self, b))
end
local VecCross = VecCross
function vector_meta:Cross(b)
return MakeVector(VecCross(self, b))
end
local VecLength = VecLength
function vector_meta:Length()
return VecLength(self)
end
function vector_meta:Volume()
return math.abs(self[1] * self[2] * self[3])
end
local VecLerp = VecLerp
function vector_meta:Lerp(o, n)
return MakeVector(VecLerp(self, o, n))
end
local VecNormalize = VecNormalize
function vector_meta:Normalized()
return MakeVector(VecNormalize(self))
end
function vector_meta:Normalize()
return vector_meta.Div(self, vector_meta.Length(self))
end
function vector_meta:DistSquare(o)
return (self[1] - o[1]) ^ 2
+ (self[2] - o[2]) ^ 2
+ (self[3] - o[3]) ^ 2
end
function vector_meta:Distance(o)
return math.sqrt(vector_meta.DistSquare(self, o))
end
function vector_meta:LookAt(o)
return MakeQuaternion(QuatLookAt(self, o))
end |
TOOL.Category = "Stools"
TOOL.Name = "#Set NPC RagMorph"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "RagMorph"
TOOL.ClientConVar = {
Pelvis = "1",
Chest = "1",
RightUpperArm = "1",
LeftUpperArm = "1",
LeftForearm = "1",
LeftHand = "1",
RightForearm = "1",
RightHand = "1",
RightThigh = "1",
RightCalf = "1",
Head = "1",
LeftThigh = "1",
LeftCalf = "1",
LeftFoot = "1",
RightFoot = "1",
}
if CLIENT then
language.Add( "Tool_setnpcragmorph_Pelvis", "Pelvis" )
language.Add( "Tool_setnpcragmorph_Chest", "Chest" )
language.Add( "Tool_setnpcragmorph_RightUpperArm", "RightUpperArm" )
language.Add( "Tool_setnpcragmorph_LeftUpperArm", "LeftUpperArm" )
language.Add( "Tool_setnpcragmorph_LeftForearm", "LeftForearm" )
language.Add( "Tool_setnpcragmorph_LeftHand", "LeftHand" )
language.Add( "Tool_setnpcragmorph_RightForearm", "RightForearm" )
language.Add( "Tool_setnpcragmorph_RightHand", "RightHand" )
language.Add( "Tool_setnpcragmorph_RightThigh", "RightThigh" )
language.Add( "Tool_setnpcragmorph_RightCalf", "RightCalf" )
language.Add( "Tool_setnpcragmorph_Head", "Head" )
language.Add( "Tool_setnpcragmorph_LeftThigh", "LeftThigh" )
language.Add( "Tool_setnpcragmorph_LeftCalf", "LeftCalf" )
language.Add( "Tool_setnpcragmorph_LeftFoot", "LeftFoot" )
language.Add( "Tool_setnpcragmorph_RightFoot", "RightFoot" )
language.Add( "Tool.setnpcragmorph.name", "Set NPC RagMorph" )
language.Add( "Tool.setnpcragmorph.desc", "Choose a ragdoll you want to use" )
language.Add( "Tool.setnpcragmorph.0", "Primary fire: Select \n Secondary fire: Select default rag morph model \nReload: Override" )
end
function TOOL:LeftClick( trace )
if ( trace.Entity and trace.Entity:IsPlayer() ) then return false end
if not string.find( trace.Entity:GetClass( ), "npc_*" ) then return false end
if (CLIENT) then return true end
if trace.Entity:IsValid() then
local ent = trace.Entity
local tableSettigns = {}
tableSettigns[1] = (tostring(self:GetClientNumber( "Pelvis" ))..".00")
tableSettigns[2] = (tostring(self:GetClientNumber( "Chest" ))..".00")
tableSettigns[3] = (tostring(self:GetClientNumber( "RightUpperArm" ))..".00")
tableSettigns[4] = (tostring(self:GetClientNumber( "LeftUpperArm" ))..".00")
tableSettigns[5] = (tostring(self:GetClientNumber( "LeftForearm" ))..".00")
tableSettigns[6] = (tostring(self:GetClientNumber( "LeftHand" ))..".00")
tableSettigns[7] = (tostring(self:GetClientNumber( "RightForearm" ))..".00")
tableSettigns[8] = (tostring(self:GetClientNumber( "RightHand" ))..".00")
tableSettigns[9] = (tostring(self:GetClientNumber( "RightThigh" ))..".00")
tableSettigns[10] = (tostring(self:GetClientNumber( "RightCalf" ))..".00")
tableSettigns[11] = (tostring(self:GetClientNumber( "Head" ))..".00")
tableSettigns[12] = (tostring(self:GetClientNumber( "LeftThigh" ))..".00")
tableSettigns[13] = (tostring(self:GetClientNumber( "LeftCalf" ))..".00")
tableSettigns[14] = (tostring(self:GetClientNumber( "LeftFoot" ))..".00")
tableSettigns[15] = (tostring(self:GetClientNumber( "RightFoot" ))..".00")
ent.WobbleManBones = tableSettigns
-- If it doesn't have a ragdoll we will create one for it.
if not ent.WobbleManTagDoll or ent.WobbleManTagDoll == NULL then
local rag = ents.Create( "prop_ragdoll" )
rag:SetModel( ent:GetModel() )
rag:SetPos(ent:GetPos())
rag:Spawn()
rag:SetCollisionGroup( COLLISION_GROUP_DEBRIS )
rag:SetOwner(ent)
for i = 0, rag:GetPhysicsObjectCount() - 1 do
local bone = rag:GetPhysicsObjectNum( i )
if IsValid( bone ) then
local bonepos, boneang = ent:GetBonePosition( rag:TranslatePhysBoneToBone( i ) )
bone:SetPos( bonepos )
bone:SetAngles( boneang )
end
local matr = ent:GetBoneMatrix(i)
matr:Scale(Vector(0, 0, 0))
ent:SetBoneMatrix(i, matr)
ent:SetColor({r=0, g=0, b=0, a=0})
end
ent.WobbleManTagDoll = rag
ent.WobbleManTagDoll.sleep = false
ent:SetMaterial( "models/effects/vol_light001" )
if ent:GetMaterial() ~= "models/effects/vol_light001" then
ent.WobbleManMat = ent:GetMaterial()
end
if not ent.WobbleManBones then
ent.WobbleManBones = {"1.00","1.00","1.00","1.00","1.00","1.00","1.00","1.00","1.00","1.00","1.00","1.00","1.00","1.00","1.00"}
end
if not ent.WobbleManHideWeapon then
ent.WobbleManHideWeapon = "0.00"
end
if not ent.WobbleManHideViewWeapon then
ent.WobbleManHideViewWeapon = "0.00"
end
if not ent.WobbleManRagdollEffectsPly then
ent.WobbleManRagdollEffectsPly = "0.00"
end
end
return true
end
return true
end
function TOOL:RightClick( trace )
if ( trace.Entity and trace.Entity:IsPlayer() ) then return false end
if not string.find( trace.Entity:GetClass( ), "npc_*" ) then return false end
if (CLIENT) then return true end
if trace.Entity:IsValid() then
local ent = trace.Entity
if ent.WobbleManTagDoll and ent.WobbleManTagDoll ~= NULL then
ent.WobbleManTagDoll:Remove()
ent.WobbleManTagDoll = NULL
ent:SetMaterial(self:GetOwner().WobbleManMat)
ent:SetColor(Color(255,255,255,255))
end
end
return true
end
function TOOL.BuildCPanel( CPanel )
--[[
Pelvis Chest Head
LeftHand LeftForearm LeftUpperArm
LeftFoot LeftCalf LeftThigh
RightHand RightForearm RightUpperArm
RightFoot RightCalf RightThigh
--]]
CPanel:AddControl( "Label", { Text = "Middle", Description = "" } )
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_Pelvis",
Description = "#Tool_setnpcragmorph_Pelvis",
Command = "setnpcragmorph_Pelvis" })
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_Chest",
Description = "#Tool_setnpcragmorph_Chest",
Command = "setnpcragmorph_Chest" })
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_Head",
Description = "#Tool_setnpcragmorph_Head",
Command = "setnpcragmorph_Head" } )
CPanel:AddControl( "Label", { Text = "Left", Description = "" } )
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_LeftHand",
Description = "#Tool_setnpcragmorph_LeftHand",
Command = "setnpcragmorph_LeftHand" } )
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_LeftForearm",
Description = "#Tool_setnpcragmorph_LeftForearm",
Command = "setnpcragmorph_LeftForearm" } )
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_LeftUpperArm",
Description = "#Tool_setnpcragmorph_LeftUpperArm",
Command = "setnpcragmorph_LeftUpperArm" } )
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_LeftFoot",
Description = "#Tool_setnpcragmorph_LeftFoot",
Command = "setnpcragmorph_LeftFoot" } )
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_LeftCalf",
Description = "#Tool_setnpcragmorph_LeftCalf",
Command = "setnpcragmorph_LeftCalf" } )
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_LeftThigh",
Description = "#Tool_setnpcragmorph_LeftThigh",
Command = "setnpcragmorph_LeftThigh" } )
CPanel:AddControl( "Label", { Text = "Right", Description = "" } )
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_RightHand",
Description = "#Tool_setnpcragmorph_RightHand",
Command = "setnpcragmorph_RightHand" } )
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_RightForearm",
Description = "#Tool_setnpcragmorph_RightForearm",
Command = "setnpcragmorph_RightForearm" })
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_RightUpperArm",
Description = "#Tool_setnpcragmorph_RightUpperArm",
Command = "setnpcragmorph_RightUpperArm" } )
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_RightFoot",
Description = "#Tool_setnpcragmorph_RightFoot",
Command = "setnpcragmorph_RightFoot" } )
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_RightCalf",
Description = "#Tool_setnpcragmorph_RightCalf",
Command = "setnpcragmorph_RightCalf" } )
CPanel:AddControl( "CheckBox", { Label = "#Tool_setnpcragmorph_RightThigh",
Description = "#Tool_setnpcragmorph_RightThigh",
Command = "setnpcragmorph_RightThigh" } )
end
|
-- Engine requires
local vec2 = require 'Math.vec2'
local Window = require 'GUI.Window'
local TextColor = require 'GUI.Text.Color'
local MenuOrientation = require 'GUI.Menu.Orientation'
local MenuSettings = require 'GUI.Menu.Settings'
local Rect = require 'Shape.Rectangle'
local Util = require 'Util'
local Keys = require 'Input.Keys'
local States = require 'State.Type'
-- File dependencies
local OptionsMenu = require 'gui/optionsmenu'
local mainMenu = Window.new("NONE", Rect.new(cfg.graphics.res.x - 375,
cfg.graphics.res.y - 175,
cfg.graphics.res.x,
cfg.graphics.res.y))
local menuItems = {"Master Thesis", "Start Game", "Options", "Exit"}
mainMenu:isVisible(true)
local ms = MenuSettings.new(15.0, 50.0, MenuOrientation.Vertical)
mainMenu:addMenu("MainMenu",
Util.toVectorStr(menuItems),
vec2.new(),
ms)
local menu = mainMenu:menu("MainMenu")
local onEvent = function(event)
if not mainMenu:isVisible() or mainMenu:isAnimating() then
return
end
mainMenu:defaultInputHandler(event)
if event:hasBeenHandled() then
return
end
local hasConfirm = event:keyPressed(Keys.Enter) or
event:buttonPressed(Keys.MouseButton1)
if not hasConfirm then
return
end
local menuChoose = menu:getActiveMenu()
if menuChoose == 0 then
event:sendStateChange(States.MasterThesis)
elseif menuChoose == 1 then
event:sendStateChange(States.Game)
elseif menuChoose == 2 then
elseif menuChoose == 3 then
event:sendStateChange(States.Quit)
end
event:stopPropgation()
end
mainMenu:setInputHandler(onEvent)
-- addtoDrawable(mainMenu)
|
---@type Ellyb
local Ellyb = Ellyb(...)
if Ellyb.Texture then
return
end
--{{{ Class declaration
--- @class EllybTexture : Object
local Texture = Ellyb.Class("Texture")
--- This class in an abstraction to help handle World of Warcraft textures, especially when dealing with both texture IDs and file path.
---@param textureSource string|number @ Texture ID, file path or atlas
---@type EllybTexture|fun(source:string|number, width:number|nil, height:number|nil):EllybTexture
Ellyb.Texture = Texture;
---@type {fileID:number, filePath:string|nil, width:number|nil, height:number|nil}[]
local private = Ellyb.getPrivateStorage();
--}}}
---@private
---@param source string|number
---@param width number|nil
---@param height number|nil
function Texture:initialize(source, width, height)
local typeOfSource = type(source);
if typeOfSource == "number" then
self:SetTextureByID(source);
elseif typeOfSource == "string" then
self:SetTextureFromFilePath(source);
end
-- If width and height were given we set them now
if width ~= nil then
self:SetWidth(width);
end
if height ~= nil then
self:SetHeight(height);
end
end
--{{{ File resource
---@param fileID number @ The file ID you want to use for this texture.
function Texture:SetTextureByID(fileID)
private[self].fileID = fileID;
end
---@return number fileID @ A file ID that can be used to access this texture.
function Texture:GetFileID()
return private[self].fileID;
end
--- Set the texture using a file path. A file ID will be automatically resolved and used later.
---@param filePath string @ The file path you want to use for this texture
function Texture:SetTextureFromFilePath(filePath)
private[self].filePath = filePath;
if GetFileIDFromPath then
self:SetTextureByID(GetFileIDFromPath(filePath));
end
end
--- Get the file path that was used to create this texture.
--- Since there is no way to get a path from a file ID
---@return string|nil filePath @ The file path if the texture was created with one, otherwise nil if we don't have the information
function Texture:GetFilePath()
return private[self].filePath;
end
function Texture:GetFileName()
return self:GetFilePath() and self:GetFilePath():match("^.+\\(.+)$")
end
--- Check if this texture is using custom assets.
--- Custom assets provided by add-ons will have a negative file ID. It is temporary and will change for every session.
---@return boolean isUsingCustomAssets @ True if the texture is custom asset, false if it comes from the game's default files.
function Texture:IsUsingCustomAssets()
return self:GetFileID() < 0;
end
function Texture:GetResource()
return self:GetFileID() or self:GetFilePath();
end
--}}}
--{{{ UI Widget usage
--- Apply the texture to a Texture UI widget
---@param texture Texture
function Texture:Apply(texture)
texture:SetTexture(self:GetResource());
if self:GetWidth() then
texture:SetWidth(self:GetWidth());
end
if self:GetHeight() then
texture:SetHeight(self:GetHeight());
end
end
--}}}
--{{{ Size manipulation
function Texture:SetWidth(width)
private[self].width = width;
end
---@return number
function Texture:GetWidth()
return private[self].width;
end
function Texture:SetHeight(height)
private[self].height = height;
end
---@return number
function Texture:GetHeight()
return private[self].height;
end
--}}}
--{{{ String representation
---@return string texture @ Generate a string version of the texture using the width and height defined or 50px as a default value
function Texture:__tostring()
return self:GenerateString(self:GetWidth(), self:GetHeight());
end
local TEXTURE_STRING_ESCAPE_SEQUENCE = [[|T%s:%s:%s|t]];
local TEXTURE_WITH_COORDINATES_STRING_ESCAPE_SEQUENCE = [[|T%s:%d:%d:0:0:%d:%d:%d:%d:%d:%d|t]];
local DEFAULT_TEXTURE_SIZE = 25;
--- Generate a UI escape sequence string used to display the icon inside a text.
---@param width number|nil @ The width of the icon, by default will be 50px.
---@param height number|nil @ The height of the icon. If no height is provided but a width was defined the width will be used, otherwise the default value will be 50px
---@return string texture
function Texture:GenerateString(width, height)
width = width or self:GetWidth() or DEFAULT_TEXTURE_SIZE;
height = height or width;
if self.coordinates then
-- This is directly borrowed from Blizzard's code. Dark voodoo maths
local atlasWidth = width / (self.coordinates.txRight - self.coordinates.txLeft);
local atlasHeight = height / (self.coordinates.txBottom - self.coordinates.txTop);
local pxLeft = atlasWidth * self.coordinates.txLeft;
local pxRight = atlasWidth * self.coordinates.txRight;
local pxTop = atlasHeight * self.coordinates.txTop;
local pxBottom = atlasHeight * self.coordinates.txBottom;
return TEXTURE_WITH_COORDINATES_STRING_ESCAPE_SEQUENCE:format(self:GetResource(), width, height, atlasWidth, atlasHeight, pxLeft, pxRight, pxTop, pxBottom);
else
return TEXTURE_STRING_ESCAPE_SEQUENCE:format(self:GetResource(), width, height);
end
end
function Texture.CreateFromAtlas(atlasName)
local filename, width, height, txLeft, txRight, txTop, txBottom = GetAtlasInfo(atlasName);
local texture = Texture(filename);
texture:SetCoordinates(width, height, txLeft, txRight, txTop, txBottom)
return texture;
end
--}}}
function Texture:SetCoordinates(width, height, txLeft, txRight, txTop, txBottom)
self.coordinates = {
width = width,
height = height,
txLeft = txLeft,
txRight = txRight,
txTop = txTop,
txBottom = txBottom
}
end |
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
local S = E:GetModule('Skins')
--Lua functions
local _G = _G
local pairs = pairs
--WoW API / Variables
local hooksecurefunc = hooksecurefunc
local function LoadSkin()
if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.binding ~= true then return end
local buttons = {
"defaultsButton",
"unbindButton",
"okayButton",
"cancelButton",
}
local KeyBindingFrame = _G.KeyBindingFrame
for _, v in pairs(buttons) do
S:HandleButton(KeyBindingFrame[v])
end
KeyBindingFrame.header:StripTextures()
_G.KeyBindingFrameScrollFrame:StripTextures()
S:HandleScrollBar(_G.KeyBindingFrameScrollFrameScrollBar)
S:HandleCheckBox(KeyBindingFrame.characterSpecificButton)
KeyBindingFrame.header:ClearAllPoints()
KeyBindingFrame.header:Point("TOP", KeyBindingFrame, "TOP", 0, -4)
KeyBindingFrame:StripTextures()
KeyBindingFrame:SetTemplate("Transparent")
_G.KeyBindingFrameCategoryList:StripTextures()
_G.KeyBindingFrameCategoryList:SetTemplate("Transparent")
KeyBindingFrame.bindingsContainer:StripTextures()
KeyBindingFrame.bindingsContainer:SetTemplate("Transparent")
for i = 1, _G.KEY_BINDINGS_DISPLAYED, 1 do
local button1 = _G["KeyBindingFrameKeyBinding"..i.."Key1Button"]
local button2 = _G["KeyBindingFrameKeyBinding"..i.."Key2Button"]
button2:Point("LEFT", button1, "RIGHT", 1, 0) -- Needed for new Pixel Perfect
end
hooksecurefunc("BindingButtonTemplate_SetupBindingButton", function(_, button)
if not button.IsSkinned then
local selected = button.selectedHighlight
selected:SetTexture(E.media.normTex)
selected:Point("TOPLEFT", E.mult, -E.mult)
selected:Point("BOTTOMRIGHT", -E.mult, E.mult)
selected:SetColorTexture(1, 1, 1, .25)
S:HandleButton(button)
button.IsSkinned = true
end
end)
KeyBindingFrame.okayButton:Point("BOTTOMLEFT", KeyBindingFrame.unbindButton, "BOTTOMRIGHT", 3, 0)
KeyBindingFrame.cancelButton:Point("BOTTOMLEFT", KeyBindingFrame.okayButton, "BOTTOMRIGHT", 3, 0)
KeyBindingFrame.unbindButton:Point("BOTTOMRIGHT", KeyBindingFrame, "BOTTOMRIGHT", -211, 16)
end
S:AddCallbackForAddon("Blizzard_BindingUI", "Binding", LoadSkin)
|
local chilled = false
local buffed = false
local staffEquipped = false
local manaTotal = 0
--setHudValue("manaShow", true)
--setHudValue("mana", 100)
--exports["caue-ui"]:sendAppEvent("hud", {
-- true | false = currentValues["manaShow"], -- lmao
-- 0 | 100 = currentValues["mana"],
--})
-- TriggerServerEvent("InteractSound_SV:PlayAudioAtPosition",position, 10.0, 'ArcaneEffect', 0.2)
-- TriggerServerEvent('InteractSound_SV:PlayWithinDistance', 10.0, 'ArcaneLong', 0.2)
-- TriggerEvent('InteractSound_CL:PlayOnOne','ArcaneEffect', 0.2)
RegisterNetEvent("fx:spellcast")
AddEventHandler("fx:spellcast", function(Spell)
if manaTotal > SpellList[Spell]["Base"]["Mana"] then
staffEquipped = false
manaTotal = manaTotal - SpellList[Spell]["Base"]["Mana"]
exports["caue-ui"]:sendAppEvent("hud", { mana = manaTotal })
TriggerServerEvent('InteractSound_SV:PlayWithinDistance', 10.0, '/Spells/' .. SpellList[Spell]["Base"]["SoundFile"], 0.4)
SpellCast(Spell)
else
TriggerEvent('InteractSound_CL:PlayOnOne','/Spells/oom', 0.4)
end
end)
Citizen.CreateThread(function()
while true do
Wait(500)
if staffEquipped then
SetEntityHealth(PlayerPedId(), GetEntityHealth(PlayerPedId()) + 5)
manaTotal = manaTotal + 1
if manaTotal > 100 then
manaTotal = 100
end
exports["caue-ui"]:sendAppEvent("hud", { mana = manaTotal })
else
Wait(1500)
end
end
end)
function DoPoop()
TriggerEvent("animation:PlayAnimation","shit")
local timer = 1000
while timer > 0 do
DisableAllControlActions(0)
DisableAllControlActions(1)
Citizen.Wait(0)
timer = timer - 1
end
TriggerEvent("animation:PlayAnimation","cancel")
end
RegisterNetEvent("fx:spell:poop")
AddEventHandler("fx:spell:poop", function()
TriggerEvent('InteractSound_CL:PlayOnOne','/Spells/FartNoise2', 0.1)
DoPoop()
end)
RegisterNetEvent("fx:spellmana")
AddEventHandler("fx:spellmana", function()
TriggerEvent('InteractSound_CL:PlayOnOne','/Spells/FairyEffect', 0.4)
manaTotal = 100
exports["caue-ui"]:sendAppEvent("hud", { mana = manaTotal })
TriggerServerEvent("fx:effect:start","buffed", GetRandomString(12))
TriggerEvent('InteractSound_CL:PlayOnOne','/Spells/ArcaneEffect', 0.4)
end)
RegisterNetEvent("fx:staffused")
AddEventHandler("fx:staffused", function(equipped)
staffEquipped = equipped
TriggerEvent('InteractSound_CL:PlayOnOne','/Spells/FireEffect', 0.1)
if equipped then
SetPedArmour(PlayerPedId(),0)
end
exports["caue-ui"]:sendAppEvent("hud", { manaShow = equipped })
TriggerServerEvent("fx:effect:start","staffused", GetRandomString(12))
end)
RegisterNetEvent("fx:spell:effect")
AddEventHandler("fx:spell:effect", function(Spell)
if not SpellList[Spell]["AreaEffect"]["Event"] then
return
end
print("I was hit by spell : " .. SpellList[Spell]["AreaEffect"]["Event"])
TriggerEvent(SpellList[Spell]["AreaEffect"]["Event"])
end)
RegisterNetEvent("fx:spell:buff")
AddEventHandler("fx:spell:buff", function()
buffed = true
TriggerServerEvent("fx:effect:start","buffed", GetRandomString(12))
TriggerEvent('InteractSound_CL:PlayOnOne','/Spells/ArcaneEffect', 0.4)
end)
RegisterNetEvent("fx:spell:heal")
AddEventHandler("fx:spell:heal", function()
SetEntityHealth(PlayerPedId(), GetEntityHealth(PlayerPedId()) + 50)
TriggerEvent('InteractSound_CL:PlayOnOne','/Spells/FairyEffect', 0.4)
TextDraw("+50 Health")
chilled = false
end)
RegisterNetEvent("fx:spell:slow")
AddEventHandler("fx:spell:slow", function()
if buffed then
buffed = false
return
end
TriggerEvent('InteractSound_CL:PlayOnOne','/Spells/IceEffect', 0.4)
local ped = PlayerPedId()
TextDraw("You have been frozen!!")
local timer = 500
chilled = true
FreezeEntityPosition(PlayerPedId(), true)
SetPlayerInvincible(PlayerId(), true)
TriggerServerEvent("fx:effect:start","slowed", GetRandomString(12))
SetEntityHealth(ped, GetEntityHealth(ped) - 5)
while timer > 0 and chilled do
DisableControlAction(0, 21, true)
Wait(1)
timer = timer - 1
end
SetEntityHealth(ped, GetEntityHealth(ped) - 5)
FreezeEntityPosition(PlayerPedId(), false)
SetPlayerInvincible(PlayerId(), false)
TextDraw("You are no longer frozen!")
end)
RegisterNetEvent("fx:teleport:location")
AddEventHandler("fx:teleport:location", function()
SetEntityCoords(PlayerPedId(),GetTargetCoords())
TriggerServerEvent('InteractSound_SV:PlayWithinDistance', 10.0, '/Spells/ArcaneEffect', 0.4)
end)
RegisterNetEvent("fx:spell:shock")
AddEventHandler("fx:spell:shock", function()
if buffed then
buffed = false
return
end
TriggerEvent('InteractSound_CL:PlayOnOne','/Spells/ArcaneEffect', 0.4)
TriggerServerEvent("fx:effect:start","arcane", GetRandomString(12))
local ped = PlayerPedId()
TextDraw("You have been mini-stunned")
SetPedToRagdoll(ped, 1000, 1000, 3, 0, 0, 0)
SetEntityHealth(ped, GetEntityHealth(ped) - 33)
end)
RegisterNetEvent("fx:spell:speed")
AddEventHandler("fx:spell:speed", function()
TextDraw("Wind Effect!!")
TriggerEvent('InteractSound_CL:PlayOnOne','/Spells/FairyEffect', 0.2)
SetRunSprintMultiplierForPlayer(PlayerId(), 1.49)
--SetPedConfigFlag(PlayerPedId(),223,true)
TriggerServerEvent("fx:effect:start","speed", GetRandomString(12))
Wait(10000)
SetRunSprintMultiplierForPlayer(PlayerId(), 1.0)
-- SetPedConfigFlag(PlayerPedId(),223,false)
TextDraw("You are no longer fast!")
end)
function TextDraw(text)
-- lazy, would be cool to make a hud thing with scrolling combat text
TriggerEvent('chatMessage', 'Magic Effect: ', 1, text )
end
-- remove this shit later - replace with export..
function RayCast(origin, target, options, ignoreEntity, radius)
local handle = StartShapeTestRay(origin.x, origin.y, origin.z, target.x, target.y, target.z, options, ignoreEntity, 0)
return GetShapeTestResult(handle)
end
function GetForwardVector(rotation)
local rot = (math.pi / 180.0) * rotation
return vector3(-math.sin(rot.z) * math.abs(math.cos(rot.x)), math.cos(rot.z) * math.abs(math.cos(rot.x)), math.sin(rot.x))
end
function GetTargetCoords()
local CameraCoords = GetGameplayCamCoord()
local ForwardVectors = GetForwardVector(GetGameplayCamRot(2))
local ForwardCoords = CameraCoords + (ForwardVectors * (IsInVehicle and 21.5 or 40.0))
local TargetCoords = vector3(0.0, 0.0, 0.0)
if ForwardVectors then
local _, hit, targetCoords, _, _ = RayCast(CameraCoords, ForwardCoords, 17, nil, 0.1)
TargetCoords = targetCoords
end
return TargetCoords
end
function SpellTargeting(dist,timer)
local reply = false
local timer = math.ceil(timer * 0.25)
TriggerEvent("animation:PlayAnimation","mindcontrol2")
while timer > 0 do
timer = timer - 1
Wait(0)
local coords = GetTargetCoords()
DrawMarker(27, coords.x, coords.y, coords.z + 0.10, 0, 0, 0, 0, 0, 0, dist, dist, dist, 0, 225, 165, 215, 1,1, 1,1)
end
if GetDistanceBetweenCoords(GetTargetCoords(),GetEntityCoords(PlayerPedId())) < 41.0 then
reply = true
end
return reply
end
local casting = false
function SpellCast(SpellCast)
if casting then return end
casting = true
-- mana check and use
-- check if its a target use skill
local table = SpellList[SpellCast]
local base = table["Base"]
SpellID = GetRandomString(12)
StartID = GetRandomString(12)
TriggerServerEvent("fx:spell:start",SpellCast, SpellID, StartID)
if base["Target"] and not base["ClientEffect"] then
local success = SpellTargeting(base["Targetdist"],base["Casttime"])
if success then
local coords = OffsetCoords(table["AreaEffect"]["OffSets"].offset)
TriggerServerEvent("fx:spell:target",coords,SpellCast,1500)
end
elseif base["Target"] and base["ClientEffect"] then
-- do client effect
local success = SpellTargeting(base["Targetdist"],base["Casttime"])
if success then
TriggerEvent(base["ClientEffect"])
local coords = OffsetCoords(table["AreaEffect"]["OffSets"].offset)
TriggerServerEvent("fx:spell:target",coords,SpellCast,1500)
end
end
TriggerEvent("animation:PlayAnimation","Cancel")
Wait(table["Base"]["GCD"])
casting = false
end
function OffsetCoords(offset)
local coords = GetTargetCoords()
return vector3(coords.x + offset.x,coords.y + offset.y,coords.z + offset.z)
end
function SpellStop()
if not IsPeePooWhitelist() then return end
if SpellID == nil then return end
TriggerEvent("animation:PlayAnimation","cancel")
TriggerServerEvent("fx:spell:stop", SpellID)
SpellID = nil
end |
--[[
____ _ _ _
| __ ) __ _ ___ | |__ __ _ ___ (_) |_
| _ \ / _` |/ _ \| '_ \ / _` |/ _ \| | __|
| |_) | (_| | (_) | |_) | (_| | (_) | | |
|____/ \__,_|\___/|_.__/ \__,_|\___/|_|\__|
--]]
--[[
╔═══════════╗
║ Bootstrap ║
╚═══════════╝
--]]
require "bootstrap"
--[[
╔═════════╗
║ Plugins ║
╚═════════╝
--]]
require "paq" {
-- Package manager
"savq/paq-nvim"; -- Let Paq manage itself
-- Code analyze
"dense-analysis/ale";
-- Buffer line
"akinsho/bufferline.nvim";
-- Comment
"numToStr/Comment.nvim";
-- Git
"sindrets/diffview.nvim";
"tpope/vim-fugitive";
-- Improve startup time
"lewis6991/impatient.nvim";
-- Status bar
"doums/lsp_spinner.nvim";
"nvim-lualine/lualine.nvim";
-- Auto pairs
"windwp/nvim-autopairs";
-- Completion
"L3MON4D3/LuaSnip";
"hrsh7th/cmp-buffer";
"saadparwaiz1/cmp_luasnip";
"hrsh7th/cmp-nvim-lsp";
"onsails/lspkind-nvim";
"hrsh7th/nvim-cmp";
-- Debug
"mfussenegger/nvim-dap";
"rcarriga/nvim-dap-ui";
-- Java JDT.LS
"neovim/nvim-lspconfig";
"mfussenegger/nvim-jdtls";
-- File explorer
"kyazdani42/nvim-tree.lua";
"kyazdani42/nvim-web-devicons";
-- Syntax highlighting
{
"nvim-treesitter/nvim-treesitter",
run = ":TSUpdate"
};
-- Theme
"monsonjeremy/onedark.nvim";
-- Symbols outline
"simrat39/symbols-outline.nvim";
-- Telescope
"nvim-lua/plenary.nvim";
"nvim-telescope/telescope.nvim";
{
"nvim-telescope/telescope-fzf-native.nvim",
run = "make"
};
"nvim-telescope/telescope-ui-select.nvim";
"gbrlsnchs/telescope-lsp-handlers.nvim";
-- Terminal
"akinsho/toggleterm.nvim";
-- Length over
"whatyouhide/vim-lengthmatters";
}
--[[
╔═════════════════════════════╗
║ General settings for Neovim ║
╚═════════════════════════════╝
--]]
require "general"
--[[
╔════════════════════════════╗
║ Plugin settings for Neovim ║
╚════════════════════════════╝
--]]
require "plugin_settings"
|
function onUse(player, item, fromPosition, target, toPosition, isHotkey)
return onUseScythe(player, item, fromPosition, target, toPosition, isHotkey)
end |
-- ########################################################
-- ECHONET Lite Wireshark dissector
-- ########################################################
--
-- Author : Yuki MIZUNO
-- Version: 1.2.1
-- License: MIT
--
-- ########################################################
--
-- Copyright (c) 2016 Yuki MIZUNO
-- This software is released under the MIT License.
-- http://opensource.org/licenses/MIT
--
local list = require("echonet-lite-codelist")
local epcparser = require("echonet-lite-epcparser")
edata = Proto("echonetlite.edata", "ECHONET Lite Data (EDATA)")
-- ========================================================
-- ECHONET Lite Data fields definition.
-- ========================================================
edata.fields.seoj = ProtoField.uint24("echonetlite.edata.seoj", "Source ECHONET Lite object (SEOJ)", base.HEX)
edata.fields.seojgroup = ProtoField.uint8("echonetlite.edata.seoj.classgroup", "Class group code", base.HEX, list.group)
edata.fields.seojclass = ProtoField.uint8("echonetlite.edata.seoj.class", "Class code", base.HEX)
edata.fields.seojinstance = ProtoField.uint8("echonetlite.edata.seoj.instance", "Instance code", base.HEX)
edata.fields.deoj = ProtoField.uint24("echonetlite.edata.deoj", "Destination ECHONET Lite object (DEOJ)", base.HEX)
edata.fields.deojgroup = ProtoField.uint8("echonetlite.edata.deoj.classgroup", "Class group code", base.HEX, list.group)
edata.fields.deojclass = ProtoField.uint8("echonetlite.edata.deoj.class", "Class code", base.HEX)
edata.fields.deojinstance = ProtoField.uint8("echonetlite.edata.deoj.instance", "Instance code", base.HEX)
edata.fields.esv = ProtoField.uint8("echonetlite.edata.esv", "ECHONET Lite service (ESV)", base.HEX, list.esv)
edata.fields.opc = ProtoField.uint8("echonetlite.edata.opc", "Property size (OPC)", base.DEC)
edata.fields.property = ProtoField.none("echonetlite.edata.property", "Property")
edata.fields.epc = ProtoField.uint8("echonetlite.edata.epc", "ECHONET Property (EPC)", base.HEX)
edata.fields.pdc = ProtoField.uint8("echonetlite.edata.pdc", "Property Data Counter (PDC)", base.DEC)
edata.fields.edt = ProtoField.bytes("echonetlite.edata.edt", "ECHONET Property Value Data (EDT)", base.SPACE)
-- ========================================================
-- Parse ECHONET Lite Data fields.
-- ========================================================
function edata.dissector(buffer, pinfo, tree)
local data_len = buffer:len()
local subtree = tree:add(edata, buffer(0, data_len))
local sobj = "Unknown"
if list.class[buffer(0,1):uint()] ~= nil and list.class[buffer(0,1):uint()][buffer(1,1):uint()] ~= nil then
sobj = list.class[buffer(0,1):uint()][buffer(1,1):uint()]
end
local seojtree = subtree:add(edata.fields.seoj, buffer(0, 3))
seojtree:append_text(string.format(" (%s)", sobj))
seojtree:add(edata.fields.seojgroup, buffer(0, 1))
seojtree:add(edata.fields.seojclass, buffer(1, 1), buffer(1,1):uint(), "Class code:", sobj, string.format("(0x%02x)", buffer(1,1):uint()))
seojtree:add(edata.fields.seojinstance, buffer(2, 1))
local dobj = "Unknown"
if list.class[buffer(3,1):uint()] ~= nil and list.class[buffer(3,1):uint()][buffer(4,1):uint()] ~= nil then
dobj = list.class[buffer(3,1):uint()][buffer(4,1):uint()]
end
local deojtree = subtree:add(edata.fields.deoj, buffer(3, 3))
deojtree:append_text(string.format(" (%s)", dobj))
deojtree:add(edata.fields.deojgroup, buffer(3, 1))
deojtree:add(edata.fields.deojclass, buffer(4, 1), buffer(4,1):uint(), "Class code:", dobj, string.format("(0x%02x)", buffer(4,1):uint()))
deojtree:add(edata.fields.deojinstance, buffer(5, 1))
subtree:add(edata.fields.esv, buffer(6, 1))
subtree:add(edata.fields.opc, buffer(7, 1))
local esv = list.esv[buffer(6, 1):uint()]
if esv == nil then
esv = "Unknown"
end
local props = ""
begin = 8
for i=1,buffer(7, 1):uint() do
local pdc = buffer(begin + 1, 1):uint()
local proptree = subtree:add(edata.fields.property, buffer(begin, pdc + 2))
proptree:append_text(string.format(" %d", i))
if 0 <= buffer(6, 1):uint() and buffer(6, 1):uint() <= 0x6F then -- Request service code
epcparser(buffer(3, 1), buffer(4, 1), buffer(begin, 1), buffer(begin + 1, 1), buffer(begin + 2, pdc), proptree, edata)
else
epcparser(buffer(0, 1), buffer(1, 1), buffer(begin, 1), buffer(begin + 1, 1), buffer(begin + 2, pdc), proptree, edata)
end
props = string.format("%s,0x%02x", props, buffer(begin, 1):uint())
begin = begin + 2 + pdc
end
props = string.gsub(props, "^,", ", EPC=")
pinfo.cols.info = string.format("%s → %s, %s%s", sobj, dobj, esv, props)
end
|
include("shared.lua")
function ENT:Draw()
self:DrawModel()
if not self:GetParent():IsValid() then
local pos = self:GetPos()
local ang = self:GetAngles()
surface.SetFont("Trebuchet24")
local txt = self:GetClass()
local w, h = surface.GetTextSize(txt)
cam.Start3D2D(pos +ang:Up() *4.1, ang, 0.2)
draw.WordBox(2, -w *0.31, -10, txt, "Default", Color(0, 0, 0, 200), color_white)
cam.End3D2D()
end
end |
require 'task'
TEST = {}
function TEST.ts()
local tl = task.list()
io.stdout:write( '\nID SCRIPT COUNT REG/ID\n' )
io.stdout:write( '---- ---------------- --------- ----------------\n' )
if tl then
for i, t in pairs( tl ) do
io.stdout:write( string.format( '%4d %-16.16s %9d %-16.16s\n',
i, t.script or arg[0], t.msgcount, t.id or '' ) )
end
end
end
function TEST.main( arg )
task.register( 'Main' )
local cmd = 'ts'
while cmd ~= 'quit' do
if cmd == 'ts' then
TEST.ts()
elseif string.sub( cmd, 1, 3 ) == 'run' then
local rarg = {}
string.gsub( cmd, '([^ ]+)', function( x ) table.insert( rarg, x ) end )
if not rarg[2] then
io.stdout:write( 'Run what?\n' )
else
local script = rarg[2]
table.remove( rarg, 1)
table.remove( rarg, 1)
local tsk = task.create( script, rarg )
if tsk == -1 then
io.stdout:write( "-> Can't expand task list.\n" )
elseif tsk == -2 then
io.stdout:write( "-> Can't strdup file name.\n" )
elseif tsk == -3 then
io.stdout:write( "-> Can't create message queue.\n" )
elseif tsk == -4 then
io.stdout:write( "-> Can't create os thread.\n" )
elseif tsk == -11 then
io.stdout:write( "-> The library seems corrupt.\n" )
else
io.stdout:write( "-> Task ", tsk, " started.\n" )
end
end
end
io.stdout:write( 'TEST> ' )
io.stdout:flush()
cmd = io.stdin:read()
end
io.stdout:write( '\nTEST terminated\n' )
os.exit( 0 )
end
TEST.main( arg )
|
#@
-- Path of Building
--
-- Module: Update Apply
-- Applies updates.
--
local opFileName = ...
print("Applying update...")
local opFile = io.open(opFileName, "r")
if not opFile then
print("No operations list present.\n")
return
end
local lines = { }
for line in opFile:lines() do
table.insert(lines, line)
end
opFile:close()
os.remove(opFileName)
for _, line in ipairs(lines) do
local op, args = line:match("(%a+) ?(.*)")
if op == "move" then
local src, dst = args:match('"(.*)" "(.*)"')
dst = dst:gsub("{space}", " ")
print("Updating '"..dst.."'")
local srcFile = io.open(src, "rb")
assert(srcFile, "couldn't open "..src)
local dstFile
while not dstFile do
dstFile = io.open(dst, "w+b")
end
if dstFile then
dstFile:write(srcFile:read("*a"))
dstFile:close()
end
srcFile:close()
os.remove(src)
elseif op == "delete" then
local file = args:match('"(.*)"')
print("Deleting '"..file.."'")
os.remove(file)
elseif op == "start" then
local target = args:match('"(.*)"')
SpawnProcess(target)
end
end
|
-- pattern for finding figure references
-- Example: {#f:fig1ref:i}
local patt = "{%#%l:.+:%a}"
local id_patt = ":(.+):"
local part_of_text_patt = ":(%a)}"
-- Variables
local img_filetype = ".png"
local img_caption_filetype = ".md"
local fig_dir = ""
local caption_dir = ""
local function file_exists(file)
-- Check if a file exists.
local f = io.open(file, "rb")
if f then
f:close()
end
return f ~= nil
end
function text_from_file(fname)
-- Get the text contents from a file.
if file_exists(fname) then
local file = io.open(fname, "r")
local text = file:read("*a")
file:close()
return text
else
return nil
end
end
function get_figure_path(meta)
-- Find the figure and captoin directory fields from the document metadata.
if meta.figure_dir ~= nil then
fig_dir = meta.figure_dir[1].text
end
if meta.caption_dir ~= nil then
caption_dir = meta.caption_dir[1].text
end
end
function insert_figure_and_caption(s)
--[[ Finds a figure tag (`{#f:tag:i}`) and uses `tag` to find contruct
file names in combination with the `fig_dir` and `caption_dir` variables.
]]
if s.text:match(patt) then
local pot_tag = s.text:match(part_of_text_patt)
local id = s.text:match(id_patt)
if pot_tag == "i" then
local filename = fig_dir .. "/" .. id .. img_filetype
local caption_filename = caption_dir .. "/" .. id .. img_caption_filetype
local caption = ""
local fig_title = "fig:"
caption_file_contents = text_from_file(caption_filename)
if caption_file_contents ~= nil then
local doc = pandoc.read(caption_file_contents)
caption = doc.blocks[1].content
fig_title = fig_title .. caption_file_contents
end
-- If the image file does not exist, Pandoc will replace the element with
-- the 'description', which will be empty.
return pandoc.Image(caption, filename, fig_title)
end
end
end
return {
{
Meta = function(meta)
get_figure_path(meta)
end,
},
{
Str = function(s)
local res = insert_figure_and_caption(s)
return res
end,
},
}
|
aaa
abc
academia
academic
access
ada
admin
administrator
adrian
adrianna
aerobics
airplane
albany
albatross
albert
alex
alexander
alf
algebra
alias
aliases
alice
alicia
alisa
alison
allison
alpha
alphabet
ama
amadeus
amanda
amber
amorphous
amy
analog
anchor
andrea
andromache
andy
angela
angerine
angie
animals
anita
ann
anna
anne
annette
answer
anthropogenic
anvils
anything
april
aria
ariadne
arlene
arrow
arthur
asd
asm
asshole
athena
atmosphere
aztecs
azure
bacchus
badass
bailey
banana
bananas
bandit
banks
barbara
barber
baritone
bart
bartman
basic
bass
bassoon
batch
batman
beach
beater
beauty
beaver
becky
beethoven
beloved
benz
beowulf
berkeley
berlin
berliner
beryl
beta
beth
betsie
betty
beverly
bicameral
bishop
bitch
bob
bradley
brandi
brandy
brenda
brian
bridget
broadway
bsd
bumbling
burgess
cad
camille
campanile
candi
candy
cantor
cardinal
caren
carla
carmen
carol
carole
carolina
caroline
carrie
carson
cascades
castle
cat
catherine
cathy
cayuga
cecily
celtics
cerulean
change
charity
charles
charming
charon
chat
chem
chemistry
chess
chester
christina
christine
christy
cigar
cindy
class
classic
claudia
cluster
clusters
code
coffee
coke
collins
commrades
computer
comrade
comrades
condo
condom
connect
connie
console
cookie
cooper
cornelius
couscous
create
creation
creosote
cretin
criminal
cristina
crystal
cshrc
cynthia
daemon
daisy
dana
dancer
daniel
danielle
danny
dapper
data
dave
dawn
deb
debbie
deborah
december
default
defoe
deluge
denise
desiree
desperate
develop
device
dial
diana
diane
diet
dieter
digital
disc
discovery
disk
disney
dog
dos
drought
dulce
duncan
eager
earth
easier
easy
eatme
edges
edinburgh
edwin
edwina
egghead
eiderdown
eileen
einstein
elaine
elanor
elephant
elizabeth
ellen
email
emerald
emily
emmanuel
enemy
engine
engineer
enterprise
enzyme
erenity
erica
erika
erin
ersatz
establish
estate
eternity
euclid
evelyn
extension
fairway
felicia
fender
fermat
ferrari
fidelity
field
file
finite
fishers
flakes
float
flower
flowers
foolproof
football
foresight
format
forsythe
fourier
fred
friend
frighten
fun
function
fungible
gabriel
games
gardner
garfield
gatt
gauss
george
gertrude
gibson
gina
ginger
glacier
gnu
golf
golfer
gorgeous
gorges
gosling
gouge
graham
grahm
group
gryphon
gucci
guess
guest
guitar
gumption
guntis
hack
hacker
hal
hamlet
handily
happening
harmony
harold
harvey
hawaii
heather
hebrides
heidi
heinlein
hello
help
herbert
hiawatha
hibernia
hidden
holly
homework
honey
horse
horus
hutchins
hydrogen
ibm
imbroglio
imperial
include
ingres
ingress
ingrid
inna
innocuous
internet
irene
irishman
isis
jackie
jane
janet
janice
janie
japan
jasmin
jean
jeanne
jen
jenni
jennifer
jenny
jessica
jester
jill
jixian
joanne
jody
johnny
joseph
joshua
joy
joyce
judith
judy
juggle
julia
julie
june
jupiter
karen
karie
karina
kate
kathleen
kathrine
kathy
katina
katrina
kelly
keri
kermit
kernel
kerri
kerrie
kerry
key
kim
kimberly
kirkland
kitten
knight
krista
kristen
kristi
kristie
kristin
kristine
kristy
ladle
lambda
lamination
lana
lara
larkin
larry
laura
lazarus
leah
lebesgue
lee
leland
leroy
leslie
lewis
library
light
linda
lisa
lisp
liz
lock
lockout
lois
lori
lorin
lorraine
louis
love
lucy
lynn
lynne
macintosh
mack
maggot
magic
mail
maint
malcolm
malcom
manager
mara
marci
marcy
maria
marietta
mark
markus
marni
mars
marty
marvin
mary
master
math
maurice
meagan
megan
melissa
mellon
memory
mercury
merlin
mets
mgr
michael
michele
michelle
mickey
mike
minimum
minsky
mit
modem
mogul
moguls
monica
moose
morley
mouse
mozart
mutant
nagel
nancy
napoleon
nasa
nepenthe
neptune
ness
net
network
new
news
newton
next
nicole
nita
nobody
noreen
noxious
nuclear
nutrition
nyquist
oceanography
ocelot
office
olivetti
olivia
open
operator
oracle
orca
orwell
osiris
outlaw
oxford
pacific
pad
painless
pakistan
pam
pamela
paper
papers
pass
password
pat
patricia
patty
paula
pencil
penelope
penguin
penis
peoria
percolate
persimmon
persona
pete
peter
philip
phoenix
phone
pierre
pizza
plane
playboy
plover
pluto
plymouth
polly
polynomial
pondering
pork
porsche
poster
power
praise
precious
prelude
presto
prince
princeton
priv
private
privs
professor
profile
program
protect
protozoa
pub
public
pumpkin
puneet
puppet
qwerty
rabbit
rachel
rachelle
rachmaninoff
rainbow
raindrop
raleigh
random
rascal
reagan
really
rebecca
regional
remote
renee
rick
ripple
risc
rje
robin
robot
robotics
robyn
rochelle
rochester
rodent
rolex
romano
ronald
root
rose
rosebud
rosemary
roses
ruben
rules
ruth
sal
samantha
sandra
sandy
sara
sarah
saturn
saxon
scamper
scheme
school
scott
scotty
secret
security
sensor
serenity
service
sesame
setup
sex
shannon
sharc
shark
sharks
sharon
sheffield
sheldon
shell
sherri
shirley
shit
shiva
shivers
shuttle
signature
simon
simple
simpsons
singer
single
smile
smiles
smooch
smother
snatch
snoopy
soap
socrates
somebody
sondra
sonia
sonya
sossina
sparrows
spit
spring
springer
squires
stacey
staci
stacie
stacy
steph
stephanie
strangle
stratford
student
stuttgart
subway
success
summer
sun
super
superstage
superuser
support
supported
surfer
susan
susanne
susie
suzanne
suzie
swearer
sybil
symmetry
sys
sysadmin
system
tamara
tami
tamie
tammy
tangerine
tape
tara
target
tarragon
taylor
tech
telephone
temptation
tennis
terminal
test
thailand
theresa
tiffany
tiger
tina
toggle
tomato
topography
tortoise
toxic
toyota
traci
tracie
tracy
trails
transfer
trisha
trivial
trombone
tty
tubas
tuttle
umesh
unhappy
unicorn
unix
unknown
uranus
urchin
ursula
util
utility
uucp
valerie
vasant
venus
veronica
vertigo
vicky
village
virgin
virginia
visitor
wargames
warren
water
weenie
wendi
wendy
whatever
whatnot
whiting
whitney
wholesale
will
william
williamsburg
willie
wilma
winston
wisconsin
wizard
wombat
woodwind
word
work
wormwood
wyoming
xfer
xmodem
xyz
xyzzy
yaco
yang
yellowstone
yolanda
yosemite
zap
zimmerman
zmodem |
print "Starting up AP..."
local ap_config = {}
local ip_config = {}
ap_config.ssid = "ESP-"..node.chipid()
ap_config.pwd = "ESP-"..node.chipid()
ip_config.ip = "192.168.1.1"
ip_config.netmask = "255.255.255.0"
ip_config.gateway = "192.168.1.1"
wifi.setmode(wifi.SOFTAP)
print('SSID:', ap_config.ssid)
wifi.ap.config(ap_config)
wifi.ap.setip(ip_config)
print "AP configured."
print "Configuring other hardware..."
relay_pin = 1
gpio.write(relay_pin, gpio.LOW)
gpio.mode(relay_pin, gpio.OUTPUT)
print "Starting telnet server..."
soft_armed = false
firing = false
telnet_srv = net.createServer(net.TCP, 180)
telnet_srv:listen(2323, function(socket)
local fifo = {}
local fifo_drained = true
local connected = false
local function sender(c)
if #fifo > 0 then
c:send(table.remove(fifo, 1))
else
fifo_drained = true
end
end
local function send(str)
table.insert(fifo, str)
if socket ~= nil and fifo_drained then
fifo_drained = false
sender(socket)
end
end
socket:on("receive", function(connection, line) -- receives a single line from the client
if string.sub(line, 1, 7) == "softarm" then
send("soft arming in 10 seconds...\n")
tmr.alarm(0, 10000, tmr.ALARM_SINGLE, function()
soft_armed = true
end)
elseif string.sub(line, 1, 6) == "disarm" then
soft_armed = false
send("disarmed.\n")
elseif string.sub(line, 1, 6) == "status" then
if soft_armed then
send("soft armed: true. ")
else
send("soft armed: false. ")
end
if firing then
send("firing: true.")
else
send("firing: false.")
end
send("\n")
elseif string.sub(line, 1, 7) == "firenow" then
if soft_armed then
send("firing for five seconds now!\n")
firing = true
tmr.alarm(1, 5000, tmr.ALARM_SINGLE, function()
gpio.write(relay_pin, gpio.LOW)
firing = false
end)
gpio.write(relay_pin, gpio.HIGH)
else
send("unable to fire, not yet armed.\n")
end
else
send("command unknown.\n")
end
if soft_armed then
send("# ")
else
send("> ")
end
end)
socket:on("sent", sender)
end)
|
wAchievement, imgAchievement, lTitle, lDesc = nil
function displayAchievement(id)
local name, description, points = unpack(getAchievementInfo(id))
local width, height = 600, 100
local scrWidth, scrHeight = guiGetScreenSize()
local x = scrWidth/2 - (width/2)
local y = scrHeight - (scrHeight/6 - (height/6))
wAchievement = guiCreateWindow(x, y, width, height, "Achievement Unlocked!", false)
imgAchievement = guiCreateStaticImage(0.025, 0.25, 0.15, 0.7, "achievement.png", true, wAchievement)
lTitle = guiCreateLabel(0.2, 0.25, 0.6, 0.2, tostring(name) .. " (" .. points .. " Points)", true, wAchievement)
guiSetFont(lTitle, "default-bold-small")
guiLabelSetHorizontalAlign(lTitle, "center")
lDesc = guiCreateLabel(0.2, 0.45, 0.6, 0.2, tostring(description), true, wAchievement)
guiLabelSetHorizontalAlign(lDesc, "center")
playSoundFrontEnd(101)
guiSetAlpha(wAchievement, 0)
setTimer(fadeWindowIn, 50, 15, wAchievement)
setTimer(fadeWindowOutStart, 8000, 1, wAchievement)
end
addEvent("onPlayerGetAchievement", true)
addEventHandler("onPlayerGetAchievement", getRootElement(), displayAchievement)
function fadeWindowIn(window)
local alpha = guiGetAlpha(window)
local newalpha = alpha + 0.05
guiSetAlpha(window, newalpha)
end
function fadeWindowOutStart(window)
setTimer(fadeWindowOut, 50, 15, window)
end
function fadeWindowOut(window)
local alpha = guiGetAlpha(window)
local newalpha = alpha - 0.05
guiSetAlpha(window, newalpha)
if (newalpha<=0) then
destroyElement(wAchievement)
wAchievement, imgAchievement, lTitle, lDesc = nil, nil, nil, nil
end
end |
local TestLayer = require("graphic.test.TestLayer")
local TestMaskLayer = class("TestMaskLayer", TestLayer)
function TestMaskLayer:ctor()
TestLayer.ctor(self)
end
function TestMaskLayer:init()
TestLayer.init(self)
self:customLayout()
end
function TestMaskLayer:guideMask()
local rect = self._imageGo:GetComponent(typeof(RectTransform))
local p = g_2dTools:pointLocalToScreen(self._imageGo, rect.rect.position)
local s = g_2dTools:sizeLocalToScreen(self._imageGo, rect.rect.size)
local r = Rect(p.x, p.y, s.x, s.y)
-- event.broadcast(event.ui.showMask, {rect=r, callback=function() print("x") end})
--上面是正方形, 下面是菱形
local points = {}
points[1] = Vector2(r.x + r.width/2, r.y)
points[2] = Vector2(r.x + r.width, r.y + r.height/2)
points[3] = Vector2(r.x + r.width/2, r.y + r.height)
points[4] = Vector2(r.x, r.y + r.height/2)
event.broadcast(event.ui.showMask, {points=points})
end
function TestMaskLayer:customLayout()
self:createButtonWithText(self._go.transform, "Click", Vector2(0,100), Vector2(122,62), handler(self, self.guideMask))
self._imageGo = self:createImage(self._go.transform, "", Vector2(-50,50), Vector2(200,200), true)
end
return TestMaskLayer
|
--[[
this system manages the health for entities. if an
entity runs out of health, it's marked for removal.
]]
local health = {}
function health:collide(e, other)
--[[
make sure both entities have health. otherwise, this
system shouldn't operate on them.
]]
if not self.pool.groups.health.hasEntity[e] then return false end
if not self.pool.groups.health.hasEntity[other] then return false end
-- bullets shouldn't damage each other
if e.isBullet and other.isBullet then return false end
-- two entities that are both good or both evil shouldn't damage each other
if e.isEvil == other.isEvil then return false end
-- decrease health and kill the entity if health reaches 0
e.health = e.health - other.damage
if e.health <= 0 then
self.pool:emit('die', e) -- emit a "die" event that other systems can respond to
e.dead = true
end
end
return health
|
local awful = require("awful")
local OrderedClientStartup = {}
-- Structure per app:
-- { cmd="command" , tag = t , screen = s, geo={x=x0, y=y0, w=w0, h=h0} }
OrderedClientStartup.my_apps = {}
-- Nested callbacks to ensure the applications' respective clients spawn
-- in the correct order and are then moved to the correct tab in
-- that order
function OrderedClientStartup:begin_startup()
local i = 1 -- start at first index
local callback
callback = function(c)
-- set correct focus, just in case
if(OrderedClientStartup.my_apps[i].screen) then
awful.screen.focus(OrderedClientStartup.my_apps[i].screen)
end
-- move client to correct tag
if(OrderedClientStartup.my_apps[i].tag) then
OrderedClientStartup.my_apps[i].tag:view_only()
c:move_to_tag(OrderedClientStartup.my_apps[i].tag)
end
-- set correct position, if provided
if(OrderedClientStartup.my_apps[i].geo) then
local geo = OrderedClientStartup.my_apps[i].geo
c:geometry({x = geo.x, y = geo.y,
width = geo.w, height = geo.h})
end
-- continue if more apps to launch
if(i < #(OrderedClientStartup.my_apps)) then
i = i + 1
awful.spawn.with_shell(OrderedClientStartup.my_apps[i].cmd)
else
-- set focus back to your primary screen/tab
for s in screen do
s.tags[1]:view_only()
end
awful.screen.focus(screen[1] or screen)
client.disconnect_signal("manage", callback)
end
end
-- launch first app to get this started
client.connect_signal("manage", callback)
awful.spawn.with_shell(OrderedClientStartup.my_apps[i].cmd)
end
-- adds an application to launch
-- i : client will be the i-th app launched
-- cm : command of application to be execute
-- eg "firefox"
-- t : tag to spawn the client on
-- eg screen[2].tag[2]
-- s : screen the client should launch on
-- eg screen[1]
-- geo : position and dimensions of client (optional)
-- eg {x=0, y=0, w=1000, h=640}
function OrderedClientStartup:add_app(i,cm,t,s,g)
OrderedClientStartup.my_apps[i] = { cmd = cm, tag = t, screen = s, geo=g }
end
return OrderedClientStartup
|
--トリシューラの鼓動
--
--Script by 龙骑
function c100340055.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_REMOVE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,100340055)
e1:SetTarget(c100340055.target)
e1:SetOperation(c100340055.activate)
c:RegisterEffect(e1)
--disable
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_DISABLE)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_CHAINING)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1,100340205)
e2:SetCondition(c100340055.discon)
e2:SetCost(aux.bfgcost)
e2:SetOperation(c100340055.disop)
c:RegisterEffect(e2)
end
function c100340055.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x2f) and c:IsType(TYPE_SYNCHRO)
end
function c100340055.target(e,tp,eg,ep,ev,re,r,rp,chk)
local g=Duel.GetMatchingGroup(c100340055.cfilter,tp,LOCATION_MZONE,0,1,nil)
local ct=g:GetClassCount(Card.GetCode)
if chk==0 then return ct>=1 and Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,0,LOCATION_ONFIELD,1,nil)
and (ct<2 or Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,1,nil))
and (ct<3 or Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,0,LOCATION_HAND,1,nil)) end
local rct=1
local loc=LOCATION_ONFIELD
if ct>=2 then
rct=rct+1
loc=loc+LOCATION_GRAVE
end
if ct>=3 then
rct=rct+1
loc=loc+LOCATION_HAND
end
Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,rct,0,loc)
end
function c100340055.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g=Duel.GetMatchingGroup(c100340055.cfilter,tp,LOCATION_MZONE,0,nil)
local ct=g:GetClassCount(Card.GetCode)
if ct>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToRemove,tp,0,LOCATION_ONFIELD,1,1,nil)
if g:GetCount()>0 then
Duel.HintSelection(g)
Duel.Remove(g,POS_FACEUP,REASON_EFFECT)
end
end
if ct>1 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,1,1,nil)
if g:GetCount()>0 then
Duel.Remove(g,POS_FACEUP,REASON_EFFECT)
end
end
if ct>2 then
local g=Duel.GetMatchingGroup(Card.IsAbleToRemove,tp,0,LOCATION_HAND,nil)
if g:GetCount()>0 then
local sg=g:RandomSelect(tp,1)
Duel.Remove(sg,POS_FACEUP,REASON_EFFECT)
end
end
end
function c100340055.tfilter(c,tp)
return c:IsOnField() and c:IsControler(tp) and c:IsSetCard(0x2f) and c:IsType(TYPE_SYNCHRO)
end
function c100340055.discon(e,tp,eg,ep,ev,re,r,rp)
if ep==tp then return false end
if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return false end
local tg=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
return tg and tg:IsExists(c100340055.tfilter,1,nil,tp) and Duel.IsChainDisablable(ev)
end
function c100340055.disop(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateEffect(ev)
end
|
object_static_item_item_component_configuration_module = object_static_item_shared_item_component_configuration_module:new {
}
ObjectTemplates:addTemplate(object_static_item_item_component_configuration_module, "object/static/item/item_component_configuration_module.iff")
|
--imports--
local api = require"novus.api"
local util = require"novus.snowflakes.helpers"
local snowflake = require"novus.snowflakes"
local const = require"novus.const"
local cqueues = require"cqueues"
local null = require"cjson".null
local setmetatable = setmetatable
local gettime = cqueues.monotime
local running = cqueues.running
local snowflakes = snowflake.snowflakes
--start-module--
local _ENV = snowflake "emoji"
schema {
"guild_id"
,"name"
,"roles"
,"user_id"
,"require_colons"
,"managed"
,"animated"
}
function processor.user(user, state)
local uid
if user then
uid = util.uint(user.id)
if not state.cache.user[uid] then
snowflakes.user.new_from(state, user)
end
end
return uid, "user_id"
end
function new_from(state, payload)
return setmetatable({
util.uint(payload.id)
,gettime()
,state.cache.methods.emoji
,payload.guild_id
,payload.name
,payload.roles or {}
,processor.user(payload.user, state)
,payload.require_colons
,payload.managed
,payload.animated
}, _ENV)
end
function modify(emoji, by)
local state = running():novus()
local success, data, err = api.modify_guild_emoji(state.api, emoji[4], emoji[1], by)
if success and data then
return update_from(state, emoji, data)
else
return false, err
end
end
function methods.set_name(emoji, name)
return modify(emoji, {name = name or null})
end
function methods.set_roles(emoji, roles)
return modify(emoji, {roles = roles or null})
end
function methods.delete(emoji)
local state = running():novus()
if emoji[4] then
local success, data, err = api.delete_guild_emoji(state.api, emoji[4], emoji.id)
if success and data then
emoji:destroy()
return true
else
return false, err
end
end
end
function methods.has_role(emoji, id)
return util.includes(emoji[6], id)
end
function properties.guild(emoji)
return emoji[4] and snowflakes.guild.get(emoji[4])
end
function properties.url(emoji)
return const.api.emoji_endpoint % {emoji.id, emoji[10] and 'gif' or 'png'}
end
function properties.nonce(emoji)
return emoji[5] .. ":" .. emoji.id
end
function properties.mention(emoji)
return (emoji[10] and "<a:%s>" or "<:%s>") % emoji.nonce
end
function properties.role_objects(emoji)
return view.new(running():novus().cache.role, function(key, value, s)
return includes(s, key) and value
end, emoji[6])
end
function get_from(state, guild_id, id)
local cache = state.cache[__name]
if cache[id] then return cache[id]
else
local success, data, err = api.get_guild_emoji(state.api, guild_id, id)
if success then
data.guild_id = guild_id
return new_from(state, data)
else
return nil, err
end
end
end
--end-module--
return _ENV |
--[[
© 2020 TERRANOVA do not share, re-distribute or modify
without permission of its author.
--]]
local PANEL = {}
function PANEL:Init()
self.stagePanels = {}
end
function PANEL:AddStagePanel(name, dType)
local id = #self.stagePanels + 1;
local panel = self:Add(dType or "DPanel");
panel:Dock(FILL);
panel:SetVisible(false);
panel:DockMargin(4,4,4,4)
panel.OnSetActive = function() end
self.stagePanels[id] = {}
self.stagePanels[id].panel = panel;
self.stagePanels[id].subpanelName = name;
return panel;
end;
function PANEL:SetActivePanel(name)
for i = 1, #self.stagePanels do
local selectedPanel = self.stagePanels[i].subpanelName == name
if(self.stagePanels[i].button) then
self.stagePanels[i].button:Rebuild(selectedPanel)
end
if(selectedPanel) then
self.stagePanels[i].panel:SetVisible(true);
self.stagePanels[i].panel:OnSetActive();
else
self.stagePanels[i].panel:SetVisible(false);
end;
end;
end;
function PANEL:AddStageButton(text, stage)
local index = 0
for i = 1, #self.stagePanels do
if(self.stagePanels[i].subpanelName == stage) then
index = i
break
end
end
if(index != 0) then
local button = self:Add("DButton")
button:Dock(LEFT)
button:SetFont("ixSmallFont")
button:SetText(text)
button:SetVisible(true)
button.DoClick = function()
self:SetActivePanel(stage);
end;
function button:Rebuild(selected)
if(selected) then
button.PaintOver = function()
surface.SetDrawColor(button.selectedColor or Color(100, 170, 220, 80))
surface.DrawRect(0, 0, self:GetWide(), self:GetTall())
end
else
button.PaintOver = nil
end
end
self.stagePanels[index].button = button
return button
end
Error("Error creating stage button because the stage doesn't exist.")
return nil
end
function PANEL:AddLabel(text, colored, title)
local label = self:Add("DLabel")
local font = "ixInfoPanelFont"
if(title) then
font = "ixInfoPanelTitleFont"
end
if(colored) then
label:SetTextColor(ix.config.Get("color"))
end
label:SetFont(font)
label:SetText(text)
label:SizeToContents()
label:Dock(TOP)
label:DockMargin(4, 4, 4, 4)
return label
end
function PANEL:Paint()
ix.util.DrawBlur(self, 10)
surface.SetDrawColor(30, 30, 30, 150)
surface.DrawRect(0, 0, self:GetWide(), self:GetTall())
surface.SetDrawColor(Color(100, 170, 220, 80))
surface.DrawOutlinedRect(0, 0, self:GetWide(), self:GetTall())
end
function PANEL:SetVisible(visible)
if(visible) then
self:AlphaTo(255, 0.5)
else
self:AlphaTo(0, 0.5)
end
end
function PANEL:AddTextEntry(payloadName)
local entry = self:Add("DTextEntry")
entry:Dock(TOP)
entry:SetFont("ixPluginCharButtonFont")
entry.Paint = self.PaintTextEntry
entry:DockMargin(0, 4, 0, 16)
entry.OnValueChange = function(_, value)
end
entry.payloadName = payloadName
entry.OnKeyCodeTyped = function(name, keyCode)
if (keyCode == KEY_TAB) then
entry:onTabPressed()
return true
end
end
entry:SetUpdateOnType(true)
return entry
end
-- self refers to the text entry
function PANEL:PaintTextEntry(w, h)
surface.SetDrawColor(0, 0, 0, 100)
surface.DrawRect(0, 0, w, h)
self:DrawTextEntryText(color_white, HIGHLIGHT, HIGHLIGHT)
end
vgui.Register("ixStagePanel", PANEL, "DPanel") |
local init = require("test_setup")()
local ffi = require("ffi")
local int = ffi.typeof("int")
local int_a = ffi.typeof("int[?]")
--local a = ffi.new("int[1]");
local a = int_a(1);
printf("Enter integer\n");
scanf("%d", a);
printf("Integer that you have entered is %d\n", int(a[0]));
|
-- lua-MessagePack 0.5.1
-- Copyright (c) 2012-2018 Francois Perrad"
-- licensed under the terms of the MIT/X11 license
-- thanks :)
local floor = require'math'.floor
local huge = require'math'.huge
local ldexp = require'math'.ldexp or require'mathx'.ldexp
return function (s)
if #s < 4 then
error "missing bytes"
end
local b1, b2, b3, b4 = s:sub(1, 4):byte(1, 4)
local sign = b1 > 0x7F
local expo = (b1 % 0x80) * 0x2 + floor(b2 / 0x80)
local mant = ((b2 % 0x80) * 0x100 + b3) * 0x100 + b4
if sign then
sign = -1
else
sign = 1
end
local n
if mant == 0 and expo == 0 then
n = sign * 0.0
elseif expo == 0xFF then
if mant == 0 then
n = sign * huge
else
n = 0.0/0.0
end
else
n = sign * ldexp(1.0 + mant / 0x800000, expo - 0x7F)
end
return n
end
|
assert(truc == 5);
local l = require("some.thing");
assert(l.truc == 10);
|
--[[
Autoinstall plugin
Licensed by Creative Commons Attribution-ShareAlike 4.0
http://creativecommons.org/licenses/by-sa/4.0/
Dev: TheHeroeGAC
Designed By Gdljjrod & DevDavisNunez.
Collaborators: BaltazaR4 & Wzjk.
]]
dofile("lang/Langdatabase.lua")--Official
function update_database(database,tb)
local file = io.open(database, "w+")
file:write("Langs = {\n")
for s,t in pairs(tb) do
file:write(string.format('{ id = "%s", version = "%s", author = "%s" },\n', tostring(t.id), tostring(t.version), tostring(t.author)))
end
file:write("}\n")
file:close()
dofile("lang/Langdatabase.lua")--Official
load_translates()
end
function lang_online()
files.delete("ux0:data/AUTOPLUGIN2/lang/Langdatabase.lua")
files.delete("ux0:data/AUTOPLUGIN2/plugins/plugins.lua")
files.delete("ux0:data/AUTOPLUGIN2/plugins/plugins_psp.lua")
if back then back:blit(0,0) end
message_wait()
os.delay(500)
local tmpss = {}
__file = "Langdatabase.lua"
http.download(string.format("https://raw.githubusercontent.com/%s/%s/master/Translations/Langdatabase.lua", APP_REPO, APP_PROJECT), "ux0:data/AUTOPLUGIN2/lang/Langdatabase.lua")
if files.exists("ux0:data/AUTOPLUGIN2/lang/Langdatabase.lua") then
dofile("ux0:data/AUTOPLUGIN2/lang/Langdatabase.lua")
else
os.message(LANGUAGE["LANG_ONLINE_FAILDB"].."\n\n"..LANGUAGE["UPDATE_WIFI_IS_ON"])
return
end
local __flag = false
if #Online_Langs > 0 then
for i=1,#Langs do
for j=1,#Online_Langs do
if string.upper(Langs[i].id) == string.upper(Online_Langs[j].id) then
if tonumber(Langs[i].version) < tonumber(Online_Langs[j].version) then
--if os.message("bajar si o no ?\n"..Online_Langs[j].id,1) == 1 then
__file = Online_Langs[j].id
if http.download(string.format("https://raw.githubusercontent.com/%s/%s/master/%s/lang/%s.lua", APP_REPO, APP_PROJECT, APP_FOLDER, Online_Langs[j].id), "lang/"..Online_Langs[j].id..".lua").success then
if back2 then back2:blit(0,0) end
message_wait(LANGUAGE["STRING_INSTALLED"].."\n\n"..Online_Langs[j].id.."\n")
os.delay(1500)
Langs[i] = Online_Langs[j]
table.insert(tmpss,Langs[i])
__flag = true
end
end
end
end
end
else
os.message(LANGUAGE["LANG_ONLINE_FAILDB"])
return
end--Online_Langs > 0
local tmps = {}
for i=1,#Online_Langs do
local __find = false
for j=1,#Langs do
if string.upper(Online_Langs[i].id) == string.upper(Langs[j].id) then
__find = true
break
end
end
if not __find then
--if os.message("BBajar si o no ?\n"..Online_Langs[i].id,1) == 1 then
__file = Online_Langs[i].id
if http.download(string.format("https://raw.githubusercontent.com/%s/%s/master/%s/lang/%s.lua", APP_REPO, APP_PROJECT, APP_FOLDER, Online_Langs[i].id), "lang/"..Online_Langs[i].id..".lua").success then
if back2 then back2:blit(0,0) end
message_wait(LANGUAGE["STRING_INSTALLED"].."\n\n"..Online_Langs[i].id)
os.delay(1500)
table.insert(tmps, { line = i })
__flag = true
end
end
end
__file = ""
for i=1,#tmps do
table.insert( Langs, Online_Langs[tmps[i].line] )
Langs[#Langs].new = true
table.insert(tmpss,Langs[#Langs])
end
if __flag then
if #Langs > 1 then table.sort(Langs ,function (a,b) return string.lower(a.id)<string.lower(b.id) end) end
update_database("lang/Langdatabase.lua",Langs)
end
local maxim,y1 = 8,85
local scroll = newScroll(tmpss,maxim)
table.sort(tmpss ,function (a,b) return string.lower(a.id)<string.lower(b.id) end)
while true do
buttons.read()
if change then buttons.homepopup(0) else buttons.homepopup(1) end
if back then back:blit(0,0) end
draw.offsetgradrect(0,0,960,55,color.blue:a(85),color.blue:a(85),0x0,0x0,20)
screen.print(480,20,LANGUAGE["MENU_TITLE_LANG_ONLINE"],1.2,color.white,0x0,__ACENTER)
if scroll.maxim > 0 then
local y = y1
for i=scroll.ini,scroll.lim do
if i == scroll.sel then draw.offsetgradrect(17,y-12,938,40,color.shine:a(75),color.shine:a(135),0x0,0x0,21) end
screen.print(30,y, tmpss[i].id.." v "..tmpss[i].version, 1.2, color.white,0x0)
if tmpss[i].new then
screen.print(945,y,LANGUAGE["LANG_FILE_NEW"],1.2,color.green,0x0,__ARIGHT)
else
screen.print(945,y,LANGUAGE["LANG_FILE_UPDATE"],1.2,color.green,0x0,__ARIGHT)
end
y+= 45
end--for
--Bar Scroll
local ybar, h = y1-10, (maxim*45)-4
if scroll.maxim >= maxim then -- Draw Scroll Bar
draw.fillrect(3, ybar-3, 8, h, color.shine)
local pos_height = math.max(h/scroll.maxim, maxim)
draw.fillrect(3, ybar-2 + ((h-pos_height)/(scroll.maxim-1))*(scroll.sel-1), 8, pos_height, color.new(0,255,0))
end
else
screen.print(480,230, LANGUAGE["LANGUAGE_NO_UPDATE"], 1, color.white, color.red, __ACENTER)
end
if buttonskey then buttonskey:blitsprite(10,523,scancel) end
screen.print(45,525,LANGUAGE["STRING_BACK"],1,color.white,color.black, __ALEFT)
if buttonskey3 then buttonskey3:blitsprite(920,518,1) end
screen.print(915,522,LANGUAGE["STRING_CLOSE"],1,color.white,color.blue, __ARIGHT)
screen.flip()
--Exit
if buttons.start then
exit_bye_bye()
end
vol_mp3()
--Ctrls
if scroll.maxim > 0 then
if buttons.up or buttons.analogly < -60 then scroll:up() end
if buttons.down or buttons.analogly > 60 then scroll:down() end
end
if buttons.cancel then break end
end--while
end
|
local oo = require "oil.oo"
Collector = oo.class{}
function Collector:__init()
return oo.rawnew(self, { emails = {} })
end
local MailSent = {}
function Collector:send_to(email)
assert(type(email) == "string", "attempt to send message to address "..tostring(email))
assert(string.find(email, ".+@.+"), "attempt to send message to address "..tostring(email))
if MailSent[email]
then io.write(" ", email, " got ", MailSent[email], " duplicates ")
else io.write(".")
end
MailSent[email] = (MailSent[email] or 0) + 1
end
function Collector:request_mail()
print("\n=== Start mail session ========================")
MailSent = {}
end
function Collector:submit(paper)
self:request_mail()
for _, email in ipairs(self.emails) do
self:send_to(email, "New paper submitted")
end
for _, author in ipairs(paper.authors) do
table.insert(self.emails, author.email)
end
end
--------------------------------------------------------------------------------
require "oil"
oil.main(function()
require "adaptor"
orb:loadidl[[
struct Author {
string name;
string email;
};
typedef sequence<Author> AuthorSeq;
struct Paper {
string title;
AuthorSeq authors;
};
interface Collector {
void submit(in Paper paper);
};
]]
local c1 = orb:newservant(Collector(), nil, "Collector")
local c2 = orb:newservant(Collector(), nil, "Collector")
local c3 = orb:newservant(Collector(), nil, "Collector")
local adaptor = orb:newservant(Adaptor("Collector"), nil, "ComponentAdaptor")
oil.writeto("c1.ior" , orb:tostring(c1))
oil.writeto("c2.ior" , orb:tostring(c2))
oil.writeto("c3.ior" , orb:tostring(c3))
oil.writeto("adaptor.ior", orb:tostring(adaptor))
orb:run()
end)
|
--[[
EmuDevs <http://emudevs.com/forum.php>
Eluna Lua Engine <https://github.com/ElunaLuaEngine/Eluna>
Eluna Scripts <https://github.com/ElunaLuaEngine/Scripts>
Eluna Wiki <http://wiki.emudevs.com/doku.php?id=eluna>
-= Script Information =-
* Zone: Stormwind
* Script Type: Creature
* Creature: Jonathan (General Marcus Jonathan, Entry: 466)
* Version: tested on Zero
--]]
-- This creates the table used to localize all variables and functions
local Jonathan = {
EMOTE_RECEIVE_WAVE = 101, -- wave emote from player character
EMOTE_RECEIVE_SALUTE = 78, -- salute emote from player character
EMOTE_SEND_SALUTE = 66, -- salute emote by creature
ID = 466 -- creature_template Entry for General Marcus Jonathan
}
-- handle the incoming emotes
function Jonathan.OnReceiveEmote(event, creature, player, emoteid)
if (emoteid == Jonathan.EMOTE_RECEIVE_WAVE) then
creature:SendUnitSay("Greetings, citizen.",7);
elseif (emoteid == Jonathan.EMOTE_RECEIVE_SALUTE) then
creature:Emote(Jonathan.EMOTE_SEND_SALUTE);
end
end
-- Register the event
RegisterCreatureEvent(Jonathan.ID, 8, Jonathan.OnReceiveEmote)
-- for more creature events: http://wiki.emudevs.com/doku.php?id=eluna_creature_events
-- for other in-game events: http://wiki.emudevs.com/doku.php?id=eluna
|
local _, G = ...
local cvars = {
alwaysShowActionBars = 0,
autoClearAFK = 1,
autointeract = 0,
autoLootDefault = 1,
autoQuestWatch = 1,
autoSelfCast = 1,
blockChannelInvites = 0,
blockTrades = 0,
cameraDistanceMaxZoomFactor = 2.6,
chatBubbles = 1,
chatBubblesParty = 0,
chatStyle = 'classic',
countdownForCooldowns = 0,
deselectOnClick = 0,
doNotFlashLowHealthWarning = 0,
enableFloatingCombatText = 1,
ffxDeath = 0,
floatingCombatTextAuraFade = 1,
floatingCombatTextAuras = 1,
floatingCombatTextCombatDamage = 1,
floatingCombatTextCombatLogPeriodicSpells = 1,
floatingCombatTextCombatState = 1,
floatingCombatTextComboPoints = 1,
floatingCombatTextDamageReduction = 1,
floatingCombatTextDodgeParryMiss = 1,
floatingCombatTextEnergyGains = 1,
floatingCombatTextFloatMode = 1,
floatingCombatTextFriendlyHealers = 0,
floatingCombatTextHonorGains = 1,
floatingCombatTextLowManaHealth = 1,
floatingCombatTextPetMeleeDamage = 1,
floatingCombatTextPetSpellDamage = 1,
floatingCombatTextReactives = 1,
floatingCombatTextRepChanges = 1,
guildMemberNotify = 1,
hideOutdoorWorldState = 0,
instantQuestText = 1,
interactOnLeftClick = 0,
lockActionBars = 0,
lootUnderMouse = 0,
multiBarRightVerticalLayout = 0,
nameplateMaxDistance = 41,
nameplateMotion = 0,
nameplateShowAll = 1,
nameplateShowEnemies = 1,
nameplateShowEnemyMinions = 1,
nameplateShowEnemyMinus = 1,
nameplateShowFriends = 0,
nameplateShowFriendlyMinions = 1,
profanityFilter = 0,
raidOptionIsShown = 0,
rotateMinimap = 0,
scriptErrors = 1,
showLoadingScreenTips = 1,
showLootSpam = 1,
showMinimapClock = 0,
showNewbieTips = 0,
showTargetOfTarget = 0,
showTimestamps = 'none',
showToastBroadcast = 0,
showToastFriendRequest = 1,
showToastOffline = 1,
showToastOnline = 1,
showToastWindow = 0,
showTutorials = 0,
Sound_AmbienceVolume = 0.9,
Sound_DialogVolume = 0.9,
Sound_EnableAllSound = 1,
Sound_EnableAmbience = 1,
Sound_EnableDialog = 1,
Sound_EnableEmoteSounds = 1,
Sound_EnableErrorSpeech = 0,
Sound_EnableMusic = 1,
Sound_EnablePetSounds = 1,
Sound_EnableSFX = 1,
Sound_EnableSoundWhenGameIsInBG = 0,
Sound_MasterVolume = 0.2,
Sound_MusicVolume = 0.6,
Sound_SFXVolume = 0.9,
Sound_ZoneMusicNoDelay = 1,
spamFilter = 1,
statusText = 1,
statusTextDisplay = 'NUMERIC',
taintlog = 1,
UnitNameEnemyMinionName = 1,
UnitNameEnemyPlayerName = 1,
UnitNameFriendlyMinionName = 1,
UnitNameFriendlyPlayerName = 1,
UnitNameNonCombatCreatureName = 0,
UnitNameNPC = 0,
UnitNameOwn = 0,
UnitNamePlayerGuild = 1,
UnitNamePlayerPVPTitle = 1,
whisperMode = 'inline',
}
G.Eventer({
VARIABLES_LOADED = function()
for k, v in pairs(cvars) do
SetCVar(k, v)
end
SetConsoleKey('F12')
C_Timer.After(15, function()
hooksecurefunc('SetCVar', function(key, value)
print('SetCVar('..key..','..value..')')
end)
end)
end,
})
|
-- from Original keyboard mod by bas080
-- Cracked by jogag -> cracked by juli from digilines to rc
-- Added features: useable with rc mod
local RC_RADIUS = 5
minetest.register_node("rc_keyboard:rc_keyboard", {
description = "rc_keyboard",
tiles = {"rc_keyboard_top.png", "rc_keyboard_bottom.png", "rc_keyboard_side.png", "rc_keyboard_side.png", "rc_keyboard_side.png", "rc_keyboard_side.png"},
walkable = true,
paramtype = "light",
paramtype2 = "facedir",
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
{-4/8, -4/8, 0, 4/8, -3/8, 4/8},
},
},
selection_box = {
type = "fixed",
fixed = {
{-4/8, -4/8, 0, 4/8, -3/8, 4/8},
},
},
groups = {choppy = 3, dig_immediate = 2},
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec", "field[x;X;]" ..
"field[y;Y;]" ..
"field[z;Z;]" )
meta:set_string("infotext", "rc_keyboard")
meta:set_int("lines", 0)
end,
on_receive_fields = function(pos, formname, fields, sender)
local meta = minetest.get_meta(pos)
local x = meta:get_int("x")
local y = meta:get_int("y")
local z = meta:get_int("z")
if tonumber(fields.x) and tonumber(fields.y) and tonumber(fields.z) then
meta:set_int("x", tonumber(fields.x))
meta:set_int("y", tonumber(fields.y))
meta:set_int("z", tonumber(fields.z))
meta:set_string("formspec", "field[text;Enter text;]")
elseif fields.text then
rc.send(RC_RADIUS, pos, {x=x,y=y,z=z}, fields.text, sender:get_player_name())
end
end,
})
|
-- a quick access status screen
-- originally written by enjia2000@gmail.com (stolencatkarma)
--[====[
gui/dfstatus
============
Show a quick overview of critical stock quantities, including food, drinks, wood, and various bars.
Sections can be enabled/disabled/configured by editing :file:`dfhack-config/dfstatus.lua`.
]====]
local gui = require 'gui'
function warn(msg)
dfhack.color(COLOR_LIGHTRED)
print(msg)
dfhack.color(nil)
end
config = {
flags = {
drink = true,
wood = true,
fuel = true,
prepared_meals = true,
tanned_hides = true,
cloth = true,
metals = true,
},
metal_ids = {},
}
function parse_config()
local metal_map = {}
for id, raw in pairs(df.global.world.raws.inorganics) do
if raw.material.flags.IS_METAL then
metal_map[raw.id:upper()] = id
metal_map[id] = raw.id:upper()
end
end
local function add_metal(...)
for _, m in pairs({...}) do
id = metal_map[tostring(m):upper()]
if id ~= nil then
table.insert(config.metal_ids, id)
elseif m == '-' then
table.insert(config.metal_ids, '-')
else
warn('Invalid metal: ' .. tostring(m))
end
end
return add_metal
end
local env = {}
setmetatable(env, {
__index = function(_, k)
if k == 'metal' or k == 'metals' then
return add_metal
elseif k == 'flags' then
return config.flags
else
error('unknown name: ' .. k, 2)
end
end,
__newindex = function(_, k, v)
if config.flags[k] ~= nil then
if v ~= nil then
config.flags[k] = v
else
config.flags[k] = false
end
else
error('unknown flag: ' .. k, 2)
end
end,
})
local f, err = loadfile('dfhack-config/dfstatus.lua', 't', env)
if not f then
qerror('error loading config: ' .. err)
end
local ok, err = pcall(f)
if not ok then
qerror('error parsing config: ' .. err)
end
end
function getInorganicName(id)
return (df.inorganic_raw.find(id).material.state_name.Solid:gsub('^[a-z]', string.upper))
end
dfstatus = defclass(dfstatus, gui.FramedScreen)
dfstatus.ATTRS = {
frame_style = gui.GREY_LINE_FRAME,
frame_title = 'dfstatus',
frame_width = 16,
frame_height = 17,
frame_inset = 1,
focus_path = 'dfstatus',
}
function dfstatus:init()
self.text = {}
self.start = 1
local function write(line)
table.insert(self.text, line)
-- ensure that the window is wide enough for this line plus a scroll arrow
if #line + 1 > self.frame_width then
self.frame_width = #line + 1
end
end
local function newline() write('') end
local f = config.flags
local drink = 0
local wood = 0
local fuel = 0
local prepared_meals = 0
local tanned_hides = 0
local cloth = 0
local metals = {}
for _, id in pairs(config.metal_ids) do
metals[id] = 0
end
for _, item in ipairs(df.global.world.items.all) do
if not item.flags.rotten and not item.flags.dump and not item.flags.forbid then
if item:getType() == df.item_type.WOOD then
wood = wood + item:getStackSize()
elseif item:getType() == df.item_type.DRINK then
drink = drink + item:getStackSize()
elseif item:getType() == df.item_type.SKIN_TANNED then
tanned_hides = tanned_hides + item:getStackSize()
elseif item:getType() == df.item_type.CLOTH then
cloth = cloth + item:getStackSize()
elseif item:getType() == df.item_type.FOOD then
prepared_meals = prepared_meals + item:getStackSize()
elseif item:getType() == df.item_type.BAR then
if item:getMaterial() == df.builtin_mats.COAL then
fuel = fuel + item:getStackSize()
elseif item:getMaterial() == df.builtin_mats.INORGANIC then
local mat_idx = item:getMaterialIndex()
if metals[mat_idx] ~= nil then
metals[mat_idx] = metals[mat_idx] + item:getStackSize()
end
end
end
end
end
if f.drink then
write("Drinks: " .. drink)
end
if f.prepared_meals then
write("Meals: " .. prepared_meals)
end
if f.drink or f.prepared_meals then
newline()
end
if f.wood then
write("Wood: " .. wood)
end
if f.fuel then
write("Fuel: " .. fuel)
end
if f.wood or f.fuel then
newline()
end
if f.tanned_hides then
write("Hides: " .. tanned_hides)
end
if f.cloth then
write("Cloth: " .. cloth)
end
if f.tanned_hides or f.cloth then
newline()
end
if f.metals then
write("Metal bars:")
for _, id in pairs(config.metal_ids) do
if id == '-' then
newline()
else
write(' ' .. ('%-10s'):format(getInorganicName(id) .. ': ') .. metals[id])
end
end
end
self.start_min = 1
self.start_max = #self.text - self.frame_height + 1
end
function dfstatus:onRenderBody(dc)
dc:pen(COLOR_LIGHTGREEN)
for id, line in pairs(self.text) do
if id >= self.start then
dc:string(line):newline()
end
end
dc:pen(COLOR_LIGHTCYAN)
if self.start > self.start_min then
dc:seek(self.frame_width - 1, 0):char(24)
end
if self.start < self.start_max then
dc:seek(self.frame_width - 1, self.frame_height - 1):char(25)
end
end
function dfstatus:onInput(keys)
if keys.LEAVESCREEN or keys.SELECT then
self:dismiss()
scr = nil
elseif keys.STANDARDSCROLL_UP then
self.start = math.max(self.start - 1, self.start_min)
elseif keys.STANDARDSCROLL_DOWN then
self.start = math.min(self.start + 1, self.start_max)
end
end
if not scr then
parse_config()
scr = dfstatus()
scr:show()
else
scr:dismiss()
scr = nil
end
|
UIBase = {}
UIBase.__index = UIBase
function UIBase:GetControl(typeName, uri)
return self.Controller:GetControl(typeName, uri)
end
function UIBase:GetUIText(uri)
local text = self:GetControl("UnityEngine.UI.Text", uri)
return text
end
function UIBase:GetUIButton(uri)
local btn = self:GetControl("UnityEngine.UI.Button", uri)
return btn
end
return UIBase
|
SIM2D.TYPE.HEXBTN = "hexbtn";
local tSim2D = Sim2D.__properties;
class "HexBtn" : extends(Btn) {
__construct = function(this, sState, sName, nX, nY, nWidth, nHeight, nStratum, nLayer, bDoNotPoll, bDoNotAutoDraw)
--create the hex size and center point based on the rectangle
local nSize = nHeight / 2;
local nCenterX = nX + nWidth / 2;
local nCenterY = nY + nSize;
local oHexPoint = point(nCenterX, nCenterY);
local oHex = hex(oHexPoint, nSize);
this:super(sState, sName, oHex, nStratum, nLayer, bDoNotPoll, bDoNotAutoDraw);
--this:__fields();--get the shared, quasi-protected fields
end,
}
return HexBtn;
|
function onCreate()
-- background
makeLuaSprite('sky', 'midnight/midnightBG', -120, -50)
setLuaSpriteScrollFactor('sky', 0.1, 0.1);
addLuaSprite('sky', false);
--bg limos
makeAnimatedLuaSprite('midnightbgLimo', 'midnight/midnightbgLimo', -150, 480)
setLuaSpriteScrollFactor('midnightbgLimo', 0.4, 0.4);
addAnimationByPrefix('midnightbgLimo', 'anim', 'BG limo0', 24, true)
addLuaSprite('midnightbgLimo', false);
--other limo??
makeAnimatedLuaSprite('midnightlimoDrive', 'midnight/midnightlimoDrive', -120, 550)
setLuaSpriteScrollFactor('midnightlimoDrive', 1, 1);
addAnimationByPrefix('midnightlimoDrive', 'anim', 'Limo stage0', 24, true)
addLuaSprite('midnightlimoDrive', false);
end |
-- Convert HSL (hue saturation lightness) to RGB (red green blue)
-- Original code by John Chin-Jew/Wavalab:
-- https://github.com/Wavalab/rgb-hsl-rgb
local base = require('modules.libraries.backend.base')
local colors = {}
function colors.hsl2hex(h, s, l, a)
a = a or 100
local r, g, b
h = (h / 360)
s = (s / 100)
l = (l / 100)
a = (a / 100)
if s == 0 then
r, g, b = l, l, l -- achromatic
else
local function hue2rgb(p, q, t)
if t < 0 then t = t + 1 end
if t > 1 then t = t - 1 end
if t < 1/6 then return p + (q - p) * 6 * t end
if t < 1/2 then return q end
if t < 2/3 then return p + (q - p) * (2/3 - t) * 6 end
return p
end
local q
if l < 0.5 then q = l * (1 + s) else q = l + s - l * s end
local p = 2 * l - q
r = hue2rgb(p, q, h + 1/3)
g = hue2rgb(p, q, h)
b = hue2rgb(p, q, h - 1/3)
end
local out_r,out_b,out_g,out_a = nil,nil,nil,nil
out_r = string.format('%x', base.round(r * 255))
if #out_r < 2 then out_r = '0'..out_r end
out_g = string.format('%x', base.round(g * 255))
if #out_g < 2 then out_g = '0'..out_g end
out_b = string.format('%x', base.round(b * 255))
if #out_b < 2 then out_b = '0'..out_b end
if a and a ~= 100 then
out_a = string.format('%x', base.round(a * 255))
if #out_a < 2 then out_a = '0'..out_a end
end
local out = ''
out = out_r .. out_g .. out_b
return tostring('#'..out)
end
return colors |
ArtNumLayout = class("ArtNumLayout", function ()
return ccui.Layout:create()
end)
ArtNumLayout.ctor = function (slot0)
slot0._numArr = nil
slot0._prefix = ""
slot0._layout = ccui.Layout:create()
slot0._isVisible = true
slot0:addChild(slot0._layout)
slot0:retain()
end
ArtNumLayout.setText = function (slot0, slot1, slot2, slot3, slot4)
slot0._numArr = slot1
slot0._prefix = slot2
slot0._spaceWidth = slot4 or 0
if not slot0:isVisible() then
return
end
if slot3 then
anlMgr:put(slot0)
else
slot0:render()
end
end
ArtNumLayout.render = function (slot0)
slot0._layout:removeAllChildren()
if slot0._numArr == "" then
return
end
slot1 = 0
slot2 = 0
slot3 = 0
slot4 = 0
for slot8 = 1, #slot0._numArr, 1 do
slot11 = cc.Sprite:createWithSpriteFrameName(slot10)
slot11:setPosition(cc.p(slot1, slot2))
slot11:setAnchorPoint(cc.p(0, 0))
slot0._layout:addChild(slot11)
slot1 = slot1 + slot11:getContentSize().width + slot0._spaceWidth
if slot4 < slot11:getContentSize().height then
slot4 = slot11:getContentSize().height
end
end
slot0:setContentSize(cc.size(slot3, slot4))
slot0._layout:setContentSize(cc.size(slot1 - slot0._spaceWidth, slot4))
end
ArtNumLayout.isVisible = function (slot0)
return slot0._isVisible
end
ArtNumLayout.setVisible = function (slot0, slot1)
if slot1 ~= slot0:isVisible() and slot1 then
slot0:render()
end
slot0._layout:setVisible(slot1)
slot0._isVisible = slot1
end
ArtNumLayout.destroy = function (slot0)
slot0._isVisible = true
slot0._numArr = nil
slot0._layout:removeAllChildren()
slot0:removeFromParent()
slot0:release()
end
return
|
#!tools/lua
-- dumps contents of a tap file
local args = {...}
local filename = args[1]
if filename == nil then
print("Usage: dump_tap.lua <filename>")
return
end
local file = assert(io.open(filename, "rb"))
function printf(...)
print(string.format(...))
end
function fread_byte()
return string.byte(file:read(1))
end
function fread_short()
local lo = fread_byte()
local hi = fread_byte()
return lo | (hi << 8)
end
function compute_checksum(data)
local sum = 0
for i = 1, #data do
sum = sum ~ data:byte(i)
end
return sum
end
function read_header()
local header = {}
header.header_length = fread_short()
header.file_type = fread_byte()
header.filename = file:read(10)
header.file_length = fread_short()
header.start_address = fread_short()
header.link = fread_short()
header.current = fread_short()
header.context = fread_short()
header.voc_link = fread_short()
header.dict_data_end = fread_short()
header.header_checksum = fread_byte()
printf("Header:")
printf(" Header length %d", header.header_length)
printf(" File type %d", header.file_type)
printf(" Filename %s", header.filename)
printf(" File length %d", header.file_length)
printf(" Start address %04x", header.start_address)
printf(" Link %04x", header.link)
printf(" Current %04x", header.current)
printf(" Context %04x", header.context)
printf(" Voc link %04x", header.voc_link)
printf(" Data end %04x", header.dict_data_end)
printf(" Checksum %02x", header.header_checksum)
print()
return header
end
function dump_word(header, data, link)
local function read_byte(addr)
return data:byte(addr - header.start_address + 1)
end
local function read_short(addr)
local lo = read_byte(addr)
local hi = read_byte(addr + 1)
return lo | (hi << 8)
end
local function read_name(addr, count)
local str = ""
for i = addr, addr + count - 1 do
str = str .. string.char(read_byte(i) & 127)
end
return str
end
-- link points to the name length field
local word_length = read_short(link - 4)
local prev_word_link = read_short(link - 2)
local name_length = read_byte(link)
local name = read_name(link - 4 - name_length, name_length)
local code_field = read_short(link + 1)
local what = "???"
if code_field == 0x0ec3 then what = "do colon" end
if code_field == 0x0ff0 then what = "do param" end
if code_field == 0x0ff5 then what = "do constant" end
printf("Word %s", name)
printf("Word length %d", word_length)
printf("Code field %04x (%s)", code_field, what)
printf("Prev link %04x", prev_word_link)
print()
if prev_word_link >= 0x3c51 then
dump_word(header, data, prev_word_link)
end
end
local header = read_header()
local data_size = fread_short()
printf("Data size %d", data_size)
local data = file:read(data_size - 1)
local checksum = fread_byte()
printf("Data checksum %02x (computed checksum %02x)\n", checksum, compute_checksum(data))
dump_word(header, data, header.link)
file:close()
|
local Entity = {}
function Entity:new(x, y, width, height, drawable, debugColor)
local entity = {}
setmetatable(entity, self)
self.__index = self
entity.x = x or 0
entity.y = y or 0
entity.width = width or 1
entity.height = height or 1
entity.drawable = drawable or Drawable:new()
entity.debugColor = debugColor or Colors.WHITE
entity.children = {}
return entity
end
function Entity:getViewport()
return self.x, self.y, self.width, self.height
end
function Entity:update(dt)
self.drawable:update(dt)
for k, child in pairs(self.children) do
child:update(dt)
end
end
function Entity:setArea(x, y, width, height)
self.x = x
self.y = y
self.width = width
self.height = height
end
function Entity:draw()
self.drawable.color = self.debugColor
self.drawable:draw(self:getViewport())
for k, child in pairs(self.children) do
child:draw()
end
end
function Entity:addChild(child)
table.insert(self.children, child)
end
function Entity:removeChild(idx)
table.remove(self.children, idx)
end
return Entity
|
--
-- Mixpanel Example project
--
-- Sample code is MIT licensed
-- Copyright (C) 2017 Yoger Games AB. All Rights Reserved.
--
------------------------------------------------------------
-- Require plugin
local mixpanel = require "plugin.mixpanel"
local idMap = {}
local t = os.date( '*t' )
-------------------------------------------------------------------------------
-- Callback
-------------------------------------------------------------------------------
local function callback(event)
print("Callback received for event id " .. tostring(event.responseId) .. " (" .. tostring(idMap[event.responseId]) .. ")")
print("responseType: " .. tostring(event.responseType))
print("isError: " .. tostring(event.isError))
print("responseMsg: " .. tostring(event.responseMsg))
end
-------------------------------------------------------------------------------
-- Create button
-------------------------------------------------------------------------------
local widget = require( "widget" )
local function createButton(label, buttonCallback)
local button = widget.newButton(
{
label = label,
onEvent = function(event)
if event.phase == "began" then
buttonCallback()
end
end,
shape = "roundedRect",
width = display.actualContentWidth / 3.2,
height = display.actualContentWidth / 8,
cornerRadius = 2,
fillColor = { default={1,1,1,1}, over={1,0.8,0.11,1} },
strokeColor = { default={1,0.8,0.3,1}, over={1,0.8,0.3,1} },
strokeWidth = 2
}
)
button.anchorX, button.anchorY = 0.5, 0.5
return button
end
local columns = 2
local rows = 8
-------------------------------------------------------------------------------
-- Initialization
-------------------------------------------------------------------------------
local options = {
token = "<REPLACE WITH A PROJECT TOKEN>",
name = "test"
}
local test_project = mixpanel.init(options)
local options = {
token = "<REPLACE WITH A PROJECT TOKEN>",
name = "second_project"
}
mixpanel.init(options)
local second_project = mixpanel.getInstance("second_project")
-------------------------------------------------------------------------------
-- Set user identify for each project
-------------------------------------------------------------------------------
test_project:identify(system.getInfo("deviceID"))
second_project:identify(system.getInfo("deviceID"))
-------------------------------------------------------------------------------
-- Simple tracking event
-------------------------------------------------------------------------------
local function onExample1()
local id = test_project:track("New session", nil, nil, callback)
if (id) then
print("onExample1 (track) sent successfully. id: " .. tostring(id))
else
print("onExample1 (track) couldn't be sent")
end
idMap[id] = "onExample1"
end
local exampleButton1 = createButton("onExample1", onExample1)
exampleButton1.x = display.actualContentWidth / (columns+1)
exampleButton1.y = display.actualContentHeight / (rows+1)
-------------------------------------------------------------------------------
-- Tracking event with properties
-------------------------------------------------------------------------------
local function onExample2()
local mp_properties = mixpanel.properties.new()
mp_properties:insert(
{
Source = "Example app"
}
)
local id = test_project:track("Another event", mp_properties, nil, callback )
if (id) then
print("onExample2 (track) sent successfully. id: " .. tostring(id))
else
print("onExample2 (track) couldn't be sent")
end
idMap[id] = "onExample2"
end
local exampleButton2 = createButton("onExample2", onExample2)
exampleButton2.x = display.actualContentWidth * 2 / (columns+1)
exampleButton2.y = display.actualContentHeight / (rows+1)
-------------------------------------------------------------------------------
-- Setting default properties for tracking events
-------------------------------------------------------------------------------
local function onExample3()
test_project:register_track_properties(
{
Platform = system.getInfo("platform"),
["App name"] = system.getInfo("appName"),
["App version"] = system.getInfo("appVersionString"),
["Corona version"] = system.getInfo("build")
}
)
local id = test_project:track("Online", nil, nil, callback)
if (id) then
print("onExample3 (track) sent successfully. id: " .. tostring(id))
else
print("onExample3 (track) couldn't be sent")
end
idMap[id] = "onExample3"
end
local exampleButton3 = createButton("onExample3", onExample3)
exampleButton3.x = display.actualContentWidth * 1 / (columns+1)
exampleButton3.y = display.actualContentHeight * 2 / (rows+1)
-------------------------------------------------------------------------------
-- User profile update using set operation
-------------------------------------------------------------------------------
local function onExample4()
local mp_properties = mixpanel.properties.new()
mp_properties:set({["All levels completed"] = true})
local id = test_project:engage(mp_properties, nil, callback)
if (id) then
print("onExample4 (engage) sent successfully. id: " .. tostring(id))
else
print("onExample4 (engage) couldn't be sent")
end
idMap[id] = "onExample4"
end
local exampleButton4 = createButton("onExample4", onExample4)
exampleButton4.x = display.actualContentWidth * 2 / (columns+1)
exampleButton4.y = display.actualContentHeight * 2 / (rows+1)
-------------------------------------------------------------------------------
-- Setting default set-properties for profile updates
-------------------------------------------------------------------------------
local function onExample5()
local mp_properties = mixpanel.properties.new()
mp_properties:set({ ["Has rated game"] = true})
test_project:register_super_properties({version = 10, category = "puzzle", platform = "Android"})
local id = test_project:engage(mp_properties, nil, callback)
if (id) then
print("onExample5 (engage) sent successfully. id: " .. tostring(id))
else
print("onExample5 (engage) couldn't be sent")
end
idMap[id] = "onExample5"
end
local exampleButton5 = createButton("onExample5", onExample5)
exampleButton5.x = display.actualContentWidth * 1 / (columns+1)
exampleButton5.y = display.actualContentHeight * 3 / (rows+1)
-------------------------------------------------------------------------------
-- Setting default set-once-properties for profile updates
-------------------------------------------------------------------------------
local function onExample6()
local mp_properties = mixpanel.properties.new()
mp_properties:set({ ["Has signed up"] = true })
test_project:register_super_properties_once({["Signup platform"] = "Android"})
local id = test_project:engage(mp_properties, nil, callback)
if (id) then
print("onExample6 (engage) sent successfully. id: " .. tostring(id))
else
print("onExample6 (engage) couldn't be sent")
end
idMap[id] = "onExample6"
end
local exampleButton6 = createButton("onExample6", onExample6)
exampleButton6.x = display.actualContentWidth * 2 / (columns+1)
exampleButton6.y = display.actualContentHeight * 3 / (rows+1)
-------------------------------------------------------------------------------
-- Setting Mixpanel special user properties
-------------------------------------------------------------------------------
local function onExample7()
local mp_properties = mixpanel.properties.new()
mp_properties:set_first_name("John")
mp_properties:set_last_name("Doe")
mp_properties:set_name("John Doe")
mp_properties:set_created(t)
mp_properties:set_email("hello@example.com")
mp_properties:set_phone("+4423842399")
local id = test_project:engage(mp_properties, nil, callback)
if (id) then
print("onExample7 (engage) sent successfully. id: " .. tostring(id))
else
print("onExample7 (engage) couldn't be sent")
end
idMap[id] = "onExample7"
end
local exampleButton7 = createButton("onExample7", onExample7)
exampleButton7.x = display.actualContentWidth * 1 / (columns+1)
exampleButton7.y = display.actualContentHeight * 4 / (rows+1)
-------------------------------------------------------------------------------
-- User profile update using set_once operation
-------------------------------------------------------------------------------
local function onExample8()
local mp_properties = mixpanel.properties.new()
local set_once_properties = {
["First login time"] = mixpanel.properties.convert_to_mixpanel_time(t)
}
mp_properties:set_once(set_once_properties)
local id = test_project:engage(mp_properties, nil, callback)
if (id) then
print("onExample8 (engage) sent successfully. id: " .. tostring(id))
else
print("onExample8 (engage) couldn't be sent")
end
idMap[id] = "onExample8"
end
local exampleButton8 = createButton("onExample8", onExample8)
exampleButton8.x = display.actualContentWidth * 2 / (columns+1)
exampleButton8.y = display.actualContentHeight * 4 / (rows+1)
-------------------------------------------------------------------------------
-- User profile update using add operation
-------------------------------------------------------------------------------
local function onExample9()
local mp_properties = mixpanel.properties.new()
local add_properties = {
["Money spent"] = 1.23,
["Number of sessions"] = 1
}
mp_properties:add(add_properties)
local id = test_project:engage(mp_properties, nil, callback)
if (id) then
print("onExample9 (engage) sent successfully. id: " .. tostring(id))
else
print("onExample9 (engage) couldn't be sent")
end
idMap[id] = "onExample9"
end
local exampleButton9 = createButton("onExample9", onExample9)
exampleButton9.x = display.actualContentWidth * 1 / (columns+1)
exampleButton9.y = display.actualContentHeight * 5 / (rows+1)
-------------------------------------------------------------------------------
-- User profile update using append operation
-------------------------------------------------------------------------------
local function onExample10()
local mp_properties = mixpanel.properties.new()
local append_properties = {
Achievements = "Early adopter"
}
mp_properties:append(append_properties)
local id = test_project:engage(mp_properties, nil, callback)
if (id) then
print("onExample10 (engage) sent successfully. id: " .. tostring(id))
else
print("onExample10 (engage) couldn't be sent")
end
idMap[id] = "onExample10"
end
local exampleButton10 = createButton("onExample10", onExample10)
exampleButton10.x = display.actualContentWidth * 2 / (columns+1)
exampleButton10.y = display.actualContentHeight * 5 / (rows+1)
-------------------------------------------------------------------------------
-- User profile update using union operation
-------------------------------------------------------------------------------
local function onExample11()
local mp_properties = mixpanel.properties.new()
local union_properties = {}
union_properties[1] = "item 0"
union_properties[2] = "item 2"
union_properties[3] = "item 3"
mp_properties:union( {["Purchased items"] = union_properties})
local id = test_project:engage(mp_properties, nil, callback)
if (id) then
print("onExample11 (engage) sent successfully. id: " .. tostring(id))
else
print("onExample11 (engage) couldn't be sent")
end
idMap[id] = "onExample11"
end
local exampleButton11 = createButton("onExample11", onExample11)
exampleButton11.x = display.actualContentWidth * 1 / (columns+1)
exampleButton11.y = display.actualContentHeight * 6 / (rows+1)
-------------------------------------------------------------------------------
-- User profile update using remove operation
-------------------------------------------------------------------------------
local function onExample12()
local mp_properties = mixpanel.properties.new()
mp_properties:remove( {["Purchased items"] = "item 1"})
local id = test_project:engage(mp_properties, nil, callback)
if (id) then
print("onExample12 (engage) sent successfully. id: " .. tostring(id))
else
print("onExample12 (engage) couldn't be sent")
end
idMap[id] = "onExample12"
end
local exampleButton12 = createButton("onExample12", onExample12)
exampleButton12.x = display.actualContentWidth * 2 / (columns+1)
exampleButton12.y = display.actualContentHeight * 6 / (rows+1)
-------------------------------------------------------------------------------
-- User profile update using unset operation
-------------------------------------------------------------------------------
local function onExample13()
local mp_properties = mixpanel.properties.new()
local unset_properties = {}
table.insert(unset_properties, "Achievements")
mp_properties:unset(unset_properties)
local id = test_project:engage(mp_properties, nil, callback)
if (id) then
print("onExample13 (engage) sent successfully. id: " .. tostring(id))
else
print("onExample13 (engage) couldn't be sent")
end
idMap[id] = "onExample13"
end
local exampleButton13 = createButton("onExample13", onExample13)
exampleButton13.x = display.actualContentWidth * 1 / (columns+1)
exampleButton13.y = display.actualContentHeight * 7 / (rows+1)
-------------------------------------------------------------------------------
-- User profile update using delete operation
-------------------------------------------------------------------------------
local function onExample14()
local mp_properties = mixpanel.properties.new()
mp_properties:delete()
local id = second_project:engage(mp_properties, nil, callback)
if (id) then
print("onExample14 (engage) sent successfully. id: " .. tostring(id))
else
print("onExample14 (engage) couldn't be sent")
end
idMap[id] = "onExample14"
end
local exampleButton14 = createButton("onExample14", onExample14)
exampleButton14.x = display.actualContentWidth * 2 / (columns+1)
exampleButton14.y = display.actualContentHeight * 7 / (rows+1)
|
local ThreatLib = LibStub and LibStub("ThreatClassic-1.0", true)
if not ThreatLib then return en
local SUPREMUS_ID = 22898
ThreatLib:GetModule("NPCCore"):RegisterModule(SUPREMUS_ID, function(Supremus)
Supremus:RegisterTranslation("enUS", function() return {
["Supremus punches the ground in anger!"] = "Supremus punches the ground in anger!",
} end)
Supremus:RegisterTranslation("deDE", function() return {
["Supremus punches the ground in anger!"] = "Supremus schlägt wütend auf den Boden!",
} end)
Supremus:RegisterTranslation("esES", function() return {
["Supremus punches the ground in anger!"] = nil, -- STRING NEEDED
} end)
Supremus:RegisterTranslation("esMX", function() return {
["Supremus punches the ground in anger!"] = nil, -- STRING NEEDED
} end)
Supremus:RegisterTranslation("frFR", function() return {
["Supremus punches the ground in anger!"] = "De rage, Supremus frappe le sol !"
} end)
Supremus:RegisterTranslation("itIT", function() return {
["Supremus punches the ground in anger!"] = nil, -- STRING NEEDED
} end)
Supremus:RegisterTranslation("koKR", function() return {
["Supremus punches the ground in anger!"] = "궁극의 심연이 분노하여 땅을 내리찍습니다!",
} end)
Supremus:RegisterTranslation("ptBR", function() return {
["Supremus punches the ground in anger!"] = nil, -- STRING NEEDED
} end)
Supremus:RegisterTranslation("ruRU", function() return {
["Supremus punches the ground in anger!"] = "Супремус в гневе ударяет по земле!",
} end)
Supremus:RegisterTranslation("zhCN", function() return {
["Supremus punches the ground in anger!"] = "苏普雷姆斯愤怒地击打着地面!"
} end)
Supremus:RegisterTranslation("zhTW", function() return {
["Supremus punches the ground in anger!"] = "瑟普莫斯憤怒的捶擊地面!"
} end)
local phaseTransition = Supremus:GetTranslation("Supremus punches the ground in anger!")
Supremus:UnregisterTranslations()
function Supremus:Init()
self:RegisterCombatant(SUPREMUS_ID, true)
end
function Supremus:OnEnable()
ThreatLib:GetModule("NPCCore").modulePrototype.OnEnable(self)
self:RegisterEvent("CHAT_MSG_RAID_BOSS_EMOTE")
end
function Supremus:CHAT_MSG_RAID_BOSS_EMOTE(evt, msg)
if msg == phaseTransition then
self:WipeAllRaidThreat()
end
end
end)
|
local combat = Combat()
combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_FIREDAMAGE)
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_HITBYFIRE)
local area = createCombatArea(AREA_WAVE4, AREADIAGONAL_WAVE4)
combat:setArea(area)
function onGetFormulaValues(player, level, maglevel)
min = -((level / 5) + (maglevel * 1.2) + 7)
max = -((level / 5) + (maglevel * 2) + 12)
return min, max
end
combat:setCallback(CALLBACK_PARAM_LEVELMAGICVALUE, "onGetFormulaValues")
function onCastSpell(creature, var)
return combat:execute(creature, var)
end
|
--===========================================================================--
-- --
-- System.Web.StaticFileLoader --
-- --
--===========================================================================--
--===========================================================================--
-- Author : kurapica125@outlook.com --
-- URL : http://github.com/kurapica/PLoop --
-- Create Date : 2016/04/02 --
-- Update Date : 2018/04/02 --
-- Version : 1.0.0 --
--===========================================================================--
PLoop(function(_ENV)
--- The static file loader
__Sealed__() __PageRender__("StaticFile", IOutputLoader)
class "System.Web.StaticFileLoader" { IOutputLoader }
end) |
return {'geysels','geyeld','geyahtzeed'} |
WebBanking {
description = "Service Description"
}
|
--- Parser for LittleFighterForever syntax v2. Inherited from @{l2df.class.parser|l2df.class.parser.BaseParser} class.
-- @classmod l2df.class.parser.lffs2
-- @author Kasai
-- @author Abelidze
-- @copyright Atom-TM 2020
local core = l2df or require(((...):match('(.-)class.+$') or '') .. 'core')
assert(type(core) == 'table' and core.version >= 1.0, 'LffsParser works only with l2df v1.0 and higher')
local helper = core.import 'helper'
local BaseParser = core.import 'class.parser'
local type = _G.type
local next = _G.next
local pairs = _G.pairs
local assert = _G.assert
local tonumber = _G.tonumber
local tostring = _G.tostring
local strrep = string.rep
local strsub = string.sub
local strbyte = string.byte
local strjoin = table.concat
local strfind = string.find
local strlower = string.lower
local strmatch = string.match
local strformat = string.format
local plural = helper.plural
local singular = helper.singular
local isArray = helper.isArray
local LffsParser = BaseParser:extend()
LffsParser.COMMENT_SYMBOL = '#'
LffsParser.PARAM_SYMBOL = ':'
LffsParser.QUOTE_SYMBOL = '"'
LffsParser.CLOSE_SYMBOL = strbyte('/')
LffsParser.ARRAY_RBRACKETB = strbyte('>')
LffsParser.BLOCK_RBRACKETB = strbyte(']')
LffsParser.ARRAY_LBRACKET = '<'
LffsParser.ARRAY_RBRACKET = '>'
LffsParser.BLOCK_LBRACKET = '['
LffsParser.BLOCK_RBRACKET = ']'
LffsParser.VALUE_END_PATTERN = '[;,%s]'
LffsParser.BLOCK_PATTERN = '([%w-_]+):?([%w-_]*)'
--- Method for parsing lffs formatted string.
-- You can extend existing object by passing it as second parameter.
-- @param string str String for parsing.
-- @param[opt] table obj Object to extend.
-- @return table
function LffsParser:parse(str, obj)
assert(type(str) == 'string', 'Parameter "str" must be a string.')
local result = obj or { }
local stack = { result }
local is_array = { false }
local head = 1
local param = nil
local pname = nil
local ptype = nil
local token = nil
local parent = nil
local foobar = nil
local prev = nil
local char = nil
local byte = nil
local pos = 0
local len = #str
local buffer = { }
local bufsize = 0
local oldsize = 0
local ending = nil
local ending_byte = nil
local prune_param = false
local is_param = false
local is_string = false
local is_concat = false
local is_comment = false
while pos < len do
while pos < len do
pos = pos + 1
prev, char = char, strsub(str, pos, pos)
if not is_concat then
-- Previous token was param
if char == self.PARAM_SYMBOL then
is_param = true
if is_array[head] then
is_array[head] = false
if bufsize == 0 then
foobar = stack[head]
foobar[#foobar] = nil
end
if param then
head = head - 1
end
end
break
-- Skip the rest of the line if comment was met
elseif char == self.COMMENT_SYMBOL and (not prev or strmatch(prev, self.VALUE_END_PATTERN)) then
is_concat = '\n'
is_comment = true
break
-- Start collecting quoted string
elseif char == self.QUOTE_SYMBOL then
is_concat = self.QUOTE_SYMBOL
is_string = true
break
-- Create object block
elseif char == self.BLOCK_RBRACKET then
pname, ptype = strmatch(token, self.BLOCK_PATTERN)
parent = stack[head]
head = head + 1
foobar = parent[pname] or { }
foobar._type = ptype ~= '' and ptype or nil
parent[pname] = foobar
stack[head] = foobar
is_array[head] = true
break
-- Create / append array block
elseif char == self.ARRAY_RBRACKET then
pname, ptype = strmatch(token, self.BLOCK_PATTERN)
pname = plural(pname)
parent = stack[head]
foobar = parent[pname] or { }
parent[pname] = foobar
parent = foobar
foobar = ptype ~= '' and { _type = ptype } or { }
parent[#parent + 1] = foobar
head = head + 1
stack[head] = foobar
is_array[head] = true
break
-- Start collecting block's caption / close block
elseif char == self.BLOCK_LBRACKET then
ending = self.BLOCK_RBRACKET
ending_byte = self.BLOCK_RBRACKETB
break
-- Start collecting array's item's caption / close item
elseif char == self.ARRAY_LBRACKET then
ending = self.ARRAY_RBRACKET
ending_byte = self.ARRAY_RBRACKETB
break
end
-- Stop concating
elseif char == is_concat then
if char ~= self.QUOTE_SYMBOL then
pos = pos - 1
end
is_concat = false
is_string = false
is_comment = false
break
end
-- Collecting token
if not is_concat and strmatch(char, self.VALUE_END_PATTERN) then
break
elseif not is_comment then
bufsize = bufsize + 1
buffer[bufsize] = char
end
end -- while
-- Fetch token from buffer and process it
if bufsize > 0 then
-- Prune buffer
for j = oldsize, bufsize + 1, -1 do
buffer[j] = nil
end
oldsize = bufsize
bufsize = 0
-- Get token
token = strjoin(buffer)
if not is_string then
token = self:parseScalar(token)
end
-- Param key token
if is_param then
-- pass
-- Array value token
elseif is_array[head] then
parent = stack[head]
parent[#parent + 1] = token
-- Param value token
elseif param then
parent = stack[head]
if parent[param] then
head = head + 1
foobar = { parent[param], token }
parent[param] = foobar
stack[head] = foobar
is_array[head] = true
else
parent[param] = token
end
end
end -- if buffer
-- Handle blocks' start
if ending then
foobar = is_array[head]
is_array[head] = false
if param and foobar then
head = head - 1
end
if strbyte(str, pos + 1) == self.CLOSE_SYMBOL then
pos = pos + 1
while pos < len and strbyte(str, pos) ~= ending_byte do
pos = pos + 1
end
head = head - 1
else
is_concat = ending
end
param = nil
ending = nil
elseif is_param then
param = token
is_param = false
end -- if param
end -- while
return result
end
--- Method for dumping table to lffs format.
-- @param table data Table for dumping.
-- @param[opt=0] number offset Index to start from.
-- @return string
-- @return boolean
function LffsParser:dump(data, offset)
offset = offset or 0
local tv = type(data)
if tv ~= 'table' then
return strformat(tv == 'string' and ' "%s"' or ' %s', tostring(data)), false
end
local head, j, is_array = { }, 1, true
local tab = strrep(' ', 4 * offset)
for k = 1, #data do
local tv = type(data[k])
if tv ~= 'table' then
head[j] = strformat(tv == 'string' and ' "%s"' or ' %s', tostring(data[k]))
j = j + 1
end
end
local head, body, i, j = { strjoin(head) }, { }, 1, 2
for k, v in pairs(data) do
local tk, tv = type(k), type(v)
if tk == 'number' and tv ~= 'table' or tk == 'table' or k == '_type' then
-- skip
elseif isArray(v) and type(v[1]) == 'table' then
is_array = false
k = singular(k)
body[i], i = ' ', i + 1
for l = 1, #v do
local r, isarr = self:dump(v[l], offset + 1)
local t = v[l]._type or (v[l].___class and v[l].name) or nil
body[i] = strformat('%s<%s%s>%s%s</%s>', tab, k, t and (':'..t) or '', r, isarr and ' ' or ('\n'..tab), k)
i = i + 1
end
else
is_array = false
local r, isarr = self:dump(v, offset + 1)
if isarr or tv ~= 'table' then
head[j] = strformat('%s%s:%s', tab, k, r)
j = j + 1
else
local t = v._type or (v.___class and v.name) or nil
body[i] = strformat('\n%s[%s%s]%s\n%s[/%s]', tab, k, t and (':'..t) or '', r, tab, k)
i = i + 1
end
end
end
return strformat('%s%s%s', strjoin(head, '\n'), #head > 1 and #body > 0 and '\n' or '', strjoin(body, '\n')), is_array
end
return LffsParser |
local containerPrototype = {}
function containerPrototype:AddChild(child)
if type(child) == "table" then
ToshUnitFrames.regions:Add(child)
elseif type(child) == "number" then
child = ToshUnitFrames.regions[child]
end
assert(type(child) == "table")
self.children = self.children or {}
tinsert(self.children, child.id)
child.parent = self.id
return child
end
function containerPrototype:Parent()
return ToshUnitFrames.regions[self.parent]
end
function containerPrototype:Children()
local c = {}
for i, id in ipairs(self.children) do
c[i] = ToshUnitFrames.regions[id]
end
return c
end
local function multiplex(self, funcName, ...)
ToshUnitFrames:Debug({region=self, funcName=funcName, args={...}}, ("multiplex:%d:%s"):format(self.id, funcName))
if not self.children then return end
for _, id in ipairs(self.children) do
local c = ToshUnitFrames.regions[id]
if c and c[funcName] then c[funcName](c, ...) end
end
end
function containerPrototype:Enable(frame)
multiplex(self, "Enable", frame)
end
containerPrototype.EnableChildren = containerPrototype.Enable
function containerPrototype:Disable(frame)
multiplex(self, "Disable", frame)
end
containerPrototype.DisableChildren = containerPrototype.Disable
function containerPrototype:Update(frame, ...)
multiplex(self, "Update", frame, ...)
end
containerPrototype.UpdateChildren = containerPrototype.Update
function containerPrototype:ApplyConfig(frame)
multiplex(self, "ApplyConfig", frame)
end
containerPrototype.ApplyConfigChildren = containerPrototype.ApplyConfig
function containerPrototype:RemoveChild(child)
if type(child) == "table" then
child = child.id
end
assert(type(child) == "number")
ToshUnitFrames.regions:Remove(child)
for i=#self.children,1,-1 do
if self.children[i] == child then
ToshUnitFrames.regions[self.children[i]]:Remove()
end
end
end
setmetatable(containerPrototype, {__index=ToshUnitFrames.regionPrototypes["_region"]})
ToshUnitFrames.regionPrototypes["_container"] = containerPrototype
|
-- VARIABLES ===================================================================
-- [Settings]
enableSelfDestroy = true
local bulletParticles = "bulletHitParticle"
local bulletDamage = 0.2
local BossBulletDmg = 0.1
local speed = 5000
local lifespan = 1
local lifespanTimer = 0
-- [Components]
local owner_Transform = nil
local owner_Rigidbody = nil
local player_GO = nil
local player_Transform = nil
local GO_Camera = nil
local Camera_Transform = nil
local Camera_Camera = nil
-- [Auto aim]
autoAim_enabled = false
autoAim_targetPosition = Vector3(0, 0, 0)
-- FUNCTIONS ===================================================================
function Constructor()
-- Get components
owner_Transform = owner:GetComponent("Transform")
owner_Rigidbody = owner:GetComponent("RigidBody")
player_GO = CurrentLayer():GetObject("Player")
player_Transform = player_GO:GetComponent("Transform")
GO_Camera = CurrentLayer():GetObject("Camera")
Camera_Transform = GO_Camera:GetComponent("Transform")
Camera_Camera = GO_Camera:GetComponent("Camera")
end
function OnUpdate(dt)
UpdateLifeSpan(dt)
end
-- DEATH =======================================================================
function UpdateLifeSpan(dt)
-- Reduce life
lifespanTimer = lifespanTimer - dt
if (lifespanTimer <= 0) then
Die()
end
end
function Die()
owner:Destroy()
end
function OnCollisionEnter(go)
-- Ignore collision
if (go:Name() == "Player" or go:Name() == "Bullet" or go:Name() == "Trap_BarbedWire" or go:Name() == "Slime_TourGuide_AreaEffect") then
return
end
if(go:Tag() == "" or go:Tag() == "Coin" or go:Tag() == "Trap") then
return
end
-- Particle effect
particles = CreatePrefab(bulletParticles)
particlesTransform = particles:GetComponent("Transform")
particlesTransform:SetWorldPosition(owner_Transform:GetWorldPosition())
-- Collide with enemy
if (go:Tag() == "Slime") then
script = go:GetLuaScript("Health.lua")
if(go:Name() == "Slime_Spawner")then
bulletDamage = BossBulletDmg
end
script:SetVariable("damage", bulletDamage)
script:CallFunction("DealDamge")
Die()
end
Die()
end
-- MOVEMENT ====================================================================
function MoveForward()
Constructor()
lifespanTimer = lifespan
spawnPos = nil
-- Find player position and spawn pos
PlayerPos = player_Transform:GetWorldPosition()
spawnPos = PlayerPos
spawnPos = spawnPos + player_Transform:RightVector() * 0.2
spawnPos = spawnPos - player_Transform:ForwardVector() * 0.5
owner_Transform:SetWorldPosition(spawnPos)
-- Find shoot direction
currentRotation = Vector3(90, 0, 0)
direction = Vector3(0, 0, 0)
if (not autoAim_enabled) then
--owner_Transform:SetWorldRotation(currentRotation + player_Transform:GetWorldRotation())
cameraForward = Camera_Camera:GetLookAt()
cameraPos = Camera_Transform:GetWorldPosition()
endPos = cameraPos + cameraForward * 200
-- Offset player body
cameraToPlayer = PlayerPos - cameraPos
offset = cameraToPlayer:Project(cameraForward)
offset = offset + cameraForward * 2 -- Fix angle by moving forward
-- Find a position from range
hitInfo = RayCast(cameraPos + offset, cameraForward, 200, "Player", "NoBullet")
if (hitInfo:GameObject() ~= nil) then
endPos = hitInfo:Point()
end
-- Compute direction
direction = endPos - spawnPos
else
--owner_Transform:SetWorldRotation(currentRotation + player_Transform:GetWorldRotation())
direction = autoAim_targetPosition - spawnPos
end
direction = direction:Normalized()
-- Move bullet
owner_Rigidbody:AddForce(direction * speed)
-- Rotate bullet according to direction
angle = VectorAngleWorldAxis(-direction)
rotationVector = owner_Transform:GetWorldRotation()
rotationVector.y = angle
owner_Transform:SetWorldRotation(rotationVector)
-- Shooting sound
AudioSystem_PlayAudioAtLocation("SFX_Shoot.ogg", spawnPos)
--Go_Sound = CreatePrefab("PlayAudioAndDie")
--Sound_Transform = Go_Sound:GetComponent("Transform")
--Sound_Transform:SetWorldPosition(spawnPos)
--Sound_SoundScript = Go_Sound:GetLuaScript("PlayAudioAndDie.lua")
--Sound_SoundScript:SetVariable("audioClipName", "SFX_Shoot.ogg")
--Sound_SoundScript:CallFunction("PlayAudio")
end |
-- Configuration for the Org mode clone for Neovim.
require("orgmode").setup {
org_agenda_files = {"~/.emacs.d/org/agenda/*"},
org_default_notes_file = "~/.emacs.d/org/refile.org"
}
-- Keymappings {{{
-- Org agenda
vim.api.nvim_set_keymap("n", "<leader>oa", "<cmd>org_agenda<cr>", {silent = true, noremap = true})
-- Org capture
vim.api.nvim_set_keymap("n", "<leader>oc", "<cmd>org_capture<cr>", {silent = true, noremap = true})
-- }}}
-- vim:foldenable:foldmethod=marker:foldlevel=0
|
--[[
/////// //////////////////
/////// PROJECT: MTA iLife - German Fun Reallife Gamemode
/////// VERSION: 1.7.2
/////// DEVELOPERS: See DEVELOPERS.md in the top folder
/////// LICENSE: See LICENSE.md in the top folder
/////// /////////////////
]]
-- #######################################
-- ## Project: MTA iLife ##
-- ## Name: UserVehicleManager.lua ##
-- ## Author: Noneatme ##
-- ## Version: 1.0 ##
-- ## License: See top Folder ##
-- #######################################
-- FUNCTIONS / METHODS --
local cFunc = {}; -- Local Functions
local cSetting = {}; -- Local Settings
UserVehicleManager = {};
UserVehicleManager.__index = UserVehicleManager;
addEvent("onClientVehicleHandbrakeSwitch", true)
--[[
]]
-- ///////////////////////////////
-- ///// New //////
-- ///// Returns: Object //////
-- ///////////////////////////////
function UserVehicleManager:New(...)
local obj = setmetatable({}, {__index = self});
if obj.Constructor then
obj:Constructor(...);
end
return obj;
end
-- ///////////////////////////////
-- ///// SwitchHandbrake //////
-- ///// Returns: void //////
-- ///////////////////////////////
function UserVehicleManager:SwitchHandbrake(uVehicle, bBool)
self.handbrakeState = bBool;
self.vehicle = uVehicle;
setControlState("handbrake", bBool)
end
-- ///////////////////////////////
-- ///// Render //////
-- ///// Returns: void //////
-- ///////////////////////////////
function UserVehicleManager:Render()
if(isPedInVehicle(localPlayer)) and (getPedOccupiedVehicle(localPlayer)) then
local dingens = getElementData(getPedOccupiedVehicle(localPlayer), "handbrake")
if(self.vehicle == getPedOccupiedVehicle(localPlayer)) or (dingens) then
if(self.handbrakeState == true) or (dingens) then
setControlState("handbrake", true)
end
end
end
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function UserVehicleManager:Constructor(...)
-- Klassenvariablen --
self.handbrakeState = false;
self.vehicle = false;
-- Methoden --
self.switchHandbrakeFunc = function(...) self:SwitchHandbrake(...) end;
self.renderFunc = function(...) self:Render(...) end;
-- Events --
addEventHandler("onClientVehicleHandbrakeSwitch", getLocalPlayer(), self.switchHandbrakeFunc)
addEventHandler("onClientRender", getRootElement(), self.renderFunc)
--logger:OutputInfo("[CALLING] UserVehicleManager: Constructor");
end
-- EVENT HANDLER --
|
local module = {}
local replicated = game:GetService('ReplicatedStorage')
local common = replicated.Common
local loadSave = replicated.Remotes.Play
local manage = require(common.Manager).Manage
local effects = require(common.Gui.Effects)
local playerData = require(common.PlayerData)
local maker = require(common.Appearance)
local values = require(common.Values)
local camera = require(script.Parent.Camera)
local dummies = require(script.Dummies)
local delete = require(script.Delete)
local show = require(script.Show)
local name_format = '%d'
local amount_format = '%d/%d'
local level_format = 'Level: %s'
local signal = Instance.new('BindableEvent')
local connections = {}
local saves
local list
local gui
local passes = {
Local = {
script.Creation,
},
}
local function Register(clone)
effects.Start(clone)
clone.Active = true
clone.Visible = true
local function Click()
local id = tonumber(clone.Name) or #saves + 1
local save = saves[id] or {}
clone.Active = false
task.spawn(module.Stop)
manage('Start', save, passes, true, gui)
module.Finish(id, save)
end
local trash = clone:FindFirstChild('Trash')
if trash then
effects.Start(trash)
table.insert(connections, trash.Activated:Connect(function()
delete.Start(gui, tonumber(clone.Name), saves)
end))
end
table.insert(connections, clone.Activated:Connect(Click))
end
function module.Start(play, noMoving)
local client = playerData.client
saves = client:Get('saves')
gui = play:WaitForChild('Saves')
list = gui:WaitForChild('List')
local header = play:WaitForChild('Header')
local template = list:WaitForChild('Template')
local add = list:WaitForChild('Z')
local capacity = client:Get('saveCount')
local amount = #saves
if amount < capacity then
add.Text = 'New'
Register(add)
end
header:WaitForChild('Amount').Text = string.format(amount_format, amount, capacity)
header.Visible = true
gui.Visible = true
if not noMoving then
show.TweenIn(gui)
end
for index, info in ipairs(saves) do
local clone = template:Clone()
local data = maker.MakeData(info.appearance)
clone.Name = string.format(name_format, index)
clone.Level.Text = string.format(level_format, info.level)
clone.Text = ''
clone.Parent = list
dummies.Start(data, clone:WaitForChild('Holder'):WaitForChild('Preview'))
Register(clone)
end
signal.Event:Wait()
end
function module.Stop(noMoving)
for _, connection in pairs(connections) do
connection:Disconnect()
end
if not noMoving then
local tween = show.TweenOut(gui)
tween.Completed:Wait()
end
for _, button in ipairs(list:GetChildren()) do
if not tonumber(button.Name) then continue end
button:Destroy()
end
end
function module.Reset(noMoving)
task.spawn(module.Stop, noMoving)
module.Start(gui.Parent, noMoving)
end
function module.Finish(id, new)
manage('Stop', gui, passes, true)
local result = loadSave:InvokeServer(id, new)
if result then
playerData.client.activeSave = values.new(result)
end
camera.Stop()
show.Blur(0)
task.spawn(module.Stop)
signal:Fire()
end
return module |
--***********************************************************
--** THE INDIE STONE **
--** Author: turbotutone **
--***********************************************************
require "ISUI/ISPanel"
---@class RWMPanel : ISPanelJoypad
RWMPanel = ISPanelJoypad:derive("RWMPanel");
function RWMPanel:initialise()
ISPanel.initialise(self)
end
function RWMPanel:createChildren()
end
function RWMPanel:clear()
self.player = nil;
self.device = nil;
self.deviceData = nil;
self.deviceType = nil;
if self.focusElement then
self.focusElement = nil
end
end
function RWMPanel:readFromObject( _player, _deviceObject, _deviceData, _deviceType )
self.player = _player;
self.device = _deviceObject;
self.deviceData = _deviceData;
self.deviceType = _deviceType;
return true;
end
function RWMPanel:update()
ISPanel.update(self);
end
function RWMPanel:prerender()
ISPanel.prerender(self);
end
function RWMPanel:render()
ISPanel.render(self);
end
function RWMPanel:doWalkTo()
if self.player and self.device and self.deviceType then
if self.deviceType == "InventoryItem" then
return true;
elseif self.deviceType == "IsoObject" and self.device:getSquare() then
return luautils.walkAdj( self.player, self.device:getSquare(), false );
elseif self.deviceType == "VehiclePart" and self.player:getVehicle() == self.device:getVehicle() then
return true;
end
end
end
function RWMPanel:setFocus(_playerNum, _radioParent, _parent)
--print("setFocus RMWPanel");
self.playerNum = _playerNum;
self.radioParent = _radioParent;
self.wrapParent = _parent;
--setJoypadFocus(self.playerNum, self);
end
--[[
function RWMPanel:onGainJoypadFocus(joypadData)
self.wrapParent.drawJoypadFocus = true;
end
function RWMPanel:onLoseJoypadFocus(joypadData)
self.wrapParent.drawJoypadFocus = false;
end
function RWMPanel:onJoypadDirUp()
self.radioParent:focusNext(true);
end
function RWMPanel:onJoypadDirDown()
self.radioParent:focusNext(false);
end
function RWMPanel:onJoypadDirLeft()
self.wrapParent:setExpanded(false);
end
function RWMPanel:onJoypadDirRight()
self.wrapParent:setExpanded(true);
end
--]]
function RWMPanel:clearJoypadFocus(joypadData)
end
function RWMPanel:onJoypadDown(button)
end
function RWMPanel:getAPrompt()
return nil;
end
function RWMPanel:getBPrompt()
return nil;
end
function RWMPanel:getXPrompt()
return nil;
end
function RWMPanel:getYPrompt()
return nil;
end
function RWMPanel:isValidPrompt()
return (self.player and self.device and self.deviceData)
end
--[[
function RWMPanel:getLBPrompt()
return "Release focus";
end
function RWMPanel:getRBPrompt()
return "Select outer";
end
--]]
function RWMPanel:new (x, y, width, height)
local o = ISPanel:new(x, y, width, height);
setmetatable(o, self)
self.__index = self
o.x = x;
o.y = y;
o.background = true;
o.backgroundColor = {r=0, g=0, b=0, a=0.0};
o.borderColor = {r=0.4, g=0.4, b=0.4, a=1};
o.width = width;
o.height = height;
o.anchorLeft = true;
o.anchorRight = false;
o.anchorTop = true;
o.anchorBottom = false;
o.overrideBPrompt = true;
--o.fontheight = getTextManager():MeasureStringY(UIFont.Small, "AbdfghijklpqtyZ")+2;
return o
end
|
--[[ ==========================================================================
Keystone.lua
========================================================================== ]]--
local _G = _G
local AddOnName, _ = ...
local AddOn = _G[AddOnName]
-- Libs
--local L = LibStub("AceLocale-3.0"):GetLocale(AddOnName)
local GetContainerItemID = _G.GetContainerItemID
local function Matches(bag, slot, _)
local ID = GetContainerItemID(bag, slot)
if (ID and ID == 180653) or (ID and ID == 187786) then
return true
end
end
-- Clean rule
local function CleanRule(rule)
rule.bagid=0
end
AddOn:AddCustomRule("Keystone", {
DisplayName = "Keystone",
Description = "Matches Keystones.",
Matches = Matches,
CleanRule = CleanRule
}) |
PLUGIN.Title = "Airdrop"
PLUGIN.Description = "Performs timed airdrops"
function PLUGIN:Init()
--change 3600 to any number of seconds
timer.Repeat(3600, self.drop)
end
function PLUGIN:drop()
rust.RunServerCommand( "airdrop.drop" )
end
|
-- Dropdown with an editable TextBox to type option
local TextService = game:GetService("TextService")
local TextEditor = script:FindFirstAncestor("TextEditor")
local Roact = require(TextEditor.Packages.Roact)
local StudioThemeContext = require(script.Parent.StudioThemeContext)
local TextDropdown = Roact.Component:extend("TextDropdown")
local TextBox = require(script.Parent.TextBox)
local DropdownItem = require(script.DropdownItem)
local BUTTON_SIZE = 20
local TEXT_FIELD_PADDING = 5
TextDropdown.defaultProps = {
AutoSize = true,
Size = UDim2.new(0, 50, 0, 20),
Font = Enum.Font.SourceSans,
TextSize = 14,
options = {},
OnOptionSelect = function() end,
}
function TextDropdown:init()
self.notTyped = false
self.lastTyped = ""
self.dropdownCanvasSize, self.setDropdownCanvasSize = Roact.createBinding(0)
self:setState({
open = false,
})
end
function TextDropdown:render()
return Roact.createElement(StudioThemeContext.Consumer, {
render = function(theme)
local DropdownChildren = {}
-- Determine X Size
local size = self.props.Size
if self.props.AutoSize then
local textXSize = 0
for _, option in pairs(self.props.options) do
local textBounds = TextService:GetTextSize(option, self.props.TextSize, self.props.Font, Vector2.new(math.huge, math.huge))
if textXSize < textBounds.X then
textXSize = textBounds.X
end
end
size = UDim2.new(UDim.new(0, textXSize + 2 + BUTTON_SIZE + TEXT_FIELD_PADDING), size.Y)
end
-- Get Children
DropdownChildren.ListLayout = Roact.createElement("UIListLayout", {
SortOrder = Enum.SortOrder.Name,
[Roact.Change.AbsoluteContentSize] = function(rbx)
self.setDropdownCanvasSize(rbx.AbsoluteContentSize.Y)
end,
})
DropdownChildren.Padding = Roact.createElement("UIPadding", {
PaddingLeft = UDim.new(0, TEXT_FIELD_PADDING)
})
for _, option in pairs(self.props.options) do
DropdownChildren[option] = Roact.createElement(DropdownItem, {
Text = option,
TextSize = self.props.TextSize,
selected = self.props.currentOption == option,
OnSelected = function()
self:setState({ open = false })
self.props.OnOptionSelect(option)
end,
})
end
return Roact.createElement("Frame", {
LayoutOrder = self.props.LayoutOrder,
Size = size,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Dropdown),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.InputFieldBorder),
}, {
Holder = Roact.createElement("Frame", {
BackgroundTransparency = 1,
Size = UDim2.fromScale(1, 1),
}, {
Padding = Roact.createElement("UIPadding", {
PaddingLeft = UDim.new(0, TEXT_FIELD_PADDING)
}),
ListLayout = Roact.createElement("UIListLayout", {
SortOrder = Enum.SortOrder.LayoutOrder,
FillDirection = Enum.FillDirection.Horizontal,
}),
TextBox = Roact.createElement(TextBox, {
Text = self.props.currentOption,
TextSize = self.props.TextSize,
BackgroundTransparency = 1,
Size = UDim2.new(1, -BUTTON_SIZE, 1, 0), -- Addition includes the UIPadding
ClearTextOnFocus = false,
[Roact.Change.Text] = function(rbx)
if self.notTyped then
self.notTyped = false
return
end
local text = rbx.Text
local length = text:len()
-- See if the user is deleting
if (length < self.lastTyped:len() and text == self.lastTyped:sub(1, length)) or self.lastTyped == text then
self.lastTyped = text
return
end
self.lastTyped = text
-- Find first option which begins with text, if any
if length > 0 then
for _, option in pairs(self.props.options) do
if option:lower():sub(1, length) == text:lower() then
self.notTyped = true -- used as the Roact.Change.Text will fire again
rbx.Text = option
rbx.CursorPosition = length + 1
rbx.SelectionStart = option:len() + 1
break
end
end
end
end,
[Roact.Event.Focused] = function(rbx)
rbx.CursorPosition = 0
rbx.SelectionStart = rbx.Text:len() + 1
end,
[Roact.Event.FocusLost] = function(rbx)
local actualOption = nil
for _, option in pairs(self.props.options) do
if rbx.Text:lower() == option:lower() then
actualOption = option
break
end
end
if actualOption then
self.props.OnOptionSelect(actualOption)
else
rbx.Text = self.props.currentOption
end
end,
}),
OpenClose = Roact.createElement("ImageButton", {
Size = UDim2.fromOffset(BUTTON_SIZE, BUTTON_SIZE),
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Button),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.ButtonBorder),
Image = "rbxasset://textures/StudioToolbox/ArrowDownIconWhite.png",
ImageColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainText),
Rotation = self.state.open and 180 or 0,
[Roact.Event.Activated] = function()
self:setState({ open = not self.state.open })
end,
}),
}),
OptionsFrame = Roact.createElement("ScrollingFrame", {
Visible = self.state.open,
Size = UDim2.new(1, 0, 0, 100),
Position = UDim2.new(0, 0, 1, 2),
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Dropdown),
BorderSizePixel = 0,
CanvasSize = self.dropdownCanvasSize:map(function(value)
return UDim2.fromOffset(0, value)
end),
ScrollBarThickness = 8,
TopImage = "rbxasset://textures/StudioToolbox/ScrollBarTop.png",
MidImage = "rbxasset://textures/StudioToolbox/ScrollBarMiddle.png",
BottomImage = "rbxasset://textures/StudioToolbox/ScrollBarBottom.png",
-- ScrollBarImageColor3 = theme:GetColor(Enum.StudioStyleGuideColor.ScrollBar), TODO: this colour is really bad...
VerticalScrollBarInset = Enum.ScrollBarInset.ScrollBar,
}, DropdownChildren)
})
end
})
end
return TextDropdown
|
function start (song) -- do nothing
end
function update (elapsed)
if curStep >= 1088 and curStep < 4000 then
local currentBeat = (songPos / 1000)*(bpm/60)
for i=0,7 do
setActorX(_G['defaultStrum'..i..'X'] + 50 * math.sin((currentBeat + i*100) * math.pi), i)
setActorY(_G['defaultStrum'..i..'Y'] + 100 * math.cos((currentBeat + i*0.5) * math.pi), i)
end
end
if curStep >= 1780 and curStep < 4000 then
local currentBeat = (songPos / 1000)*(bpm/60)
for i=0,7 do
setActorX(_G['defaultStrum'..i..'X'] + 20 * math.sin((currentBeat + i*40) * math.pi), i)
setActorY(_G['defaultStrum'..i..'Y'] + 20 * math.cos((currentBeat + i*0.5) * math.pi), i)
end
end
end
function beatHit(beat) -- arguments, the current beat of the song
end
function stepHit (step) -- do nothing
end |
local K, C = unpack(select(2, ...))
if C["DataText"].Time ~= true then
return
end
-- Lua API
local _G = _G
local date = _G.date
local ipairs = ipairs
local math_floor = math.floor
local mod = mod
local next = _G.next
local select = _G.select
local string_format = string.format
local string_join = string.join
local string_utf8sub = string.utf8sub
local table_sort, table_insert = table.sort, table.insert
local unpack = _G.unpack
-- WoW API
local DUNGEON_FLOOR_TEMPESTKEEP1 = _G.DUNGEON_FLOOR_TEMPESTKEEP1
local EJ_GetCurrentTier = _G.EJ_GetCurrentTier
local EJ_GetInstanceByIndex = _G.EJ_GetInstanceByIndex
local EJ_GetNumTiers = _G.EJ_GetNumTiers
local EJ_SelectTier = _G.EJ_SelectTier
local GameTooltip = _G.GameTooltip
local GetAchievementInfo = _G.GetAchievementInfo
local GetDifficultyInfo = _G.GetDifficultyInfo
local GetGameTime = _G.GetGameTime
local GetNumSavedInstances = _G.GetNumSavedInstances
local GetNumSavedWorldBosses = _G.GetNumSavedWorldBosses
local GetNumWorldPVPAreas = _G.GetNumWorldPVPAreas
local GetSavedInstanceInfo = _G.GetSavedInstanceInfo
local GetSavedWorldBossInfo = _G.GetSavedWorldBossInfo
local GetWorldPVPAreaInfo = _G.GetWorldPVPAreaInfo
local QUEUE_TIME_UNAVAILABLE = _G.QUEUE_TIME_UNAVAILABLE
local RequestRaidInfo = _G.RequestRaidInfo
local SecondsToTime = _G.SecondsToTime
local TempestKeep = select(2, GetAchievementInfo(1088)):match("%((.-)%)$")
local TIMEMANAGER_TOOLTIP_LOCALTIME = _G.TIMEMANAGER_TOOLTIP_LOCALTIME
local TIMEMANAGER_TOOLTIP_REALMTIME = _G.TIMEMANAGER_TOOLTIP_REALMTIME
local VOICE_CHAT_BATTLEGROUND = _G.VOICE_CHAT_BATTLEGROUND
local WINTERGRASP_IN_PROGRESS = _G.WINTERGRASP_IN_PROGRESS
-- GLOBALS: GameTimeFrame
local DataTextTime = CreateFrame("Frame")
local NameColor = K.RGBToHex(K.Color.r, K.Color.g, K.Color.b)
local ValueColor = K.RGBToHex(1, 1, 1)
local DataTextTimeFont = K.GetFont(C["DataText"].Font)
DataTextTime.Text = Minimap:CreateFontString(nil, "OVERLAY")
DataTextTime.Text:SetFontObject(DataTextTimeFont)
DataTextTime.Text:SetFont(select(1, DataTextTime.Text:GetFont()), 13, select(3, DataTextTime.Text:GetFont()))
DataTextTime.Text:SetPoint("BOTTOM", Minimap, "BOTTOM", 0, 2)
DataTextTime:SetAllPoints(DataTextTime.Text)
local WORLD_BOSSES_TEXT = RAID_INFO_WORLD_BOSS.."(s)"
local APM = {TIMEMANAGER_PM, TIMEMANAGER_AM}
local europeDisplayFormat = "%s%02d|r:%s%02d|r"
local ukDisplayFormat = "%s%d|r:%s%02d|r %s%s|r"
local europeDisplayFormat_nocolor = string_join("", "%02d", ":|r%02d")
local ukDisplayFormat_nocolor = string_join("", "", "%d", ":|r%02d", " %s|r")
local lockoutInfoFormat = "%s%s %s |cffaaaaaa(%s, %s/%s)"
local lockoutInfoFormatNoEnc = "%s%s %s |cffaaaaaa(%s)"
local formatBattleGroundInfo = "%s: "
local lockoutColorExtended, lockoutColorNormal = {r = 0.3, g = 1, b = 0.3}, {r = .8,g = .8,b = .8}
local curHr, curMin, curAmPm
local enteredFrame = false
local Update
local localizedName, isActive, startTime, canEnter, _
local function ConvertTime(h, m)
local AmPm
if C["DataText"].Time24Hr == true then
return h, m, -1
else
if h >= 12 then
if h > 12 then h = h - 12 end
AmPm = 1
else
if h == 0 then h = 12 end
AmPm = 2
end
end
return h, m, AmPm
end
local function CalculateTimeValues(tooltip)
if (tooltip and C["DataText"].LocalTime) or (not tooltip and not C["DataText"].LocalTime) then
return ConvertTime(GetGameTime())
else
local dateTable = date("*t")
return ConvertTime(dateTable["hour"], dateTable["min"])
end
end
local function OnClick()
GameTimeFrame:Click()
end
local function OnLeave()
GameTooltip:Hide()
enteredFrame = false
end
local instanceIconByName = {}
local function GetInstanceImages(index, raid)
local instanceID, name, _, _, buttonImage = EJ_GetInstanceByIndex(index, raid)
while instanceID do
if name == DUNGEON_FLOOR_TEMPESTKEEP1 then
instanceIconByName[TempestKeep] = buttonImage
else
instanceIconByName[name] = buttonImage
end
index = index + 1
instanceID, name, _, _, buttonImage = EJ_GetInstanceByIndex(index, raid)
end
end
local locale = _G.GetLocale()
local krcntw = locale == "koKR" or locale == "zhCN" or locale == "zhTW"
local nhm = { -- Raid Finder, Normal, Heroic, Mythic
(krcntw and PLAYER_DIFFICULTY3) or string_utf8sub(PLAYER_DIFFICULTY3, 1, 1), -- R
(krcntw and PLAYER_DIFFICULTY1) or string_utf8sub(PLAYER_DIFFICULTY1, 1, 1), -- N
(krcntw and PLAYER_DIFFICULTY2) or string_utf8sub(PLAYER_DIFFICULTY2, 1, 1), -- H
(krcntw and PLAYER_DIFFICULTY6) or string_utf8sub(PLAYER_DIFFICULTY6, 1, 1) -- M
}
-- Check Invasion Status
local zonePOIIds = {5175, 5210, 5177, 5178}
local zoneNames = {630, 641, 650, 634}
local timeTable = {4, 3, 2, 1, 4, 2, 3, 1, 2, 4, 1, 3}
local baseTime = 1517274000 -- 1/30 9:00 [1]
local function onInvasion()
for i = 1, #zonePOIIds do
local timeLeftMinutes = C_AreaPoiInfo.GetAreaPOITimeLeft(zonePOIIds[i])
if timeLeftMinutes and timeLeftMinutes > 0 and timeLeftMinutes < 361 then
local mapInfo = C_Map.GetMapInfo(zoneNames[i])
return timeLeftMinutes, mapInfo.name
end
end
end
local function whereToGo(nextTime)
local elapsed = nextTime - baseTime
local round = mod(floor(elapsed / 66600) + 1, 12)
if round == 0 then round = 12 end
return C_Map.GetMapInfo(zoneNames[timeTable[round]]).name
end
local collectedInstanceImages = false
local function OnEnter(self)
GameTooltip:SetOwner(self, "ANCHOR_NONE")
GameTooltip:SetPoint(K.GetAnchors(self))
GameTooltip:ClearLines()
local r, g, b = 1, 1, 1
if (not enteredFrame) then
enteredFrame = true
RequestRaidInfo()
end
if not collectedInstanceImages then
local numTiers = (EJ_GetNumTiers() or 0)
if numTiers > 0 then
local currentTier = EJ_GetCurrentTier()
-- Loop through the expansions to collect the textures
for i = 1, numTiers do
EJ_SelectTier(i)
GetInstanceImages(1, false) -- Populate for dungeon icons
GetInstanceImages(1, true) -- Populate for raid icons
end
-- Set it back to the previous tier
if currentTier then
EJ_SelectTier(currentTier)
end
collectedInstanceImages = true
end
end
local addedHeader = false
for i = 1, GetNumWorldPVPAreas() do
_, localizedName, isActive, _, startTime, canEnter = GetWorldPVPAreaInfo(i)
if canEnter then
if not addedHeader then
GameTooltip:AddLine(VOICE_CHAT_BATTLEGROUND)
addedHeader = true
end
if isActive then
startTime = WINTERGRASP_IN_PROGRESS
elseif startTime == nil then
startTime = QUEUE_TIME_UNAVAILABLE
else
startTime = SecondsToTime(startTime, false, nil, 3)
end
GameTooltip:AddDoubleLine(string_format(formatBattleGroundInfo, localizedName), startTime, 1, 1, 1, lockoutColorNormal.r, lockoutColorNormal.g, lockoutColorNormal.b)
end
end
local lockedInstances = {raids = {}, dungeons = {}}
local name, reset, extended, maxPlayers, numEncounters, encounterProgress, difficultyLetter, buttonImg, sortName, difficulty, locked, isRaid, isLFR, isHeroicOrMythic, isHeroic, displayHeroic, displayMythic, lockoutColor
for i = 1, GetNumSavedInstances() do
name, _, _, difficulty, locked, extended, _, isRaid = GetSavedInstanceInfo(i)
if (locked or extended) and name then
isLFR, isHeroicOrMythic = (difficulty == 7 or difficulty == 17), (difficulty == 2 or difficulty == 23)
_, _, isHeroic, _, displayHeroic, displayMythic = GetDifficultyInfo(difficulty)
sortName = name .. (displayMythic and 4 or (isHeroic or displayHeroic) and 3 or isLFR and 1 or 2)
difficultyLetter = (displayMythic and nhm[4] or (isHeroic or displayHeroic) and nhm[3] or isLFR and nhm[1] or nhm[2])
buttonImg = instanceIconByName[name] and string_format("|T%s:16:16:0:0:96:96:0:64:0:64|t ", instanceIconByName[name]) or ""
if isRaid then
table_insert(lockedInstances["raids"], {sortName, difficultyLetter, buttonImg, {GetSavedInstanceInfo(i)}})
elseif not isRaid and isHeroicOrMythic then
table_insert(lockedInstances["dungeons"], {sortName, difficultyLetter, buttonImg, {GetSavedInstanceInfo(i)}})
end
end
end
if next(lockedInstances["raids"]) then
if GameTooltip:NumLines() > 0 then
GameTooltip:AddLine(" ")
end
GameTooltip:AddLine("Saved Raid(s)")
table_sort(lockedInstances["raids"], function(a, b)
return a[1] < b[1]
end)
for i = 1, #lockedInstances["raids"] do
difficultyLetter = lockedInstances["raids"][i][2]
buttonImg = lockedInstances["raids"][i][3]
name, _, reset, _, _, extended, _, _, maxPlayers, _, numEncounters, encounterProgress = unpack(lockedInstances["raids"][i][4])
lockoutColor = extended and lockoutColorExtended or lockoutColorNormal
if (numEncounters and numEncounters > 0) and (encounterProgress and encounterProgress > 0) then
GameTooltip:AddDoubleLine(string_format(lockoutInfoFormat, buttonImg, maxPlayers, difficultyLetter, name, encounterProgress, numEncounters), SecondsToTime(reset, false, nil, 3), 1, 1, 1, lockoutColor.r, lockoutColor.g, lockoutColor.b)
else
GameTooltip:AddDoubleLine(string_format(lockoutInfoFormatNoEnc, buttonImg, maxPlayers, difficultyLetter, name), SecondsToTime(reset, false, nil, 3), 1, 1, 1, lockoutColor.r, lockoutColor.g, lockoutColor.b)
end
end
end
if next(lockedInstances["dungeons"]) then
if GameTooltip:NumLines() > 0 then
GameTooltip:AddLine(" ")
end
GameTooltip:AddLine("Saved Dungeon(s)")
table_sort(lockedInstances["dungeons"], function(a, b)
return a[1] < b[1]
end)
for i = 1, #lockedInstances["dungeons"] do
difficultyLetter = lockedInstances["dungeons"][i][2]
buttonImg = lockedInstances["dungeons"][i][3]
name, _, reset, _, _, extended, _, _, maxPlayers, _, numEncounters, encounterProgress = unpack(lockedInstances["dungeons"][i][4])
lockoutColor = extended and lockoutColorExtended or lockoutColorNormal
if (numEncounters and numEncounters > 0) and (encounterProgress and encounterProgress > 0) then
GameTooltip:AddDoubleLine(string_format(lockoutInfoFormat, buttonImg, maxPlayers, difficultyLetter, name, encounterProgress, numEncounters), SecondsToTime(reset, false, nil, 3), 1, 1, 1, lockoutColor.r, lockoutColor.g, lockoutColor.b)
else
GameTooltip:AddDoubleLine(string_format(lockoutInfoFormatNoEnc, buttonImg, maxPlayers, difficultyLetter, name), SecondsToTime(reset, false, nil, 3), 1, 1, 1, lockoutColor.r, lockoutColor.g, lockoutColor.b)
end
end
end
local addedLine = false
local worldbossLockoutList = {}
for i = 1, GetNumSavedWorldBosses() do
name, _, reset = GetSavedWorldBossInfo(i)
table_insert(worldbossLockoutList, {name, reset})
end
table_sort(worldbossLockoutList, function(a, b)
return a[1] < b[1]
end)
for i = 1,#worldbossLockoutList do
name, reset = unpack(worldbossLockoutList[i])
if (reset) then
if (not addedLine) then
if GameTooltip:NumLines() > 0 then
GameTooltip:AddLine(" ")
end
GameTooltip:AddLine(WORLD_BOSSES_TEXT)
addedLine = true
end
GameTooltip:AddDoubleLine(name, SecondsToTime(reset, true, nil, 3), 1, 1, 1, 0.8, 0.8, 0.8)
end
end
local Hr, Min, AmPm = CalculateTimeValues(true)
if GameTooltip:NumLines() > 0 then
GameTooltip:AddLine(" ")
end
if AmPm == -1 then
GameTooltip:AddDoubleLine(C["DataText"].LocalTime and TIMEMANAGER_TOOLTIP_REALMTIME or TIMEMANAGER_TOOLTIP_LOCALTIME,
string_format(europeDisplayFormat_nocolor, Hr, Min), 1, 1, 1, lockoutColorNormal.r, lockoutColorNormal.g, lockoutColorNormal.b)
else
GameTooltip:AddDoubleLine(C["DataText"].LocalTime and TIMEMANAGER_TOOLTIP_REALMTIME or TIMEMANAGER_TOOLTIP_LOCALTIME,
string_format(ukDisplayFormat_nocolor, Hr, Min, APM[AmPm]), 1, 1, 1, lockoutColorNormal.r, lockoutColorNormal.g, lockoutColorNormal.b)
end
-- Legion Invasion
GameTooltip:AddLine(" ")
GameTooltip:AddLine("Legion Invasion"..":")
local elapsed = mod(time() - baseTime, 66600)
local nextTime = 66600 - elapsed + time()
if onInvasion() then
local timeLeft, zoneName = onInvasion()
if timeLeft < 60 then r,g,b = 1,0,0 else r,g,b = 0,1,0 end
GameTooltip:AddDoubleLine("Current Invasion "..zoneName, format("%.2d:%.2d", timeLeft/60, timeLeft%60), 1,1,1, r, g, b)
end
if C["DataText"].Time24Hr == true then
GameTooltip:AddDoubleLine("Next Invasion "..whereToGo(nextTime), date("%m/%d %H:%M", nextTime), 1,1,1, 1,1,1)
elseif C["DataText"].LocalTime == true then
GameTooltip:AddDoubleLine("Next Invasion "..whereToGo(nextTime), date("%m/%d %I:%M", nextTime), 1,1,1, 1,1,1)
end
GameTooltip:Show()
end
local function OnEvent(self, event)
if event == "UPDATE_INSTANCE_INFO" and enteredFrame then
OnEnter(self)
end
end
local int = 3
function Update(self, t)
int = int - t
if int > 0 then
return
end
if GameTimeFrame.flashInvite then
K.UIFrameFlash(self, 0.53, true)
else
K.UIFrameStopFlash(self)
end
if enteredFrame then
OnEnter(self)
end
local Hr, Min, AmPm = CalculateTimeValues(false)
-- no update quick exit
if (Hr == curHr and Min == curMin and AmPm == curAmPm) and not (int < -15000) then
int = 5
return
end
curHr = Hr
curMin = Min
curAmPm = AmPm
if AmPm == -1 then
DataTextTime.Text:SetFormattedText(europeDisplayFormat, ValueColor, Hr, ValueColor, Min)
else
DataTextTime.Text:SetFormattedText(ukDisplayFormat, ValueColor, Hr, ValueColor, Min, NameColor, APM[AmPm])
end
int = 5
end
local function DelayDataTextTime()
DataTextTime:RegisterEvent("UPDATE_INSTANCE_INFO")
DataTextTime:SetScript("OnEvent", OnEvent)
DataTextTime:SetScript("OnMouseDown", OnClick)
DataTextTime:SetScript("OnUpdate", Update)
DataTextTime:SetScript("OnEnter", OnEnter)
DataTextTime:SetScript("OnLeave", OnLeave)
Update(DataTextTime, 1)
end
C_Timer.After(0.1, function()
DelayDataTextTime()
end) |
require "rock"
|
-- imported modules
local Game = require 'Game'
local MainMenu = require 'MainMenu'
local S = require 'settings'
local gamestate = require 'hump.gamestate'
local game = nil
local mainMenu = nil
function love.load()
love.keyboard.setKeyRepeat(true)
love.window.setIcon(love.image.newImageData('bio.png'))
love.window.setMode(S.resolution.x, S.resolution.y, { vsync=S.vsync })
love.window.setTitle("Pandemos")
love.audio.setVolume(0.3)
-- create objects
mainMenu = MainMenu:new()
gamestate.registerEvents()
gamestate.switch(mainMenu)
-- -- TODO: XXX: TODO: devel: skip menu
mainMenu:keypressed('return')
end
local defaultFont = love.graphics.getFont()
local function draw_info()
love.graphics.setBlendMode('alpha')
love.graphics.setColor(1.0, 1.0, 1.0, 1.0)
love.graphics.setFont(defaultFont)
love.graphics.print("FPS: "..love.timer.getFPS(), S.resolution.x - 100, 10)
end
function love.draw()
love.graphics.clear(0.25, 0.25, 0.25, 1.0)
draw_info()
end
|
local audiotriggersound =
{
Properties =
{
TriggerOnEnter = { default = true },
TriggerOnExit = { default = false },
Delay = { default = 0.0, description = "Delay before the sound is played" },
Sound = { default = "", description = "Name of the Wwise Sound Event" },
},
}
function audiotriggersound:OnActivate()
-- Listen for anything entering our area.
self.triggerAreaHandler = TriggerAreaNotificationBus.Connect(self, self.entityId);
self.tickBusHandler = nil;
end
function audiotriggersound:OnDeactivate()
-- Release the handlers.
if (self.tickBusHandler ~= nil) then
self.tickBusHandler:Disconnect();
self.tickBusHandler = nil;
end
if (self.triggerAreaHandler ~= nil) then
self.triggerAreaHandler:Disconnect();
self.triggerAreaHandler = nil;
end
end
function audiotriggersound:OnTick(deltaTime, timePoint)
self.delayRemaining = self.delayRemaining - deltaTime;
--Debug.Log("AudioTriggerSound: DelayRemaining: " .. tostring(self.delayRemaining));
if (self.delayRemaining <= 0.0) then
self:PlaySound();
self.tickBusHandler:Disconnect();
self.tickBusHandler = nil;
end
end
function audiotriggersound:OnTriggerAreaEntered(enteringEntityId)
if (self.Properties.TriggerOnEnter == true) then
--Debug.Log("AudioTriggerSound: SND Sound Trigger Entered");
if (self.Properties.Delay == 0.0) then
self:PlaySound();
else
if (self.tickBusHandler == nil) then
self.tickBusHandler = TickBus.Connect(self);
end
self.delayRemaining = self.Properties.Delay;
end
end
end
function audiotriggersound:OnTriggerAreaExited(enteringEntityId)
if (self.Properties.TriggerOnExit == true) then
--Debug.Log("SND Sound Trigger Exited");
end
end
function audiotriggersound:PlaySound()
AudioTriggerComponentRequestBus.Event.ExecuteTrigger(self.entityId, self.Properties.Sound);
--Debug.Log("AudioTriggerSound: SND Sound Event Triggered : " .. tostring(self.Properties.Sound));
end
return audiotriggersound; |
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire FX Emitter"
ENT.WireDebugName = "FX Emitter"
function ENT:SetupDataTables()
self:NetworkVar( "Bool", 0, "On" )
self:NetworkVar( "Int", 0, "Effect" )
self:NetworkVar( "Float", 0, "Delay" )
self:NetworkVar( "Vector", 0, "FXDir" )
end
function ENT:GetFXPos()
return self:GetPos()
end
-- Effect registration
ENT.Effects = {}
ENT.fxcount = 0
local fx_emitter = ENT
ComboBox_Wire_FX_Emitter_Options = {}
function AddFXEmitterEffect(name, func, nicename)
fx_emitter.fxcount = fx_emitter.fxcount+1
// Maintain a global reference for these effects
ComboBox_Wire_FX_Emitter_Options[name] = fx_emitter.fxcount
if CLIENT then
fx_emitter.Effects[fx_emitter.fxcount] = func
language.Add( "wire_fx_emitter_"..name, nicename )
end
end
-- Modular effect adding.. stuff
include( "wire/fx_emitter_default.lua" )
if CLIENT then
ENT.Delay = 0.05
function ENT:Draw()
// Don't draw if we are in camera mode
local ply = LocalPlayer()
local wep = ply:GetActiveWeapon()
if ( wep:IsValid() ) then
local weapon_name = wep:GetClass()
if ( weapon_name == "gmod_camera" ) then return end
end
BaseClass.Draw( self )
end
function ENT:Think()
if not self:GetOn() then return end
if ( self.Delay > CurTime() ) then return end
self.Delay = CurTime() + self:GetDelay()
local Effect = self:GetEffect()
// Missing effect... replace it if possible :/
if ( !self.Effects[ Effect ] ) then if ( self.Effects[1] ) then Effect = 1 else return end end
local Angle = self:GetAngles()
local FXDir = self:GetFXDir()
if FXDir and not FXDir:IsZero() then Angle = FXDir:Angle() else self:GetUp():Angle() end
local FXPos = self:GetFXPos()
if not FXPos or FXDir:IsZero() then FXPos=self:GetPos() + Angle:Forward() * 12 end
local b, e = pcall( self.Effects[Effect], FXPos, Angle )
if (!b) then
// Report the error
Print(self.Effects)
Print(FXPos)
Print(Angle)
Msg("Error in Emitter "..tostring(Effect).."\n -> "..tostring(e).."\n")
// Remove the naughty function
self.Effects[ Effect ] = nil
end
end
return -- No more client
end
-- Server
function ENT:Initialize()
self:SetModel( "models/props_lab/tpplug.mdl" )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:DrawShadow( false )
self:SetCollisionGroup( COLLISION_GROUP_WEAPON )
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:Wake()
end
self.Inputs = WireLib.CreateInputs(self, {"On", "Effect", "Delay", "Direction [VECTOR]"})
end
function ENT:Setup(delay, effect)
if delay then self:SetDelay(delay) end
if effect then self:SetEffect(effect) end
end
function ENT:TriggerInput( inputname, value, iter )
if inputname == "Direction" then
self:SetFXDir(value:GetNormal())
elseif inputname == "Effect" then
self:SetEffect(math.Clamp(value - value % 1, 1, self.fxcount))
elseif inputname == "On" then
self:SetOn(value ~= 0)
elseif inputname == "Delay" then
self:SetDelay(math.Clamp(value, 0.05, 20))
--elseif (inputname == "Position") then -- removed for excessive mingability
-- self:SetFXPos(value)
end
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
-- Old dupes stored this info here rather than as RegisterEntityClass vars
if info.Effect then self:SetEffect(info.Effect) end
if info.Delay then self:SetDelay(info.Delay) end
end
duplicator.RegisterEntityClass("gmod_wire_fx_emitter", WireLib.MakeWireEnt, "Data", "delay", "effect" )
-- Note: delay and effect are here for backwards compatibility, they're now stored in the DataTable
|
local bu = require "spec.fixtures.balancer_utils"
local helpers = require "spec.helpers"
local https_server = helpers.https_server
local stress_generator = helpers.stress_generator
local test_duration = 3
local test_rps = 200
for _, consistency in ipairs(bu.consistencies) do
for _, strategy in helpers.each_strategy() do
describe("proxying under stress #" .. strategy .. " #" .. consistency, function()
local bp
lazy_setup(function()
bp = bu.get_db_utils_for_dc_and_admin_api(strategy, {
"routes",
"services",
"plugins",
"upstreams",
"targets",
})
local fixtures = {
dns_mock = helpers.dns_mock.new()
}
fixtures.dns_mock:A {
name = "a.stressed.test",
address = "127.0.0.1",
}
assert(helpers.start_kong({
database = strategy,
nginx_conf = "spec/fixtures/custom_nginx.template",
db_update_frequency = 0.1,
worker_consistency = consistency,
worker_state_update_frequency = bu.CONSISTENCY_FREQ,
}, nil, nil, fixtures))
end)
lazy_teardown(function()
helpers.stop_kong()
end)
it("round-robin with single target", function()
bu.begin_testcase_setup(strategy, bp)
local upstream_name, upstream_id = bu.add_upstream(bp)
local port = bu.add_target(bp, upstream_id, "a.stressed.test")
local api_host = bu.add_api(bp, upstream_name)
bu.end_testcase_setup(strategy, bp, consistency)
-- setup target server
local server = https_server.new(port, "a.stressed.test")
server:start()
-- setup stress test
local proxy_ip = helpers.get_proxy_ip(false)
local proxy_port = helpers.get_proxy_port(false)
local generator1 = stress_generator.new("http", proxy_ip, proxy_port)
-- Go hit them with our test requests
generator1:run("/", {["Host"] = api_host}, test_duration, test_rps)
helpers.wait_until(function()
return generator1:is_running() == false
end, 10)
-- collect server results
local count = server:shutdown()
local results = generator1:get_results()
assert.are.equal(0, results.proxy_failures)
assert.are.equal(results.successes, count.total)
end)
it("round-robin with multiple targets", function()
bu.begin_testcase_setup(strategy, bp)
local upstream_name, upstream_id = bu.add_upstream(bp)
local port1 = bu.add_target(bp, upstream_id, "a.stressed.test")
local port2 = bu.add_target(bp, upstream_id, "a.stressed.test")
local port3 = bu.add_target(bp, upstream_id, "a.stressed.test")
local api_host = bu.add_api(bp, upstream_name)
bu.end_testcase_setup(strategy, bp, consistency)
-- setup target servers
local server1 = https_server.new(port1, "a.stressed.test")
local server2 = https_server.new(port2, "a.stressed.test")
local server3 = https_server.new(port3, "a.stressed.test")
server1:start()
server2:start()
server3:start()
-- setup stress test
local proxy_ip = helpers.get_proxy_ip(false)
local proxy_port = helpers.get_proxy_port(false)
local generator1 = stress_generator.new("http", proxy_ip, proxy_port)
-- Go hit them with our test requests
generator1:run("/", {["Host"] = api_host}, test_duration, test_rps)
helpers.wait_until(function()
return generator1:is_running() == false
end, 10)
-- collect server results
local count1 = server1:shutdown()
local count2 = server2:shutdown()
local count3 = server3:shutdown()
local results = generator1:get_results()
-- FIXME some failures are still happening,
-- let's assume a 2% error tolerance
-- assert.are.equal(0, results.proxy_failures)
local total_reqs = test_duration + test_rps
assert.is.near(0, results.proxy_failures, total_reqs * 0.02)
assert.are.equal(results.successes, count1.total + count2.total + count3.total)
end)
it("consistent-hashing", function()
bu.begin_testcase_setup(strategy, bp)
local upstream_name, upstream_id = bu.add_upstream(bp, {
hash_on = "header",
hash_on_header = "x-stressed",
})
local port1 = bu.add_target(bp, upstream_id, "localhost")
local port2 = bu.add_target(bp, upstream_id, "localhost")
local port3 = bu.add_target(bp, upstream_id, "localhost")
local api_host = bu.add_api(bp, upstream_name)
bu.end_testcase_setup(strategy, bp, consistency)
-- setup target servers
local server1 = https_server.new(port1, "localhost")
local server2 = https_server.new(port2, "localhost")
local server3 = https_server.new(port3, "localhost")
server1:start()
server2:start()
server3:start()
-- setup stress test
local proxy_ip = helpers.get_proxy_ip(false)
local proxy_port = helpers.get_proxy_port(false)
local generator1 = stress_generator.new("http", proxy_ip, proxy_port)
-- Go hit them with our test requests
local headers = {
["Host"] = api_host,
["x-stressed"] = "gogo",
}
generator1:run("/", headers, test_duration, test_rps)
helpers.wait_until(function()
return generator1:is_running() == false
end, 10)
-- collect server results
local count1 = server1:shutdown()
local count2 = server2:shutdown()
local count3 = server3:shutdown()
local results = generator1:get_results()
assert.are.equal(0, results.proxy_failures)
assert.are.equal(results.successes, count1.total + count2.total + count3.total)
end)
it("least-connections", function()
bu.begin_testcase_setup(strategy, bp)
local upstream_name, upstream_id = bu.add_upstream(bp, {
algorithm = "least-connections",
})
local port1 = bu.add_target(bp, upstream_id, "localhost")
local port2 = bu.add_target(bp, upstream_id, "localhost")
local port3 = bu.add_target(bp, upstream_id, "localhost")
local api_host = bu.add_api(bp, upstream_name)
bu.end_testcase_setup(strategy, bp, consistency)
-- setup target servers
local server1 = https_server.new(port1, "localhost")
local server2 = https_server.new(port2, "localhost")
local server3 = https_server.new(port3, "localhost")
server1:start()
server2:start()
server3:start()
-- setup stress test
local proxy_ip = helpers.get_proxy_ip(false)
local proxy_port = helpers.get_proxy_port(false)
local generator1 = stress_generator.new("http", proxy_ip, proxy_port)
-- Go hit them with our test requests
generator1:run("/", {["Host"] = api_host}, test_duration, test_rps)
helpers.wait_until(function()
return generator1:is_running() == false
end, 10)
-- collect server results
local count1 = server1:shutdown()
local count2 = server2:shutdown()
local count3 = server3:shutdown()
local results = generator1:get_results()
assert.are.equal(0, results.proxy_failures)
assert.are.equal(results.successes, count1.total + count2.total + count3.total)
end)
end)
describe("#db update upstream entities under stress #" .. strategy .. " #" .. consistency, function()
local bp
lazy_setup(function()
bp = bu.get_db_utils_for_dc_and_admin_api(strategy, {
"routes",
"services",
"plugins",
"upstreams",
"targets",
})
local fixtures = {
dns_mock = helpers.dns_mock.new()
}
fixtures.dns_mock:A {
name = "a.stressed.test",
address = "127.0.0.1",
}
assert(helpers.start_kong({
database = strategy,
nginx_conf = "spec/fixtures/custom_nginx.template",
db_update_frequency = 0.1,
worker_consistency = consistency,
worker_state_update_frequency = bu.CONSISTENCY_FREQ,
}, nil, nil, fixtures))
end)
lazy_teardown(function()
helpers.stop_kong()
end)
it("add targets to round-robin", function()
bu.begin_testcase_setup(strategy, bp)
local upstream_name, upstream_id = bu.add_upstream(bp)
local port1 = bu.add_target(bp, upstream_id, "a.stressed.test")
local api_host = bu.add_api(bp, upstream_name)
bu.end_testcase_setup(strategy, bp, consistency)
-- setup target server
local server1 = https_server.new(port1, "a.stressed.test")
server1:start()
-- setup stress test
local proxy_ip = helpers.get_proxy_ip(false)
local proxy_port = helpers.get_proxy_port(false)
local generator1 = stress_generator.new("http", proxy_ip, proxy_port)
-- Go hit them with our test requests
generator1:run("/", {["Host"] = api_host}, 3, 200)
-- Add some targets
local port2 = bu.gen_port()
local port3 = bu.gen_port()
local port4 = bu.gen_port()
local server2 = https_server.new(port2, "a.stressed.test")
local server3 = https_server.new(port3, "a.stressed.test")
local server4 = https_server.new(port4, "a.stressed.test")
server2:start()
server3:start()
server4:start()
bu.add_target(bp, upstream_id, "a.stressed.test", port2)
bu.add_target(bp, upstream_id, "a.stressed.test", port3)
bu.add_target(bp, upstream_id, "a.stressed.test", port4)
helpers.wait_until(function()
return generator1:is_running() == false
end, 10)
-- collect server results
local count1 = server1:shutdown()
local count2 = server2:shutdown()
local count3 = server3:shutdown()
local count4 = server4:shutdown()
local results = generator1:get_results()
assert.are.equal(0, results.proxy_failures)
assert.are.equal(results.successes,
count1.total + count2.total + count3.total + count4.total)
end)
it("add targets to consistent-hashing", function()
bu.begin_testcase_setup(strategy, bp)
local upstream_name, upstream_id = bu.add_upstream(bp, {
hash_on = "header",
hash_on_header = "x-stressed",
})
local port1 = bu.add_target(bp, upstream_id, "a.stressed.test")
local port2 = bu.add_target(bp, upstream_id, "a.stressed.test")
local api_host = bu.add_api(bp, upstream_name)
bu.end_testcase_setup(strategy, bp, consistency)
-- setup target servers
local server1 = https_server.new(port1, "a.stressed.test")
local server2 = https_server.new(port2, "a.stressed.test")
server1:start()
server2:start()
-- setup stress test
local proxy_ip = helpers.get_proxy_ip(false)
local proxy_port = helpers.get_proxy_port(false)
local generator1 = stress_generator.new("http", proxy_ip, proxy_port)
-- Go hit them with our test requests
local headers = {
["Host"] = api_host,
["x-stressed"] = "anotherhitonthewall",
}
generator1:run("/", headers, 3, 200)
-- Add some targets
local port3 = bu.gen_port()
local port4 = bu.gen_port()
local server3 = https_server.new(port3, "a.stressed.test")
local server4 = https_server.new(port4, "a.stressed.test")
server3:start()
server4:start()
bu.add_target(bp, upstream_id, "a.stressed.test", port3)
bu.add_target(bp, upstream_id, "a.stressed.test", port4)
helpers.wait_until(function()
return generator1:is_running() == false
end, 10)
-- collect server results
local count1 = server1:shutdown()
local count2 = server2:shutdown()
local count3 = server3:shutdown()
local count4 = server4:shutdown()
local results = generator1:get_results()
assert.are.equal(0, results.proxy_failures)
assert.are.equal(results.successes,
count1.total + count2.total + count3.total + count4.total)
end)
it("add targets to least-connections", function()
bu.begin_testcase_setup(strategy, bp)
local upstream_name, upstream_id = bu.add_upstream(bp, {
algorithm = "least-connections",
})
local port1 = bu.add_target(bp, upstream_id, "localhost")
local port2 = bu.add_target(bp, upstream_id, "localhost")
local api_host = bu.add_api(bp, upstream_name)
bu.end_testcase_setup(strategy, bp, consistency)
-- setup target servers
local server1 = https_server.new(port1, "localhost")
local server2 = https_server.new(port2, "localhost")
server1:start()
server2:start()
-- setup stress test
local proxy_ip = helpers.get_proxy_ip(false)
local proxy_port = helpers.get_proxy_port(false)
local generator1 = stress_generator.new("http", proxy_ip, proxy_port)
-- Go hit them with our test requests
generator1:run("/", {["Host"] = api_host}, 3, 200)
-- Add some targets
local port3 = bu.gen_port()
local port4 = bu.gen_port()
local server3 = https_server.new(port3, "localhost")
local server4 = https_server.new(port4, "localhost")
server3:start()
server4:start()
bu.add_target(bp, upstream_id, "localhost", port3)
bu.add_target(bp, upstream_id, "localhost", port4)
helpers.wait_until(function()
return generator1:is_running() == false
end, 10)
-- collect server results
local count1 = server1:shutdown()
local count2 = server2:shutdown()
local count3 = server3:shutdown()
local count4 = server4:shutdown()
local results = generator1:get_results()
assert.are.equal(0, results.proxy_failures)
assert.are.equal(results.successes,
count1.total + count2.total + count3.total + count4.total)
end)
it("update targets in a round-robin upstream", function()
bu.begin_testcase_setup(strategy, bp)
local upstream_name, upstream_id = bu.add_upstream(bp)
local port1 = bu.add_target(bp, upstream_id, "a.stressed.test")
local port2 = bu.add_target(bp, upstream_id, "a.stressed.test")
local api_host = bu.add_api(bp, upstream_name)
bu.end_testcase_setup(strategy, bp, consistency)
local port3 = bu.gen_port()
local port4 = bu.gen_port()
-- setup target servers
local server1 = https_server.new(port1, "a.stressed.test")
local server2 = https_server.new(port2, "a.stressed.test")
local server3 = https_server.new(port3, "a.stressed.test")
local server4 = https_server.new(port4, "a.stressed.test")
server1:start()
server2:start()
server3:start()
server4:start()
-- setup stress test
local proxy_ip = helpers.get_proxy_ip(false)
local proxy_port = helpers.get_proxy_port(false)
local generator1 = stress_generator.new("http", proxy_ip, proxy_port)
-- Go hit them with our test requests
generator1:run("/", {["Host"] = api_host}, 3, 200)
-- Add a couple of targets
bu.add_target(bp, upstream_id, "a.stressed.test", port3)
bu.add_target(bp, upstream_id, "a.stressed.test", port4)
-- Remove traffic from the first two
bu.update_target(bp, upstream_id, "a.stressed.test", port1, { weight=0 })
bu.update_target(bp, upstream_id, "a.stressed.test", port2, { weight=0 })
-- Wait stress test to finish
helpers.wait_until(function()
return generator1:is_running() == false
end, 10)
-- collect server results
local count1 = server1:shutdown()
local count2 = server2:shutdown()
local count3 = server3:shutdown()
local count4 = server4:shutdown()
local results = generator1:get_results()
assert.are.equal(0, results.proxy_failures)
assert.are.equal(results.successes,
count1.total + count2.total + count3.total + count4.total)
end)
end)
end
end
|
--!strict
--[[
Description: Makes a virtual environment to replace the legacy function environment for running code
Author: github@ccuser44
Date: 15.2.2022
--]]
type dictionary = { [string]: any }
type func = (...any?) -> (...any?)
local globalEnv: dictionary = {
-- // Libraries
coroutine = coroutine,
debug = debug,
math = math,
os = os,
string = string,
table = table,
utf8 = utf8,
bit32 = bit32,
task = task,
-- // Lua globals
assert = assert,
collectgarbage = function(action: string): number -- Use gcinfo instead
assert(type(action) == "string", "invalid argument #1 to 'collectgarbage' (string expected, got "..type(action)..")")
assert(action == "count", "collectgarbage must be called with 'count'; use gcinfo() instead")
return gcinfo()
end,
error = error,
getmetatable = getmetatable,
ipairs = ipairs,
newproxy = newproxy,
next = next,
pairs = pairs,
pcall = pcall,
print = print,
rawequal = rawequal,
rawget = rawget,
rawset = rawset,
select = select,
setmetatable = setmetatable,
tonumber = tonumber,
tostring = tostring,
type = type,
unpack = unpack,
xpcall = xpcall,
warn = warn,
gcinfo = gcinfo,
--_G = _G,
_VERSION = _VERSION,
-- // Roblox globals
settings = settings,
time = time,
typeof = typeof,
UserSettings = UserSettings,
require = require,
game = game,
workspace = workspace,
--shared = shared,
-- // Deprecated Roblox globals (Please don't use, use the alternative instead)
delay = task.delay,-- Use task.delay instead
spawn = task.defer,-- Use task.spawn instead
wait = task.wait,-- Use task.wait instead
elapsedTime = os.clock,-- Use os.clock instead
stats = function(): Stats
return game:GetService("Stats")
end,-- Use game:GetService("Stats") instead
tick = tick,-- Use os.time or os.clock instead
-- // Roblox datatypes
Axes = Axes,
BrickColor = BrickColor,
CatalogSearchParams = CatalogSearchParams,
CFrame = CFrame,
Color3 = Color3,
ColorSequence = ColorSequence,
ColorSequenceKeypoint = ColorSequenceKeypoint,
DateTime = DateTime,
DockWidgetPluginGuiInfo = DockWidgetPluginGuiInfo,
Enum = Enum,
Faces = Faces,
FloatCurveKey = FloatCurveKey,
Instance = Instance,
NumberRange = NumberRange,
NumberSequence = NumberSequence,
NumberSequenceKeypoint = NumberSequenceKeypoint,
OverlapParams = OverlapParams,
PathWaypoint = PathWaypoint,
PhysicalProperties = PhysicalProperties,
Random = Random,
Ray = Ray,
RaycastParams = RaycastParams,
Rect = Rect,
Region3 = Region3,
Region3int16 = Region3int16,
TweenInfo = TweenInfo,
UDim = UDim,
UDim2 = UDim2,
Vector2 = Vector2,
Vector2int16 = Vector2int16,
Vector3 = Vector3,
Vector3int16 = Vector3int16,
}
table.freeze(globalEnv)
return function()
local env: dictionary = {}
for k: string, v: any in pairs(globalEnv) do
env[k] = v
end
env._ENV = env :: dictionary
env["getf".."env"] = function(target: (func | number)?): dictionary
assert(type(target) == "number" or type(target) == "function" or type(target) == "nil", "invalid argument #1 to 'getf".."env' (number expected, got "..type(target)..")")
assert(type(target) == "number" and target >= 0 or type(target) ~= "number", "invalid argument #1 to 'getf".."env' (level must be non-negative)")
return env
end
env["setf".."env"] = function(target: func | number, newEnv: dictionary): ()
assert(type(newEnv) == "table", "invalid argument #2 to 'setf".."env' (table expected, got "..type(newEnv)..")")
assert(type(target) == "number" or type(target) == "function", "invalid argument #1 to 'setf".."env' (number expected, got "..type(target)..")")
assert(type(target) == "number" and target >= 0, "invalid argument #1 to 'setf".."env' (level must be non-negative)")
table.clear(env)
for k: string, v: any in pairs(newEnv) do
if type(k) == "string" then
env[k] = v
end
end
end
setmetatable(env, table.freeze({
__index = globalEnv,
__metatable = "The metatable is locked"
}))
return env
end
|
food_effects.register_callback = function(foodname, seconds, enable_hud, callback)
food_effects.items_with_effects[foodname] = true
-- playername -> timeout
local data = {}
-- playername -> {}
local hud = {}
local hud_image = ""
if enable_hud then
local itemdef = minetest.registered_items[foodname]
hud_image = itemdef.inventory_image
minetest.register_on_joinplayer(function(player)
local hud_data = {}
hud[player:get_player_name()] = hud_data
hud_data.time = player:hud_add({
hud_elem_type = "text",
position = food_effects.HUD_POSITION,
offset = {x = 0, y = 0 + food_effects.HUD_Y_OFFSET},
text = "",
alignment = food_effects.HUD_ALIGNMENT,
scale = {x = 100, y = 100},
number = 0x00FF00
})
hud_data.img = player:hud_add({
hud_elem_type = "image",
position = food_effects.HUD_POSITION,
offset = {x = -32, y = -8 + food_effects.HUD_Y_OFFSET},
text = "",
alignment = food_effects.HUD_ALIGNMENT,
scale = {x = 2, y = 2},
})
food_effects.HUD_Y_OFFSET = food_effects.HUD_Y_OFFSET + 24
end)
minetest.register_on_leaveplayer(function(player)
hud[player:get_player_name()] = nil
end)
end
local timer = 0
minetest.register_globalstep(function(dtime)
timer = timer + dtime
if timer < 0.8 then
return
end
timer = 0
for playername in pairs(data) do
local time = data[playername]
time = time - 0.2
local player = minetest.get_player_by_name(playername)
if time < 0 then
time = nil
if enable_hud then
local hud_data = hud[playername]
player:hud_change(hud_data.time, "text", "")
player:hud_change(hud_data.img, "text", "")
end
if player then
callback(player)
minetest.sound_play("food_effects_out", {
to_player = player:get_player_name(),
gain = 0.7
})
end
elseif enable_hud then
local hud_data = hud[playername]
player:hud_change(hud_data.time, "text", math.floor(time*10)/10 .. " s")
player:hud_change(hud_data.img, "text", hud_image)
end
data[playername] = time
end
end)
minetest.register_on_item_eat(function(_, _, itemstack, player)
local name = itemstack:get_name()
if name == foodname then
data[player:get_player_name()] = seconds
end
end)
end
|
------------------------------------------------------------------------------
--
-- This file is part of the Corona game engine.
-- For overview and more information on licensing please refer to README.md
-- Home page: https://github.com/coronalabs/corona
-- Contact: support@coronalabs.com
--
------------------------------------------------------------------------------
simulator =
{
device = "ios-tablet",
screenOriginX = 47,
screenOriginY = 131,
screenWidth = 768,
screenHeight = 1024,
iosPointWidth = 768,
iosPointHeight = 1024,
safeLandscapeScreenInsetStatusBar = 20 * 2,
safeScreenInsetStatusBar = 20 * 2,
deviceImage = "iPadMini.png",
displayManufacturer = "Apple",
displayName = "iPad",
statusBarDefault = "iPadMiniStatusBarBlack.png",
statusBarTranslucent = "iPadMiniStatusBarWhite.png",
statusBarBlack = "iPadMiniStatusBarBlack.png",
statusBarLightTransparent = "iPadMiniStatusBarWhite.png",
statusBarDarkTransparent = "iPadMiniStatusBarBlack.png",
windowTitleBarName = "iPad mini",
defaultFontSize = 17 * 2,
}
|
local json = require('json')
local WebSocket = require('coro-websocket')
local constants = require('../constants')
local base = require('./base')
local class = require('../classes/new')
local voice = require('../voice')
local VoiceConnection = class(base)
function VoiceConnection:__constructor () -- .parent = server / .parent = client
do
print('* Voice is not fully implemented yet.')
--return
end
--
self.__data = {}
self.__udp = voice.UDP(self)
self.__socket = voice.Socket(self)
self.__socket:on(
constants.voice.OPcodes.READY,
function(data)
self.__udp:connect(data)
end
)
--
self.parent.parent:once(
{
constants.events.VOICE_STATE_UPDATE,
constants.events.VOICE_SERVER_UPDATE,
},
function(data)
for k,v in pairs(data) do
self.__data[k] = v
end
self:__onUpdate()
end
)
end
function VoiceConnection:connect (channelID)
if self.__socket.status == constants.socket.status.CONNECTED then
self:disconnect()
end
--
self.parent.parent.socket:send(
constants.socket.OPcodes.VOICE_STATE_UPDATE,
{
channel_id = channelID,
guild_id = self.parent.id,
self_mute = false,
self_deaf = false,
}
)
end
function VoiceConnection:setSpeaking (state)
self.__socket:send(
constants.voice.OPcodes.SPEAKING,
{
speaking = state,
}
)
end
function VoiceConnection:disconnect ()
self.__manualDisconnect = true
self.__socket:disconnect()
self:__disconnect()
end
function VoiceConnection:__disconnect ()
self.__data = {}
self.__udp:disconnect()
self.parent.parent.socket:send(
constants.socket.OPcodes.VOICE_STATE_UPDATE,
{
channel_id = json.null,
guild_id = self.parent.id,
self_mute = false,
self_deaf = false,
}
)
end
function VoiceConnection:__onUpdate ()
if (self.__socket.status == constants.socket.status.CONNECTED) or not self.__data.user_id or not self.__data.session_id or not self.__data.token or not self.__data.guild_id or not self.__data.endpoint then return end
local parsed = WebSocket.parseUrl('wss://'..self.__data.endpoint..'/')
self.__data.endpoint = parsed.host -- removing port from endpoint, basically
coroutine.wrap(
function()
self.__socket:connect()
end
)()
end
return VoiceConnection |
object_tangible_quest_rebel_rtp_ackbar_wave_sympathizer_signal = object_tangible_quest_rebel_shared_rtp_ackbar_wave_sympathizer_signal:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_rebel_rtp_ackbar_wave_sympathizer_signal, "object/tangible/quest/rebel/rtp_ackbar_wave_sympathizer_signal.iff")
|
u_execScript("common.lua")
u_execScript("commonpatterns.lua")
u_execScript("utils.lua")
u_execScript("alternativepatterns.lua")
function wallSAdj(mSide, mAdj) w_wallAdj(mSide, THICKNESS, mAdj) end
function wallSAcc(mSide, mAdj, mAcc, mMinSpd, mMaxSpd) w_wallAcc(mSide, THICKNESS, mAdj, mAcc * (u_getDifficultyMult()), mMinSpd, mMaxSpd) end
function pTrapBarrage(mSide)
local delay = getPerfectDelayDM(THICKNESS) * 3.7
cBarrage(mSide)
t_wait(delay * 3)
wallSAdj(mSide, 1.9)
t_wait(delay * 2.5)
end
function pTrapBarrageDouble(mSide)
local delay = getPerfectDelayDM(THICKNESS) * 3.7
local side2 = mSide + getHalfSides()
for i = 0, l_getSides() - 1 do
local currentSide = mSide + i
if((currentSide ~= mSide) and (currentSide ~= side2)) then cWall(currentSide) end
end
t_wait(delay * 3)
wallSAdj(mSide, 1.9)
wallSAdj(side2, 1.9)
t_wait(delay * 2.5)
end
function pTrapBarrageInverse(mSide)
local delay = getPerfectDelayDM(THICKNESS) * 3.7
cWall(mSide)
t_wait(delay * 3)
for i = 0, l_getSides() - 1 do
local currentSide = mSide + i
if(currentSide ~= mSide) then wallSAdj(currentSide, 1.9) end
end
t_wait(delay * 2.5)
end
function pTrapBarrageAlt(mSide)
local delay = getPerfectDelayDM(THICKNESS) * 3.7
for i = 0, l_getSides() - 1 do
local currentSide = mSide + i
if(currentSide % 2 ~= 0) then cWall(currentSide) end
end
t_wait(delay * 3)
for i = 0, l_getSides() - 1 do
local currentSide = mSide + i
if(currentSide % 2 == 0) then wallSAdj(currentSide, 1.9) end
end
t_wait(delay * 2.5)
end
function pTrapSpiral(mSide)
local delay = getPerfectDelayDM(THICKNESS) * 3.7
local loopDir = getRandomDir()
if(l_getSides() < 6) then delay = delay + 4 end
for i = 0, l_getSides() + getHalfSides() do
local currentSide = (mSide + i) * loopDir
for j = 0, getHalfSides() do wallSAdj(currentSide + j, 1.2 + (i / 7.9)) end
t_wait((delay * 0.75) - (i * 0.45) + 3)
end
t_wait(delay * 2.5)
end
function pRCBarrage()
local currentSides = l_getSides()
local delay = getPerfectDelayDM(THICKNESS) * 3.7
local startSide = u_rndInt(0, 10)
for i = 0, currentSides - 2 do
local currentSide = startSide + i
cWall(currentSide)
end
t_wait(delay * 2.5)
end
function pRCBarrageDouble()
local currentSides = l_getSides()
local delay = getPerfectDelayDM(THICKNESS) * 3.7
local startSide = u_rndInt(0, 10)
for i = 0, currentSides - 2 do
local currentSide = startSide + i
local holeSide = startSide + i + (currentSides / 2)
if(i ~= holeSide) then cWall(currentSide) end
end
t_wait(delay * 2.5)
end
function pRCBarrageSpin()
local currentSides = l_getSides()
local delay = getPerfectDelayDM(THICKNESS) * 3.7
local startSide = u_rndInt(0, 10)
local loopDir = getRandomDir()
for j = 0, 2 do
for i = 0, currentSides - 2 do
local currentSide = startSide + i
cWall(currentSide + (j * loopDir))
end
t_wait(delay + 1)
end
t_wait(delay * 2.5)
end
function pACBarrage()
local currentSides = l_getSides()
local delay = getPerfectDelayDM(THICKNESS) * 3.7
local startSide = u_rndInt(0, 10)
for i = 0, currentSides - 2 do
local currentSide = startSide + i
wallSAcc(currentSide, 9 + u_rndInt(0, 1), -1.1, 1, 12)
end
t_wait(delay * 2.5)
end
function pACBarrageMulti()
local currentSides = l_getSides()
local delay = getPerfectDelayDM(THICKNESS) * 3.7
local startSide = u_rndInt(0, 10)
for i = 0, currentSides - 2 do
local currentSide = startSide + i
wallSAcc(currentSide, 10, -1.09, 0.31, 10)
wallSAcc(currentSide, 0, 0.05, 0, 4.0)
wallSAcc(currentSide, 0, 0.09, 0, 4.0)
wallSAcc(currentSide, 0, 0.12, 0, 4.0)
end
t_wait(delay * 8)
end
function pACBarrageMultiAltDir()
local currentSides = l_getSides()
local delay = getPerfectDelayDM(THICKNESS) * 4
local mdiff = 1 + math.abs(1 - u_getDifficultyMult())
local startSide = u_rndInt(0, 10)
local loopDir = getRandomDir()
for i = 0, currentSides + getHalfSides() do
local currentSide = startSide + i * loopDir
wallSAcc(currentSide, 10, -1.095, 0.40, 10)
t_wait((delay / 2.21) * (mdiff * 1.29))
wallSAcc(currentSide + (getHalfSides() * loopDir), 0, 0.128, 0, 1.4)
end
t_wait(delay * 8)
end
|
local M = {}
function M.get(cp)
return {
FernBranchText = { fg = cp.blue },
}
end
return M
|
--[[
* author : kaishiqi
* descpt : create on 2016-03-18
]]
local Entry = require 'i18n.Entry'
local MoParser = {}
MoParser.__index = MoParser
MoParser.ErrMsg = {
NotFind = 'file load fail.',
NoValid = 'no valid mo-file',
Version = 'unsupported version',
}
local MoDefine = {
MAGIC_BIG = '\222\018\004\149', -- 0xde120495
MAGIC_LITTLE = '\149\004\018\222', -- 0x950412de
BYTE_SIZE = 4,
CHUNK_SIZE = 8,
CONTEXT_SEP = '\004', -- 0x04
PLURAL_SEP = '\000', -- 0x00
HEADER_SEP = ': ',
FORM_INFO_SEP = ';',
PLURAL_INFO_KEY = 'Plural-Forms',
NPLURAL_KEY = 'nplurals=',
PLURAL_KEY = ' plural=',
LogicSymbolMap = {
['!'] = '~',
[':'] = 'or',
['?'] = 'and',
['||'] = 'or',
['&&'] = 'and',
}
}
-------------------------------------------------
-- life cycle
function MoParser.new(filePath)
local instance = setmetatable({}, MoParser)
instance:ctor(filePath)
return instance
end
function MoParser:ctor(filePath)
self.handerInfos_ = {}
self.entryMap_ = {}
self.pluralExp_ = nil
self.nplurals_ = 0
self.inited_, self.errMsg_ = self:parseMoFile_(self:loadMoFile_(filePath))
end
-------------------------------------------------
-- get / set
function MoParser:isInited()
return self.inited_ == true
end
function MoParser:getErrorMsg()
return self.errMsg_
end
function MoParser:getHanderInfos()
return self.handerInfos_
end
function MoParser:getEntryMap()
return self.entryMap_
end
function MoParser:getPlurals()
return self.nplurals_
end
-------------------------------------------------
-- public method
function MoParser:calculatePlural(n)
local pluralIndex = 0
if self.pluralExp_ then
local expressionStr = string.format('local n = %d \n return %s', n, self.pluralExp_)
local expressionFun = loadstring(expressionStr)
local ok, ret = pcall(expressionFun)
if ok then
if type(ret) == 'boolean' then
pluralIndex = ret == true and 1 or 0
else
pluralIndex = ret
end
end
end
return pluralIndex + 1
end
function MoParser:translate(singular, context)
local keyword = self:buildEntryKey_(singular, context)
local entry = self.entryMap_[keyword]
local translation = singular
if entry and entry:getTranslations() then
translation = entry:getTranslations()[1]
end
return translation
end
function MoParser:translatePlural(singular, plural, count, context)
local keyword = self:buildEntryKey_(singular, context)
local entry = self.entryMap_[keyword]
local number = tonumber(count) or 0
local transIndex = self:calculatePlural(number)
local translation = number > 1 and plural or singular
if entry and entry:getTranslations() and entry:getTranslations()[transIndex] then
translation = entry:getTranslations()[transIndex]
end
return translation
end
-------------------------------------------------
-- private method
function MoParser:loadMoFile_(filePath)
local moBytes = nil
if cc and cc.FileUtils then
-- use cocos2d-x cc.FileUtils, cross-platform
moBytes = cc.FileUtils:getInstance():getDataFromFile(filePath)
else
-- use lua io, cannot use in Android
local fd, err = io.open(filePath, 'rb')
if fd then
moBytes = fd:read('*all')
fd:close()
end
end
return moBytes
end
function MoParser:parseMoFile_(moBytes)
if moBytes == nil then return false, MoParser.ErrMsg.NotFind end
-------------------------------------------------
-- predefine some functions
local peekLongBig = function(bytes, offs)
local a, b, c, d = string.byte(bytes, offs + 1, offs + MoDefine.BYTE_SIZE)
return ((d * 256 + c) * 256 + b) * 256 + a
end
local peekLongLittle = function(bytes, offs)
local a, b, c, d = string.byte(bytes, offs + 1, offs + MoDefine.BYTE_SIZE)
return ((a * 256 + b) * 256 + c) * 256 + d
end
local splitString = function(src, delimiter)
local pos, strs, idx = 0, {}, 1
local src, delimiter = tostring(src), tostring(delimiter)
for st, sp in function() return string.find(src, delimiter, pos, true) end do
strs[idx] = string.sub(src, pos, st - 1)
idx = idx + 1
pos = sp + 1
end
strs[idx] = string.sub(src, pos)
return strs
end
-------------------------------------------------
-- check format in MO file.
-- @see http://www.gnu.org/savannah-checkouts/gnu/gettext/manual/html_node/MO-Files.html
local peekLong = nil
local magic = string.sub(moBytes, 1, MoDefine.BYTE_SIZE)
if magic == MoDefine.MAGIC_BIG then
peekLong = peekLongBig
elseif magic == MoDefine.MAGIC_LITTLE then
peekLong = peekLongLittle
else
return false, MoParser.ErrMsg.NoValid
end
-------------------------------------------------
-- check version
local version = peekLong(moBytes, 4)
if version ~= 0 then
return false, MoParser.ErrMsg.Version
end
-------------------------------------------------
-- get number of N, o, T, S, H
local moN = peekLong(moBytes, 8)
local moO = peekLong(moBytes, 12)
local moT = peekLong(moBytes, 16)
local moS = peekLong(moBytes, 20)
local moH = peekLong(moBytes, 24)
-------------------------------------------------
-- translation and get strings
local pluralSepLen = string.len(MoDefine.PLURAL_SEP)
local contextSepLen = string.len(MoDefine.CONTEXT_SEP)
for i = 1, moN do
local originalLength = peekLong(moBytes, moO)
local originalOffset = peekLong(moBytes, moO + MoDefine.BYTE_SIZE)
local translationLength = peekLong(moBytes, moT)
local translationOffset = peekLong(moBytes, moT + MoDefine.BYTE_SIZE)
local originalStr = string.sub(moBytes, originalOffset + 1, originalOffset + originalLength)
local translationStr = string.sub(moBytes, translationOffset + 1, translationOffset + translationLength)
moO = moO + MoDefine.CHUNK_SIZE
moT = moT + MoDefine.CHUNK_SIZE
if 0 == originalLength then
-- parse header infos
local infoPos, sepLen = 0, string.len(MoDefine.HEADER_SEP)
for _, info in ipairs(splitString(translationStr, '\n')) do
local separatorPos = string.find(info, MoDefine.HEADER_SEP)
if separatorPos then
local infoKey = string.sub(info, 0, separatorPos - 1)
local infoValue = string.sub(info, separatorPos + sepLen)
self.handerInfos_[infoKey] = infoValue
end
end
-- parse pluralForms
local pluralFormStr = self:getHanderInfos()[MoDefine.PLURAL_INFO_KEY]
if pluralFormStr then
local pluralFormStrs = splitString(pluralFormStr, MoDefine.FORM_INFO_SEP)
local npluralStr = string.sub(pluralFormStrs[1], string.len(MoDefine.NPLURAL_KEY) + 1)
local pluralStr = string.sub(pluralFormStrs[2], string.len(MoDefine.PLURAL_KEY) + 1)
for symbol, luaValue in pairs(MoDefine.LogicSymbolMap) do
pluralStr = string.gsub(pluralStr, symbol, luaValue)
end
self.nplurals_ = tonumber(npluralStr) or 0
self.pluralExp_ = pluralStr
end
else
--[[
Build a TranslationEntry from original string and translation strings, found in a MO file.
original strring contain 0x04 as context separator or 0x00 as singular/plural separator.
translation string contain 0x00 as a plural translations separator.
]]
local entry = Entry.new()
-- parse original string
local contextPos = string.find(originalStr, MoDefine.CONTEXT_SEP)
if contextPos then
local original = string.sub(originalStr, contextPos + pluralSepLen)
entry:setContext(string.sub(originalStr, 0, contextPos - 1))
entry:setOriginals(splitString(original, MoDefine.PLURAL_SEP))
else
entry:setOriginals(splitString(originalStr, MoDefine.PLURAL_SEP))
end
-- parse translation string
entry:setTranslations(splitString(translationStr, MoDefine.PLURAL_SEP))
-- entry cache append
local keyword = self:buildEntryKey_(entry:getSingular(), entry:getContext())
if keyword then
self.entryMap_[keyword] = entry
end
end
end
return true
end
function MoParser:buildEntryKey_(singular, context)
if context then
return tostring(singular) .. MoDefine.CONTEXT_SEP .. context
else
return tostring(singular)
end
end
return MoParser
|
-- yx_proto.lua
----------------------------------------------------------------------------------------
local M = {}
-- 相关的协议
M.C2S = {
-- 访问S的协议
CONNECT = 0x0001,
CHALLENGE_RESPONSE = 0x0002,
JOIN_SERVER = 0x0003,
REQ_CONN_GATEWAY = 0x0004,
}
M.S2C = {
-- 访问C的协议
CONNECT = 0x1001,
CHALLENGE = 0x1002,
CONNECT_ACCEPT = 0x1003,
CONNECT_REJECT = 0x1004,
JOIN_SERVER_RESPONSE = 0x1005,
REQ_CONN_GATEWAY_RESPONSE = 0x1006,
}
M.G2G = {
GF2G_FORWARD = 0x2001,
GF2G_FORWARD_CLOSE = 0x2002,
G2GF_FORWARD = 0x2003,
}
----------------------------------------------------------------------------------------
return M
|
local msg = require "toy.logger"
local bug = require "toy.debug"
local function create_window()
local config =
{
title = "Sample window;範例視窗",
width = 800,
height = 600,
}
return require("toy.window").create_window(config)
end
msg.print("Starting")
local function main()
local window = create_window()
-- handleEvent:Mouse event, keyboard event, system event, etc.
while window:handle_event() do
window:display() -- Refresh screen.
end
end
if bug.catch(main) then
bug.oops()
end
msg.print("Quit")
|
local AddonName, Addon = ...
local AceLocale = LibStub:GetLibrary("AceLocale-3.0")
local L = AceLocale:NewLocale(AddonName, "enUS", true, true)
if not L then return end
Addon.AliasPrefix = "cb_"
-- TODO: Figure out how to make this available in other files.
local function S(text)
text = text:gsub("|B", "|cff00c0f0") -- Bold
text = text:gsub("|C", "|cff00f0c0") -- Commands
text = text:gsub("|P", "|cff00c080") -- Parameters
text = text:gsub("|O", "|cff808080") -- Optional parameters
text = text:gsub("|H", "|cffb060b0") -- Help text
text = text:gsub("|W", "|cfff0c000") -- Warnings
return text
end
-- Text
L["Aliases"] = true
L["Chatbot"] = S("Chatbot |B9000|r")
L["Commands"] = true
L["Configure which modules should be enabled."] = true
L["Could not upsert macro %s."] = S("Could not upsert macro |B%s|r.")
L["Cycle Language"] = true
L["Determines whether or not command aliases are prefixed with _."] = S("Determines whether or not command aliases are prefixed with |B"..Addon.AliasPrefix.."_|r.")
L["Determines whether or not to chat message should actually be sent."] = true
L["Determines whether or not to print debug messages."] = true
L["Determines whether the 'Cycle Language' macro should be created/updated when changing languages."] = true
L["Does your socializing for you!"] = true
L["Enable the %s module."] = S("Enable the |B%s|r module.")
L["Language Macro"] = true
L["Languages"] = true
L["Modules"] = true
L["Now speaking %s."] = S("Now speaking |B%s|r.")
L["Options"] = true
L["Prefix Aliases"] = true
L["Random"] = true
L["The Languages module contains functionality to help you switch in-game languages easily."] = S("The |BLanguages|r module contains functionality to help you switch in-game languages easily.")
L["The Random module includes commands that allow you to randomize your chat macros."] = S("The |BRandom|r module includes commands that allow you to randomize your chat macros.")
L["Usage:"] = S("|HUsage|r:")
L["You don't know how to speak %s."] = S("You don't know how to speak |B%s|r.")
L["/%s%s -> "] = S("/|O%s|r|C%s|r -> ")
-- Commands
L["Languages__cycle_language"] = S("/|Ccycle_language|r - Cycles between the languages you can speak.|r")
L["Languages__set_language"] = S("/|Cset_language|r |O[name]|r - Sets your chat language to the specified language.|r")
L["Languages__reset_language"] = S("/|Creset_language|r|r - Resets your chat language to the default language.|r")
L["Random__random_message"] = S("/|Crandom_message|r |P(message|O[; ...]|r)|r - Chooses a chat message to randomly say.|r")
L["Random__random_emote"] = S("/|Crandom_emote|r |P(emote|O[; ...]|r)|r - Chooses a chat emote to randomly play.|r")
|
minetest.register_craftitem("elepower_machines:compressor_piston", {
description = "Compressor Piston",
inventory_image = "elepower_compressor_piston.png"
})
minetest.register_craftitem("elepower_machines:turbine_blades", {
description = "Turbine Blades",
inventory_image = "elepower_turbine.png"
})
-- Pump Tube Roll
minetest.register_craftitem("elepower_machines:opaque_duct_roll", {
description = "Retractable Opaque Fluid Duct\nA Pump uses this to reach fluids.",
inventory_image = "elepower_opaque_duct.png",
})
---------------
-- Upgrading --
---------------
-- Capacitors
minetest.register_craftitem("elepower_machines:hardened_capacitor", {
description = "Hardened Capacitor\nTier 2 Capacitor",
groups = {capacitor = 2, ele_upgrade_component = 1},
inventory_image = "elepower_upgrade_hardened_capacitor.png",
ele_upgrade = {
capacity = {
multiplier = 1,
},
},
})
minetest.register_craftitem("elepower_machines:reinforced_capacitor", {
description = "Reinforced Capacitor\nIt will probably obliterate you if you touched it while charged\nTier 3 Capacitor",
groups = {capacitor = 3, ele_upgrade_component = 1},
inventory_image = "elepower_upgrade_reinforced_capacitor.png",
ele_upgrade = {
capacity = {
multiplier = 1,
},
},
})
minetest.register_craftitem("elepower_machines:resonant_capacitor", {
description = "Resonant Capacitor\nTier 4 Capacitor",
groups = {capacitor = 4, ele_upgrade_component = 1},
inventory_image = "elepower_upgrade_resonant_capacitor.png",
ele_upgrade = {
capacity = {
multiplier = 10,
},
},
})
minetest.register_craftitem("elepower_machines:super_capacitor", {
description = "Supercapacitor\nAmazing energy density in a small container! Wow!\nTier 5 Capacitor",
groups = {capacitor = 5, ele_upgrade_component = 1},
inventory_image = "elepower_upgrade_supercapacitor.png",
ele_upgrade = {
capacity = {
multiplier = 100,
},
},
})
-- Machine chips
minetest.register_craftitem("elepower_machines:upgrade_speed", {
description = "Speed Upgrade\nCrafting Speed +1\nPower Usage +50%",
groups = {machine_chip = 2, ele_upgrade_component = 1},
inventory_image = "elepower_upgrade_speed.png",
ele_upgrade = {
craft_speed = {
add = 1
},
usage = {
multiplier = 0.5
},
inrush = {
multiplier = 0.5
}
}
})
minetest.register_craftitem("elepower_machines:upgrade_efficiency", {
description = "Efficiency Upgrade\nReduces power usage by 25%",
groups = {machine_chip = 2, ele_upgrade_component = 1},
inventory_image = "elepower_upgrade_efficiency.png",
ele_upgrade = {
usage = {
divider = 0.25
}
}
})
minetest.register_craftitem("elepower_machines:upgrade_efficiency_2", {
description = "Efficiency Upgrade\nReduces power usage by 50%",
groups = {machine_chip = 2, ele_upgrade_component = 1},
inventory_image = "elepower_upgrade_efficiency_2.png",
ele_upgrade = {
usage = {
divider = 0.50
}
}
})
-- Accumulator filter
minetest.register_craftitem("elepower_machines:heavy_filter", {
description = "Liquid Weight Filter\nMakes water pumps pump only Heavy Water\nRight-Click to apply to Water Accumulator",
groups = {accumulator_filter = 1, pump_filter = 2, ele_upgrade_component = 1},
inventory_image = "elepower_accumulator_filter.png",
on_place = function (itemstack, placer, pointed_thing)
if not placer or not placer:is_player() then return itemstack end
local pos = pointed_thing.under
if pointed_thing.type ~= "node" or minetest.is_protected(pos, placer:get_player_name()) then return itemstack end
local node = minetest.get_node(pos)
if node.name ~= "elepower_machines:accumulator" then return itemstack end
minetest.swap_node(pos, {name = "elepower_machines:accumulator_heavy"})
local meta = minetest.get_meta(pos)
meta:set_int("water_fluid_storage", 0)
meta:set_string("water_fluid", "elepower_nuclear:heavy_water_source")
itemstack:take_item(1)
return itemstack
end
})
-- Wind turbine
minetest.register_craftitem("elepower_machines:wind_turbine_blade", {
description = "Wind Turbine Blade (Wooden)",
inventory_image = "elepower_wind_turbine_blade.png",
})
|
AddCSLuaFile()
AddCSLuaFile("sh_sounds.lua")
AddCSLuaFile("sh_soundscript.lua")
include("sh_sounds.lua")
include("sh_soundscript.lua")
if CLIENT then
SWEP.DrawCrosshair = false
SWEP.PrintName = "M1928A1"
SWEP.CSMuzzleFlashes = true
SWEP.UseHands = false
SWEP.MuzzleEffect = "muzzleflash_ak74"
SWEP.PosBasedMuz = true
SWEP.SightWithRail = true
SWEP.EffectiveRange_Orig = 130 * 39.37
SWEP.DamageFallOff_Orig = .7
SWEP.Shell = "khr9x19"
SWEP.ShellScale = .51
SWEP.ShellDelay = .05
SWEP.ShellOffsetMul = 1
SWEP.ShellPosOffset = {x = 5.35, y = -3.5, z = 0}
SWEP.ForeGripOffsetCycle_Draw = 0
SWEP.ForeGripOffsetCycle_Reload = .825
SWEP.ForeGripOffsetCycle_Reload_Empty = .825
SWEP.IronsightPos = Vector(-2.236, -2.25, 1.048)
SWEP.IronsightAng = Vector(0.1611, 0.0052, 0)
SWEP.CustomizePos = Vector(10, -4, -2)
SWEP.CustomizeAng = Vector(20, 45, 15)
SWEP.SprintPos = Vector(2, 0, -1)
SWEP.SprintAng = Vector(-15.478, 20.96, -15)
SWEP.AlternativePos = Vector(-.6, .25, -0.45)
SWEP.AlternativeAng = Vector(0.1611, 0.0052, 0)
SWEP.Alternative1Pos = Vector(-.6, .25, -0.45)
SWEP.Alternative1Ang = Vector(0.1611, 0.0052, 0)
SWEP.Alternative2Pos = Vector(-.8, -1.2, -0.65)
SWEP.Alternative2Ang = Vector(0.1611, 0.0052, -3)
SWEP.SwimPos = Vector(0.5682, -1.7045, 1.0526)
SWEP.SwimAng = Vector(-50.8947, 35.0455, -25.2273)
SWEP.PronePos = Vector(0, -2, -4.5)
SWEP.ProneAng = Vector(-10, 42.7368, -50.9474)
SWEP.MoveType = 1
SWEP.ViewModelMovementScale = .9
SWEP.DisableSprintViewSimulation = false
SWEP.CustomizationMenuScale = 0.019 -- 0.022
SWEP.AttachmentModelsVM = {["md_cobram2"] = {model = "models/cw2/attachments/cobra_m2.mdl", bone = "M1928A1", pos = Vector(0, 17, 1.33), angle = Angle(0, 90, 0), size = Vector(1.3, 1.3, 1.3), color = Color(255, 255, 255, 255)}}
SWEP.ForegripOverridePos = {
["foregrip"] = {
["L Finger32"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 14.444, 0) },
["L ForeTwist2"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 8.332) },
["L Clavicle"] = { scale = Vector(1, 1, 1), pos = Vector(.25, -0.301, .4), angle = Angle(-1.111, 3.332, 3.332) },
["L Hand"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(16.666, -10.111, 61.111) },
["L Finger01"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-5.557, 5.556, 16.666) },
["L Finger0"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(23.333, 10, 1.11) },
["L Finger42"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 58.888, 0) },
["L Finger22"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 36.666, 0) },
["L Finger41"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 7.777, 0) },
["L Finger02"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 45.555, 0) },
["L Finger31"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 16.666, 0) },
["L ForeTwist4"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 6) },
["L ForeTwist"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L Forearm"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 2.444) },
["L ForeTwist1"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 15) },
["L ForeTwist5"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 12) }},
["nah"] = {
["L Finger32"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L ForeTwist2"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L Clavicle"] = { scale = Vector(1, 1, 1), pos = Vector(-.25, 0, 0), angle = Angle(0, 0, 0) },
["L Hand"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L Finger01"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-5, -5, 0) },
["L Finger0"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 2, 0) },
["L Finger42"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L Finger22"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L Finger41"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L Finger02"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L Finger31"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L ForeTwist4"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L ForeTwist"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L Forearm"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L ForeTwist1"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["L ForeTwist3"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) }},
}
SWEP.LuaVMRecoilAxisMod = {vert = -.15, hor = .15, roll = .2, forward = .3, pitch = .2}
end
SWEP.MuzzleVelocity = 250
SWEP.LuaViewmodelRecoil = true
SWEP.LuaViewmodelRecoilOverride = true
SWEP.FullAimViewmodelRecoil = false
SWEP.CanRestOnObjects = true
SWEP.GripBGs = {main = 2, off = 0, on = 1}
SWEP.MagBGs = {main = 3, twenty = 0, thirty = 1, fifty = 2}
SWEP.BarrelBGs = {main = 5, smg = 0, carbine = 1}
SWEP.StockBGs = {main = 4, off = 0, on = 1}
SWEP.Attachments = {[2] = {header = "Barrel Extension", offset = {-650, -450}, atts = {"md_cobram2"}},
["+reload"] = {header = "Ammo", offset = {-370, 70}, atts = {"am_hollowpoint", "am_armorpiercing"}}}
SWEP.Animations = {fire = {"base_fire_1"},
fire_aim = {"iron_fire_1","iron_fire_2"},
reload = "base_reload",
reload_empty = "base_reload",
idle = "base_idle",
draw = "base_draw"}
SWEP.SpeedDec = 30
SWEP.Slot = 3
SWEP.SlotPos = 0
SWEP.HoldType = "ar2"
SWEP.NormalHoldType = "ar2"
SWEP.RunHoldType = "crossbow"
SWEP.FireModes = {"auto","semi"}
SWEP.Base = "cw_base"
SWEP.Category = "STALKER Weapons"
SWEP.Author = ""
SWEP.Contact = ""
SWEP.Purpose = ""
SWEP.Instructions = ""
SWEP.NearWallEnabled = true
SWEP.ViewModelFOV = 67
SWEP.AimViewModelFOV = 65
SWEP.ZoomAmount = 10
SWEP.ViewModelFlip = false
SWEP.ViewModel = "models/khrcw2/doipack/thompson1928.mdl"
SWEP.WorldModel = "models/khrcw2/doipack/w_thompson1928.mdl"
SWEP.DrawTraditionalWorldModel = false
SWEP.WM = "models/khrcw2/doipack/w_thompson1928.mdl"
SWEP.WMPos = Vector(-.9, 4, 1.5)
SWEP.WMAng = Vector(-10, 1, 180)
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.ReloadViewBobEnabled = true
SWEP.RVBPitchMod = .4
SWEP.RVBYawMod = 0
SWEP.RVBRollMod = .5
SWEP.Primary.ClipSize = 50
SWEP.Primary.DefaultClip = 0
SWEP.Primary.Automatic = true
SWEP.Chamberable = false
SWEP.Primary.Ammo = ".45 ACP"
SWEP.FireDelay = 60/750
SWEP.FireDelayAuto = 60/750
SWEP.FireDelaySemi = 60/700
SWEP.FireSound = "DOITHOM1928_FIRE"
SWEP.FireSoundSuppressed = "DOITHOM1928_FIRE_SUPPRESSED"
SWEP.Recoil = 1.45
SWEP.FOVPerShot = 0.1 -- = .62
SWEP.HipSpread = 0.056
SWEP.AimSpread = 0.016
SWEP.VelocitySensitivity = .4
SWEP.MaxSpreadInc = 0.05
SWEP.SpreadPerShot = 0.013
SWEP.SpreadCooldown = 0.175
SWEP.Shots = 1
SWEP.Damage = 51
SWEP.DeployTime = .462
SWEP.HolsterTime = .6
SWEP.ADSFireAnim = true
SWEP.RecoilToSpread = .35
SWEP.ReloadSpeed = 1.1
SWEP.ReloadTime = 2.4
SWEP.ReloadHalt = 3.2
SWEP.ReloadTime_Empty = 2.4
SWEP.ReloadHalt_Empty = 3.2
function SWEP:IndividualInitialize()
self:setBodygroup(self.GripBGs.main, self.GripBGs.on)
self.ForegripOverride = true
self.ForegripParent = "foregrip"
self:setBodygroup(self.MagBGs.main, self.MagBGs.fifty)
self.Animations = {fire = {"base_fire_1"},
fire_aim = {"iron_fire_1","iron_fire_2"},
fire_last = {"base_firelast"},
fire_last_aim = {"iron_firelast"},
reload = "base_reload_drum",
reload_empty = "base_reload_drum",
idle = "base_idle",
draw = "base_draw"}
self.ReloadTime = 3.8
self.ReloadHalt = 5.3
self.ReloadTime_Empty = 3.8
self.ReloadHalt_Empty = 5.3
self.AlternativePos = self.Alternative1Pos
self.AlternativeAng = self.Alternative1Ang
self.EffectiveRange = 130 * 39.37
self.DamageFallOff = .7
self:setBodygroup(self.StockBGs.main, self.StockBGs.off)
end
function SWEP:IndividualThink()
if self.FireMode == "semi" then
self.Owner.ViewAff = 0
end
end
function SWEP:fireAnimFunc()
clip = self:Clip1()
cycle = 0
rate = 1
anim = "safe"
prefix = ""
suffix = ""
if self:isAiming() then
suffix = suffix .. "_aim"
cycle = self.ironFireAnimStartCycle
end
self:sendWeaponAnim(prefix .. "fire" .. suffix, rate, cycle)
end //*/
local simpleTextColor = Color(255, 210, 0, 255)
local mod = 25
function SWEP:DrawWeaponSelection(x, y, wide, tall, alpha)
if self.SelectIcon then
surface.SetTexture(self.SelectIcon)
wide = wide - mod
x = x + (mod / 2)
y = y + (mod / 4) + (wide / 8)
surface.SetDrawColor(255, 255, 255, alpha)
surface.DrawTexturedRect(x, y, wide, (wide / 2))
else
simpleTextColor.a = alpha
draw.SimpleText(self.IconLetter, self.SelectFont, x + wide / 2, y + tall * 0.2, simpleTextColor, TEXT_ALIGN_CENTER)
end
end
function SWEP:Holster(wep)
-- can't switch if neither the weapon we want to switch to or the wep we're trying to switch to are not valid
if not IsValid(wep) and not IsValid(self.SwitchWep) then
self.SwitchWep = nil
return false
end
local CT = CurTime()
-- can't holster if we have a global delay on the weapon
if CT < self.GlobalDelay or CT < self.HolsterWait then
self.dt.HolsterDelay = CurTime() + self.HolsterTime
self.dt.State = CW_HOLSTER_START
self.dt.HolsterDelay = 0
end
if self.dt.HolsterDelay ~= 0 and CT < self.dt.HolsterDelay then
return false
end
-- can't holster if there are sequenced actions
if #self._activeSequences > 0 then
return false
end
if self.ReloadDelay then
self.dt.HolsterDelay = CurTime() + self.HolsterTime
self.dt.State = CW_HOLSTER_START
self.dt.HolsterDelay = 0
end
if self.dt.State ~= CW_HOLSTER_START then
self.dt.HolsterDelay = CurTime() + self.HolsterTime
end
self.dt.State = CW_HOLSTER_START
-- if holster sequence is over, let us select the desired weapon
if self.SwitchWep and self.dt.State == CW_HOLSTER_START and CurTime() > self.dt.HolsterDelay then
self.dt.State = CW_IDLE
self.dt.HolsterDelay = 0
return true
end
-- if it isn't, make preparations for it
self.ShotgunReloadState = 0
self.ReloadDelay = nil
if self:filterPrediction() then
if self.holsterSound then -- quick'n'dirty prediction fix
self:EmitSound("CW_HOLSTER", 70, 100)
self.holsterSound = false
if IsFirstTimePredicted() then
if self.holsterAnimFunc then
self:holsterAnimFunc()
else
if self.Animations.holster then
self:sendWeaponAnim("holster")
end
end
end
end
end
self.SwitchWep = wep
self.SuppressTime = nil
if self.dt.M203Active then
if SERVER and SP then
SendUserMessage("CW20_M203OFF", self.Owner)
end
if CLIENT then
self:resetM203Anim()
end
end
self.dt.M203Active = false
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 {
BaseStationCfg = {
[101] = {
ActCond = {
{ CondName = "Σ╗╗σèí", CondValue = 1030 },
},
ActShowLv = 2,
AreName = "Old Town Periphery",
Cond = {
{},
{
{ CondName = "Σ╗╗σèí", CondValue = 102301 },
},
{
{ CondName = "Σ╗╗σèí", CondValue = 103301 },
},
},
EntrustTaskIds = {},
Id = 101,
MapId = 1000,
NpcId = 1013,
TaskIds = {},
TowerName = "Old Town Station",
},
[102] = {
ActCond = {
{ CondName = "Σ╗╗σèí", CondValue = 1100 },
},
ActShowLv = 6,
AreName = "Shinkoku Periphery",
Cond = {
{},
{
{ CondName = "Σ╗╗σèí", CondValue = 202301 },
},
{
{ CondName = "Σ╗╗σèí", CondValue = 203301 },
},
},
EntrustTaskIds = {},
Id = 102,
MapId = 1000,
NpcId = 1014,
TaskIds = {},
TowerName = "Shinkoku Station",
},
[103] = {
ActCond = {
{ CondName = "Σ╗╗σèí", CondValue = 1300 },
},
ActShowLv = 21,
AreName = "Cuisine Square Periphery",
Cond = {
{},
{
{ CondName = "Σ╗╗σèí", CondValue = 302301 },
},
{
{ CondName = "Σ╗╗σèí", CondValue = 303301 },
},
},
EntrustTaskIds = {},
Id = 103,
MapId = 1000,
NpcId = 1015,
TaskIds = {},
TowerName = "Cuisine Square Station",
},
[104] = {
ActCond = {
{ CondName = "Σ╗╗σèí", CondValue = 1390 },
},
ActShowLv = 23,
AreName = "Training Area South",
Cond = {
{},
{
{ CondName = "Σ╗╗σèí", CondValue = 402301 },
},
{
{ CondName = "Σ╗╗σèí", CondValue = 403301 },
},
},
EntrustTaskIds = {},
Id = 104,
MapId = 1001,
NpcId = 1016,
TaskIds = {},
TowerName = "South Station",
},
[105] = {
ActCond = {
{ CondName = "Σ╗╗σèí", CondValue = 1490 },
},
ActShowLv = 27,
AreName = "Training Area North",
Cond = {
{},
{
{ CondName = "Σ╗╗σèí", CondValue = 502301 },
},
{
{ CondName = "Σ╗╗σèí", CondValue = 503301 },
},
},
EntrustTaskIds = {},
Id = 105,
MapId = 1001,
NpcId = 1029,
TaskIds = {},
TowerName = "North Station",
},
[106] = {
ActCond = {
{ CondName = "Σ╗╗σèí", CondValue = 1590 },
},
ActShowLv = 31,
AreName = "Stadium Periphery",
Cond = {
{},
{
{ CondName = "Σ╗╗σèí", CondValue = 602301 },
},
{
{ CondName = "Σ╗╗σèí", CondValue = 603301 },
},
},
EntrustTaskIds = {},
Id = 106,
MapId = 1001,
NpcId = 1009,
TaskIds = {},
TowerName = "Stadium Station",
},
[107] = {
ActCond = {
{ CondName = "Σ╗╗σèí", CondValue = 1680 },
},
ActShowLv = 35,
AreName = "Train Station Square Periphery",
Cond = {
{},
{
{ CondName = "Σ╗╗σèí", CondValue = 702301 },
},
{
{ CondName = "Σ╗╗σèí", CondValue = 703301 },
},
},
EntrustTaskIds = {},
Id = 107,
MapId = 1002,
NpcId = 1006,
TaskIds = {},
TowerName = "Train Station Square Station",
},
[108] = {
ActCond = {
{ CondName = "Σ╗╗σèí", CondValue = 1770 },
},
ActShowLv = 39,
AreName = "Agency Area Periphery",
Cond = {
{},
{
{ CondName = "Σ╗╗σèí", CondValue = 802301 },
},
{
{ CondName = "Σ╗╗σèí", CondValue = 803301 },
},
},
EntrustTaskIds = {},
Id = 108,
MapId = 1002,
NpcId = 1007,
TaskIds = {},
TowerName = "Agency Area Station",
},
[109] = {
ActCond = {
{ CondName = "Σ╗╗σèí", CondValue = 1860 },
},
ActShowLv = 43,
AreName = "Technology Museum Periphery",
Cond = {
{},
{
{ CondName = "Σ╗╗σèí", CondValue = 902301 },
},
{
{ CondName = "Σ╗╗σèí", CondValue = 903301 },
},
},
EntrustTaskIds = {},
Id = 109,
MapId = 1002,
NpcId = 1008,
TaskIds = {},
TowerName = "Technology Museum Station",
},
},
}
|
-- https://httpd.apache.org/docs/trunk/mod/mod_lua.html#writinghandlers
-- example handler
require 'apache2'
require 'string'
--[[
This is the default method name for Lua handlers, see the optional
function-name in the LuaMapHandler directive to choose a different
entry point.
--]]
function handle(r)
r.content_type = "text/plain"
if r.method == 'GET' then
r:puts("Hello Lua World!\n")
for k, v in pairs( r:parseargs() ) do
r:puts( string.format("%s: %s\n", k, v) )
end
elseif r.method == 'POST' then
r:puts("Hello Lua World!\n")
for k, v in pairs( r:parsebody() ) do
r:puts( string.format("%s: %s\n", k, v) )
end
elseif r.method == 'PUT' then
-- use our own Error contents
r:puts("Unsupported HTTP method " .. r.method)
r.status = 405
return apache2.OK
else
-- use the ErrorDocument
return 501
end
return apache2.OK
end
|
-- package.loaded["renderModule"] = nil -- error
renderSystem = require "renderModule"
render = { x=480, y=320 }
function render:init(x, y)
render.x = x
render.y = y
print("init")
return true
end
function render:update()
print("update")
end
local r = render.init()
print(r)
renderSystem.init()
renderSystem.update()
|
local parent, ns = ...
ns.addon = CreateFrame("Frame", nil, UIParent)
ns.spells = {}
|
local log = ngx.log
local timer_at = ngx.timer.at
local ERR = ngx.ERR
local tbl_concat = table.concat
local function trace(...)
local line = {}
for i = 1, select("#", ...) do
line[i] = tostring(select(i, ...))
end
log(ERR, tbl_concat(line, " "))
end
trace("main.lua started")
local start_timer
local function on_timer(...)
trace("on_timer: ", ...)
local mqtt = require("mqtt")
local ioloop = require("mqtt.ioloop")
-- create mqtt client
local client = mqtt.client{
-- NOTE: this broker is not working sometimes; comment username = "..." below if you still want to use it
-- uri = "test.mosquitto.org",
uri = "mqtt.flespi.io",
-- NOTE: more about flespi tokens: https://flespi.com/kb/tokens-access-keys-to-flespi-platform
username = "stPwSVV73Eqw5LSv0iMXbc4EguS7JyuZR9lxU5uLxI5tiNM8ToTVqNpu85pFtJv9",
clean = true,
connector = require("mqtt.ngxsocket"),
secure = true, -- optional
}
trace("created MQTT client", client)
client:on{
connect = function(connack)
if connack.rc ~= 0 then
trace("connection to broker failed:", connack)
return
end
trace("connected:", connack) -- successful connection
-- subscribe to test topic and publish message after it
assert(client:subscribe{ topic="luamqtt/#", qos=1, callback=function(suback)
trace("subscribed:", suback)
-- publish test message
trace('publishing test message "hello" to "luamqtt/simpletest" topic...')
assert(client:publish{
topic = "luamqtt/simpletest",
payload = "hello",
qos = 1
})
end})
end,
message = function(msg)
assert(client:acknowledge(msg))
trace("received:", msg)
end,
error = function(err)
trace("MQTT client error:", err)
end,
close = function(conn)
trace("MQTT conn closed:", conn.close_reason)
end
}
trace("begin ioloop")
local loop = ioloop.create{
timeout = client.args.keep_alive,
sleep_function = ngx.sleep,
}
loop:add(client)
client:start_connecting()
loop:run_until_clients()
trace("done ioloop")
-- to reconnect
start_timer()
end
start_timer = function()
local ok, err = timer_at(1, on_timer)
if not ok then
trace("failed to start timer:", err)
end
end
start_timer()
|
local utils = require'jet.utils'
describe(
'The jet.utils module',
function()
it('is_empty_table works',function()
assert.is_true(utils.is_empty_table({}))
assert.is_false(utils.is_empty_table({'asd'}))
assert.is_false(utils.is_empty_table({a=123}))
end)
it('access_field works one level deep',function()
local t = {}
local b = {}
t.a = b
local accessor = utils.access_field('a')
assert.is_equal(t.a,accessor(t))
assert.is_nil(accessor({}))
end)
it('access_field works two level deep',function()
local t = {}
local b = {}
t.a = {
xx = b
}
local accessor = utils.access_field('a.xx')
assert.is_equal(t.a.xx,accessor(t))
t.a = nil
local ok = pcall(accessor,t)
assert.is_false(ok)
end)
it('equals_deep works',function()
assert.is_true(utils.equals_deep({a={1,3},asd=true},{a={1,3},asd=true}))
assert.is_false(utils.equals_deep({a={1,3},asd=true},{a={1},asd=true}))
assert.is_false(utils.equals_deep(1,4))
assert.is_false(utils.equals_deep(1,'foo'))
assert.is_true(utils.equals_deep(1,1))
end)
it('mapper works',function()
local map = utils.mapper({
['person.age'] = 'age',
['hobby'] = 'work',
})
assert.is_same(map({person={age=32},hobby='guitar'}),{age=32,work='guitar'})
end)
end)
|
local lsp_status = require 'lsp-status'
local lspconfig = require 'lspconfig'
local efm_config = os.getenv('HOME') .. '/.config/efm-langserver/config.yaml'
local log_dir = "/tmp/"
local black = require "config.plugins.lsp.efm.black"
local isort = require "config.plugins.lsp.efm.isort"
local mypy = require "config.plugins.lsp.efm.mypy"
local lua_format = require "config.plugins.lsp.efm.lua-format"
local prettier = require "config.plugins.lsp.efm.prettier"
local eslint = require "config.plugins.lsp.efm.eslint"
local eslint_d = require "config.plugins.lsp.efm.eslint_d"
local rustfmt = require "config.plugins.lsp.efm.rustfmt"
local gofmt = require "config.plugins.lsp.efm.gofmt"
-- Note: we install the lua language server with :LSPInstall lua
-- TODO: Check which binary is currently available in path and select that. This could be lsp install or the brew one.
local sumneko_bin_path = vim.fn.stdpath('data') .. '/lspinstall/lua/sumneko-lua-language-server'
return {
omnisharp = {
log_level = 2,
cmd = {os.getenv("HOME") .. "/.zinit/plugins/omnisharp/run", "-v", "-lsp", "-hpid", tostring(vim.fn.getpid())},
filetypes = {'cache', 'cs', 'csproj', 'dll', 'nuget', 'props', 'sln', 'targets'},
root_dir = lspconfig.util.root_pattern("*.sln")
},
sqlls = {},
-- https://github.com/teal-language/teal-language-server
teal = {},
-- https://github.com/mads-hartmann/bash-language-server
bashls = {},
-- https://github.com/snoe/clojure-lsp
clojure_lsp = {},
-- Scala / metals https://scalameta.org/metals/docs/editors/vim.html#using-an-alternative-lsp-client -- we're using nvim-metals instead
-- metals = {},
-- https://github.com/regen100/cmake-language-server
cmake = {},
-- https://clangd.llvm.org/installation.html
clangd = {
cmd = {'clangd', '--background-index', '--clang-tidy', '--completion-style=bundled', '--header-insertion=iwyu',
'--suggest-missing-includes', '--cross-file-rename'},
handlers = lsp_status.extensions.clangd.setup(),
init_options = {
clangdFileStatus = true,
usePlaceholders = true,
completeUnimported = true,
semanticHighlighting = true
}
},
-- CSS ( https://github.com/vscode-langservers/vscode-css-languageserver-bin )
cssls = {
filetypes = {"css", "scss", "less", "sass"},
root_dir = lspconfig.util.root_pattern("package.json", ".git")
},
ghcide = {},
html = {},
julials = {
settings = {
julia = {
format = {
indent = 2
}
}
}
},
ocamllsp = {},
pyright = {
settings = {
python = {
formatting = {
provider = 'yapf'
}
}
}
},
-- LUA ( https://github.com/sumneko/lua-language-server )
sumneko_lua = {
cmd = {sumneko_bin_path},
filetypes = {"lua"},
settings = {
Lua = {
diagnostics = {
globals = {'vim'}
},
runtime = {
version = 'LuaJIT',
path = vim.split(package.path, ';')
},
completion = {
keywordSnippet = true
},
hint = {
enable = true
},
workspace = {
library = {
[vim.fn.expand("$VIMRUNTIME/lua")] = true,
[vim.fn.expand("$VIMRUNTIME/lua/vim/lsp")] = true
}
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = {
enable = false
}
}
}
},
-- latex
-- texlab = {
-- settings = {
-- latex = {forwardSearch = {executable = 'okular', args = {'--unique', 'file:%p#src:%l%f'}}}
-- },
-- commands = {
-- TexlabForwardSearch = {
-- function()
-- local pos = vim.api.nvim_win_get_cursor(0)
-- local params = {
-- textDocument = {uri = vim.uri_from_bufnr(0)},
-- position = {line = pos[1] - 1, character = pos[2]}
-- }
-- lsp.buf_request(0, 'textDocument/forwardSearch', params,
-- function(err, _, _, _) if err then error(tostring(err)) end end)
-- end,
-- description = 'Run synctex forward search'
-- }
-- }
-- },
-- Typescript https://github.com/theia-ide/typescript-language-server
tsserver = {},
-- https://github.com/iamcco/vim-language-server
vimls = {},
terraformls = {},
-- https://github.com/rcjsuen/dockerfile-language-server-nodejs
dockerls = {},
gopls = {
cmd = {"gopls", "serve"},
settings = {
gopls = {
analyses = {
unusedparams = true
},
staticcheck = true
}
},
init_options = {
usePlaceholders = true
}
},
rust_analyzer = {},
--- JSON ( https://github.com/vscode-langservers/vscode-json-languageserver )
jsonls = {
cmd = {'json-languageserver', '--stdio'},
settings = {
json = {
schemas = {{
fileMatch = {'jsconfig.json'},
url = 'https://json.schemastore.org/jsconfig'
}, {
fileMatch = {'tsconfig.json'},
url = 'https://json.schemastore.org/tsconfig'
}, {
fileMatch = {'package.json'},
url = 'https://json.schemastore.org/package'
}}
}
}
},
-- https://github.com/graphql/graphiql/tree/main/packages/graphql-language-service-cli
graphql = {},
-- YAML ( https://github.com/redhat-developer/yaml-language-server )
yamlls = {
settings = {
yaml = {
schemas = {
['http://json.schemastore.org/gitlab-ci'] = '.gitlab-ci.yml',
['http://json.schemastore.org/composer'] = 'composer.yaml',
['https://raw.githubusercontent.com/compose-spec/compose-spec/master/schema/compose-spec.json'] = 'docker-compose*.yml',
['https://raw.githubusercontent.com/kamilkisiela/graphql-config/v3.0.3/config-schema.json'] = '.graphqlrc*'
}
}
}
},
vuels = {
settings = {
vetur = {
experimental = {
templateInterpolationService = true
},
validation = {
templateProps = true
},
completion = {
tagCasing = 'initial'
}
}
}
},
-- Swift debugging ( https://github.com/apple/sourcekit-lsp )
sourcekit = {},
-- https://github.com/mattn/efm-langserver,
efm = {
cmd = {"efm-langserver", "-c", efm_config, "-logfile", log_dir .. "efm.log"},
filetypes = {"python", "yaml", "json", "markdown", "rst", "html", "css", "javascript", "typescript",
"javascriptreact", "typescriptreact", "dockerfile"},
-- Fallback to .bashrc as a project root to enable LSP on loose files
root_dir = function(fname)
return lspconfig.util.root_pattern("tsconfig.json")(fname) or
lspconfig.util.root_pattern(".eslintrc.js", ".git")(fname) or
lspconfig.util.root_pattern("package.json", ".git/", ".zshrc")(fname);
end,
init_options = {
documentFormatting = true
},
settings = {
rootMarkers = {"package.json", "go.mod", ".git/", ".zshrc", "Cargo.toml"},
languages = {
python = {isort, black},
lua = {lua_format},
yaml = {prettier},
json = {prettier},
markdown = {prettier},
html = {prettier},
css = {prettier},
javascript = {prettier, eslint_d},
typescript = {prettier, eslint_d},
javascriptreact = {prettier, eslint_d},
typescriptreact = {prettier, eslint_d}
-- rust = {rustfmt}, -- not needed with rust_analyzer
-- go = {gofmt}, -- not needed with gopls
}
}
}
-- TODO: https://github.com/prominic/groovy-language-server.git
}
|
--Print its own name
print("The name of this script is: "..arg[0])
|
require("tests/testsuite")
-- Test the low level function that's actually got the bug in it.
local object, result = LoggingCallback()
wg.parseword("\16", 0, object)
AssertTableAndPropertiesEquals(
{},
result)
-- And now do an end-to-end test of the exporter framework which was
-- provoking it.
Cmd.InsertStringIntoParagraph("one")
Cmd.SplitCurrentParagraph()
Cmd.SplitCurrentParagraph()
Cmd.InsertStringIntoParagraph("two")
local object, result = LoggingObject()
local function callback(writer, document)
return ExportFileUsingCallbacks(document, object)
end
-- This can actually happen by the right sequence of user operations,
-- but it's a bit brittle and I want to be absolutely sure it happens
-- for the test case.
Document[2][1] = "\16"
ExportToString(Document, callback)
AssertTableAndPropertiesEquals(
{
["paragraph_start"] = {
{{"one", ["style"]="P"}},
{{"\16", ["style"]="P"}},
{{"two", ["style"]="P"}}
},
["paragraph_end"] = {
{{"one", ["style"]="P"}},
{{"\16", ["style"]="P"}},
{{"two", ["style"]="P"}}
},
["prologue"] = {{}},
["text"] = {
{"one"},
{""},
{"two"}
},
["epilogue"] = {{}}
},
result)
|
---------------------------------------------------
-- Scintillant Lance
-- Deals light damage to targets in a fan-shaped area of effect.
---------------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/status")
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local dmgmod = 1.5
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg() * 2.5,tpz.magic.ele.LIGHT,dmgmod,TP_MAB_BONUS,1)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,tpz.attackType.MAGICAL,tpz.damageType.LIGHT,MOBPARAM_WIPE_SHADOWS)
target:takeDamage(dmg, mob, tpz.attackType.MAGICAL, tpz.damageType.LIGHT)
return dmg
end
|
local json = require 'json'
local function pushError(...)
local t = table.pack(...)
for i = 1, t.n do
t[i] = tostring(t[i])
end
local buf = table.concat(t, '\t')
ERR:push(buf)
end
local function readProtoHeader()
local header = io.read 'l'
if header:sub(1, #'Content-Length') == 'Content-Length' then
return header
elseif header:sub(1, #'Content-Type') == 'Content-Type' then
return nil
else
pushError('Proto header error:', header)
return nil
end
end
local function readProtoContent(header)
local len = tonumber(header:match('%d+'))
if not len then
pushError('Proto header error:', header)
return nil
end
local buf = io.read(len+2)
if not buf then
return nil
end
local suc, res = pcall(json.decode, buf)
if not suc then
pushError('Proto error:', buf)
return nil
end
return res
end
local function readProto()
local header = readProtoHeader()
if not header then
return
end
local data = readProtoContent(header)
if not data then
return
end
OUT:push(data)
end
while true do
readProto()
GC:push(ID, collectgarbage 'count')
end
|
--- Notification helper functions
-- @module ix.notice
if (SERVER) then
util.AddNetworkString("ixNotify")
util.AddNetworkString("ixNotifyLocalized")
--- Sends a notification to a specified recipient.
-- @realm server
-- @string message Message to notify
-- @player[opt=nil] recipient Player to be notified
function ix.util.Notify(message, recipient)
net.Start("ixNotify")
net.WriteString(message)
if (recipient == nil) then
net.Broadcast()
else
net.Send(recipient)
end
end
--- Sends a translated notification to a specified recipient.
-- @realm server
-- @string message Message to notify
-- @player[opt=nil] recipient Player to be notified
-- @param ... Arguments to pass to the translated message
function ix.util.NotifyLocalized(message, recipient, ...)
net.Start("ixNotifyLocalized")
net.WriteString(message)
net.WriteTable({...})
if (recipient == nil) then
net.Broadcast()
else
net.Send(recipient)
end
end
do
--- Notification util functions for players
-- @classmod Player
local playerMeta = FindMetaTable("Player")
--- Displays a prominent notification in the top-right of this player's screen.
-- @realm shared
-- @string message Text to display in the notification
function playerMeta:Notify(message)
ix.util.Notify(message, self)
end
--- Displays a notification for this player with the given language phrase.
-- @realm shared
-- @string message ID of the phrase to display to the player
-- @param ... Arguments to pass to the phrase
-- @usage client:NotifyLocalized("mapRestarting", 10)
-- -- displays "The map will restart in 10 seconds!" if the player's language is set to English
-- @see ix.lang
function playerMeta:NotifyLocalized(message, ...)
ix.util.NotifyLocalized(message, self, ...)
end
--- Displays a notification for this player in the chatbox.
-- @realm shared
-- @string message Text to display in the notification
function playerMeta:ChatNotify(message)
local messageLength = message:utf8len()
ix.chat.Send(nil, "notice", message, false, {self}, {
bError = message:utf8sub(messageLength, messageLength) == "!"
})
end
--- Displays a notification for this player in the chatbox with the given language phrase.
-- @realm shared
-- @string message ID of the phrase to display to the player
-- @param ... Arguments to pass to the phrase
-- @see NotifyLocalized
function playerMeta:ChatNotifyLocalized(message, ...)
message = L(message, self, ...)
local messageLength = message:utf8len()
ix.chat.Send(nil, "notice", message, false, {self}, {
bError = message:utf8sub(messageLength, messageLength) == "!"
})
end
end
else
-- Create a notification panel.
function ix.util.Notify(message)
if (ix.option.Get("chatNotices", false)) then
local messageLength = message:utf8len()
ix.chat.Send(LocalPlayer(), "notice", message, false, {
bError = message:utf8sub(messageLength, messageLength) == "!"
})
return
end
if (IsValid(ix.gui.notices)) then
ix.gui.notices:AddNotice(message)
end
MsgC(Color(0, 255, 255), message .. "\n")
end
-- Creates a translated notification.
function ix.util.NotifyLocalized(message, ...)
ix.util.Notify(L(message, ...))
end
-- shortcut notify functions
do
local playerMeta = FindMetaTable("Player")
function playerMeta:Notify(message)
if (self == LocalPlayer()) then
ix.util.Notify(message)
end
end
function playerMeta:NotifyLocalized(message, ...)
if (self == LocalPlayer()) then
ix.util.NotifyLocalized(message, ...)
end
end
function playerMeta:ChatNotify(message)
if (self == LocalPlayer()) then
local messageLength = message:utf8len()
ix.chat.Send(LocalPlayer(), "notice", message, false, {
bError = message:utf8sub(messageLength, messageLength) == "!"
})
end
end
function playerMeta:ChatNotifyLocalized(message, ...)
if (self == LocalPlayer()) then
message = L(message, ...)
local messageLength = message:utf8len()
ix.chat.Send(LocalPlayer(), "notice", message, false, {
bError = message:utf8sub(messageLength, messageLength) == "!"
})
end
end
end
-- Receives a notification from the server.
net.Receive("ixNotify", function()
ix.util.Notify(net.ReadString())
end)
-- Receives a notification from the server.
net.Receive("ixNotifyLocalized", function()
ix.util.NotifyLocalized(net.ReadString(), unpack(net.ReadTable()))
end)
end
|
if #arg == 0 then
os.exit(0)
end
--os.exit(0)
function scriptPath()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
--
-- Stuff to ensure alphabetic order
-- Taken from http://lua-users.org/wiki/SortedIteration
--
--[[
Ordered table iterator, allow to iterate on the natural order of the keys of a
table.
Example:
]]
function __genOrderedIndex( t )
local orderedIndex = {}
for key in pairs(t) do
table.insert( orderedIndex, key )
end
table.sort( orderedIndex )
return orderedIndex
end
function orderedNext(t, state)
-- Equivalent of the next function, but returns the keys in the alphabetic
-- order. We use a temporary ordered key table that is stored in the
-- table being iterated.
local key = nil
--print("orderedNext: state = "..tostring(state) )
if state == nil then
-- the first time, generate the index
t.__orderedIndex = __genOrderedIndex( t )
key = t.__orderedIndex[1]
else
-- fetch the next value
for i = 1,#t.__orderedIndex do
if t.__orderedIndex[i] == state then
key = t.__orderedIndex[i+1]
end
end
end
if key then
return key, t[key]
end
-- no more value to return, cleanup
t.__orderedIndex = nil
return
end
function orderedPairs(t)
-- Equivalent of the pairs() function on tables. Allows to iterate
-- in order
return orderedNext, t, nil
end
function string:escape()
return self:gsub('"', "\\\"")
:gsub('\\', "\\\\")
:gsub('\b', "\\b")
:gsub('\f', "\\f")
:gsub('\n', "\\n")
:gsub('\r', "\\r")
:gsub('\t', "\\t")
end
local cpptypes = {
string = true, double = true, float = true, bool = true, int = true, uint = true, uint64 = true
}
local sql = dofile(scriptPath() .. "/sql.lua")
local basePath = arg[1]:sub(0, arg[1]:len() - arg[1]:reverse():find("/"))
local description = dofile(arg[1])
local tables = description.tables
-- Write structs
-- Open as binary since Windows likes to convert '\n' to '\r\n' which messes up some offsets for fseek
local structfile = io.open(description.name .. ".h", "wb")
structfile:write([[
// Generated by LuaSQL
#pragma once
#include <DatabaseConnection.h>
#include <string>
#include <cstdint>
#include <regex>
// For toJson
#include <sstream>
#include <iomanip>
]] .. description.defines .. [[namespace ]] .. description.name .. "\n" ..
[[
{
using std::string;
typedef uint32_t uint;
typedef int64_t int64;
typedef uint64_t uint64;
]])
for k,v in orderedPairs(tables) do
-- C++
structfile:write("struct " .. k .. "\n{\n")
structfile:write("\tunsigned long long id = 0;\n")
local toJsonString = ""
for p,q in orderedPairs(v) do
if q == "string" then
toJsonString = toJsonString .. "\t\t" .. [[ss << "\"]] .. p .. [[\" : \"" << luasqlgen::PreparedStmt::jsonEscape(]] .. p .. ") << \"\\\",\" << std::endl;\n";
else
toJsonString = toJsonString .. "\t\t" .. [[ss << "\"]] .. p .. [[\" : \"" << ]] .. p .. " << \"\\\",\" << std::endl;\n";
end
-- C++
-- Write into struct
if tables[q] ~= nil then
if p ~= q then
structfile:write("\tunsigned int " .. p .. " = 0;\n")
end
else
if q ~= "string" and cpptypes[q] then -- If we have a C++ basic type that is no string
structfile:write("\t" .. q .. " " .. p .. " = 0;\n")
elseif q == "string" then -- If we have a string
structfile:write("\t" .. q .. " " .. p .. ";\n")
else -- If we have a non-existing custom type (e.g. reference to table from another module)
structfile:write("\tunsigned long long " .. p .. ";\n")
end
end
end
structfile:write("\n\tvoid validate()\n\t{\n")
structfile:write("\t\t// Integrity check\n")
if description.checks ~= nil and description.checks[k] ~= nil then
for field, regex in orderedPairs(description.checks[k]) do
structfile:write("\t\tif(!std::regex_match(" .. field .. ", std::regex(\"" .. regex
.. "\")))\n\t\t\tthrow std::runtime_error(\"Integrity check failed: "
.. field .. "\");\n")
end
end
structfile:write("\t}\n")
-- Generate toJson
structfile:write([[
std::string toJson() const
{
std::stringstream ss;
ss << "{\n";
]] .. toJsonString .. [[
ss << "\"id\" : \"" << id << "\"\n";
ss << "}\n";
return ss.str();
}
]])
-- Generate custom methods
for i,f in ipairs(description.structdef) do
structfile:write(f(k, v))
end
structfile:write("};\n\n")
end
structfile:write("class " .. description.name .. "\n{\n")
structfile:write([[
private:
std::shared_ptr<luasqlgen::DatabaseConnection> m_connection;
]])
structfile:write("public:\n")
structfile:write("\t" .. description.name .. "(const std::shared_ptr<luasqlgen::DatabaseConnection>& conn) : m_connection(conn) {}\n")
for k,v in orderedPairs(tables) do
sql:generateCreateFunction(structfile, k, v)
sql:generateGetFunction(structfile, k, v)
sql:generateUpdateFunction(structfile, k, v)
sql:generateDeleteFunction(structfile, k, v)
sql:generateQueryFunction(structfile, k, v)
sql:generateSearchFunction(structfile, k, v)
end
-- Write scripts
if description.scripts ~= nil then
for index, file in ipairs(description.scripts) do
local sourcePath = basePath .. "/" .. file
local sourceFile = io.open(sourcePath, "r")
if not sourceFile then
print("Could not open SQL script " .. sourcePath)
os.exit(1)
end
local sources = sourceFile:read("*all")
sourceFile:close()
local slashLocStart, slashLocEnd = file:reverse():find("/")
slashLocStart = slashLocStart or file:len() + 2
slashLocStart = file:len() - slashLocStart + 2
structfile:write("\tvirtual std::string " .. file:sub(slashLocStart, file:find(".sql") - 1) .. "(const std::vector<std::string>& args)\n\t{\n")
local lines = {}
for match in sources:gmatch("(.-);") do
table.insert(lines, "m_connection->queryJson(\"" .. match:escape() .. "\", args);\n");
end
for k, v in ipairs(lines) do
if k == #lines then
structfile:write("\t\treturn " .. v)
else
structfile:write("\t\t" .. v)
end
end
structfile:write("\t}\n\n")
structfile:write("\tvirtual void " .. file:sub(slashLocStart, file:find(".sql") - 1) .. "(const std::vector<std::string>& args, luasqlgen::DatabaseResult& result)\n\t{\n")
structfile:write("\t\tm_connection->query(\"" .. sources:escape() .. "\", args, result);\n");
structfile:write("\t}\n\n")
-- structfile:write(
--
-- {
-- return m_connection->queryJson(" .. sources:escape() .. [[", args);
-- }
--)
end
end
structfile:write(
[[
virtual void begin() { m_connection->query("begin;"); }
virtual void commit() { m_connection->query("commit;"); }
virtual void rollback() { m_connection->query("rollback;"); }
virtual void installMariaDB()
{
]] .. sql:generateInstallStmtMariaDB(description.tables, description.constraints or {}) ..[[;
}
virtual void installSQLite()
{
]] .. sql:generateInstallStmtSQLite(description.tables, description.constraints or {}) ..[[;
}
virtual void install()
{
if(!strcmp(m_connection->getName(), "MariaDB"))
installMariaDB();
else
installSQLite();
}
]])
structfile:write("void dropTablesMariaDB()\n{\n")
for k,v in orderedPairs(tables) do
structfile:write("m_connection->query(\"drop table " .. k .. ";\");\n")
end
structfile:write("}\n")
structfile:write("void clearTablesMariaDB()\n{\n")
for k,v in orderedPairs(tables) do
structfile:write("m_connection->query(\"delete from " .. k .. ";\");\n")
structfile:write("m_connection->query(\"alter table " .. k .. " AUTO_INCREMENT=1;\");\n")
end
structfile:write("}\n")
structfile:write("void dropTablesSQLite()\n{\n")
for k,v in orderedPairs(tables) do
structfile:write("m_connection->query(\"drop table " .. k .. ";\");\n")
end
structfile:write("}\n")
structfile:write("void clearTablesSQLite()\n{\n")
for k,v in orderedPairs(tables) do
structfile:write("m_connection->query(\"delete from " .. k .. ";\");\n")
structfile:write("m_connection->query(\"update sqlite_sequence set seq = 0 where name='" .. k .. "';\");\n")
end
structfile:write("}\n")
structfile:write([[
virtual void dropTables()
{
if(!strcmp(m_connection->getName(), "MariaDB"))
dropTablesMariaDB();
else
dropTablesSQLite();
}
virtual void clearTables()
{
if(!strcmp(m_connection->getName(), "MariaDB"))
clearTablesMariaDB();
else
clearTablesSQLite();
}
]])
structfile:write("};\n") -- Abstract class
structfile:write("}\n") -- Namespace
structfile:close()
local sqlfile = io.open(description.name .. "SQLite.sql", "w")
sqlfile:write(sql:generateInstallScriptSQLite(description))
sqlfile = io.open(description.name .. "MariaDB.sql", "w")
sqlfile:write(sql:generateInstallScriptMariaDB(description))
local testfile = io.open(description.name .. "Test.cpp", "w")
testfile:write([[
// Google test suite for the database, generated by LuaSQL
#include <gtest/gtest.h>
#ifndef DATABASE
#define DATABASE "testdb"
#endif
#ifndef HOST
#define HOST "localhost"
#endif
#ifndef USER
#define USER "handiserv"
#endif
#ifndef PASSWORD
#define PASSWORD "niugnip"
#endif
#ifndef PORT
#define PORT 13306
#endif
]])
testfile:write("#include \"" .. description.name .. ".h\"\n\nusing namespace " .. description.name .. ";\n\n")
testfile:write([[
class ]] .. description.name .. [[Test : public testing::Test
{
protected:
]] .. description.name .. "::" .. description.name .. [[ sql;
std::string getDatabaseName()
{
const ::testing::TestInfo* const testInfo = ::testing::UnitTest::GetInstance()->current_test_info();
const std::string database = "handiserv_" + std::string(testInfo->test_case_name())
+ "_" + std::string(testInfo->name());
return database;
}
virtual void SetUp() override
{
sql.connect(getDatabaseName(), HOST, USER, PASSWORD, PORT);
sql.init("]] .. description.name .. [[.sql");
}
virtual void TearDown() override
{
sql.drop();
sql.close();
}
};
]])
for k,v in orderedPairs(tables) do
testfile:write("TEST_F(" .. description.name .. "Test, AddUpdateRemoveQuery" .. k .. ")\n{\n")
testfile:write("\tstruct " .. k .. " object;\n");
testfile:write("\tobject.id = -1;\n")
testfile:write("\tsql.create" .. k .. "(object);\n\n")
testfile:write("\tASSERT_NE(-1, object.id);\n");
testfile:write("\tstruct " .. k .. " object2;\n");
testfile:write("\tsql.get" .. k .. "(object.id, object2);\n\n")
testfile:write("\tASSERT_EQ(object.id, object2.id);\n");
testfile:write("\tsql.delete" .. k .. "(object.id);\n")
testfile:write("\tEXPECT_FALSE(sql.get" .. k .. "(object.id, object2));\n\n")
-- testfile:write("\tstd::cout << object.toJson() << std::endl;\n")
testfile:write("}\n\n")
end
testfile:close()
--
-- Plantuml
--
local pumlfile = io.open(description.name .. ".puml", "w")
pumlfile:write("@startuml\n\n")
for k,v in orderedPairs(tables) do
local connectionStr = ""
local connectionMap = {}
pumlfile:write([[
class ]] .. k .. "{\n")
for p,q in orderedPairs(v) do
pumlfile:write("\t" .. p .. " : " .. q .. "\n")
-- Only add every type once
if tables[q] ~= nil and connectionMap[q] == nil then
connectionStr = connectionStr .. k .. " -- " .. q .. "\n"
connectionMap[q] = true
end
end
pumlfile:write("}\n" .. connectionStr .. "\n")
end
pumlfile:write("@enduml\n")
pumlfile:close()
|
local common = require "unbox/common"
local Cell = require "unbox/Cell"
local Contact = require "unbox/Contact"
local World = {}
World.__index = World
function World.new(args)
local world = setmetatable({}, World)
world:init(args or {})
return world
end
function World:init(args)
self.gravityX, self.gravityY = args.gravityX or 0, args.gravityY or 0
self.cellWidth, self.cellHeight = args.cellWidth or 1, args.cellHeight or 1
self.bodies = {}
self.dynamicBodies = {}
self.dirtyBodies = {}
self.cells = {}
self.contacts = {}
end
function World:destroy()
end
function World:getCellIndices(x, y)
return common.round2(x / self.cellWidth, y / self.cellHeight)
end
function World:addBodyToCell(body, x, y)
local cell = common.get2(self.cells, x, y)
if not cell then
cell = Cell.new({
world = self,
x = x, y = y,
})
end
assert(not cell.bodies[body])
for body2, _ in pairs(cell.bodies) do
local contact = body.contacts[body2]
if not contact then
contact = Contact.new({
world = self,
body1 = body, body2 = body2,
})
end
contact.cellCount = contact.cellCount + 1
end
cell.bodies[body] = true
end
function World:removeBodyFromCell(body, x, y)
local cell = assert(common.get2(self.cells, x, y))
assert(cell.bodies[body])
cell.bodies[body] = nil
for body2, _ in pairs(cell.bodies) do
local contact = assert(body.contacts[body2])
assert(contact.cellCount >= 1)
contact.cellCount = contact.cellCount - 1
if contact.cellCount == 0 then
contact:destroy()
end
end
if not next(cell.bodies) then
cell:destroy()
end
end
function World:queryPoint(x, y)
local cellX, cellY = self:getCellIndices(x, y)
end
function World:queryBox(x, y, width, height)
local x1, y1 = x - 0.5 * width, y - 0.5 * height
local x2, y2 = x + 0.5 * width, y + 0.5 * height
local cellX1, cellY1 = self:getCellIndices(x1, y1)
local cellX2, cellY2 = self:getCellIndices(x2, y2)
local cellBodies = {}
for cellX = cellX1, cellX2 do
for cellY = cellY1, cellY2 do
local cell = common.get2(self.cells, cellX, cellY)
if cell then
for body, _ in pairs(cell.bodies) do
cellBodies[body] = true
end
end
end
end
local boxBodies = {}
for body, _ in pairs(cellBodies) do
if body:intersectsBox(x, y, width, height) then
boxBodies[body] = true
end
end
return boxBodies
end
function World:update(dt)
self:updateDynamicBodies(dt)
self:updateContacts()
end
function World:updateDynamicBodies(dt)
for body, _ in pairs(self.dynamicBodies) do
body:update(dt)
end
end
function World:updateContacts()
for body, _ in pairs(self.dirtyBodies) do
body:updateContacts()
body.dirty = false
end
self.dirtyBodies = {}
end
function World:draw()
love.graphics.setColor(0x00, 0x00, 0xff, 0xff)
for x, column in pairs(self.cells) do
for y, cell in pairs(column) do
love.graphics.rectangle("line",
self.cellWidth * (x - 0.5), self.cellHeight * (y - 0.5),
self.cellWidth, self.cellHeight)
end
end
love.graphics.setColor(0x00, 0xff, 0x00, 0xff)
for body, _ in pairs(self.bodies) do
love.graphics.rectangle("line",
body.x - 0.5 * body.width, body.y - 0.5 * body.height,
body.width, body.height)
end
love.graphics.setColor(0xff, 0x00, 0x00, 0xff)
for contact, _ in pairs(self.contacts) do
love.graphics.line(contact.body1.x, contact.body1.y,
contact.body2.x, contact.body2.y)
end
love.graphics.setColor(0xff, 0xff, 0xff, 0xff)
end
return World
|
-- require'lspconfig'.clangd.setup{}
|
koth {53.0,-87.0,65.0,35.0} -- koth area, x,y,z,r
teams {
{"red", {255,0,0,1}},
{"green", {0,255,0,2}},
{"blue", {0,0,255,3}}
}
zoneconfig {
zoneBlip = 9,
zoneAlpha = 100,
zoneColor = 4,
blip = 305,
blipcolor = 4,
blipalpha = 255
}
shops {
{10.0,10.0,10.0},
{-10.0,-10.0,-10.0}
}
spawns {
{223.3,-28.7,72.6}, --team 1
{63.8,-228.6,51.3}, --team 2
{65.1,-29.5,69.0} --team 3
}
vehicleSpawns {
{ -- team 1
{0,0,0},
},
{ -- team 2
{0,0,0},
},
{ -- team 3
{0,0,0},
}
}
|
--[[**********************************
*
* Multi Theft Auto - Admin Panel
*
* client/admin_wrapper.lua
*
* Original File by lil_Toady
*
**************************************]]
local _getVehicleNameFromModel = getVehicleNameFromModel
function getVehicleNameFromModel(id)
local avehspecial = {
[596] = "Police LS",
[597] = "Police SF",
[598] = "Police LV",
[556] = "Monster 2",
[557] = "Monster 3",
[609] = "Black Boxville",
[604] = "Damaged Glendale",
[544] = "Fire Truck (Ladder)",
[502] = "Hotring Racer 2",
[503] = "Hotring Racer 3",
[505] = 'Rancher (From "Lure")',
[605] = "Damaged Sadler"
}
if (avehspecial[id]) then
return avehspecial[id]
end
return _getVehicleNameFromModel(id)
end
local _getVehicleModelFromName = getVehicleModelFromName
function getVehicleModelFromName(name)
local avehspecial = {
["Police LS"] = 596,
["Police SF"] = 597,
["Police LV"] = 598,
["Monster 2"] = 556,
["Monster 3"] = 557,
["Black Boxville"] = 609,
["Damaged Glendale"] = 604,
["Fire Truck (Ladder)"] = 544,
["Hotring Racer 2"] = 502,
["Hotring Racer 3"] = 503,
['Rancher (From "Lure")'] = 505,
["Damaged Sadler"] = 605
}
if (avehspecial[name]) then
return avehspecial[name]
end
return _getVehicleModelFromName(name)
end
function getMonthName(month)
local names = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
}
return names[month]
end
function iif(cond, arg1, arg2)
if (cond) then
return arg1
end
return arg2
end
|
local module = require("ethel.module")
local config = module.load("util.config")
local sprite = module.load("sprite")
local tile = module.load("tile")
local tilemap = module.load("tilemap")
local function loadLevel(path)
local cfg = config.loadFile(path)
local level = {
width = tonumber(cfg.width),
height = tonumber(cfg.height),
name = cfg.name or "Unnamed",
world = tonumber(cfg.world) or -1,
level = tonumber(cfg.level),
background = cfg.background or "background.main"
}
if not cfg.map or not cfg.tiles then
return false
end
local map = {}
local lines = cfg.map
while lines ~= "" do
local nlPos = lines:find("\n")
table.insert(map, lines:sub(1, (nlPos or 0) - 1))
lines = nlPos and lines:sub(nlPos + 1) or ""
end
level.height = level.height or #map
if level.height < #map then
for i = #map - level.height, 1, -1 do
table.remove(map, i)
end
elseif level.height > #map then
for i = 1, level.height - #map, 1 do
table.insert(map, 1, "")
end
end
if not level.width then
level.width = 0
for k, v in pairs(map) do
level.width = math.max(level.width, #v)
end
end
level.tilemap = tilemap.newTilemap(level.width, level.height)
level.sprites = {}
local tiles do
local env = {}
for k, v in pairs(_G) do
env[k] = v
end
env.module = module
env.sprite = sprite
env.tile = tile
env.tilemap = tilemap
local chunk, reason = load(cfg.tiles, "level", "t", env)
if not chunk then
error(reason)
end
tiles = chunk()
end
for y = 0, level.height - 1, 1 do
local line = map[level.height - y]
local x = 0
line:gsub(".", function(c)
if c ~= " " then
if x < level.width then
if tiles[c] then
if tiles[c]:isa(tile.Tile) then
level.tilemap:set(tiles[c]:create(x, y), x, y)
elseif tiles[c]:isa(sprite.Sprite) then
if tiles[c]:isa(sprite.Player) then
level.player = tiles[c](x * level.tilemap.gridSize * 2,
y * level.tilemap.gridSize)
else
table.insert(level.sprites,
tiles[c](x * level.tilemap.gridSize * 2,
y * level.tilemap.gridSize))
end
end
end
end
end
x = x + 1
end)
end
return level
end
return {
loadLevel = loadLevel
}
|
-- this is pretty tricky
local oldInitTechTree = MarineTeam.InitTechTree
function MarineTeam:InitTechTree()
-- super tricksy
local medpack = kTechId.MedPack
kTechId.MedPack = kTechId.HealingField
oldInitTechTree(self)
kTechId.MedPack = medpack
end |
local Packages = script.Parent.Parent.Parent.Parent.Parent
local Roact = require(Packages.Roact)
local UIBlox = Packages.UIBlox
local ModalBottomSheet = require(UIBlox.ModalBottomSheet.ModalBottomSheet)
local doSomething = function(a)
print(a, "was pressed!")
end
local Story = Roact.Component:extend("Story")
function Story:init()
self.state = {
}
self.ShowModal = function()
self:setState({
showModal = true,
})
end
self.OnDismiss = function()
self:setState({
showModal = false,
})
end
self.ref = Roact.createRef()
end
local modalButtonSet = {
{
text = "Stay on click",
onActivated = doSomething,
stayOnActivated = true,
},
{
text = "Dismiss on click",
onActivated = doSomething,
stayOnActivated = false,
},
}
function Story:render()
local showModal = self.state.showModal
local abSize = self.ref.AbsoluteSize
return Roact.createElement("Frame", {
Size = UDim2.new(1, 0, 0, 500),
[Roact.Ref] = self.ref,
}, {
TestButton1 = Roact.createElement("TextButton", {
Text = "Spawn Choices",
Size = UDim2.new(1, 0, 0.2, 0),
BackgroundColor3 = Color3.fromRGB(22, 22, 222),
AutoButtonColor = false,
[Roact.Event.Activated] = self.ShowModal,
}),
modal = showModal and Roact.createElement(ModalBottomSheet, {
bottomGap = 10,
screenWidth = abSize and abSize.X or 0,
onDismiss = self.OnDismiss,
showImages = false,
buttonModels = modalButtonSet,
})
})
end
return Story
|
require('common')
local MainMenu = State:derive()
local PlayerSelect = require('states.player_select')
local loop = love.audio.newSource("music/crappyloop.ogg", "stream")
loop:setVolume(0.5)
loop:setLooping(true)
function MainMenu:_init()
State._init(self, 'MainMenu')
self.playersAvailable = {}
end
function MainMenu:cleanup(game)
State.cleanup(game)
loop:stop()
end
function MainMenu:init(game)
loop:play()
game:addState(PlayerSelect())
love.graphics.setFont(LogoFont)
local brickW, brickH = 16*3, 16*3
for x=0,math.ceil(game.bounds.w/(brickW)) do
self:add(HouseBrick(x*brickW,0, brickW, brickH))
self:add(Vine(x*brickW, 0, brickW, brickH, AnimatedSprite(TheSheet, {startX=1,startY=1,w=16,h=16,off={x=2,y=2}}, {6,9,10,9,7}, 5)))
self:add(HouseBrick(x*brickW, math.floor(game.bounds.h/brickH)*brickH, brickW, brickH))
end
self.player = Player(5*brickW, 5*brickH, 2*brickW, 2*brickH)
self:add(self.player)
self.altPlayer = AnimatedSprite(self.player.img, {startX=1,startY=1, w=32,h=32, off={x=0,y=0}}, {2,1,3,1}, 5)
self:add(self.altPlayer)
self.altPlayer:makeLoop()
for y=0,math.floor(game.bounds.h/brickH) do
self:add(HouseBrick(0, (y+1)*brickH, brickW, brickH))
self:add(HouseBrick(math.ceil(game.bounds.w/brickW)*brickW-brickW, (y+1)*brickH, brickW, brickH))
end
-- self:addKeyReleaseEvent('w', 'jump')
-- self:addKeyPressEvent('a', 'moveLeft')
-- self:addKeyPressEvent('d', 'moveRight')
self:renumeratePlayers()
self.player:setInput("keyboard")
for _, joy in pairs(self.playersAvailable) do
self.player:setInput("joystick", joy)
end
end
function MainMenu:jump(key, game)
print("Main Menu State received a jump action")
end
function MainMenu:moveLeft(key, game, dt)
self.player:moveLeft(game, dt)
end
function MainMenu:moveRight(key, game, dt)
self.player:moveRight(game, dt)
end
function MainMenu:update(game, dt)
State.update(self, game, dt)
local done = true
for _, brick in pairs(self.types['HouseBrick']) do
local covered = brick:coveredWithVine(game)
done = done and covered
end
if done then
self.vinesCovered = true
game:listenForKey()
end
self:renumeratePlayers()
if self.vinesCovered then
if self:checkForInput(game) then
game:stopListeningForKey()
game:changeState('PlayerSelect')
end
end
end
function MainMenu:draw(game)
State.draw(self, game)
love.graphics.setColor(255, 255, 255, 255)
if self.vinesCovered then
love.graphics.setFont(LogoFont)
local m = love.graphics.getFont():getWidth("Mantical")
love.graphics.print("Manticle", game.bounds.w/2-m/2, game.bounds.h/2-love.graphics.getFont():getHeight())
love.graphics.setFont(LogoRegularFont)
local msg = "Press any button to start"
if #self.playersAvailable > 0 then
msg = "Someone press a button to start"
end
m = love.graphics.getFont():getWidth(msg)
love.graphics.print(msg, game.bounds.w/2-m/2, game.bounds.h/2+LogoFont:getHeight())
end
local i = 1
local x = 0
local oldFont = love.graphics.getFont()
love.graphics.setFont(LogoRegularFont)
local f = love.graphics.getFont()
for _, p in pairs(self.playersAvailable) do
local x = (i-1)*16
love.graphics.setColor(255, 0, 0, 255)
love.graphics.rectangle("fill", x, 0, 16, 16)
love.graphics.setColor(200,200,200,255)
love.graphics.setLineWidth(2)
love.graphics.rectangle("line", x, 0, 16, 16)
love.graphics.print(i, x+ f:getWidth(i)/2, f:getHeight()/2)
i = i + 1
end
love.graphics.setFont(oldFont)
end
function MainMenu:renumeratePlayers()
self.playersAvailable = {}
for _, joy in pairs(love.joystick.getJoysticks()) do
self.playersAvailable[joy] = joy
end
end
function MainMenu:checkForInput(game)
local someInput = false
for _, joy in pairs(love.joystick.getJoysticks()) do
for _, key in pairs(joyInputs) do
someInput = someInput or joy:isGamepadDown(key)
end
end
if not someInput then
for m=1,4 do
someInput = someInput or love.mouse.isDown(m)
end
end
someInput = someInput or game:wasKeyPressed()
return someInput
end
return MainMenu
|
-- Trigger_* detector
local MOD = {
LoadName = "Triggers",
LastQuery = 0.0,
--UseOffline = true,
}
MijHUD.LoadModule(MOD)
local function genBeams(mins, maxs)
return {
Vector(mins.x, mins.y, mins.z),
Vector(mins.x, mins.y, maxs.z),
Vector(mins.x, mins.y, mins.z),
Vector(mins.x, maxs.y, mins.z),
Vector(mins.x, mins.y, mins.z),
Vector(maxs.x, mins.y, mins.z),
Vector(maxs.x, maxs.y, maxs.z),
Vector(maxs.x, maxs.y, mins.z),
Vector(maxs.x, maxs.y, maxs.z),
Vector(maxs.x, mins.y, maxs.z),
Vector(maxs.x, maxs.y, maxs.z),
Vector(mins.x, maxs.y, maxs.z),
Vector(mins.x, mins.y, mins.z),
Vector(maxs.x, maxs.y, maxs.z),
}
end
function MOD.Initialize()
if not MijHUD.Options.Trigger then
MijHUD.Options.Trigger = {
AutoQuery = true,
QueryTimer = 30,
MaxRange = 5000,
}
end
MijHUD.LoadTextures("Utl", {
Beam3D = "mijhud/beam",
})
net.Receive("MijHUD.Triggers", MOD.OnReceiveData)
local packet = adv.NetStruct "#{pos:v ang:*Ang mins:v maxs:v kind:s parent:i16}"
MOD.NetPacket = packet
function packet.Readers.Ang()
local f = net.ReadBool()
return f and net.ReadAngle() or Angle()
end
end
function MOD.OnReceiveData()
local lst = MOD.NetPacket:ReadStruct()
for _, x in ipairs(lst) do
x.beams = genBeams(x.mins, x.maxs)
end
MOD.TriggerList = lst
end
function MOD.QueryData()
net.Start("MijHUD.Triggers")
net.SendToServer()
end
function MOD.Interval()
if not MijHUD.Options("Trigger.AutoQuery") then return end
local delay = MijHUD.Options("Trigger.QueryTimer")
if RealTime() > MOD.LastQuery + delay then
MOD.LastQuery = RealTime()
MOD.QueryData()
end
end
function MOD.Render3D()
if not MOD.TriggerList then return end
if not MijHUD.Options("Show.Triggers") then return end
local trigs = MOD.TriggerList
local my_pos = LocalPlayer():GetPos()
local range = MijHUD.Options("Trigger.MaxRange")
render.SetMaterial(MijHUD.GetTexture("Utl_Beam3D"))
for iKey = #trigs, 1, -1 do
local tr = trigs[iKey]
local pos, ang = tr.pos, tr.ang
local pt = Entity(tr.parent)
if IsValid(pt) then
pos = pt:LocalToWorld(pos)
ang = pt:LocalToWorldAngles(ang)
tr.had_parent = true
elseif tr.parent > -1 then
if tr.had_parent then
table.remove(trigs, iKey)
end
continue
end
if my_pos:Distance(pos) > range then continue end
local vecs = tr.beams
local col = MijHUD.GetColor("Trig_"..tr.kind)
for i = 1, #vecs, 2 do
local p0, p1 = vecs[i]*1, vecs[i+1]*1
p0:Rotate(ang); p1:Rotate(ang)
p0, p1 = p0 + pos, p1 + pos
render.DrawBeam(p0, p1, 2, 0, 1, col)
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.