content
stringlengths 5
1.05M
|
---|
if reaper.GetToggleCommandStateEx(0, 40671) ==
(string.match(select(2, reaper.get_action_context()), "on%.lua$") and 0 or 1) then
reaper.Main_OnCommand(40671, 0) -- Transport: Toggle preserve pitch in audio items when changing master playrate
end
|
-- load test base
local TheClassicRace = require("testbase")
-- aliases
local Events = TheClassicRace.Config.Events
local NetEvents = TheClassicRace.Config.Network.Events
describe("Sync", function()
local db
---@type TheClassicRaceConfig
local core
---@type TheClassicRaceEventBus
local eventbus
---@type TheClassicRaceNetwork
local network
---@type TheClassicRaceSync
local sync
local time = 1000000000
local AdvanceClock
before_each(function()
-- easier to only test channel
_G.SetIsInGuild(false)
-- reset
_G.C_Timer.Reset()
-- stubs
AdvanceClock = function(seconds)
time = time + seconds
_G.C_Timer.Advance(seconds)
end
db = LibStub("AceDB-3.0"):New("TheClassicRace_DB", TheClassicRace.DefaultDB, true)
db:ResetDB()
core = TheClassicRace.Core(TheClassicRace.Config, "Nub", "NubVille")
-- mock core:Now() to return our mocked time
function core:Now() return time end
eventbus = TheClassicRace.EventBus()
network = {SendObject = function() end}
sync = TheClassicRace.Sync(TheClassicRace.Config, core, db, eventbus, network)
end)
after_each(function()
-- reset any mocking of IsInGuild we did
_G.SetIsInGuild(nil)
end)
it("can request sync, marks ready when no partner", function()
local networkSpy = spy.on(network, "SendObject")
sync:InitSync()
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.RequestSync, 11, "CHANNEL")
assert.spy(networkSpy).called_at_most(1)
networkSpy:clear()
-- advance our clock so the sync happens
AdvanceClock(TheClassicRace.Config.RequestSyncWait)
assert.equals(true, sync.isReady)
end)
it("can request sync", function()
local networkSpy = spy.on(network, "SendObject")
_G.SetIsInGuild(true)
sync:InitSync()
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.RequestSync, 11, "CHANNEL")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.RequestSync, 11, "GUILD")
assert.spy(networkSpy).called_at_most(2)
end)
it("can init and start sync with partner", function()
local networkSpy = spy.on(network, "SendObject")
sync:InitSync()
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.RequestSync, 11, "CHANNEL")
assert.spy(networkSpy).called_at_most(1)
networkSpy:clear()
eventbus:PublishEvent(NetEvents.OfferSync, {11, nil}, "Dude")
-- advance our clock so the sync happens
AdvanceClock(TheClassicRace.Config.RequestSyncWait)
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.StartSync, 11, "WHISPER", "Dude")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Dude")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Dude")
assert.spy(networkSpy).called_at_most(3)
end)
it("can init and chooses preferred partner", function()
local networkSpy = spy.on(network, "SendObject")
sync:InitSync()
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.RequestSync, 11, "CHANNEL")
assert.spy(networkSpy).called_at_most(1)
networkSpy:clear()
-- Dude provides a
eventbus:PublishEvent(NetEvents.OfferSync, {11, time}, "Dude")
eventbus:PublishEvent(NetEvents.OfferSync, {11, nil}, "Chick")
-- overload SelectPartnerFromList to avoid randomness, hacky but works...
sync.SelectPartnerFromList = function(self, offers)
return table.remove(offers, 1)
end
-- advance our clock so the sync happens
AdvanceClock(TheClassicRace.Config.RequestSyncWait)
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.StartSync, 11, "WHISPER", "Chick")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Chick")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Chick")
assert.spy(networkSpy).called_at_most(3)
networkSpy:clear()
-- advance our clock so the retry happens
AdvanceClock(TheClassicRace.Config.RetrySyncWait)
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.StartSync, 11, "WHISPER", "Dude")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Dude")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Dude")
assert.spy(networkSpy).called_at_most(3)
end)
it("can init and sync with partner, won't (re)try other partners", function()
local networkSpy = spy.on(network, "SendObject")
sync:InitSync()
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.RequestSync, 11, "CHANNEL")
assert.spy(networkSpy).called_at_most(1)
networkSpy:clear()
eventbus:PublishEvent(NetEvents.OfferSync, {11, nil}, "Dude")
eventbus:PublishEvent(NetEvents.OfferSync, {11, nil}, "Chick")
-- overload SelectPartnerFromList to avoid randomness, hacky but works...
sync.SelectPartnerFromList = function(self, offers)
return table.remove(offers, 1)
end
-- advance our clock so the sync happens
AdvanceClock(TheClassicRace.Config.RequestSyncWait)
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.StartSync, 11, "WHISPER", "Dude")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Dude")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Dude")
assert.spy(networkSpy).called_at_most(3)
networkSpy:clear()
-- receive payload from Dude
eventbus:PublishEvent(NetEvents.SyncPayload, "", "Dude")
-- advance our clock so the retry happens
AdvanceClock(TheClassicRace.Config.RetrySyncWait)
assert.spy(networkSpy).called_at_most(0)
end)
it("can init and retry sync with unresponsive partner", function()
local networkSpy = spy.on(network, "SendObject")
sync:InitSync()
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.RequestSync, 11, "CHANNEL")
assert.spy(networkSpy).called_at_most(1)
networkSpy:clear()
eventbus:PublishEvent(NetEvents.OfferSync, {11, nil}, "Dude")
eventbus:PublishEvent(NetEvents.OfferSync, {11, nil}, "Chick")
-- overload SelectPartnerFromList to avoid randomness, hacky but works...
sync.SelectPartnerFromList = function(self, offers)
return table.remove(offers, 1)
end
-- advance our clock so the sync happens
AdvanceClock(TheClassicRace.Config.RequestSyncWait)
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.StartSync, 11, "WHISPER", "Dude")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Dude")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Dude")
assert.spy(networkSpy).called_at_most(3)
networkSpy:clear()
-- advance our clock so the retry happens
AdvanceClock(TheClassicRace.Config.RetrySyncWait)
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.StartSync, 11, "WHISPER", "Chick")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Chick")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Chick")
assert.spy(networkSpy).called_at_most(3)
end)
it("can offer and sync", function()
local networkSpy = spy.on(network, "SendObject")
-- mark as ready
sync.isReady = true
eventbus:PublishEvent(NetEvents.RequestSync, 11, "Dude")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.OfferSync, {11, nil}, "WHISPER", "Dude")
assert.spy(networkSpy).called_at_most(1)
networkSpy:clear()
eventbus:PublishEvent(NetEvents.StartSync, 11, "Dude")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Dude")
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, "", "WHISPER", "Dude")
assert.spy(networkSpy).called_at_most(2)
end)
it("won't offer when not ready offer and sync", function()
local networkSpy = spy.on(network, "SendObject")
eventbus:PublishEvent(NetEvents.RequestSync, 11, "Dude")
assert.spy(networkSpy).called_at_most(0)
end)
it("won't offer when networking is disabled", function()
local networkSpy = spy.on(network, "SendObject")
-- disable networking in options
db.profile.options.networking = false
-- mark as ready
sync.isReady = true
eventbus:PublishEvent(NetEvents.RequestSync, 11, "Dude")
assert.spy(networkSpy).called_at_most(0)
end)
it("won't request sync when networking is disabled", function()
local networkSpy = spy.on(network, "SendObject")
-- disable networking in options
db.profile.options.networking = false
sync:InitSync()
assert.spy(networkSpy).called_at_most(0)
end)
it("won't request sync when networking race is finished", function()
local networkSpy = spy.on(network, "SendObject")
-- mark race finished
db.factionrealm.finished = true
sync:InitSync()
assert.spy(networkSpy).called_at_most(0)
end)
it("produces proper payload for global leaderboard", function()
local networkSpy = spy.on(network, "SendObject")
db.factionrealm.leaderboard[0].players = {
{name = "Nub1", level = 5, dingedAt = time, classIndex = 8},
{name = "Nub2", level = 5, dingedAt = time, classIndex = 7},
{name = "Nub3", level = 5, dingedAt = time, classIndex = 6},
{name = "Nub4", level = 5, dingedAt = time, classIndex = 5},
{name = "Nub5", level = 5, dingedAt = time + 10, classIndex = 4},
}
sync:Sync("Dude", 0)
local expectedPayload = TheClassicRace.Serializer.SerializePlayerInfoBatch(db.factionrealm.leaderboard[0].players)
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, expectedPayload, "WHISPER", "Dude")
assert.spy(networkSpy).called_at_most(1)
end)
it("produces proper payload for class leaderboard", function()
local networkSpy = spy.on(network, "SendObject")
db.factionrealm.leaderboard[8].players = {
{name = "Nub1", level = 5, dingedAt = time, classIndex = 8},
}
sync:Sync("Dude", 8)
local expectedPayload = TheClassicRace.Serializer.SerializePlayerInfoBatch(db.factionrealm.leaderboard[8].players)
assert.spy(networkSpy).was_called_with(match.is_ref(network), NetEvents.SyncPayload, expectedPayload, "WHISPER", "Dude")
assert.spy(networkSpy).called_at_most(1)
end)
it("consumes proper payload", function()
local eventBusSpy = spy.on(eventbus, "PublishEvent")
sync:OnNetSyncPayload(TheClassicRace.Serializer.SerializePlayerInfoBatch({
{name = "Nubone", level = 5, dingedAt = time, classIndex = 8},
{name = "Nubtwo", level = 5, dingedAt = time, classIndex = 7},
{name = "Nubthree", level = 5, dingedAt = time, classIndex = 6},
{name = "Nubfour", level = 5, dingedAt = time + 10, classIndex = 5},
{name = "Nubfive", level = 5, dingedAt = time - 11, classIndex = 4},
}), "Dude")
assert.spy(eventBusSpy).was_called_with(match.is_ref(eventbus), Events.SyncResult,
match.is_same({
{name = "Nubone", level = 5, dingedAt = time, classIndex = 8},
{name = "Nubtwo", level = 5, dingedAt = time, classIndex = 7},
{name = "Nubthree", level = 5, dingedAt = time, classIndex = 6},
{name = "Nubfour", level = 5, dingedAt = time + 10, classIndex = 5},
{name = "Nubfive", level = 5, dingedAt = time - 11, classIndex = 4},
}), false)
assert.spy(eventBusSpy).called_at_most(1)
end)
end)
|
local h = require("null-ls.helpers")
local methods = require("null-ls.methods")
local DIAGNOSTICS_ON_SAVE = methods.internal.DIAGNOSTICS_ON_SAVE
return h.make_builtin({
name = "rstcheck",
meta = {
url = "https://github.com/myint/rstcheck",
description = "Checks syntax of reStructuredText and code blocks nested within it.",
},
method = DIAGNOSTICS_ON_SAVE,
filetypes = { "rst" },
generator_opts = {
command = "rstcheck",
args = { "-r", "$DIRNAME" },
to_stdin = true,
from_stderr = true,
format = "line",
multiple_files = true,
check_exit_code = function(code)
return code <= 1
end,
on_output = h.diagnostics.from_pattern(
[[([^:]+):(%d+): %((.+)/%d%) (.+)]],
{ "filename", "row", "severity", "message" }
),
},
factory = h.generator_factory,
})
|
--version = 1
-- ----------------------------------------------------------------------------
PAC_name = 'DEMO'
PAC_id = '124231'
-- ----------------------------------------------------------------------------
--Узлы WAGO
nodes =
{
{
name = 'A100',
ntype = 100,
n = 1,
IP = '192.168.0.100',
modules =
{
{ 1504 },
{ 600 },
}
}
}
------------------------------------------------------------------------------
--Устройства
devices =
{
{
name = 'LINE1V1',
descr = 'Вода из сети',
dtype = 0,
subtype = 1, -- V_DO1
DO =
{
{
node = 0,
offset = 0
},
},
},
}
|
-- this script adds a group button to create groups for your players --
local Event = require 'utils.event'
local function build_group_gui(player)
local group_name_width = 160
local description_width = 220
local members_width = 90
local member_columns = 3
local actions_width = 60
local total_height = 350
if not player.gui.top["group_button"] then
local b = player.gui.top.add({type = "button", name = "group_button", caption = global.player_group[player.name], tooltip = "Join / Create a group"})
b.style.font_color = {r = 0.1, g = 0.1, b = 0.1}
b.style.font = "default-bold"
b.style.minimal_height = 38
b.style.minimal_width = 38
b.style.top_padding = 2
b.style.left_padding = 4
b.style.right_padding = 4
b.style.bottom_padding = 2
end
if player.online_time < 1 then return end
if player.gui.left["group_frame"] then player.gui.left["group_frame"].destroy() end
local frame = player.gui.left.add({type = "frame", name = "group_frame", direction = "vertical"})
frame.style.minimal_height = total_height
local t = frame.add({type = "table", column_count = 5})
local headings = {{"Title", group_name_width}, {"Description", description_width}, {"Members", members_width * member_columns}, {"", actions_width*2 - 30}}
for _, h in pairs (headings) do
local l = t.add({ type = "label", caption = h[1]})
l.style.font_color = { r=0.98, g=0.66, b=0.22}
l.style.font = "default-listbox"
l.style.top_padding = 6
l.style.minimal_height = 40
l.style.minimal_width = h[2]
l.style.maximal_width = h[2]
end
local b = t.add {type = "button", caption = "X", name = "close_group_frame", align = "right"}
b.style.font = "default"
b.style.minimal_height = 30
b.style.minimal_width = 30
b.style.top_padding = 2
b.style.left_padding = 4
b.style.right_padding = 4
b.style.bottom_padding = 2
local scroll_pane = frame.add({ type = "scroll-pane", name = "scroll_pane", direction = "vertical", horizontal_scroll_policy = "never", vertical_scroll_policy = "auto"})
scroll_pane.style.maximal_height = total_height - 50
scroll_pane.style.minimal_height = total_height - 50
local t = scroll_pane.add({type = "table", name = "groups_table", column_count = 4})
for _, h in pairs (headings) do
local l = t.add({ type = "label", caption = ""})
l.style.minimal_width = h[2]
l.style.maximal_width = h[2]
end
for _, group in pairs (global.tag_groups) do
local l = t.add({ type = "label", caption = group.name})
l.style.font = "default-bold"
l.style.top_padding = 16
l.style.bottom_padding = 16
l.style.minimal_width = group_name_width
l.style.maximal_width = group_name_width
local color = game.players[group.founder].color
color = {r = color.r * 0.6 + 0.4, g = color.g * 0.6 + 0.4, b = color.b * 0.6 + 0.4, a = 1}
l.style.font_color = color
l.style.single_line = false
local l = t.add({ type = "label", caption = group.description})
l.style.top_padding = 16
l.style.bottom_padding = 16
l.style.minimal_width = description_width
l.style.maximal_width = description_width
l.style.font_color = {r = 0.90, g = 0.90, b = 0.90}
l.style.single_line = false
local tt = t.add({ type = "table", column_count = member_columns})
for _, p in pairs (game.connected_players) do
if group.name == global.player_group[p.name] then
local l = tt.add({ type = "label", caption = p.name})
local color = {r = p.color.r * 0.6 + 0.4, g = p.color.g * 0.6 + 0.4, b = p.color.b * 0.6 + 0.4, a = 1}
l.style.font_color = color
--l.style.minimal_width = members_width
l.style.maximal_width = members_width * 2
end
end
local tt = t.add({ type = "table", name = group.name, column_count = 2})
if player.admin == true or group.founder == player.name then
local b = tt.add({ type = "button", caption = "Delete"})
b.style.font = "default-bold"
b.style.minimal_width = actions_width
b.style.maximal_width = actions_width
else
local l = tt.add({ type = "label", caption = ""})
l.style.minimal_width = actions_width
l.style.maximal_width = actions_width
end
if group.name ~= global.player_group[player.name] then
local b = tt.add({ type = "button", caption = "Join"})
b.style.font = "default-bold"
b.style.minimal_width = actions_width
b.style.maximal_width = actions_width
else
local b = tt.add({ type = "button", caption = "Leave"})
b.style.font = "default-bold"
b.style.minimal_width = actions_width
b.style.maximal_width = actions_width
end
end
local frame2 = frame.add({type = "frame", name = "frame2"})
local t = frame2.add({type = "table", name = "group_table", column_count = 3})
local textfield = t.add({ type = "textfield", name = "new_group_name", text = "Name" })
textfield.style.minimal_width = group_name_width
local textfield = t.add({ type = "textfield", name = "new_group_description", text = "Description" })
textfield.style.minimal_width = description_width + members_width * member_columns
local b = t.add({type = "button", name = "create_new_group", caption = "Create"})
b.style.minimal_width = actions_width*2 - 12
b.style.font = "default-bold"
end
local function refresh_gui()
for _, p in pairs(game.connected_players) do
if p.gui.left["group_frame"] then
local frame = p.gui.left["group_frame"]
local new_group_name = frame.frame2.group_table.new_group_name.text
local new_group_description = frame.frame2.group_table.new_group_description.text
build_group_gui(p)
local frame = p.gui.left["group_frame"]
frame.frame2.group_table.new_group_name.text = new_group_name
frame.frame2.group_table.new_group_description.text = new_group_description
end
end
end
local function on_player_joined_game(event)
local player = game.players[event.player_index]
if not global.player_group then global.player_group = {} end
if not global.player_group[player.name] then global.player_group[player.name] = "[Group]" end
if not global.join_spam_protection then global.join_spam_protection = {} end
if not global.join_spam_protection[player.name] then global.join_spam_protection[player.name] = game.tick end
if not global.tag_groups then global.tag_groups = {} end
if player.online_time < 10 then
build_group_gui(player)
end
end
local function on_gui_click(event)
if not event then return end
if not event.element then return end
if not event.element.valid then return end
local player = game.players[event.element.player_index]
local name = event.element.name
local frame = player.gui.left["group_frame"]
if name == "group_button" then
if frame then
frame.destroy()
else
build_group_gui(player)
end
end
if not event.element.valid then return end
if name == "close_group_frame" then
frame.destroy()
end
if not event.element.valid then return end
if not frame then return end
if name == "create_new_group" then
local new_group_name = frame.frame2.group_table.new_group_name.text
local new_group_description = frame.frame2.group_table.new_group_description.text
if new_group_name ~= "" and new_group_name ~= "Name" and new_group_description ~= "Description" then
if string.len(new_group_name) > 64 then
player.print("Group name is too long. 64 characters maximum.", { r=0.90, g=0.0, b=0.0})
return
end
if string.len(new_group_description) > 128 then
player.print("Description is too long. 128 characters maximum.", { r=0.90, g=0.0, b=0.0})
return
end
global.tag_groups[new_group_name] = {name = new_group_name, description = new_group_description, founder = player.name}
local color = {r = player.color.r * 0.7 + 0.3, g = player.color.g * 0.7 + 0.3, b = player.color.b * 0.7 + 0.3, a = 1}
game.print(player.name .. " has founded a new group!", color)
game.print('>> ' .. new_group_name, { r=0.98, g=0.66, b=0.22})
game.print(new_group_description, { r=0.85, g=0.85, b=0.85})
frame.frame2.group_table.new_group_name.text = "Name"
frame.frame2.group_table.new_group_description.text = "Description"
refresh_gui()
return
end
end
local p = event.element.parent
if p then p = p.parent end
if p then
if p.name == "groups_table" then
if event.element.type == "button" and event.element.caption == "Join" then
global.player_group[player.name] = event.element.parent.name
local str = "[" .. event.element.parent.name
str = str .. "]"
player.gui.top["group_button"].caption = str
player.tag = str
if game.tick - global.join_spam_protection[player.name] > 600 then
local color = {r = player.color.r * 0.7 + 0.3, g = player.color.g * 0.7 + 0.3, b = player.color.b * 0.7 + 0.3, a = 1}
game.print(player.name .. ' has joined group "' .. event.element.parent.name .. '"', color)
global.join_spam_protection[player.name] = game.tick
end
refresh_gui()
return
end
if event.element.type == "button" and event.element.caption == "Delete" then
for _, p in pairs(game.players) do
if global.player_group[p.name] then
if global.player_group[p.name] == event.element.parent.name then
global.player_group[p.name] = "[Group]"
p.gui.top["group_button"].caption = "[Group]"
p.tag = ""
end
end
end
game.print(player.name .. ' deleted group "' .. event.element.parent.name .. '"')
global.tag_groups[event.element.parent.name] = nil
refresh_gui()
return
end
if event.element.type == "button" and event.element.caption == "Leave" then
global.player_group[player.name] = "[Group]"
player.gui.top["group_button"].caption = "[Group]"
player.tag = ""
refresh_gui()
return
end
end
end
end
Event.add(defines.events.on_gui_click, on_gui_click)
Event.add(defines.events.on_player_joined_game, on_player_joined_game) |
ys = ys or {}
ys.Battle.InterruptState = class("InterruptState", ys.Battle.IUnitState)
ys.Battle.InterruptState.__name = "InterruptState"
ys.Battle.InterruptState.Ctor = function (slot0)
slot0.super.Ctor()
end
ys.Battle.InterruptState.AddIdleState = function (slot0, slot1, slot2)
return
end
ys.Battle.InterruptState.AddMoveState = function (slot0, slot1, slot2)
return
end
ys.Battle.InterruptState.AddMoveLeftState = function (slot0, slot1, slot2)
return
end
ys.Battle.InterruptState.AddAttackState = function (slot0, slot1, slot2)
return
end
ys.Battle.InterruptState.AddDeadState = function (slot0, slot1, slot2)
slot1:OnDeadState()
end
ys.Battle.InterruptState.AddSkillState = function (slot0, slot1, slot2)
return
end
ys.Battle.InterruptState.AddSpellState = function (slot0, slot1, slot2)
return
end
ys.Battle.InterruptState.AddVictoryState = function (slot0, slot1, slot2)
slot1:OnVictoryState()
end
ys.Battle.InterruptState.AddVictorySwimState = function (slot0, slot1, slot2)
slot1:OnVictorySwimState()
end
ys.Battle.InterruptState.AddStandState = function (slot0, slot1, slot2)
return
end
ys.Battle.InterruptState.AddDiveState = function (slot0, slot1, slot2)
return
end
ys.Battle.InterruptState.AddDiveLeftState = function (slot0, slot1, slot2)
return
end
ys.Battle.InterruptState.AddInterruptState = function (slot0, slot1, slot2)
return
end
ys.Battle.InterruptState.AddDivingState = function (slot0, slot1, slot2)
slot1:OnDivingState()
end
ys.Battle.InterruptState.OnTrigger = function (slot0, slot1)
slot1:GetTarget():SetInterruptSickness(true)
end
ys.Battle.InterruptState.OnStart = function (slot0, slot1)
return
end
ys.Battle.InterruptState.OnEnd = function (slot0, slot1)
slot1:GetTarget().SetInterruptSickness(slot2, false)
slot1:ChangeToMoveState()
end
ys.Battle.InterruptState.CacheWeapon = function (slot0)
return true
end
return
|
modifier_disable_healing = class({})
function modifier_disable_healing:IsHidden() return true end
function modifier_disable_healing:RemoveOnDeath() return false end
function modifier_disable_healing:DeclareFunctions()
local funcs =
{
[MODIFIER_PROPERTY_DISABLE_HEALING] = true,
}
return funcs
end
function modifier_disable_healing:GetDisableHealing()
return 1
end
|
-- PublicUIMenu.lua
-- Created by [email protected]
-- on 14-04-01
local uibutton = import("..ui.UIButton")
local successView = import("..views.SuccessView");
local database = import("..common.dao")
local game_1 = import("..views.PyinFindChinese")
local game_2 = import("..views.ChineseFindPyin")
local game_3 = import("..views.PhraseFindLostCharacter")
local uianimationex = import("..ui.UIAnimationEx")
local controlMenuView = require("app.views.ControlMenuView")
local PublicUIMenu = {}
function PublicUIMenu:addUI(configtable)
local parent = configtable["parent"]
-- 绑定父节点
self.parent = parent
-- 问题回答正确回调方法
self.callback_right = configtable["listener_right"]
-- 问题错误正确回调方法
self.callback_wrong = configtable["listener_wrong"]
-- 绑定事件委托
require("framework.api.EventProtocol").extend(self)
local AssetsPath = "ChapterMaterial/Ch_%d_%d/%s"
local m_ch_id = app.currentChapterID
local m_ch_index = app.currentChapterIndex
local m_story_id = (m_ch_id - 1) * 4 + m_ch_index
if m_story_id > 8 then
m_story_id = 8
end
-- 添加自定义图层
self.layer = display.newLayer()
-- 添加导航栏
self.parent:performWithDelay(function()
controlMenuView:new():addTo(self.layer)
end, 1)
-- 添加图集
display.addSpriteFramesWithFile(PUBLIC_UI_MENU_TEXTURE_PLIST,PUBLIC_UI_MENU_TEXTURE_PNG)
-- 返回按钮
self.returnbutton = uibutton:newSpriteButton({
image = "#PUIM_Button_Return.png",
setAlpha = true,
x = display.left + 44,
y = display.top - 37,
listener = function(tag)
self:onExit()
app:playStartScene()
end
}):addTo(self.layer)
-- 复读按钮
self.rewindbutton = uibutton:newSpriteButton({
image = "#PUIM_Button_Rewind.png",
setAlpha = true,
x = display.right - 44,
y = display.top - 37,
listener = function()
self:onExit()
self:dispatchEvent({ name = "onRewindButtonClicked" })
app:rewindCurrentChapterIndex()
end
}):addTo(self.layer)
-- 加载动画资源
CCArmatureDataManager:sharedArmatureDataManager():addArmatureFileInfo(
PUBLIC_UI_MENU_ANIMATION_PNG,
PUBLIC_UI_MENU_ANIMATION_PLIST,
PUBLIC_UI_MENU_ANIMATION_XML
)
-- 兔子动画
self.rabbit = CCNodeExtend.extend(CCArmature:create("tuzi"))
self.rabbit:setPosition(display.cx, display.top - 40)
uianimationex:playAnim(self.rabbit, "tuzi", true)
self.rabbit:addTo(self.layer)
-- 给兔子添加动画点击事件
uianimationex:animationAddTouchEvent(self.rabbit, function(target)
self:onRabbitButtonClicked(target)
end)
-- 升降字幕背景
self.captionscreen = display.newSprite("#PUIM_Background_Detail.png", display.cx, display.cy + display.height):addTo(self.layer)
local m_content = database:getStoryConfig(m_story_id)["content"]
-- 故事文字内容
self.storylabel = ui.newTTFLabel({
text = m_content,
font = "DFYuanW7-GB",
x = 100,
y = 220,
size = 28,
dimensions = CCSize(700,450),
color = ccc3(86, 14, 0),
}):addTo(self.captionscreen)
-- 字幕关闭按钮
uibutton:newSpriteButton({
image = "#PUIM_Button_Close.png",
setAlpha = true,
setScale = true,
x = 860,
y = 320,
listener = function () self:onRabbitButtonClicked(self.rabbit) end,
}):addTo(self.captionscreen)
-- 将自定义图层添加到父节点
parent:addChild(self.layer)
-- 播放故事音频文件
parent:performWithDelay(function()
-- audio.playMusic(string.format(AssetsPath, m_ch_id, m_ch_index, "Sound/Story.MP3"), false)
end, 0.2)
end
function PublicUIMenu:setTouchEnabled(state)
if state ~= true then
state = false
end
-- self.returnbutton:setTouchEnabled(state)
self.rewindbutton:setTouchEnabled(state)
self.rabbit:setTouchEnabled(state)
end
function PublicUIMenu:onAnswerRightCallback(index)
if index < 4 then
print ("Right Index:", index)
self.callback_right(index)
elseif index >= 4 then
local m_ch_id = app.currentChapterID
local m_ch_index = app.currentChapterIndex
local m_story_id = (m_ch_id - 1) * 4 + m_ch_index
local AssetsPath = "ChapterMaterial/Ch_%d_%d/%s"
audio.playMusic(string.format(AssetsPath, m_ch_id, m_ch_index, "Sound/Win.MP3"), false)
successView:showSuccess(self.parent, function()
self:onExit()
end)
end
end
function PublicUIMenu:onAnswerWrongCallback()
self.callback_wrong()
end
function PublicUIMenu:displayQuestionButton(position)
position = position or CCPoint(display.cx, display.cy)
-- 问题按钮点击事件
local function onQuestionButtonClicked()
local m_ch_id = app.currentChapterID
local m_ch_index = app.currentChapterIndex
local m_story_id = (m_ch_id - 1) * 4 + m_ch_index
local AssetsPath = "ChapterMaterial/Ch_%d_%d/%s"
audio.playMusic(string.format(AssetsPath, m_ch_id, m_ch_index, "Sound/Question.MP3"), false)
self:dispatchEvent({ name = "onQuestionButtonClicked" })
self:setTouchEnabled(false)
self.m_questionButton:removeFromParentAndCleanup(true)
self.parent:performWithDelay(function()
self:playGame()
end, 4)
end
-- Question Button
self.m_questionButton = uibutton:newSpriteButton({
image = "#PUIM_Button_Question.png",
setAlpha = true,
setScale = true,
x = position.x,
y = position.y,
listener = onQuestionButtonClicked,
}):addTo(self.layer)
end
function PublicUIMenu:playGame()
-- 拼音找汉字游戏
if app.currentChapterIndex == 1 then
game_1:init(
self.parent,
function(index)
self:onAnswerRightCallback(index)
end,
function()
self:onAnswerWrongCallback()
end
)
return
end
-- 汉字找拼音游戏
if app.currentChapterIndex == 2 then
game_2:init(
self.parent,
function(index)
self:onAnswerRightCallback(index)
end,
function()
self:onAnswerWrongCallback()
end
)
return
end
-- 词语找汉字游戏
if app.currentChapterIndex == 3 then
game_3:init(
self.parent,
function(index)
self:onAnswerRightCallback(index)
end,
function()
self:onAnswerWrongCallback()
end
)
return
else
-- 彩蛋
game_3:init(
self.parent,
function(index)
self:onAnswerRightCallback(index)
end,
function()
self:onAnswerWrongCallback()
end
)
return
end
end
-- 方法名称:播放动画
-- 参数:
-- @animobj 动画对象
-- @animname 要播放的动画名字
-- @duration 动画持续时间
-- @loop 是否重复播放动画,默认为false
function PublicUIMenu:playAnimation(animobj, animname, duration, loop)
self.parent:performWithDelay(function()
if animobj == nil then return end
local animation = animobj:getAnimation()
if animation ~= nil then
animation:setAnimationScale(24 / 60)
animation:play(animname)
end
if loop == true then
self:playAnimation(animobj, animname, duration, loop)
end
end, duration)
end
-- 兔子动画及字幕关闭按钮点击事件
function PublicUIMenu:onRabbitButtonClicked(target)
local pos_y = target:getPositionY()
local m_speed_1 = 150.0/1.0
local m_speed_2 = 400.0/1.0
if pos_y <= display.top - 40 then
local m_target_pos_y = display.top + 110
local m_screen_pos_y = display.cy + 150
local duration = (m_target_pos_y - pos_y)/m_speed_1
transition.moveTo(target, {y = m_target_pos_y, time = duration})
duration = (self.captionscreen:getPositionY() - m_screen_pos_y)/m_speed_2
transition.moveTo(self.captionscreen, {y = m_screen_pos_y, time = duration})
else
local m_target_pos_y = display.top - 40
local m_screen_pos_y = display.cy + display.height
local duration = (pos_y - m_target_pos_y)/m_speed_1
transition.moveTo(target, {y = m_target_pos_y, time = duration})
duration = (m_screen_pos_y - self.captionscreen:getPositionY())/m_speed_2
transition.moveTo(self.captionscreen, {y = m_screen_pos_y, time = duration})
end
end
-- 添加监听事件
function PublicUIMenu:addEventListener(eventname, func_pointer)
self:addEventListener(eventname, func_pointer)
end
function PublicUIMenu:showScreenCurtain(layer)
local m_sprite = app.currentChapterIndex == 1 and "ChapterMaterial/Universal/ScreenCurtain_Yellow.png" or "ChapterMaterial/Universal/ScreenCurtain_Purple.png"
local curtain = display.newSprite(m_sprite,display.cx,display.cy):addTo(layer)
curtain:setTouchEnabled(true)
curtain:addTouchEventListener(function(event, x, y)
if event == "began" then
return true
end
end)
local x, y = curtain:getPosition()
transition.moveTo(curtain, {y = y + display.height * 3 / 2, time = 3})
self.parent:performWithDelay(function()
curtain:removeFromParentAndCleanup(true)
end,3.5)
end
-- 对象退出时移除所有监听事件
function PublicUIMenu:onExit()
print "All Event Listeners has been Removed!"
audio.stopMusic()
self:removeAllEventListeners()
game_1:onExit()
end
return PublicUIMenu |
local M = {}
---Get the highlight groups for the plugin
---@param theme table
---@return table
function M.get(theme)
return {
TroubleCount = { fg = theme.colors.purple, style = theme.options.bold },
TroubleFile = { bg = "NONE", fg = theme.colors.cyan },
TroubleFoldIcon = { bg = "NONE", fg = theme.colors.fg },
TroubleLocation = { bg = "NONE", fg = theme.colors.cyan }
}
end
return M
|
package = "blunty666.nodes_demo.views"
imports = {
"blunty666.nodes.gui.objects.Button",
"blunty666.nodes.gui.objects.Label",
}
class = "TimeView"
extends = "BaseView"
local WIDTH, HEIGHT = 10, 4
local function drawableDrag(drawable, mouseDragEvent)
local xPos, yPos = unpack(drawable.pos)
drawable.pos = {xPos + mouseDragEvent.delta_x, yPos + mouseDragEvent.delta_y}
end
local function getTime()
return textutils.formatTime(os.time(), false)
end
variables = {
startX = NIL,
startY = NIL,
topLabel = NIL,
closeButton = NIL,
timeLabel = NIL,
}
methods = {
Update = function(self)
self.timeLabel.text = getTime()
end,
ResetPos = function(self)
self.pos = {self.startX, self.startY}
end,
}
constructor = function(self, node, x, y, order)
self.startX = x - math.ceil(WIDTH/2)
self.startY = y - math.ceil(HEIGHT/2)
self.super(node, self.startX, self.startY, order, WIDTH, HEIGHT, colours.grey)
-- make draggable
local function backgroundDrag(_, mouseDragEvent)
local xPos, yPos = unpack(self.pos)
self.pos = {xPos + mouseDragEvent.delta_x, yPos + mouseDragEvent.delta_y}
end
self.background:SetCallback("mouse_drag", "time_view_drag", backgroundDrag)
-- add top label
self.topLabel = Label(self, 0, 0, 1, "Time", WIDTH - 1, 1, colours.white, colours.cyan)
self.topLabel.horizontalAlignment = "LEFT"
self.topLabel.clickable = false -- so we can still drag the background
-- add closeButton
self.closeButton = Button(self, WIDTH - 1, 0, 1, "X", colours.red, colours.white, 1, 1)
self.closeButton.clickedMainColour = colours.orange
self.closeButton.onRelease = function()
self.drawn = false
end
-- add time label
self.timeLabel = Label(self, 1, 2, 1, getTime(), WIDTH - 2, 1, colours.white, colours.grey)
self.timeLabel.horizontalAlignment = "RIGHT"
self.timeLabel.clickable = false -- so we can still drag the background
end
|
return {
name = 'SpriteBatchUsage',
description = 'Usage hints for SpriteBatches and Meshes to optimize data storage and access.',
constants = {
{
name = 'dynamic',
description = 'The object\'s data will change occasionally during its lifetime. ',
},
{
name = 'static',
description = 'The object will not be modified after initial sprites or vertices are added.',
},
{
name = 'stream',
description = 'The object data will always change between draws.',
},
},
} |
local type = _G.type
local function doflat(result, v, index, level)
if type(v) == "table" and (level == nil or level > 0) then
for k = 1, #v do
index = doflat(result, v[k], index, level and (level-1))
end
else
index = index + 1
result[index] = v
end
return index
end
local function flat(arr, level)
local result, j = {}, 0
for i = 1, #arr do
j = doflat(result, arr[i], j, level)
end
return result
end
return flat
|
-- Behavior for koray, the glowing moon
isCheckpoint = false
speechBubbleState = 0
update = function(B, W)
if (not isCheckpoint and W:isConditionFulfilled("npc_koray","level_checkpoint")) then
B:setPosition(150, 750)
isCheckpoint = true
speechBubbleState = 5
return
end
if (speechBubbleState == 0) then
B:say("KorayStart", 6)
B:wait(6)
speechBubbleState = 1
return
end
if (speechBubbleState == 1) then
B:say("KorayStart2", 4)
B:wait(4)
speechBubbleState = 2
end
if (speechBubbleState == 2 and B:getPosX() < 1300) then
B:say("KorayPiranhas", 4)
speechBubbleState = 3
return
end
if (speechBubbleState == 3 and B:getPosX() < 700) then
B:say("KorayTricky", 4)
speechBubbleState = 4
return
end
if (speechBubbleState == 4 and B:getPosX() > 600) then
B:say("KoraySoon", 4)
speechBubbleState = 5
return
end
if (speechBubbleState == 5 and B:getPosY() < 750 and B:getPosX() > 1100) then
B:say("KorayLetMe", 4)
B:setMovingTarget(1100,660)
B:executeSpell(0, 1200, 450)
B:wait(4)
speechBubbleState = 6
return
end
if (speechBubbleState == 6) then
B:resetMovingTarget()
speechBubbleState = 7
return
end
if (speechBubbleState == 7 and B:getPosY() < 600 and B:getPosX() > 1300) then
B:say("KorayThere", 4)
speechBubbleState = 8
return
end
if (speechBubbleState == 8 and B:getPosY() < 600 and B:getPosX() > 1800) then
B:say("KoraySpell", 4)
B:setMovingTarget(1900,660)
B:wait(4)
speechBubbleState = 9
return
end
if (speechBubbleState == 9) then
B:executeSpell(0, 1920, 430)
B:wait(3)
speechBubbleState = 10
return
end
if (speechBubbleState == 10) then
B:say("KorayGotIt", 4)
B:wait(4)
speechBubbleState = 11
return
end
if (speechBubbleState == 11) then
B:say("KorayTelekinesis", 4)
B:wait(5)
speechBubbleState = 12
return
end
if (speechBubbleState == 12) then
B:say("KorayTelekinesis2", 4)
W:learnSpell(5)
W:addQuestProgress("element_master", "master_earth")
W:changeQuestState("help_koray", "completed")
W:addConditionProgress("npc_koray", "level_stop")
-- this quest automatically fails because now, Bjarne is gone and this quest cannot be completed anymore.
if (W:isQuestState("runas_deal", "started") and not W:isQuestDescriptionUnlocked("runas_deal", 1)) then
W:changeQuestState("runas_deal", "failed")
end
B:setReplaceDistance(10000)
B:wait(5)
speechBubbleState = 13
return
end
if (speechBubbleState == 13) then
B:setMovingTarget(1720, 710)
B:wait(2)
speechBubbleState = 14
return
end
if (speechBubbleState == 14) then
B:setMovingTarget(1620, 860)
B:wait(1)
speechBubbleState = 15
return
end
if (speechBubbleState == 15) then
B:setMovingTarget(1820, 1010)
B:wait(2)
speechBubbleState = 16
return
end
if (speechBubbleState == 16) then
B:setMovingTarget(1960, 1210)
B:wait(1)
speechBubbleState = 17
return
end
if (speechBubbleState == 17) then
B:setMovingTarget(1780,1210)
B:wait(1)
speechBubbleState = 18
return
end
if (speechBubbleState == 18) then
B:say("KorayBye", 4)
B:wait(4)
speechBubbleState = 19
return
end
if (speechBubbleState == 19) then
B:leaveLevel()
speechBubbleState = 20
return
end
end
|
--[[
########################
# #
# Walter White #
# #
# #
# 2018 #
# #
# #
########################
--]]
resource_manifest_version "44febabe-d386-4d18-afbe-5e627f4af937"
client_script {
'cfg/config.lua',
'radarfix_client.lua'
}
server_scripts {
'cfg/config.lua',
'radarfix_serveur.lua'
}
|
--------------------
-- helper
--------------------
function urlDecode(url)
return url:gsub('%%(%x%x)', function(x)
return string.char(tonumber(x, 16))
end)
end
function guessType(filename)
local types = {
['.css'] = 'text/css',
['.js'] = 'application/javascript',
['.html'] = 'text/html',
['.png'] = 'image/png',
['.jpg'] = 'image/jpeg'
}
for ext, type in pairs(types) do
if string.sub(filename, -string.len(ext)) == ext
or string.sub(filename, -string.len(ext .. '.gz')) == ext .. '.gz' then
return type
end
end
return 'text/plain'
end
--------------------
-- Response
--------------------
Res = {
_skt = nil,
_type = nil,
_status = nil,
_redirectUrl = nil,
}
function Res:new(skt)
local o = {}
setmetatable(o, self)
self.__index = self
o._skt = skt
return o
end
function Res:redirect(url, status)
status = status or 302
self:status(status)
self._redirectUrl = url
self:send(status)
end
function Res:type(type)
self._type = type
end
function Res:status(status)
self._status = status
end
function Res:send(body)
self._status = self._status or 200
self._type = self._type or 'text/html'
local buf = 'HTTP/1.1 ' .. self._status .. '\r\n'
.. 'Content-Type: ' .. self._type .. '\r\n'
.. 'Content-Length:' .. string.len(body) .. '\r\n'
if self._redirectUrl ~= nil then
buf = buf .. 'Location: ' .. self._redirectUrl .. '\r\n'
end
buf = buf .. '\r\n' .. body
local function doSend()
if buf == '' then
self:close()
else
self._skt:send(string.sub(buf, 1, 512))
buf = string.sub(buf, 513)
end
end
self._skt:on('sent', doSend)
doSend()
end
function Res:sendFile(filename)
if file.exists(filename .. '.gz') then
filename = filename .. '.gz'
elseif not file.exists(filename) then
self:status(404)
if filename == '404.html' then
self:send(404)
else
self:sendFile('404.html')
end
return
end
self._status = self._status or 200
local header = 'HTTP/1.1 ' .. self._status .. '\r\n'
self._type = self._type or guessType(filename)
header = header .. 'Content-Type: ' .. self._type .. '\r\n'
if string.sub(filename, -3) == '.gz' then
header = header .. 'Content-Encoding: gzip\r\n'
end
header = header .. '\r\n'
print('* Sending ', filename)
local pos = 0
local function doSend()
file.open(filename, 'r')
if file.seek('set', pos) == nil then
self:close()
print('* Finished ', filename)
else
local buf = file.read(512)
pos = pos + 512
self._skt:send(buf)
end
file.close()
end
self._skt:on('sent', doSend)
self._skt:send(header)
end
function Res:close()
self._skt:on('sent', function() end) -- release closures context
self._skt:on('receive', function() end)
self._skt:close()
self._skt = nil
end
--------------------
-- Middleware
--------------------
function parseHeader(req, res)
local _, _, method, path, vars = string.find(req.source, '([A-Z]+) (.+)?(.*) HTTP')
if method == nil then
_, _, method, path = string.find(req.source, '([A-Z]+) (.+) HTTP')
end
local _GET = {}
if (vars ~= nil and vars ~= '') then
vars = urlDecode(vars)
for k, v in string.gmatch(vars, '([^&]+)=([^&]*)&*') do
_GET[k] = v
end
end
req.method = method
req.query = _GET
req.path = path
return true
end
function staticFile(req, res)
local filename = ''
if req.path == '/' then
filename = 'index.html'
else
filename = string.gsub(string.sub(req.path, 2), '/', '_')
end
res:sendFile(filename)
end
--------------------
-- HttpServer
--------------------
httpServer = {
_srv = nil,
_mids = {{
url = '.*',
cb = parseHeader
}, {
url = '.*',
cb = staticFile
}}
}
function httpServer:use(url, cb)
table.insert(self._mids, #self._mids, {
url = url,
cb = cb
})
end
function httpServer:close()
self._srv:close()
self._srv = nil
end
function httpServer:listen(port)
self._srv = net.createServer(net.TCP)
self._srv:listen(port, function(conn)
conn:on('receive', function(skt, msg)
local req = { source = msg, path = '', ip = skt:getpeer() }
local res = Res:new(skt)
for i = 1, #self._mids do
if string.find(req.path, '^' .. self._mids[i].url .. '$')
and not self._mids[i].cb(req, res) then
break
end
end
collectgarbage()
end)
end)
end
|
local libchest = require("libchest")
local libplan = require("libplan")
local libnav = require("libnav")
local robot = require("robot")
local util = require("util")
local component = require("component")
local librecipe = require("librecipe")
util.init()
local ico = component.inventory_controller
local args = { ... }
local function help()
print("Usage:")
print(" cleanup")
print(" Reinventorizes all items in all chests.")
end
if not(#args == 0) then
help()
return
end
local backup = libnav.get_location()
local chestnames = libchest.list_chests()
for k,v in pairs(chestnames) do
local info = libchest.get_info(v)
for i = 1, info.capacity do
local slot = info.slots[i]
if slot.name then
local is_known = librecipe.reverse_name(slot.name, true)
if not is_known then
print("No alias defined for '"..slot.name.."'!")
end
local plan, error = libplan.plan:new()
plan, error = libplan.action_fetch(plan, 1, slot.name, slot.count, slot.count)
assert(plan, error)
libplan.enact(plan, true)
local stack = ico.getStackInInternalSlot(1)
assert(stack)
util.check_stack(stack)
plan = libplan.plan:new()
plan, error = libplan.action_store(plan, 1, stack.name, stack.size, stack.maxSize)
assert(plan, error)
libplan.enact(plan, true)
end
end
end
libnav.go_to(backup)
libnav.flush()
|
require('pathfinding/math');
local PolyGrid = class.new();
Pathfinding.PolyGrid = PolyGrid;
local Point = Pathfinding.Point;
local Polygon = Pathfinding.Polygon;
function PolyGrid:constructor(nodes)
self.nodes = nodes or {};
self.offsetPolygons = {};
end
--[[
(Re-)create a PolyGrid from a set of polygons
--]]
function PolyGrid:createFromPolygons(polygons, actorSize)
self.nodes = {};
self.offsetPolygons = {};
-- Step 1: offset polygons
for polyIndex,polygon in pairs(polygons) do
-- Scale polygon up here
local solutions = polygon:offset(actorSize);
for i,v in pairs(solutions) do
table.insert(self.offsetPolygons, v);
end
end
-- Step 2: Now we can convert polygons to nodes
for polyIndex, polygon in pairs(self.offsetPolygons) do
-- Extract nodes from this polygon
local newNodes = polygon:toNodes();
for i,v in pairs(newNodes) do
table.insert(self.nodes, v);
end
end
-- Step 3: Check visibility between nodes, adding connections where there is visibility
for i,v in pairs(self.nodes) do
for j,k in pairs(self.nodes) do
if( v ~= k ) then -- Don't try connecting to yourself...
local vis = Pathfinding.checkVisibility(self.offsetPolygons, v, k);
if( vis ) then
-- Add a connection both ways
v:connectTo(k);
k:connectTo(v);
end
end
end
end
return self;
end
function PolyGrid:findPath(startPoint, endPoint)
--[[ Used to insert a new point into the grid, connect it to visible nodes, and returns it's index in the self.nodes table
Useful for temporarily inserting the start/end points
--]]
local function addNode(point)
-- Make a new copy of the point so we don't mess anything up in the original
table.insert(self.nodes, Point(point.x, point.y));
local index = #self.nodes;
-- Check visibility between nodes, adding connections where there is visibility
local v = self.nodes[index];
for j,k in pairs(self.nodes) do
if( v ~= k ) then -- Don't try connecting to yourself...
local vis = Pathfinding.checkVisibility(self.offsetPolygons, v, k);
if( vis ) then
-- Add a connection both ways
v:connectTo(k);
k:connectTo(v);
end
end
end
return index;
end
-- Used to remove those (temporary?) nodes, specified by index
local function removeNode(index)
-- Remove any connections to this point first
local node = self.nodes[index];
for i,v in pairs(self.nodes) do
if( i ~= index ) then
v:disconnect(node);
end
end
table.remove(self.nodes, index);
end
--[[ "Retrace" our steps to contruct a path by traversing childs & parents
--]]
local function retrace(startPoint, endPoint)
local path = {};
local function tableReverse(tab)
-- Only have to swap first half of the table
for i = 1, math.floor(#tab/2) do
local tmp = tab[i]; -- Tmp copy this one.
tab[i] = tab[#tab-i + 1]; -- Flip tab[i] and tab[n-i+1]; +1 because Lua tables start at index 1
tab[#tab-i + 1] = tmp;
end
return tab;
end
local currentPoint = endPoint;
while( currentPoint ~= startPoint ) do
table.insert(path, Point(currentPoint.x, currentPoint.y));
currentPoint = currentPoint.parent;
end
return tableReverse(path);
end
-- Insert the temporary points into the nodes table; we will remove them at the end so we must track their indices
local tmpStartPointIndex, tmpEndPointIndex = addNode(startPoint), addNode(endPoint);
-- Now that we've made our temporaries, we can override startPoint/endPoint for ease-of-use
startPoint = self.nodes[tmpStartPointIndex];
endPoint = self.nodes[tmpEndPointIndex];
local openSet = {};
local closedSet = {};
table.insert(openSet, startPoint);
while(#openSet > 0 ) do
local node = openSet[1]; -- 'node' starts off pointing to our start point
for i = 2, #openSet do
if( openSet[i]:getFCost() <= node:getFCost() ) then
if( openSet[i]:getHCost() < node:getHCost() ) then
-- Total cost is lower & closer to goal, so update our 'node'
node = openSet[i];
end
end
end
-- Move node from open to closed
table.remove(openSet, table.find(openSet, node));
table.insert(closedSet, node);
-- Check if we've reached the goal
if( node == endPoint or (node.x == endPoint.x and node.y == endPoint.y) ) then
-- Retrace our steps
local path = retrace(startPoint, endPoint);
-- Remove temporary nodes
removeNode(tmpStartPointIndex);
removeNode(tmpEndPointIndex);
return path;
end
-- Grab connections, set costs
for i,neighbor in pairs(node:getConnections()) do
-- Make sure it's not already closed so we aren't wasting time recalculating
if( not table.find(closedSet, neighbor) ) then
-- Calculate costs, add to open set
local newCostToNeighbor = node:getGCost() + math.distance(node.x, node.y, neighbor.x, neighbor.y);
if( newCostToNeighbor < neighbor:getGCost() or not table.find(openSet, neighbor) ) then
neighbor:setGCost(newCostToNeighbor);
neighbor:setHCost(math.distance(neighbor.x, neighbor.y, endPoint.x, endPoint.y));
neighbor:setParent(node);
if( not table.find(openSet, neighbor) ) then
table.insert(openSet, neighbor);
end
end
end
end
end
-- Remove temporary nodes
removeNode(tmpStartPointIndex);
removeNode(tmpEndPointIndex);
return false; -- No path found
end
|
-- Copyright 2021 SmartThings
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local test = require "integration_test"
local capabilities = require "st.capabilities"
local constants = require "st.zwave.constants"
local zw = require "st.zwave"
local zw_test_utils = require "integration_test.zwave_test_utils"
local SwitchMultilevel = (require "st.zwave.CommandClass.SwitchMultilevel")({ version=4 })
local t_utils = require "integration_test.utils"
-- supported comand classes: SWITCH_MULTILEVEL
local window_shade_switch_multilevel_endpoints = {
{
command_classes = {
{value = zw.SWITCH_MULTILEVEL}
}
}
}
local mock_springs_window_fashion_shade = test.mock_device.build_test_zwave_device({
profile = t_utils.get_profile_definition("base-window-treatment.yml"),
zwave_endpoints = window_shade_switch_multilevel_endpoints,
zwave_manufacturer_id = 0x026E,
zwave_product_type = 0x4353,
zwave_product_id = 0x5A31,
})
local function test_init()
test.mock_device.add_test_device(mock_springs_window_fashion_shade)
end
test.set_test_init_function(test_init)
test.register_coroutine_test(
"Setting window shade preset generate correct zwave messages",
function()
test.timer.__create_and_queue_test_time_advance_timer(5, "oneshot")
test.socket.capability:__queue_receive(
{
mock_springs_window_fashion_shade.id,
{ capability = "windowShadePreset", command = "presetPosition", args = {} }
}
)
test.socket.zwave:__expect_send(
zw_test_utils.zwave_test_build_send_command(
mock_springs_window_fashion_shade,
SwitchMultilevel:Set({
value = SwitchMultilevel.value.ON_ENABLE,
duration = constants.DEFAULT_DIMMING_DURATION
})
)
)
test.wait_for_events()
test.mock_time.advance_time(5)
test.socket.zwave:__expect_send(
zw_test_utils.zwave_test_build_send_command(
mock_springs_window_fashion_shade,
SwitchMultilevel:Get({})
)
)
end
)
test.run_registered_tests()
|
modifier_frozen_heroes = class({})
function modifier_frozen_heroes:CheckState() return {[MODIFIER_STATE_STUNNED] = true, [MODIFIER_STATE_INVULNERABLE] = true} end
function modifier_frozen_heroes:GetTexture() return 'modifier_invulnerable' end
function modifier_frozen_heroes:IsPurgable() return false end
function modifier_frozen_heroes:GetStatusEffectName() return "particles/status_fx/status_effect_avatar.vpcf" end
function modifier_frozen_heroes:GetEffectName() return "particles/items_fx/black_king_bar_avatar.vpcf" end
function modifier_frozen_heroes:GetEffectAttachType() return PATTACH_ABSORIGIN_FOLLOW end
if IsServer() then
tHeroInfos = LoadKeyValues('scripts/npc/npc_heroes.txt')
tAbilityInfos = LoadKeyValues('scripts/npc/npc_abilities.txt')
tStats = {'AttackDamageMin', 'AttackDamageMax', 'AttackRate', 'AttackAnimationPoint', 'AttackRange', 'MovementSpeed', 'MovementTurnRate', 'AttributeBaseStrength', 'AttributeStrengthGain', 'AttributeBaseIntelligence', 'AttributeIntelligenceGain', 'AttributeBaseAgility', 'AttributeAgilityGain', 'StatusHealthRegen', 'ArmorPhysical', 'VisionNighttimeRange', 'VisionDaytimeRange'}
local tMaxMinStats = {}
local ProjectileSpeed = {}
local tBasicAbilities = {{}}
local tUltiAbilities = {}
local tTalents = {{},{},{},{}}
local tUniqueTalents = {{},{},{},{}}
local iGroup = 1
local iHeroIndex = 1
local iGroupSize = 10
for k, v in pairs(tHeroInfos) do
if k ~= 'npc_dota_hero_target_dummy' and k ~= 'npc_dota_hero_base' and k ~= 'Version' then
for i,u in ipairs(tStats) do
if v[u] then
if not tMaxMinStats[u] then
tMaxMinStats[u] = {}
tMaxMinStats[u][1] = tonumber(v[u])
tMaxMinStats[u][2] = tonumber(v[u])
else
if tMaxMinStats[u][1] > tonumber(v[u]) then tMaxMinStats[u][1] = tonumber(v[u]) end
if tMaxMinStats[u][2] < tonumber(v[u]) then tMaxMinStats[u][2] = tonumber(v[u]) end
end
end
end
if v.ProjectileSpeed then
if tonumber(v.ProjectileSpeed) ~= 0 then
if not ProjectileSpeed[1] then
ProjectileSpeed[1] = tonumber(v.ProjectileSpeed)
ProjectileSpeed[2] = tonumber(v.ProjectileSpeed)
else
if ProjectileSpeed[1] > tonumber(v.ProjectileSpeed) then ProjectileSpeed[1] = tonumber(v.ProjectileSpeed) end
if ProjectileSpeed[2] < tonumber(v.ProjectileSpeed) then ProjectileSpeed[2] = tonumber(v.ProjectileSpeed) end
end
end
end
local iTalentTire = 1
if iHeroIndex > iGroupSize then
iHeroIndex = 1
iGroup = iGroup+1
tBasicAbilities[iGroup] = {}
else
iHeroIndex = iHeroIndex+1
end
for i = 1, 24 do
if v['Ability'..i] then
if v['Ability'..i] == 'troll_warlord_battle_trance' or tAbilityInfos[v['Ability'..i]].AbilityType == "DOTA_ABILITY_TYPE_ULTIMATE" and not string.find(tAbilityInfos[v['Ability'..i]].AbilityBehavior, 'DOTA_ABILITY_BEHAVIOR_NOT_LEARNABLE') and not string.find(tAbilityInfos[v['Ability'..i]].AbilityBehavior, 'DOTA_ABILITY_BEHAVIOR_HIDDEN') then
tUltiAbilities[k]=tUltiAbilities[k] or {}
if tAbilityInfos[v['Ability'..i]].AbilitySpecial then
for k1, v1 in pairs(tAbilityInfos[v['Ability'..i]].AbilitySpecial) do
if v1.LinkedSpecialBonus then
tUltiAbilities[k][v['Ability'..i]] = tUltiAbilities[k][v['Ability'..i]] or {}
tUltiAbilities[k][v['Ability'..i]][v1.LinkedSpecialBonus] = true
end
end
end
if not tUltiAbilities[k][v['Ability'..i]] then
tUltiAbilities[k][v['Ability'..i]] = 'none'
end
elseif tAbilityInfos[v['Ability'..i]].AbilityType == "DOTA_ABILITY_TYPE_ATTRIBUTES" then
if string.find(v['Ability'..i],'unique') then
local iTire = math.floor(iTalentTire)
tUniqueTalents[iTire][v['Ability'..i]] = true
else
local iTire = math.floor(iTalentTire)
table.insert(tTalents[iTire], v['Ability'..i])
end
iTalentTire = iTalentTire + 0.5
elseif not string.find(tAbilityInfos[v['Ability'..i]].AbilityBehavior, 'DOTA_ABILITY_BEHAVIOR_NOT_LEARNABLE') and not string.find(tAbilityInfos[v['Ability'..i]].AbilityBehavior, 'DOTA_ABILITY_BEHAVIOR_HIDDEN') and not tAbilityInfos[v['Ability'..i]].LinkedAbility then
tBasicAbilities[iGroup][k]=tBasicAbilities[iGroup][k] or {}
if tAbilityInfos[v['Ability'..i]].AbilitySpecial then
for k1, v1 in pairs(tAbilityInfos[v['Ability'..i]].AbilitySpecial) do
if v1.LinkedSpecialBonus then
tBasicAbilities[iGroup][k][v['Ability'..i]] = tBasicAbilities[iGroup][k][v['Ability'..i]] or {}
table.insert(tBasicAbilities[iGroup][k][v['Ability'..i]],v1.LinkedSpecialBonus)
end
end
end
if not tBasicAbilities[iGroup][k][v['Ability'..i]] then
tBasicAbilities[iGroup][k][v['Ability'..i]] = 'none'
end
end
end
end
end
end
local function FindLastUnderscore(s)
local i = 1
while string.find(s,'_',i) do
i = string.find(s,'_',i)+1
end
return i-1
end
local SortFunction = function (s1, s2)
local iLen1 = string.len(s1)
local iLen2 = string.len(s2)
-- print(s1, s2, iLen1, iLen2)
local iLastUnderscoreLoc = FindLastUnderscore(s1)
if string.sub(s1, 1, iLastUnderscoreLoc) == string.sub(s2, 1, iLastUnderscoreLoc) and tonumber(string.sub(s1, iLastUnderscoreLoc+1, -1)) and tonumber(string.sub(s2, iLastUnderscoreLoc+1, -1)) then
-- print(string.sub(s1, 1, iLastUnderscoreLoc))
if tonumber(string.sub(s1, iLastUnderscoreLoc+1, -1)) > tonumber(string.sub(s2, iLastUnderscoreLoc+1, -1)) then
return true
else
return false
end
end
local iLenMin
if iLen1 > iLen2 then
iLenMin = iLen2
else
iLenMin = iLen1
end
for i = 1, iLenMin do
if string.byte(string.sub(s1, i, i)) > string.byte(string.sub(s2, i, i)) then
return true
elseif string.byte(string.sub(s1, i, i)) < string.byte(string.sub(s2, i, i)) then
return false
end
end
if iLen1 > iLen2 then return true else return false end
end
table.sort(tTalents[1], SortFunction)
table.sort(tTalents[2], SortFunction)
table.sort(tTalents[3], SortFunction)
table.sort(tTalents[4], SortFunction)
local function RemoveDuplicate(aStrings)
local i = 1
while i < #aStrings do
-- print(FindLastUnderscore(aStrings[i]))
-- print(string.sub(aStrings[i], 1, FindLastUnderscore(aStrings[i])-1))
if string.sub(aStrings[i], 1, FindLastUnderscore(aStrings[i])-1) == string.sub(aStrings[i+1], 1, FindLastUnderscore(aStrings[i+1])-1) then
table.remove(aStrings, i+1)
else
i = i+1
end
end
end
-- PrintTable(tTalents[1])
RemoveDuplicate(tTalents[1])
RemoveDuplicate(tTalents[2])
RemoveDuplicate(tTalents[3])
RemoveDuplicate(tTalents[4])
local tBestBaseStats = {
MovementSpeed = tMaxMinStats.MovementSpeed[2],
AttackAnimationPoint = tMaxMinStats.AttackAnimationPoint[1],
AttackRate = tMaxMinStats.AttackRate[1],
AttackDamageMin = tMaxMinStats.AttackDamageMin[2],
AttackDamageMax = tMaxMinStats.AttackDamageMax[2],
AttributeBaseStrength = tMaxMinStats.AttributeBaseStrength[2],
AttributeBaseAgility = tMaxMinStats.AttributeBaseAgility[2],
AttributeBaseIntelligence = tMaxMinStats.AttributeBaseIntelligence[2],
AttributeStrengthGain = tMaxMinStats.AttributeStrengthGain[2],
AttributeAgilityGain = tMaxMinStats.AttributeAgilityGain[2],
AttributeIntelligenceGain = tMaxMinStats.AttributeIntelligenceGain[2],
ArmorPhysical = tMaxMinStats.ArmorPhysical[2],
AttackRange = tMaxMinStats.AttackRange[2],
StatusHealthRegen = tMaxMinStats.StatusHealthRegen[2],
ProjectileSpeed = ProjectileSpeed[2],
MovementTurnRate = tMaxMinStats.MovementTurnRate[2],
VisionDaytimeRange = tMaxMinStats.VisionDaytimeRange[2],
VisionNighttimeRange = tMaxMinStats.VisionNighttimeRange[2],
}
-- PrintTable(tBestBaseStats)
local tWorstBaseStats = {
MovementSpeed = tMaxMinStats.MovementSpeed[1],
AttackAnimationPoint = tMaxMinStats.AttackAnimationPoint[2],
AttackRate = tMaxMinStats.AttackRate[2],
AttackDamageMin = tMaxMinStats.AttackDamageMin[1],
AttackDamageMax = tMaxMinStats.AttackDamageMax[1],
AttributeBaseStrength = tMaxMinStats.AttributeBaseStrength[1],
AttributeBaseAgility = tMaxMinStats.AttributeBaseAgility[1],
AttributeBaseIntelligence = tMaxMinStats.AttributeBaseIntelligence[1],
AttributeStrengthGain = tMaxMinStats.AttributeStrengthGain[1],
AttributeAgilityGain = tMaxMinStats.AttributeAgilityGain[1],
AttributeIntelligenceGain = tMaxMinStats.AttributeIntelligenceGain[1],
ArmorPhysical = tMaxMinStats.ArmorPhysical[1],
AttackRange = tMaxMinStats.AttackRange[1],
StatusHealthRegen = tMaxMinStats.StatusHealthRegen[1],
ProjectileSpeed = ProjectileSpeed[1],
MovementTurnRate = tMaxMinStats.MovementTurnRate[1],
PrimaryAttribute = DOTA_ATTRIBUTE_AGILITY,
VisionDaytimeRange = tMaxMinStats.VisionDaytimeRange[1],
VisionNighttimeRange = tMaxMinStats.VisionNighttimeRange[1],
}
CustomNetTables:SetTableValue("fun_hero_stats", "worst_stats_hero", tWorstBaseStats)
CustomNetTables:SetTableValue("fun_hero_stats", "best_stats_hero", tBestBaseStats)
local function RestoreFloat(f)
return math.ceil(math.floor(f*100000)/10)/10000
end
for k, v in pairs(tBestBaseStats) do
tBestBaseStats[k] = RestoreFloat(v)
end
for k, v in pairs(tWorstBaseStats) do
tWorstBaseStats[k] = RestoreFloat(v)
end
local tNewAbilitiesBest = {}
local tNewAbilitiesWorst = {}
function BestStatsInit(hHero, context)
if not hHero:IsIllusion() and not hHero:IsClone() and not hHero:HasModifier('modifier_arc_warden_tempest_double') then
hHero:AddNewModifier(hHero, nil, "modifier_frozen_heroes", {})
end
hHero:AddNewModifier(hHero, nil, "modifier_attribute_growth_str_global", {}):SetStackCount(tBestBaseStats.AttributeStrengthGain*100)
hHero:AddNewModifier(hHero, nil, "modifier_attribute_growth_agi_global", {}):SetStackCount(tBestBaseStats.AttributeAgilityGain*100)
hHero:AddNewModifier(hHero, nil, "modifier_attribute_growth_int_global", {}):SetStackCount(tBestBaseStats.AttributeIntelligenceGain*100)
hHero:AddNewModifier(hHero, nil, "modifier_turn_rate_change", tNewAbilitiesBest):SetStackCount(166)
GameMode:InitiateHeroStats(hHero, tNewAbilitiesBest, tBestBaseStats)
end
function WorstStatsInit(hHero, context)
if not hHero:GetPlayerOwner().bBWInited then
hHero:AddNewModifier(hHero, nil, "modifier_frozen_heroes", {})
hHero:GetPlayerOwner().bBWInited = true
end
hHero:AddNewModifier(hHero, nil, "modifier_attribute_growth_str_global", {}):SetStackCount(tWorstBaseStats.AttributeStrengthGain*100)
hHero:AddNewModifier(hHero, nil, "modifier_attribute_growth_agi_global", {}):SetStackCount(tWorstBaseStats.AttributeAgilityGain*100)
hHero:AddNewModifier(hHero, nil, "modifier_attribute_growth_int_global", {}):SetStackCount(tWorstBaseStats.AttributeIntelligenceGain*100)
GameMode:InitiateHeroStats(hHero, tNewAbilitiesWorst, tWorstBaseStats)
end
LinkLuaModifier('modifier_frozen_heroes', 'heroes/best_worst_stats/best_worst_stats_init.lua', LUA_MODIFIER_MOTION_NONE)
for i = 1, 4 do
CustomNetTables:SetTableValue('game_options', 'unique_talents_'..tostring(i), tUniqueTalents[i])
CustomNetTables:SetTableValue('game_options', 'talents_'..tostring(i), tTalents[i])
end
CustomNetTables:SetTableValue('game_options', 'ulti_abilities', tUltiAbilities)
for i = 1, iGroup do
CustomNetTables:SetTableValue('game_options', 'basic_abilities'..tostring(i), tBasicAbilities[i])
end
CustomNetTables:SetTableValue('game_options', 'basic_abilities_group_count', {iGroup})
function BestWorstStatsListener(eventSourceIndex, keys)
local hPlayer = PlayerResource:GetPlayer(keys.PlayerID)
local hHero = hPlayer:GetAssignedHero()
if not hHero:HasModifier('modifier_frozen_heroes') then return end
local bBest = true
if type(keys.abilities[tostring(0)]) == 'string' then
tNewAbilitiesWorst[1] = keys.abilities[tostring(0)]
tNewAbilitiesWorst[2] = keys.abilities[tostring(1)]
tNewAbilitiesWorst[3] = keys.abilities[tostring(2)]
tNewAbilitiesWorst[4] = "generic_hidden"
tNewAbilitiesWorst[5] = "generic_hidden"
tNewAbilitiesWorst[6] = keys.abilities[tostring(3)]
bBest = false
local j = 7
for i = 0, 3 do
if type(keys.talents[tostring(i)]) == 'string' then
tNewAbilitiesWorst[j] = keys.talents[tostring(i)]
else
tNewAbilitiesWorst[j] = 'special_bonus_empty_'..tostring(j-6)
end
j = j+1
tNewAbilitiesWorst[j] = 'special_bonus_empty_'..tostring(j-6)
j = j+1
end
else
tNewAbilitiesBest[1] = "generic_hidden"
tNewAbilitiesBest[2] = "generic_hidden"
tNewAbilitiesBest[3] = "generic_hidden"
tNewAbilitiesBest[4] = "generic_hidden"
tNewAbilitiesBest[5] = "generic_hidden"
tNewAbilitiesBest[6] = "generic_hidden"
local j = 7
for i = 0, 3 do
if type(keys.talents[tostring(i)]) == 'string' then
tNewAbilitiesBest[j] = keys.talents[tostring(i)]
else
tNewAbilitiesBest[j] = 'special_bonus_empty_'..tostring(j-6)
end
j = j+1
tNewAbilitiesBest[j] = 'special_bonus_empty_'..tostring(j-6)
j = j+1
end
end
if tonumber(keys.primary_attribute) > 0 then
tBestBaseStats.PrimaryAttribute = tonumber(keys.primary_attribute)-1
end
if bBest then
BestStatsInit(hHero, nil)
else
WorstStatsInit(hHero, nil)
end
hHero:RemoveModifierByName('modifier_frozen_heroes')
end
CustomGameEventManager:RegisterListener("best_worst_stats_selected_abilities", BestWorstStatsListener)
end |
local _, Addon = ...
local DB = Addon.DB
local L = Addon.Locale
local MinimapIcon = Addon.UI.MinimapIcon
local Options = Addon.UI.Groups.Options
local Widgets = Addon.UI.Widgets
function Options:Create(parent)
Widgets:Heading(parent, L.OPTIONS)
self:AddGeneral(parent)
end
function Options:AddGeneral(parent)
parent = Widgets:InlineGroup({
parent = parent,
title = L.GENERAL,
fullWidth = true
})
-- Minimap Icon.
Widgets:CheckBox({
parent = parent,
label = L.MINIMAP_ICON,
tooltip = L.MINIMAP_ICON_TOOLTIP,
get = function() return not DB.global.minimapIcon.hide end,
set = function() MinimapIcon:Toggle() end
})
-- NPC Tooltips.
Widgets:CheckBox({
parent = parent,
label = L.NPC_TOOLTIPS,
tooltip = L.NPC_TOOLTIPS_TOOLTIP,
get = function() return DB.global.npc_tooltips end,
set = function(value) DB.global.npc_tooltips = value end
})
end
|
-- map helper
local function map(mode, lhs, rhs, opts)
local options = {noremap = true}
if opts then options = vim.tbl_extend('force', options, opts) end
vim.api.nvim_set_keymap(mode, lhs, rhs, options)
end
local cmd = vim.cmd
local s = {silent = true}
------------------------
-- Mapping Goes Here --
------------------------
map('n', '<Space>', '<Nop>')
vim.g.mapleader = ' '
map('n', '<leader>s', ':Dashboard<cr>', s)
map('n', '<leader>n', ':tabnew<cr>', s)
map('n', '<leader>t', ':ToggleTerm<cr>', s)
map('n', '<leader>f', ':Telescope find_files<cr>', s)
map('n', '<leader>l', ':IndentBlanklineToggle<cr>', s)
map('', '<space>c', ':quickmenu#toggle(0)<cr>', s)
map('n', '<C-right>', ':BufferLineCycleNext<cr>', s)
map('n', '<C-left>', ':BufferLineCyclePrev<cr>', s)
map('n', '<C-c>', ':NvimTreeToggle<cr>', s)
map('n', '<leader>nf', ':NvimTreeFindFile<cr>', s)
map('n', '<leader>n', ':DashboardNewFile<cr>', s)
map('n', '<leader>i', ':e ~/.config/nvim/lua/options.lua<cr>', s)
-- Save, Exit
map('n', '<C-s>', ':w<cr>')
map('n', '<C-q>', ':wq<cr>')
map('n', 'qq', ':q!<cr>')
map('n', '<C-z>', '<esc>ua<esc>')
map('n', '<z>', '<esc>ua<esc>')
-- Map ; to :
map('n', ';', ':')
map('n', ';', ':')
-- Tab cycles Buffer
map('n', '<tab>', ':bnext<cr>', s)
map('v', '<s-tab>', ':bprevious<cr>', s)
-- Run Packer Sync
map('n', '<leader>cs', ':PackerSync<cr>', s)
-- Don't Insert in newline
map('n', 'o', 'o<esc>', s)
map('n', 'O', 'O<esc>', s)
-- Prevent x from overriding Paste
map('', 'x', '"_x', s)
map('', 'X', '"_x', s)
map('', '<del>', '"_x', s)
-- Undo BreakPoints
--map('i', ',', ',<c-q>u')
--map('i', '.', '.<c-q>u')
--map('i', '!', '!<c-q>u')
--map('i', '?', '?<c-q>u')
-- Duplicate Line up/down
map('n', '<C-m-j>', '"dY"dp')
map('n', '<C-m-k>', '"dY"dP')
------------------------
-- Some Defaults --
------------------------
local place = vim.api.nvim_set_keymap
local sn = {noremap = false, silent = true}
-- Sellect all text
place('n', '<C-x>', ':%y<cr>', sn)
-- disable macros
place('', 'q', '<Nop>', sn)
-- smoothie
place('', 'ScrollWheelUp', '<C-u>', sn)
place('', 'ScrollWheelDown', '<C-d>', sn)
-- don't go below the line
place('', '<PageUp>', '1000<C-u>', sn)
place('', '<PageDown>', '1000<C-d>', sn)
place('i', '<PageUp>', '<C-o>1000<C-u>', sn)
place('i', '<PageDown>', '<C-o>1000<C-d>', sn)
--__Unused__--
-- Window Navigation
--place('n', '<up>', '<C-w><up>', sn)
--place('n', '<down>', '<C-w><down>', sn)
--place('n', '<left>', '<C-w><left>', sn)
--place('n', '<right>', '<C-w><right>', sn)
-- Better Complete
--" Navigate the complete menu items like CTRL+n / CTRL+p would.
--inoremap <expr> <Down> pumvisible() ? "<C-n>" :"<Down>"
--inoremap <expr> <Up> pumvisible() ? "<C-p>" : "<Up>"
--" Select the complete menu item like CTRL+y would.
--inoremap <expr> <Right> pumvisible() ? "<C-y>" : "<Right>"
--inoremap <expr> <CR> pumvisible() ? "<C-y>" :"<CR>
--" Cancel the complete menu item like CTRL+e would.
--inoremap <expr> <Left> pumvisible() ? "<C-e>" : "<Left>"
|
local mgr = require 'backend.master.mgr'
local event = {}
function event.initialized()
mgr.sendToClient {
type = 'event',
seq = mgr.newSeq(),
event = 'initialized',
}
end
function event.capabilities()
mgr.sendToClient {
type = 'event',
seq = mgr.newSeq(),
event = 'capabilities',
body = {
capabilities = require 'common.capabilities'
}
}
end
function event.stopped(threadId, msg)
mgr.sendToClient {
type = 'event',
seq = mgr.newSeq(),
event = 'stopped',
body = {
reason = msg,
threadId = threadId,
}
}
end
function event.breakpoint(reason, breakpoint)
mgr.sendToClient {
type = 'event',
seq = mgr.newSeq(),
event = 'breakpoint',
body = {
reason = reason,
breakpoint = breakpoint,
}
}
end
function event.output(category, output, source, line)
mgr.sendToClient {
type = 'event',
seq = mgr.newSeq(),
event = 'output',
body = {
category = category,
output = output,
source = source,
line = line,
}
}
end
function event.terminated()
mgr.sendToClient {
type = 'event',
seq = mgr.newSeq(),
event = 'terminated',
body = {
restart = false,
}
}
end
function event.loadedSource(reason, source)
mgr.sendToClient {
type = 'event',
seq = mgr.newSeq(),
event = 'loadedSource',
body = {
reason = reason,
source = source,
}
}
end
function event.thread(reason, threadId)
mgr.sendToClient {
type = 'event',
seq = mgr.newSeq(),
event = 'thread',
body = {
reason = reason,
threadId = threadId,
}
}
end
function event.invalidated(areas, threadId)
if not mgr.getClient().supportsInvalidatedEvent then
return
end
mgr.sendToClient {
type = 'event',
seq = mgr.newSeq(),
event = 'invalidated',
body = {
areas = areas,
threadId = threadId,
}
}
end
return event
|
createTeam("Minigames",100,50,225)
createTeam("Drag",50,55,90)
createTeam("Trials",250,100,100)
createTeam("Shooter",100,250,20)
createTeam("Destruction Derby",250,0,150)
createTeam("Deathmatch",150,80,80)
createTeam("Counter Strike",250,150,0)
---: 3923, 3917, 3911, 3907, 3906, 3905, 3903, 3902, 3900, 3899, 3898, 3897, 3895, 3894, 3893
-- Status of event
ShooterEnabled = false
FFAEnabled = false
SWEnabled = false
HFEnabled = false
DDEnabled = false
moneyEarn = 25000
WaitingTime = 200000
EventTimer = nil
nextEvent = nil
positions = {}
startingEvent = "DD"
-- t
--[[setTimer(function()
serverCount = getPlayerCount()
end,500,0)]]
events = {
["SW"] = true,
["FFA"] = true,
["HF"] = true,
["Shooter"] = true,
["DD"] = true,
}
function isPlayerSigned(player)
--[[if HFPlayer[player] then
return true
elseif FFAPlayer[player] then
return true
elseif DDPlayer[player] then
return true
elseif ShooterPlayer[player] then
return true
elseif SWPlayer[player] then
return true
else
return false
end]]
if getElementDimension(player) == 5006 or getElementDimension(player) == 5005 or getElementDimension(player) == 5001 or getElementDimension(player) == 5002 or getElementDimension(player) == 5003 or getElementDimension(player) == 5004 then
return true
end
end
-- Trigger the Event
function onCalculateBanktime(theTime)
if (theTime >= 60000) then
local plural = ""
if (math.floor((theTime/1000)/60) >= 2) then
plural = "s"
end
return tostring(math.floor((theTime/1000)/60) .. " minute" .. plural)
else
local plural = ""
if (math.floor((theTime/1000)) >= 2) then
plural = "s"
end
return tostring(math.floor((theTime/1000)) .. " second" .. plural)
end
end
function triggerTheEvent(event)
if (not events[event]) then
outputDebugString("Bad argument 1 @ triggerTheEvent "..tostring(event).." is not registered", 1)
return
end
if isFFAEnabled == true or isSWEnabled == true or isHFEnabled == true or isShooterEnabled == true or isDDEnabled == true then
return
end
if (event == "Shooter") then
ShooterEnabled = true
elseif (event == "DD") then
DDEnabled = true
elseif (event == "HF") then
HFEnabled = true
elseif (event == "FFA") then
FFAEnabled = true
elseif (event == "SW") then
SWEnabled = true
end
if event == "HF" then
addEventMsg("Ev","#FFF000(Mini-Game) #FF0000Hydra Fight #FFFFFFis ready", getRootElement(), 255, 255, 0,10000)
outputChatBox("#FF0000(Mini-Game) #FFFF00Hydra Fight #FFFFFFis ready , use /play to participate in the event!",root, 255, 255, 0,true)
elseif event == "SW" then
addEventMsg("Ev","#FFF000(Mini-Game) #FF0000Ship War #FFFFFFis ready", getRootElement(), 255, 255, 0,10000)
outputChatBox("#FF0000(Mini-Game) #FFFF00Ship War #FFFFFFis ready , use /play to participate in the event!",root, 255, 255, 0,true)
else
addEventMsg("Ev","#FFF000(Mini-Game) #FF0000"..tostring(event).." #FFFFFFis ready", getRootElement(), 255, 255, 0,10000)
outputChatBox("#FF0000(Mini-Game) #FFFF00"..tostring(event).." #FFFFFFis ready , use /play to participate in the event!",root, 255, 255, 0,true)
--outputText(event)
end
end
-- Stop the Event
function stopEvent(event)
if (not events[event]) then
outputDebugString("Bad argument 1 @ stopEvent, event name specified is incorrect: "..tostring(event).."", 1)
return
end
if (event == "Shooter") then
ShooterEnabled = false
elseif (event == "HF") then
HFEnabled = false
elseif (event == "SW") then
SWEnabled = false
elseif (event == "FFA") then
FFAEnabled = false
elseif (event == "DD") then
DDEnabled = false
end
---outputChatBox("(Mini-Game) "..event.." has ended /eventtime for more details.",root,255,255,255)
end
-- Check if event is started
function isEventStarted(event)
if (not events[event]) then
outputDebugString("Bad argument 1 @ isEventStarted, event name specified is incorrect: "..tostring(event).."", 1)
return
end
if (event == "Shooter") then
if (ShooterEnabled == true) then
return true
elseif (ShooterEnabled ~= true) then
return false
end
elseif (event == "DD") then
if (DDEnabled == true) then
return true
elseif (DDEnabled ~= true) then
return false
end
elseif (event == "HF") then
if (HFEnabled == true) then
return true
elseif (HFEnabled ~= true) then
return false
end
elseif (event == "SW") then
if (SWEnabled == true) then
return true
elseif (SWEnabled ~= true) then
return false
end
elseif (event == "FFA") then
if (FFAEnabled == true) then
return true
elseif (FFAEnabled ~= true) then
return false
end
end
end
-- Start event
function startEvent(event)
if (not events[event]) then
outputDebugString("Bad argument 1 @ startEvent, event name specified is incorrect: "..tostring(event).."", 1)
return
end
if (isFFAEnabled == true or isSWEnabled == true or isHFEnabled == true or isShooterEnabled == true or isDDEnabled == true) then
return
end
--EventTimer = setTimer(triggerTheEvent, 200000, 1, event)
nextEvent = event
end
-- Get nearst copy
function getNearestCop( thePlayer )
if ( exports.server:getPlayerAccountName ( thePlayer ) ) then
local x, y, z = getElementPosition( thePlayer )
local distance = nil
local theCopNear = false
for i, theCop in ipairs ( getElementsByType( "player" ) ) do
local x1, x2, x3 = getElementPosition( theCop )
if ( exports.server:getPlayerAccountName ( theCop ) ) then
if exports.DENlaw:isLaw(theCop) then
if ( distance ) and ( getDistanceBetweenPoints2D( x, y, x1, x2 ) < distance ) then
distance = getDistanceBetweenPoints2D( x, y, x1, x2 )
theCopNear = theCop
elseif ( getDistanceBetweenPoints2D( x, y, x1, x2 ) < 100 ) then
distance = getDistanceBetweenPoints2D( x, y, x1, x2 )
theCopNear = theCop
end
end
end
end
return theCopNear
end
end
function joinEvent(plr)
if getPlayerWantedLevel(plr) >= 3 then
local isCopNear = getNearestCop(plr)
if isCopNear then
exports.NGCdxmsg:createNewDxMessage( plr, "You can't warp while you are being chased by a cop!", 225, 0, 0 )
return false
end
end
if (ShooterEnabled == true) then
-- if getElementData(plr,"isPlayerPrime") then
if getElementData(plr,"isPlayerFlagger") then
exports.NGCdxmsg:createNewDxMessage(plr,"You can't warp while you have the Flag!",255,0,0)
return false
end
signupForShooter(plr)
-- end
elseif (DDEnabled == true) then
-- i-f getElementData(plr,"isPlayerPrime") then
if getElementData(plr,"isPlayerFlagger") then
exports.NGCdxmsg:createNewDxMessage(plr,"You can't warp while you have the Flag!",255,0,0)
return false
end
signupForDD(plr)
-- end
elseif (HFEnabled == true) then
-- i-f getElementData(plr,"isPlayerPrime") then
if getElementData(plr,"isPlayerFlagger") then
exports.NGCdxmsg:createNewDxMessage(plr,"You can't warp while you have the Flag!",255,0,0)
return false
end
signupForHF(plr)
-- end
elseif (SWEnabled == true) then
-- i-f getElementData(plr,"isPlayerPrime") then
if getElementData(plr,"isPlayerFlagger") then
exports.NGCdxmsg:createNewDxMessage(plr,"You can't warp while you have the Flag!",255,0,0)
return false
end
signupForSW(plr)
-- end
elseif (FFAEnabled == true) then
-- i-f getElementData(plr,"isPlayerPrime") then
if getElementData(plr,"isPlayerFlagger") then
exports.NGCdxmsg:createNewDxMessage(plr,"You can't warp while you have the Flag!",255,0,0)
return false
end
signupForFFA(plr)
-- end
end
end
--addCommandHandler("play", joinEvent)
--[[addCommandHandler("givexd",function(p,cmd,r)
if getElementData(p,"isPlayerPrime") then
if r then
loadMap(r)
setElementPosition(p,ShooterPos[r][1][1],ShooterPos[r][1][2],ShooterPos[r][1][3])
end
end
end)
addCommandHandler("startxd",function(p,cmd,r)
if getElementData(p,"isPlayerPrime") then
startEvent(r)
end
end)]]
-- On resource start
function hasProsiner(p)
if exports.DENlaw:isPlayerLawEnforcer(p) then
local arrestedTable = exports.DENlaw:getCopArrestedPlayers( p )
if arrestedTable then
if arrestedTable and #arrestedTable == 0 or arrestedTable == nil then
return true
else
for i, thePrisoner in ipairs ( arrestedTable ) do
if thePrisoner and i > 0 then
return false
else
return true
end
end
end
else
return true
end
else
return true
end
end
function onStart()
if (isFFAEnabled == true or isSWEnabled == true or isHFEnabled == true or isShooterEnabled == true or isDDEnabled == true) then
return
end
nextEvent = startingEvent
---EventTimer = setTimer(triggerTheEvent, WaitingTime, 1, startingEvent)
end
addEventHandler("onResourceStart", resourceRoot, onStart)
function outputText(event)
--addEventMsg("startingEvent", "#FF0000(Mini-Game) #FFFF00"..tostring(event).."",getRootElement(), 255, 255, 0, 5000)
end
function stopText()
--addEventMsg("startingEvent","",root, 255, 255, 0, 5000)
end
-- Time until next event
function outputTime(plr)
if (isTimer(EventTimer)) then
a, b, c = getTimerDetails(EventTimer)
timeLeftt = a/1000
timeLeft = math.floor(timeLeftt)
addEventMsg("Ev1","#00FF00Mini-Game ("..nextEvent..") #FFFFFFEvent upcoming within: "..onCalculateBanktime(math.floor(a)).."", plr, 255, 255, 0)
elseif (DDEnabled == true) then
if DDStarted == false then
addEventMsg("Ev2","#00FF00Mini-Game (DD) Use /play to play this event", plr, 255, 255, 0)
else
addEventMsg("Ev1","#00FF00Mini-Game (DD) in progres", plr, 255, 255, 0)
end
elseif (ShooterEnabled == true) then
if ShooterStarted == false then
addEventMsg("Ev2","#00FF00Mini-Game (Shooter) Use /play to play this event", plr, 255, 255, 0)
else
addEventMsg("Ev1","#00FF00Mini-Game (Shooter) in progres", plr, 255, 255, 0)
end
elseif (HFEnabled == true) then
if HFStarted == false then
addEventMsg("Ev2","#00FF00Mini-Game (Hydra Fight) Use /play to play this event", plr, 255, 255, 0)
else
addEventMsg("Ev1","#00FF00Mini-Game (Hydra Fight) in progres", plr, 255, 255, 0)
end
elseif (SWEnabled == true) then
if SWStarted == false then
addEventMsg("Ev2","#00FF00Mini-Game (Ship War) Use /play to play this event", plr, 255, 255, 0)
else
addEventMsg("Ev1","#00FF00Mini-Game (Ship War) in progres", plr, 255, 255, 0)
end
elseif (FFAEnabled == true) then
if FFAStarted == false then
addEventMsg("Ev2","#00FF00Mini-Game (FFA) Use /play to play this event", plr, 255, 255, 0)
else
addEventMsg("Ev1","#00FF00Mini-Game (FFA) in progres", plr, 255, 255, 0)
end
end
end
addCommandHandler("eventtime", outputTime)
function addEventMsg(id, text, player, r, g, b, timer)
-- if (type(id) ~= "string") then return false end
--triggerClientEvent(player, "addEventMsg", player, id, text, r, g, b, timer)
--for k,v in ipairs(getElementsByType("player")) do
-- if getPlayerTeam(v) and getTeamName(getPlayerTeam(v)) == "Staff" or getElementData(v,"isPlayerPrime") then
-- exports.killMessages:outputMessage(removeHEX(text),v,0,255,0)
triggerClientEvent(player, "addEventMsg", player, id, text, r, g, b, timer)
-- end
--end
return true
end
function removeHEX( message )
return string.gsub(message,"#%x%x%x%x%x%x", "")
end
|
modifier_sona_crescendo_celerity_attack = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_sona_crescendo_celerity_attack:IsHidden()
return false
end
function modifier_sona_crescendo_celerity_attack:IsDebuff()
return true
end
function modifier_sona_crescendo_celerity_attack:IsPurgable()
return true
end
function modifier_sona_crescendo_celerity_attack:GetTexture()
return "custom/sona_song_of_celerity"
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_sona_crescendo_celerity_attack:OnCreated( kv )
-- references
self.ms_bonus = self:GetAbility():GetSpecialValueFor( "celerity_slow" ) -- special value
end
function modifier_sona_crescendo_celerity_attack:OnRefresh( kv )
-- references
self.ms_bonus = self:GetAbility():GetSpecialValueFor( "celerity_slow" ) -- special value
end
function modifier_sona_crescendo_celerity_attack:OnDestroy( kv )
end
--------------------------------------------------------------------------------
-- Modifier Effects
function modifier_sona_crescendo_celerity_attack:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
}
return funcs
end
function modifier_sona_crescendo_celerity_attack:GetModifierMoveSpeedBonus_Percentage()
return self.ms_bonus
end
--------------------------------------------------------------------------------
-- Graphics & Animations
-- function modifier_sona_crescendo_celerity_attack:GetEffectName()
-- return "particles/string/here.vpcf"
-- end
-- function modifier_sona_crescendo_celerity_attack:GetEffectAttachType()
-- return PATTACH_ABSORIGIN_FOLLOW
-- end
-- function modifier_sona_crescendo_celerity_attack:PlayEffects()
-- -- Get Resources
-- local particle_cast = "string"
-- local sound_cast = "string"
-- -- Get Data
-- -- Create Particle
-- local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_NAME, hOwner )
-- ParticleManager:SetParticleControl( effect_cast, iControlPoint, vControlVector )
-- ParticleManager:SetParticleControlEnt(
-- effect_cast,
-- iControlPoint,
-- hTarget,
-- PATTACH_NAME,
-- "attach_name",
-- vOrigin, -- unknown
-- bool -- unknown, true
-- )
-- ParticleManager:SetParticleControlForward( effect_cast, iControlPoint, vForward )
-- SetParticleControlOrientation( effect_cast, iControlPoint, vForward, vRight, vUp )
-- ParticleManager:ReleaseParticleIndex( effect_cast )
-- -- buff particle
-- self:AddParticle(
-- nFXIndex,
-- bDestroyImmediately,
-- bStatusEffect,
-- iPriority,
-- bHeroEffect,
-- bOverheadEffect
-- )
-- -- Create Sound
-- EmitSoundOnLocationWithCaster( vTargetPosition, sound_location, self:GetCaster() )
-- EmitSoundOn( sound_target, target )
-- end |
------------------------
----- Hunger Games -----
------------------------
local tonumber = GLOBAL.tonumber
local TheNet = GLOBAL.TheNet
local SpawnPrefab = GLOBAL.SpawnPrefab
local function DoTaskInTime(time, task) GLOBAL.TheWorld:DoTaskInTime(time, task) end
local maxplayers = TheNet:GetServerMaxPlayers()
local ismastersim = TheNet:GetIsMasterSimulation()
local hunger_games = GLOBAL.GAME_MODES["hunger_games"]
local DEBUG = true -- TODO
----- Zugehöriges --------------------------------------------------------------
--- Liste der neuen Gegenstände
PrefabFiles = {
"cornucopia",
"platform"
}
----- Optionen -----------------------------------------------------------------
--- Unveränderlich
hunger_games.resource_renewal = false
hunger_games.ghost_sanity_drain = false
hunger_games.portal_rez = false
hunger_games.reset_time = nil
hunger_games.invalid_recipes = { "lifeinjector", "resurrectionstatue", "reviver" }
--- Einstellungen
hunger_games.waiting_time = GetModConfigData("waiting_time")
hunger_games.ghost_enabled = GetModConfigData("ghost_enabled")
hunger_games.fancy_option = GetModConfigData("fancy_option")
----- Allgemein ----------------------------------------------------------------
--- Liste aller Methoden, die bei Beginn des Spiels ausgeführt werden sollen
local on_begin = { }
--- Das Spiel beginnt in t Sekunden
local function BeginGame(t)
t = tonumber(t) or 10
if t <= 0 then
for index, task in pairs(on_begin) do task() end
else
if ismastersim then TheNet:Announce(t) end
DoTaskInTime(1, function() BeginGame(t-1) end)
end
end
--- Ein Spieler hat gewonnen, die Partie wird beendet
local function EndGame()
TheNet:Announce("The game is over!")
end
--- Positionen um das Füllhorn herum
local RadialPosition = nil
--- Abstände der Gegenstände vom Füllhorn
local platform = 15
local backpack = 7
--- Listet für alle Startpositionen auf, ob sie von einem Spieler besetzt sind
local platform_used = { }
----- Veränderte Spieldateien --------------------------------------------------
--- Startumgebung mit Füllhorn
AddPrefabPostInit("multiplayer_portal", function(inst)
DoTaskInTime(0, function()
inst:Hide()
-- Position des Füllhorns
local x0, y, z0 = inst:GetPosition():Get()
SpawnPrefab("cornucopia").Transform:SetPosition(x0, y, z0)
-- Halbkreis vor dem Füllhorn
local delta = math.pi / maxplayers
RadialPosition = function(r, i)
local phi = i * delta
local x = x0 + r * math.sin(phi)
local z = z0 + r * math.cos(phi)
return x, y, z
end
-- TODO Voraussetzung ist genügend freier Raum, i.A. aber nicht der Fall
for i = 1, maxplayers do
platform_used[i] = false
local x, y, z = RadialPosition(platform, i)
SpawnPrefab("platform").Transform:SetPosition(x, y, z)
-- Rucksäcke für den Start
if i ~= maxplayers then
local x, y, z = RadialPosition(backpack, i+0.5)
local pack = SpawnPrefab("backpack")
pack.Transform:SetPosition(x, y, z)
-- TODO Zufällig befüllen
--pack.components.container.slots[0] =
end
end
end)
end)
--- Verhalten der Charaktere
AddPlayerPostInit(function(inst)
-- Figur bleibt beim Ausloggen bestehen
inst.OnDespawn = function(inst)
if inst.components.playercontroller ~= nil then
inst.components.playercontroller:Enable(false)
end
inst.components.locomotor:StopMoving()
inst.components.locomotor:Clear()
end
-- Keine Spielerindikatoren
inst:AddTag("noplayerindicator")
if ismastersim then
-- Den Spieler vor Beginn einfrieren
inst.components.health:SetInvincible(true)
inst.components.hunger:Pause()
local _speed = inst.components.locomotor.runspeed
inst.components.locomotor.runspeed = 0
table.insert(on_begin, function()
inst.components.health:SetInvincible(false)
inst.components.hunger:Resume()
inst.components.locomotor.runspeed = _speed
end)
-- Verstecken ermöglichen
inst:AddComponent("hideaway")
end
-- Das Spiel bei Erreichen der gewünschten Spieleranzahl beginnen
if #TheNet:GetClientTable() >= maxplayers or DEBUG then
DoTaskInTime(0, BeginGame)
end
end)
--- Charaktere auf den Startplattformen absetzen
AddComponentPostInit("playerspawner", function(inst)
inst.SpawnAtNextLocation = function(self, inst, player)
local i = 1
while platform_used[i] do
i = i + 1
end
platform_used[i] = true
local x, y, z = RadialPosition(platform, i)
self:SpawnAtLocation(inst, player, x, y, z)
end
end)
--- Zeit vor Beginn anhalten
AddComponentPostInit("clock", function(inst)
local _OnUpdate = inst.OnUpdate
inst.OnUpdate = nil
inst.LongUpdate = nil
table.insert(on_begin, function()
inst.OnUpdate = _OnUpdate
inst.LongUpdate = _OnUpdate
end)
end)
--- Versteckmöglichkeit in Büschen und Bäumen
-- TODO SCHÖNER
for index, prefab in pairs({"evergreen", "twiggytree", "berrybush"}) do
AddPrefabPostInit(prefab, function(inst)
if GLOBAL.TheWorld.ismastersim then
inst:AddComponent("hideaway")
end
end)
end
AddAction("HIDE", "Hide", function(act)
if act.doer ~= nil and act.target ~= nil and act.doer:HasTag("player")
and act.target.components.hideaway --and act.target:HasTag("tree")
and not act.target:HasTag("burnt") and not act.target:HasTag("fire")
and not act.target:HasTag("stump") then
act.target.components.hideaway:Hide(act.doer)
return true
else
return false
end
end)
AddComponentAction("SCENE", "hideaway", function(inst, doer, actions, right)
if right and not inst:HasTag("burnt") and not inst:HasTag("fire") and (
inst:HasTag("tree") and not inst:HasTag("stump")
or inst:HasTag("berrybush")
) then
table.insert(actions, GLOBAL.ACTIONS.HIDE)
end
end)
AddStategraphState("wilson", GLOBAL.State{ name = "hide",
tags = { "hiding", "notarget", "nomorph", "busy", "nopredict" },
onenter = function(inst)
inst.components.locomotor:Stop()
inst.SoundEmitter:PlaySound("dontstarve/movement/foley/hidebush")
inst.sg.statemem.action = inst.bufferedaction
inst.sg:SetTimeout(20)
if not GLOBAL.TheWorld.ismastersim then
inst:PerformPreviewBufferedAction()
end
end,
timeline = {
GLOBAL.TimeEvent(6 * GLOBAL.FRAMES, function(inst)
if GLOBAL.TheWorld.ismastersim then
inst:PerformBufferedAction()
end
inst:Hide()
inst.DynamicShadow:Enable(false)
inst.sg:RemoveStateTag("busy")
end),
GLOBAL.TimeEvent(24 * GLOBAL.FRAMES, function(inst)
inst.sg:RemoveStateTag("nopredict")
inst.sg:AddStateTag("idle")
end),
},
onexit = function(inst)
inst:Show()
inst.DynamicShadow:Enable(true)
inst.AnimState:PlayAnimation("run_pst")
inst.SoundEmitter:PlaySound("dontstarve/movement/foley/hidebush")
if inst.bufferedaction == inst.sg.statemem.action then
inst:ClearBufferedAction()
end
inst.sg.statemem.action = nil
end,
ontimeout = function(inst)
inst:Show()
inst.DynamicShadow:Enable(true)
inst.AnimState:PlayAnimation("run_pst")
inst.SoundEmitter:PlaySound("dontstarve/movement/foley/hidebush")
if not GLOBAL.TheWorld.ismastersim then
inst:ClearBufferedAction()
end
inst.sg:GoToState("idle")
end,
})
AddStategraphActionHandler("wilson", GLOBAL.ActionHandler(GLOBAL.ACTIONS.HIDE, "hide"))
----- Kalkstein -----
|
local Enemy = require 'nodes/enemy'
local gamestate = require 'vendor/gamestate'
local sound = require 'vendor/TEsound'
local Timer = require 'vendor/timer'
local Projectile = require 'nodes/projectile'
local sound = require 'vendor/TEsound'
local utils = require 'utils'
local window = require 'window'
local camera = require 'camera'
local fonts = require 'fonts'
return {
name = 'acornpod',
attackDelay = 1,
height = 24,
width = 24,
antigravity = true,
jumpkill = false,
damage = 5,
knockback = 0,
hp = 1000,
tokens = 4,
tokenTypes = { -- p is probability ceiling and this list should be sorted by it, with the last being 1
{ item = 'coin', v = 1, p = 0.9 },
{ item = 'health', v = 1, p = 1 }
},
animations = {
attack = {
right = {'loop', {'1-2,1'}, 0.2},
left = {'loop', {'1-2,1'}, 0.2}
},
default = {
right = {'loop', {'1,1'}, 0.25},
left = {'loop', {'1,1'}, 0.25}
},
hurt = {
right = {'loop', {'1-2,1'}, 0.2},
left = {'loop', {'1-2,1'}, 0.2}
},
dying = {
right = {'once', {'1-2,1'}, 0.25},
left = {'once', {'1-2,1'}, 0.25}
},
},
enter = function( enemy )
enemy.spawned = 0
end,
spawn_minion = function( enemy, direction )
local node = {
x = enemy.position.x,
y = enemy.position.y,
type = 'enemy',
properties = {
enemytype = 'jumpingacorn'
}
}
local spawnedJumpingacorn = Enemy.new(node, enemy.collider, enemy.type)
spawnedJumpingacorn.velocity.x = math.random(10,100)*direction
spawnedJumpingacorn.velocity.y = -math.random(100,200)
enemy.containerLevel:addNode(spawnedJumpingacorn)
end,
update = function( dt, enemy, player, level )
if enemy.dead then return end
local direction = player.position.x > enemy.position.x + 40 and -1 or 1
spawnMax = math.random(1,4)
if enemy.state == 'hurt' and enemy.spawned < spawnMax then
enemy.props.spawn_minion(enemy, direction)
enemy.spawned = enemy.spawned + 1
elseif enemy.state == 'attack' and enemy.spawned < spawnMax then
enemy.props.spawn_minion(enemy, direction)
enemy.spawned = enemy.spawned + 1
elseif enemy.state == 'default' and enemy.current_enemy == enemy.name then
enemy.spawned = 0
end
end
} |
-- This resource is part of the default Cfx.re asset pack (cfx-server-data)
-- Altering or recreating for local use only is strongly discouraged.
version '1.0.0'
author 'Cfx.re <[email protected]>'
description 'A flexible handler for game type/map association.'
repository 'https://github.com/citizenfx/cfx-server-data'
client_scripts {
"mapmanager_shared.lua",
"mapmanager_client.lua"
}
server_scripts {
"mapmanager_shared.lua",
"mapmanager_server.lua"
}
fx_version 'cerulean'
games { 'gta5', 'rdr3' }
server_export "getCurrentGameType"
server_export "getCurrentMap"
server_export "changeGameType"
server_export "changeMap"
server_export "doesMapSupportGameType"
server_export "getMaps"
server_export "roundEnded"
rdr3_warning 'I acknowledge that this is a prerelease build of RedM, and I am aware my resources *will* become incompatible once RedM ships.'
|
----
-- Dev Tools mod submenu.
--
-- Includes submenu for the "Dev Tools" mod.
--
-- **Source Code:** [https://github.com/dstmodders/mod-auto-join](https://github.com/dstmodders/mod-auto-join)
--
-- @classmod DevToolsSubmenu
--
-- @author [Depressed DST Modders](https://github.com/dstmodders)
-- @copyright 2019
-- @license MIT
-- @release 0.9.0-alpha
----
require "class"
local SDK = require "autojoin/sdk/sdk/sdk"
local _API
--- Helpers
-- @section helpers
local function ToggleAutoJoinCheckbox(self, name, field)
return {
type = MOD_DEV_TOOLS.OPTION.CHECKBOX,
options = {
label = "Toggle " .. name,
on_accept_fn = function()
return self.defaults[field]
end,
on_get_fn = function()
return self.autojoin[field]
end,
on_set_fn = function(_, _, value)
self.autojoin[field] = value
end,
},
}
end
local function ToggleIndicatorVisibility(self, name)
return {
type = MOD_DEV_TOOLS.OPTION.CHECKBOX,
on_add_to_root_fn = MOD_DEV_TOOLS.ON_ADD_TO_ROOT_FN.IS_NO_WORLD,
options = {
label = name,
on_get_fn = function()
return self.indicator_visibility
end,
on_set_fn = function(_, _, value)
self.indicator_visibility = value
local indicators = self.autojoin:GetIndicators()
for _, indicator in pairs(indicators) do
indicator:Update()
end
end,
},
}
end
local function NumericConfigOption(self, name, min, max, field, on_add_to_root_fn)
return {
type = MOD_DEV_TOOLS.OPTION.NUMERIC,
on_add_to_root_fn = on_add_to_root_fn,
options = {
label = name,
min = min,
max = max,
on_accept_fn = function()
local value = self.autojoin.config_default[field]
self.autojoin.config[field] = value
end,
on_get_fn = function()
return self.autojoin.config[field]
end,
on_set_fn = function(_, _, value)
self.autojoin.config[field] = value
end,
},
}
end
local function NumericIndicatorConfigOption(self, name, min, max, step, field, setter_name)
return {
type = MOD_DEV_TOOLS.OPTION.NUMERIC,
options = {
label = name,
min = min,
max = max,
step = step,
on_accept_fn = function()
local value = self.autojoin.config_default[field]
print(self.autojoin.config[field], value)
self.autojoin.config[field] = value
local indicators = self.autojoin:GetIndicators()
for _, indicator in pairs(indicators) do
indicator[setter_name](indicator, self.autojoin.config[field])
end
end,
on_get_fn = function()
return self.autojoin.config[field]
end,
on_set_fn = function(_, _, value)
self.autojoin.config[field] = value
local indicators = self.autojoin:GetIndicators()
for _, indicator in pairs(indicators) do
indicator[setter_name](indicator, value)
end
end,
},
}
end
local function Add(self)
_API:AddSubmenu({
label = "Auto Join",
name = "AutoJoinSubmenu",
options = {
ToggleAutoJoinCheckbox(self, "Fake Joining", "is_fake_joining"),
{
type = MOD_DEV_TOOLS.OPTION.CHECKBOX,
options = {
label = "Toggle Global AutoJoin",
on_get_fn = function()
return self.is_global_autojoin
end,
on_set_fn = function(_, _, value)
self.is_global_autojoin = value
__STRICT = false
_G.AutoJoin = value and self.autojoin or nil
__STRICT = true
end,
},
},
ToggleIndicatorVisibility(self, "Toggle Indicator Visibility"),
{
type = MOD_DEV_TOOLS.OPTION.DIVIDER,
on_add_to_root_fn = MOD_DEV_TOOLS.ON_ADD_TO_ROOT_FN.IS_NO_WORLD,
},
{
type = MOD_DEV_TOOLS.OPTION.CHOICES,
on_add_to_root_fn = MOD_DEV_TOOLS.ON_ADD_TO_ROOT_FN.IS_NO_WORLD,
options = {
label = "State",
choices = {
{ name = "Default", value = MOD_AUTO_JOIN.STATE.DEFAULT },
{ name = "Default (Focus)", value = MOD_AUTO_JOIN.STATE.DEFAULT_FOCUS },
{ name = "Countdown", value = MOD_AUTO_JOIN.STATE.COUNTDOWN },
{ name = "Countdown (Focus)", value = MOD_AUTO_JOIN.STATE.COUNTDOWN_FOCUS },
{ name = "Connect", value = MOD_AUTO_JOIN.STATE.CONNECT },
{ name = "Connect (Focus)", value = MOD_AUTO_JOIN.STATE.CONNECT_FOCUS },
},
on_accept_fn = function()
self.autojoin:SetState(self.defaults.state)
end,
on_get_fn = function()
return self.autojoin:GetState()
end,
on_set_fn = function(_, _, value)
self.autojoin:SetState(value)
end,
},
},
{
type = MOD_DEV_TOOLS.OPTION.CHOICES,
on_add_to_root_fn = MOD_DEV_TOOLS.ON_ADD_TO_ROOT_FN.IS_NO_WORLD,
options = {
label = "Status",
choices = {
{ name = "Default", value = "nil" },
{
name = "Already Connected",
value = MOD_AUTO_JOIN.STATUS.ALREADY_CONNECTED,
},
{ name = "Banned", value = MOD_AUTO_JOIN.STATUS.BANNED },
{ name = "Full", value = MOD_AUTO_JOIN.STATUS.FULL },
{
name = "Invalid Password",
value = MOD_AUTO_JOIN.STATUS.INVALID_PASSWORD,
},
{ name = "Kicked", value = MOD_AUTO_JOIN.STATUS.KICKED },
{ name = "Not Responding", value = MOD_AUTO_JOIN.STATUS.NOT_RESPONDING },
{ name = "Unknown", value = MOD_AUTO_JOIN.STATUS.UNKNOWN },
},
on_get_fn = function()
local value = self.autojoin:GetStatus()
return value == nil and "nil" or value
end,
on_set_fn = function(_, _, value)
self.autojoin:SetStatus(value)
end,
},
},
{
type = MOD_DEV_TOOLS.OPTION.DIVIDER,
on_add_to_root_fn = MOD_DEV_TOOLS.ON_ADD_TO_ROOT_FN.IS_NO_WORLD,
},
{
type = MOD_DEV_TOOLS.OPTION.NUMERIC,
on_add_to_root_fn = MOD_DEV_TOOLS.ON_ADD_TO_ROOT_FN.IS_NO_WORLD,
options = {
label = "Default Refresh Seconds",
min = 1,
max = 120,
on_accept_fn = function()
local value = self.defaults.default_refresh_seconds
self.autojoin.default_refresh_seconds = value
end,
on_get_fn = function()
return self.autojoin.default_refresh_seconds
end,
on_set_fn = function(_, _, value)
self.autojoin.default_refresh_seconds = value
end,
},
},
NumericConfigOption(
self,
"Default Rejoin Initial Wait",
0,
15,
"rejoin_initial_wait",
MOD_DEV_TOOLS.ON_ADD_TO_ROOT_FN.IS_NO_WORLD
),
NumericConfigOption(
self,
"Default Waiting Time",
0,
99,
"waiting_time",
MOD_DEV_TOOLS.ON_ADD_TO_ROOT_FN.IS_NO_WORLD
),
{
type = MOD_DEV_TOOLS.OPTION.DIVIDER,
on_add_to_root_fn = MOD_DEV_TOOLS.ON_ADD_TO_ROOT_FN.IS_NO_WORLD,
},
{
type = MOD_DEV_TOOLS.OPTION.SUBMENU,
options = {
label = "Indicator", -- label in the menu will be: "Your submenu..."
on_add_to_root_fn = MOD_DEV_TOOLS.ON_ADD_TO_ROOT_FN.IS_NO_WORLD,
options = function()
return {
ToggleIndicatorVisibility(self, "Toggle Visibility"),
{ type = MOD_DEV_TOOLS.OPTION.DIVIDER },
NumericIndicatorConfigOption(
self,
"Padding",
0,
100,
1,
"indicator_padding",
"SetPadding"
),
{
type = MOD_DEV_TOOLS.OPTION.CHOICES,
options = {
label = "Position",
choices = {
{ name = "Top Left", value = 1 },
{ name = "Top Right", value = 2 },
{ name = "Bottom Right", value = 3 },
{ name = "Bottom Left", value = 4 },
},
on_accept_fn = function()
local v = self.autojoin.config_default.indicator_position
self.autojoin.config.indicator_position = v
local indicators = self.autojoin:GetIndicators()
for _, indicator in pairs(indicators) do
indicator:SetScreenPosition(
self.autojoin.config.indicator_position
)
end
end,
on_get_fn = function()
return self.autojoin.config.indicator_position
end,
on_set_fn = function(_, _, value)
self.autojoin.config.indicator_position = value
local indicators = self.autojoin:GetIndicators()
for _, indicator in pairs(indicators) do
indicator:SetScreenPosition(
self.autojoin.config.indicator_position
)
end
end,
},
},
NumericIndicatorConfigOption(
self,
"Scale",
0.5,
5,
0.1,
"indicator_scale",
"SetScreenScale"
),
}
end,
},
},
{ type = MOD_DEV_TOOLS.OPTION.DIVIDER },
{
type = MOD_DEV_TOOLS.OPTION.ACTION,
options = {
label = "Dump Last Join Server",
on_accept_fn = function()
dumptable(SDK.PersistentData
.Load()
.SetMode(SDK.PersistentData.DEFAULT)
.Get("last_join_server"))
end,
},
},
{
type = MOD_DEV_TOOLS.OPTION.ACTION,
options = {
label = "Dump Stored Data",
on_accept_fn = function()
dumptable(SDK.PersistentData
.Load()
.SetMode(SDK.PersistentData.DEFAULT)
.GetData())
end,
},
},
{ type = MOD_DEV_TOOLS.OPTION.DIVIDER },
{
type = MOD_DEV_TOOLS.OPTION.ACTION,
options = {
label = "Clear Stored Data",
on_accept_fn = function()
SDK.PersistentData
.Load()
.SetMode(SDK.PersistentData.DEFAULT)
.Set("last_join_server", nil)
.Save()
end,
},
},
},
})
end
--- Lifecycle
-- @section lifecycle
--- Constructor.
-- @function _ctor
-- @tparam AutoJoin autojoin
-- @usage local devtoolssubmenu = DevToolsSubmenu(autojoin)
local DevToolsSubmenu = Class(function(self, autojoin)
-- general
self.autojoin = autojoin
self.is_global_autojoin = false
-- defaults
self.defaults = {
default_refresh_seconds = self.autojoin.default_refresh_seconds,
is_fake_joining = self.autojoin.is_fake_joining,
state = self.autojoin.state,
}
-- api
if getmetatable(_G).__declared.DevToolsAPI then
_API = _G.DevToolsAPI
if _API and _API:GetAPIVersion() < 1 then
Add(self)
end
end
end)
return DevToolsSubmenu
|
--[[
YUITI : Löve2D Blank Template : Main
======================================================================
Main game file, manages Löve2D's callbacks and the game loop.
It's kinda monstrous, but you don't need to use everything, delete
unused stuff, please!
----------------------------------------------------------------------
@author Fabio Y. Goto <[email protected]>
@version 0.0.1
@copyright ©2017 Fabio Y. Goto
--]]
-- LIBRARIES AND ADDITIONAL MODULES
-- ======================================================================
-- Test library
require("test");
-- GLOBAL VARIABLES
-- ======================================================================
-- Simple time counter
time = 0;
-- BOOTSTRAPPING
-- ======================================================================
--[[
Called when the game's started, usually loads assets and resources
used in the game, variables and some settings (not the conf ones).
--]]
function love.load()
-- Was the project loaded?
print("Project Loaded");
-- Does the Test Library works?
test.healthcheck();
-- Can we access the Test Library variables?
print(test.vals);
end
-- GAME LOOP + WINDOW UPDATES
-- ======================================================================
--[[
Updates the game logic on every frame.
@param dt number
Delta time, in seconds, since this function was last called
--]]
function love.update(dt)
-- Update timer
time = time + 0.05;
-- Since I came from JS, I often used +=, but this won't work in
-- Lua, unless you're using PICO-8, which makes it possible.
end
--[[
Updates the game's canvas on every frame.
Call all drawing functions inside this one only.
--]]
function love.draw()
-- Draw the nice wave
test.nice_wave(time);
-- Draw FPS
test.fancy_fps();
end
--[[
Checks whether the game's window gained or lost focus, like when the
user clicks outside and then back again.
Useful for pausing whenever the window loses focus.
@param status boolean
Whether the window has, or not, focus
--]]
function love.focus(status)
if not status then
-- LOST FOCUS
else
-- GAINED FOCUS
end
end
--[[
Called whenever the window loses/receives mouse focus.
@param status boolean
Whether the window has, or not, the mouse focus
--]]
function love.mousefocus(status)
if not status then
-- LOST MOUSE FOCUS
else
-- GAINED MOUSE FOCUS
end
end
--[[
Triggered when the window is minimized/maximized by the user.
@param visible boolean
If the window is visible, or not
--]]
function love.visible(visible)
end
--[[
Triggered when the window is resized, either by dragging the corners
or by using `love.window.setMode`.
@param w number
New width, in pixels
@param h number
New height, in pixels
--]]
function love.resize(w, h)
end
--[[
Executes code when the user closes the window by clicking on the close
button.
Useful to save stuff before quitting.
--]]
function love.quit()
-- Just quit already!
print("So long, Cowboy!");
end
-- KEYBOARD + MOUSE + TOUCH INPUT MONITORING
-- ======================================================================
--[[
Triggered when the user entered text using the keyboard.
On Android/iOS, this is disabled by default, and can be enabled by
setting `love.keyboard.setTextInput`.
@param text string
A UTF-8 encoded text string
--]]
function love.textinput(text)
end
--[[
Triggered whenever a key was pressed on the keyboard.
@param key string
String containing the key that was just pressed
--]]
function love.keypressed(key)
end
--[[
Triggered whenever a key was released on the keyboard.
@param key string
String containing the key that was just released
--]]
function love.keyreleased(key)
-- Simply quit, if escape was released
if (key == "escape") then
love.event.quit();
end
end
--[[
Triggered whenever the mouse cursor moves within the game's window.
@param x number
Current X position of the cursor
@param y number
Current Y position of the cursor
@param dx number
Delta X, relative to the last time this function was called
@param dy number
Delta Y, relative to the last time this function was called
@param istouch boolean
If this action was triggered, or not, by using a touchscreen
--]]
function love.mousemoved(x, y, dx, dy, istouch)
end
--[[
Triggered when the user pressed a mouse button.
@param x number
Current X position of the cursor
@param y number
Current Y position of the cursor
@param button number
Number identifying which button was pressed
@param istouch boolean
If this action was triggered, or not, by using a touchscreen
--]]
function love.mousepressed(x, y, button, istouch)
end
--[[
Triggered when the user releases a mouse button.
@param x number
Current X position of the cursor
@param y number
Current Y position of the cursor
@param button number
Number identifying which button was pressed
@param istouch boolean
If this action was triggered, or not, by using a touchscreen
--]]
function love.mousereleased(x, y, button, istouch)
end
--[[
Called whenever the mouse's scroll wheel was moved, usually values are
either -1, 0 or 1.
@param x number
The amount of horizontal movement the wheel produced, negative
value means it's moving to the left, while a positive is right
@param y number
The amount of vertical movement the wheel produced, negative
value means it's moving downward, while a positive value means
upward movement
--]]
function love.wheelmoved(x, y)
end
--[[
Triggered whenever a touch press inside the touch screen moved.
@param id number
Touch point identifier, since each point should have an ID
@param x number
Current X position of the touch point
@param y number
Current Y position of the touch point
@param dx number
X-axis movement of the touch inside the window, in pixels
@param dy number
Y-axis movement of the touch inside the window, in pixels
@param pressure number
Amount of pressure being applied, since most touch screens
aren't pressure sensitive, will mostly be 1
--]]
function love.touchmoved(id, x, y, dx, dy, pressure)
end
--[[
Triggered when the screen is touched.
@param id number
Touch point identifier, since each point should have an ID
@param x number
Current X position of the touch point
@param y number
Current Y position of the touch point
@param dx number
X-axis movement of the touch inside the window, in this
function, it should always be zero
@param dy number
Y-axis movement of the touch inside the window, in this
function, it should always be zero
@param pressure number
Amount of pressure being applied, since most touch screens
aren't pressure sensitive, will mostly be 1
--]]
function love.touchpressed(id, x, y, dx, dy, pressure)
end
--[[
Triggered when the touch screen is released.
@param id number
Touch point identifier, since each point should have an ID
@param x number
Current X position of the touch point
@param y number
Current Y position of the touch point
@param dx number
X-axis movement of the touch inside the window, in pixels
@param dy number
Y-axis movement of the touch inside the window, in pixels
@param pressure number
Amount of pressure being applied, since most touch screens
aren't pressure sensitive, will mostly be 1
--]]
function love.touchreleased(id, x, y, dx, dy, pressures)
end
-- GAMEPAD + JOYSTICK INPUT MONITORING
-- ======================================================================
--[[
Called when a Joystick object's virtual gamepad axis is moved.
@param joystick Joystick
Joystick object
@param axis GamepadAxis
Virtual gamepad axis' name
@param value number
The new axis value
--]]
function love.gamepadaxis(joystick, axis, value)
end
--[[
Called when a Joystick object's virtual gamepad butotn is pressed.
@param joystick Joystick
Joystick object
@param button GamepadButton
Virtual gamepad button
--]]
function love.gamepadpressed(joystick, button)
end
--[[
Called when a Joystick object's virtual gamepad butotn is released.
@param joystick Joystick
Joystick object
@param button GamepadButton
Virtual gamepad button
--]]
function love.gamepadreleased(joystick, button)
end
--[[
Called when a Joystick is connected.
@param joystick Joystick
The connected Joystick object
--]]
function love.joystickadded(joystick)
end
--[[
Called when a Joystick is disconnected.
@param joystick Joystick
The disconnected Joystick object
--]]
function love.joystickremoved(joystick)
end
--[[
Called when one of the Joystick axis moves.
@param joystick Joystick
Joystick object
@param axis number
Joystick axis number
@param value number
Axis value
--]]
function love.joystickaxis(joystick, axis, value)
end
--[[
Called when the Joystick hat direction changes. On X360 controllers
this means the D-pad.
@param joystick Joystick
Joystick object
@param hat number
The hat number
@param direction JoystickHat
New hat direction
--]]
function love.joystickhat(joystick, hat, direction)
end
--[[
Called wheh a Joystick button is pressed.
@param joystick Joystick
Joystick object
@param button number
Button number
--]]
function love.joystickpressed(joystick, button)
end
--[[
Called wheh a Joystick button is released.
@param joystick Joystick
Joystick object
@param button number
Button number
--]]
function love.joystickreleased(joystick, button)
end
-- FILE + DIRECTORY DRAG AND DROP
-- ======================================================================
--[[
Triggered when the user drags and drops a file inside the window.
@param path string
Full, platform-independent, path to the directory, can be used as
argument to `love.filesystem.mount` to gain read access to this
folder using `love.filesystem`
--]]
function love.directroydropped(path)
end
--[[
Triggered when the user drags and drops a file inside the window.
@param file File
Unoneped file object, representing what was dropped
--]]
function love.filedropped(file)
end
|
belt = Instance.new("Part", game.Players.LocalPlayer.Character)
belt.FormFactor = "Custom"
belt.Size = Vector3.new(0.3,2.5,1.2)
belt.Name = "Belt"
belt.BrickColor = BrickColor.new("Really black")
belt:BreakJoints()
function Weld(a,b,c,d)
weld = Instance.new("Weld",a)
weld.Part0 = a
weld.Part1 = b
if c then
weld.C0 = c
end
if d then
weld.C1 = d
end
end
Weld(belt,belt.Parent.Torso,CFrame.Angles(0,0,math.rad(-45)))
|
local metric_major = monitoring.gauge("version_major", "monitoring major version")
local metric_minor = monitoring.gauge("version_minor", "monitoring minor version")
metric_major.set( monitoring.version_major )
metric_minor.set( monitoring.version_minor )
|
-- LuaTools需要PROJECT和VERSION这两个信息
PROJECT = "gpiodemo"
VERSION = "1.0.0"
-- sys库是标配
_G.sys = require("sys")
local NETLED = gpio.setup(19, 0, gpio.PULLUP) -- 输出模式
local G18 = gpio.setup(18, 0, gpio.PULLUP) -- 输出模式
local G7 = gpio.setup(7, function() -- 中断模式, 下降沿,需要将GPIO18和GPIO7连在一起
log.info("gpio7", "BOOT button release")
end, gpio.PULLUP,gpio.FALLING)
local G1 = gpio.setup(1, function() -- 中断模式, 下降沿
log.info("gpio1", "BOOT button release")
end, gpio.PULLUP,gpio.FALLING)
sys.taskInit(function()
while 1 do
-- 一闪一闪亮晶晶
NETLED(0)
G18(0)
log.info("gpio", "7", G7())
sys.wait(500)
NETLED(1)
G18(1)
sys.wait(500)
log.info("gpio", "7", G7())
end
end)
-- 用户代码已结束---------------------------------------------
-- 结尾总是这一句
sys.run()
-- sys.run()之后后面不要加任何语句!!!!!
|
require("xavante")
require("xavante.httpd")
require("wsapi.xavante")
require("wsapi.request")
require("xmlrpc")
--- XML-RPC WSAPI handler
-- @param wsapi_env WSAPI environment
function wsapi_handler(wsapi_env)
local headers = { ["Content-type"] = "text/xml" }
local req = wsapi.request.new(wsapi_env)
local method, arg_table = xmlrpc.srvDecode(req.POST.post_data)
local func = xmlrpc.dispatch(method)
local result = { pcall(func, unpack(arg_table or {})) }
local ok = result[1]
if not ok then
result = { code = 3, message = result[2] }
else
table.remove(result, 1)
if table.getn(result) == 1 then
result = result[1]
end
end
local r = xmlrpc.srvEncode(result, not ok)
headers["Content-length"] = tostring(#r)
local function xmlrpc_reply(wsapienv)
coroutine.yield(r)
end
return 200, headers, coroutine.wrap(xmlrpc_reply)
end
-- XML-RPC exported functions
xmlrpc_exports = {}
--- Get simple string.
-- @return simple string
function xmlrpc_exports.hello_world()
return "Hello World"
end
local rules = {{ match = ".", with = wsapi.xavante.makeHandler(wsapi_handler) }}
local config = { server = {host = "*", port = 12345}, defaultHost = { rules = rules} }
xmlrpc.srvMethods(xmlrpc_exports)
xavante.HTTP(config)
xavante.start()
|
return function()
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Packages = ReplicatedStorage.Packages
local Llama = require(Packages.Llama)
local None = Llama.None
it("should be a userdata", function()
expect(None).to.be.a("userdata")
end)
it("should have a nice string name", function()
local coerced = tostring(None)
expect(coerced:find("^userdata: ")).never.to.be.ok()
expect(coerced:find("None")).to.be.ok()
end)
end |
--[[
Author: Brian Lee Yung Rowe
An example of approximating a function with a neural network
--]]
require 'torch'
require 'nn'
dofile "train.lua"
--[[
The function we want to approximate
--]]
function z(x,y) return 2*x^2 - 3*y^2 + 1 end
--[[
The only requirement for the dataset is that it needs to be a Lua table
with method size() returning the number of elements in the table.
Each element will be a subtable with two elements: the input (a Tensor of
size 1 x input_size) and the target class (a Tensor of size 1 x 1).
http://mdtux89.github.io/2015/12/11/torch-tutorial.html
Example
makeTestSet(range(-4,4))
--]]
function makeTrainSet(a)
local dataset = {}
local i = 1
-- Generate each row of data
fn = function(x,y)
--print(string.format("x=%s, y=%s", x,y))
local zi = z(x,y)
local input = torch.Tensor({x,y})
local output = torch.Tensor({zi})
dataset[i] = {input, output}
i = i + 1
end
each(function(t) fn(t[1], t[2]) end, cartprod(a,a))
function dataset:size() return (i - 1) end
return dataset
end
print("Make train set")
trainset = makeTrainSet(range(-10,10, 0.05))
print("Build network")
-- Design your network architecture
model = nn.Sequential()
model:add(nn.Linear(2, 1))
print("Train network")
-- Choose which cost function you want to use
criterion = nn.AbsCriterion()
-- Choose your learning algorithm and set parameters
trainer = nn.StochasticGradient(model, criterion)
trainer:train(trainset)
print("Evaluate in-sample results")
result = evaluateModel(model, trainset, "result.csv")
|
PLUGIN.name = "Jobs"
PLUGIN.author = "Lechu2375"
Jobs = Jobs or {}
Jobs.Tasks = {}
Jobs.ActiveTasks = Jobs.ActiveTasks or {}
if(SERVER) then
function RegisterJob(JobTable)
Jobs.Tasks[JobTable.UniqueID] = JobTable
end
end
ix.util.Include("jobs/sv_trash.lua")
ix.util.Include("jobs/sv_mechanic.lua")
ix.util.Include("jobs/cl_mechanic.lua")
ix.command.Add("checkjobs", {
description = "ehe",
OnRun = function(self)
for k,v in pairs(Jobs.Tasks) do
if(v.CanActivate()) then
Jobs.ActiveTasks[v.UniqueID] = {}
v.GenerateTask()
end
end
end
})
if ( SERVER ) then
function PLUGIN:PlayerUse(ply,ent )
if(IsValid(ent.BrokenEffect)) then
return false
end
if(ent.IsTrash and ((ply.TrashNotifyDelay or 1) <CurTime())) then //trash job handle
local class = ply:GetCharacter():GetClass()
if!(class==CLASS_JANITOR)then
ply:NotifyLocalized("notYourJob")
ply.TrashNotifyDelay = CurTime()+1
return false
end
if(!ply.PickingUpTrash) then
ply:SetAction(L("pickingUp",ply), 2) // for displaying the progress bar
ply.PickingUpTrash = true
ply:DoStaredAction(ent, function()
ent:Remove()
Jobs.Tasks.Janitor.Reward(ply)
ply.PickingUpTrash = false
end,2,function() ply.PickingUpTrash = false end,100)
end
end
end
function PLUGIN:AcceptInput(ent,input,activator,caller,value )
if((input=="Open" or input=="Close") and IsValid(ent.BrokenEffect)) then
local random = math.random(0,3)
if(random==3) then
ent:Fire("unlock") //hmm
ent:Fire("open")
timer.Simple(0.2, function()
ent:Fire("close") //:trollface:
end)
else
return true
end
end
if((input=="Toggle") and IsValid(ent.BrokenEffect)) then //some doors open by EntFire Toggle instead of OPEN and CLOSE
return true
end
end
end |
local wibox = require('wibox')
local gears = require('gears')
local beautiful = require('beautiful')
local mat_list_item = require('widget.material.list-item')
local mat_list_sep = require('widget.material.list-item-separator')
local dpi = require('beautiful').xresources.apply_dpi
local volSlider = require('widget.volume.volume-slider')
local brightnessSlider = require('widget.brightness.brightness-slider')
return wibox.widget {
layout = wibox.layout.fixed.vertical,
{
layout = wibox.layout.fixed.vertical,
{
{
volSlider,
bg = beautiful.bg_modal,
shape = function(cr, width, height)
gears.shape.partially_rounded_rect(cr, width, height, true, true, false, false, beautiful.modal_radius) end,
widget = wibox.container.background
},
widget = mat_list_item
}
},
layout = wibox.layout.fixed.vertical,
{
{
brightnessSlider,
bg = beautiful.bg_modal,
shape = function(cr, width, height)
gears.shape.partially_rounded_rect(cr, width, height, false, false, true, true, beautiful.modal_radius) end,
widget = wibox.container.background
},
widget = mat_list_item,
}
}
|
include("terms")
style =
{["off_color"] = "fff",
["on_color"] = "fff",
["line_color"] = "000",
["line_width"] = "1"};
diff_style =
{["off_color"] = "fff",
["on_color"] = "ff0",
["line_color"] = "000",
["line_width"] = "2"};
check_style =
{["off_color"] = "fff",
["on_color"] = "6f6",
["line_color"] = "fff",
["line_width"] = "1"};
choice = math.random(4)
place = array_position[choice]
out = math.random(2)
figure = part[out]
include("shapes")
mycanvas = function()
if (out == 1) then
results = ""
solutions = ""
for i = 1,4 do
if (i > 1) then
results = results .. "&& "
solutions = solutions .. "; "
end
results = results .. "result[" .. tostring(i-1) .. "] == "
solutions = solutions .. "solution[" .. tostring(i-1) .. "] = "
if (i == choice) then
results = results .. "1 "
solutions = solutions .. "1 "
else
results = results .. "0 "
solutions = solutions .. "0 "
end
end
results = results .. "&& result[4] == 0 && result[5] == 0 && result[6] == 0 && result[7] == 0 && result[8] == 0"
solutions = solutions .. "; solution[4] = 0; solution[5] = 0; solution[6] = 0; solution[7] = 0; solution[8] = 0;"
else
results = "result[0] == 0 && result[1] == 0 && result[2] == 0 && result[3] == 0 "
solutions = "solution[0] = 0; solution[1] = 0; solution[2] = 0; solution[3] = 0; "
for i = 4,7 do
results = results .. "&& result[" .. tostring(i) .. "] == "
solutions = solutions .. "; solution[" .. tostring(i) .. "] = "
if (i == choice + 3) then
results = results .. "1 "
solutions = solutions .. "1 "
else
results = results .. "0 "
solutions = solutions .. "0 "
end
if (i == 7 and choice == 4) then
results = results .. "&& " .. "result[8] == " .. "1"
solutions = solutions .. "; " .. "solution[8] = " .. "1"
end
end
end
-- Example of solution variable representing one valid solution to the question.
-- solution[i] corrsponds to the same object as result[i]
-- solution[i] == true means the object is selected, otherwise false
-- given values of solution should (obviously) satisfy the result condition
-- In this example, the following simpler version would also work:
-- lib.start_canvas(300, 250, "center", results)
-- but there are cases where deriving a solution from results is non-trivial
lib.start_canvas(300, 250, "center", results, solutions)
w = 100
ow = 40
for i = 1,3 do
lib.add_line(ow, ow+(i-1)*w, 2*w, 0, style, false, false)
lib.add_line(ow+(i-1)*w, ow, 0, 2*w, style, false, false)
end
lib.add_rectangle(ow+5, ow+5, w-10, w-10, check_style, false, true)
lib.add_rectangle(ow+5, ow+5+w, w-10, w-10, check_style, false, true)
lib.add_rectangle(ow+w+5, ow+5+w, w-10, w-10, check_style, false, true)
lib.add_rectangle(ow+w+5, ow+5, w-10, w-10, check_style, false, true)
scale = 1.5
lib.add_triangle (85, 80, 50, 50, diff_style, false, true)
diamond(lib, 65, 190, scale, diff_style, false, true)
lib.add_ellipse(190, 190, 35, 20, diff_style, false, true)
heart(lib, 190, 120, scale, diff_style, false, true)
lib.end_canvas()
end
|
CLASS.name = "Elite Metropolice"
CLASS.faction = FACTION_OTA
CLASS.isDefault = false
CLASS_EMP = CLASS.index |
local M = {}
function M.config()
local cmp_status_ok, cmp = pcall(require, "cmp")
if not cmp_status_ok then
return
end
local snip_status_ok, luasnip = pcall(require, "luasnip")
if not snip_status_ok then
return
end
local check_backspace = function()
local col = vim.fn.col "." - 1
return col == 0 or vim.fn.getline("."):sub(col, col):match "%s"
end
local kind_icons = {
Text = "",
Method = "",
Function = "",
Constructor = "",
Field = "ﰠ",
Variable = "",
Class = "",
Interface = "",
Module = "",
Property = "",
Unit = "",
Value = "",
Enum = "",
Keyword = "",
Snippet = "",
Color = "",
File = "",
Reference = "",
Folder = "",
EnumMember = "",
Constant = "",
Struct = "פּ",
Event = "",
Operator = "",
TypeParameter = "",
}
cmp.setup {
formatting = {
fields = { "kind", "abbr", "menu" },
format = function(entry, vim_item)
vim_item.kind = string.format("%s", kind_icons[vim_item.kind])
return vim_item
end,
},
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body)
end,
},
duplicates = {
nvim_lsp = 1,
luasnip = 1,
cmp_tabnine = 1,
buffer = 1,
path = 1,
},
confirm_opts = {
behavior = cmp.ConfirmBehavior.Replace,
select = false,
},
window = {
documentation = {
border = { "╭", "─", "╮", "│", "╯", "─", "╰", "│" },
},
},
experimental = {
ghost_text = false,
native_menu = false,
},
completion = {
keyword_length = 1,
},
sources = {
{ name = "nvim_lsp" },
{ name = "luasnip" },
{ name = "buffer" },
{ name = "path" },
},
mapping = {
["<C-k>"] = cmp.mapping.select_prev_item(),
["<C-j>"] = cmp.mapping.select_next_item(),
["<C-d>"] = cmp.mapping(cmp.mapping.scroll_docs(-1), { "i", "c" }),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(1), { "i", "c" }),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
["<C-y>"] = cmp.config.disable,
["<C-e>"] = cmp.mapping {
i = cmp.mapping.abort(),
c = cmp.mapping.close(),
},
["<CR>"] = cmp.mapping.confirm { select = true },
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expandable() then
luasnip.expand()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif check_backspace() then
fallback()
else
fallback()
end
end, {
"i",
"s",
}),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, {
"i",
"s",
}),
},
}
end
return M
|
local description = [=[
Usage: lua bin2c.lua -c -o [optput file] -n [name of array] -x [? or value] [input filename]
switches:
c - compile script, applicable only to lua files
o - select output file, defaults to [input filename] + '.h'
n - name of created array, defaults to [input filename] without path
x - xor file data, use ? to generate random mask
]=]
function GetFileName(url)
return url:match("^.+[/\\](.+)$")
end
function GetFileExtension(url)
return url:match("^.+(%..+)$")
end
function ParseArgs(args)
local cfg = { }
local switches = {
["-o"] = {
c = 1,
h = function(v)
cfg.output = v
end,
},
["-n"] = {
c = 1,
h = function(v)
cfg.name = v
end,
},
["-c"] = {
c = 0,
h = function(v)
cfg.compile = true
end,
},
["-x"] = {
c = 0,
h = function(v)
if v == "?" then
math.randomseed( os.time() )
cfg.xor = math.random(255)
else
cfg.xor = tonumber(v)
end
end,
}
}
local opcode
for _,v in ipairs(arg) do
if opcode == nil then
local sw = switches[v]
if sw then
assert(opcode == nil)
if sw.c > 0 then
opcode = v
end
else
assert(cfg.filename == nil)
cfg.filename = v
end
else
local h = switches[opcode]
assert(h)
h.h(v)
opcode = nil
end
end
assert(cfg.filename)
if not cfg.output then
cfg.output = cfg.filename .. ".h"
end
if not cfg.name then
cfg.name = GetFileName(cfg.filename):gsub(".", "_")
end
cfg.islua = GetFileExtension(cfg.filename) == ".lua"
return cfg
end
function BitXOR(a,b)--Bitwise xor
local p,c=1,0
while a>0 and b>0 do
local ra,rb=a%2,b%2
if ra~=rb then c=c+p end
a,b,p=(a-ra)/2,(b-rb)/2,p*2
end
if a<b then a=b end
while a>0 do
local ra=a%2
if ra>0 then c=c+p end
a,p=(a-ra)/2,p*2
end
return c
end
function write(cfg, data)
local header = [=[
//code automatically generated by bin2c -- DO NOT EDIT
]=]
local footer = [=[
]=]
local out = assert(io.open(cfg.output, "wb"))
out:write(header);
if cfg.xor then
out:write(string.format("static constexpr uint8_t %s_xor = 0x%02x;\n", cfg.name, cfg.xor))
end
out:write(string.format("static constexpr uint32_t %s_size = %d;\n", cfg.name, data:len()))
out:write(string.format("static constexpr unsigned char %s[%d] = {\n ", cfg.name, data:len()))
for idx=1,data:len() do
local byte = data:byte(idx)
if cfg.xor then
byte = BitXOR(byte, cfg.xor)
end
out:write(string.format("0x%02x, ", byte))
if (idx % 16) == 0 then
out:write("\n ")
end
end
out:write("\n};\n")
out:write(footer);
out:close()
end
function LoadFile(cfg)
return assert(io.open(cfg.filename,"rb")):read"*a"
end
function LoadLua(cfg)
local bin = assert(loadfile(cfg.filename))
if cfg.compile then
return string.dump(bin)
else
return LoadFile(cfg)
end
end
local succ, cfg = pcall(ParseArgs,arg)
if not succ then
print(description)
print(cfg)
os.exit(1)
end
local content
if cfg.islua then
content = LoadLua(cfg)
else
content = LoadFile(cfg)
end
write(cfg, content)
|
--Fearful Earthbound (Fix)
function c700009.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_ATTACK,TIMING_END_PHASE+TIMING_MAIN_END)
c:RegisterEffect(e1)
--atk
--local e01=Effect.CreateEffect(c)
--e01:SetType(EFFECT_TYPE_FIELD)
--e01:SetRange(LOCATION_SZONE)
--e01:SetCode(EFFECT_UPDATE_ATTACK)
--e01:SetTargetRange(0,LOCATION_MZONE)
--e01:SetTarget(aux.TargetBoolFunction(Card.IsRace,RACE_ZOMBIE))
--e01:SetCondition(c62188962.atkcon2)
--e01:SetValue(-500)
c:RegisterEffect(e01)
--atk damage and atk reduce
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(700009,0))
e2:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DAMAGE)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_ATTACK_ANNOUNCE+EFFECT_UPDATE_ATTACK)
e2:SetTargetRange(0,LOCATION_MZONE)
e2:SetRange(LOCATION_SZONE)
e2:SetCondition(c700009.atkcon)
e2:SetTarget(c700009.target)
e2:SetOperation(c700009.operation)
c:RegisterEffect(e2)
--sent to hand for GY
local e02=Effect.CreateEffect(c)
e02:SetCategory(CATEGORY_TOHAND)
e02:SetType(EFFECT_TYPE_IGNITION)
e02:SetRange(LOCATION_GRAVE)
e02:SetProperty(EFFECT_FLAG_CARD_TARGET)
--e2:SetCode(EVENT_FREE_CHAIN)
--e02:SetCondition(aux.exccon)
e02:SetCondition(c700009.cond)
e02:SetCost(c700009.cost)
e02:SetTarget(c700009.thtg)
e02:SetOperation(c700009.thop)
c:RegisterEffect(e02)
end
function c700008.cond(e,tp,eg,ep,ev,re,r,rp)
return tp==Duel.GetTurnPlayer() and Duel.GetFieldGroupCount(tp,LOCATION_GRAVE,0)>0
and Duel.IsExistingTarget(c700009.filter,tp,LOCATION_GRAVE,0,1,e:GetHandler())
end
function c700009.filter(c)
return c:IsSetCard(0x235) and c:IsAbleToHand()
end
function c700009.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c700009.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c700009.filter,tp,LOCATION_GRAVE,0,1,e:GetHandler()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c700009.filter,tp,LOCATION_GRAVE,0,1,1,e:GetHandler())
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c700009.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tc)
end
end
function c700009.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
--function c62188962.atkcon2(e)
-- return Duel.GetCurrentPhase()==PHASE_DAMAGE_CAL
--end
function c700009.atkcon(e,tp,eg,ep,ev,re,r,rp)
return tp~=Duel.GetTurnPlayer() and Duel.GetCurrentPhase()==PHASE_DAMAGE_CAL
end
function c700009.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,500)
end
function c700009.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Damage(1-tp,500,REASON_EFFECT)
end
end
|
-- видеоскрипт для сайтов http://www.hdkinoteatr.com https://kinogo.cc/ (18/03/21)
-- необходимы скрипты: collaps (autor - nexterr)
-- открывает подобные ссылки:
-- http://www.hdkinoteatr.com/drama/28856-vse_ispravit.html
-- https://kinogo.cc/75043-poslednee-voskresenie-last-station-kinogo-2009.html
if m_simpleTV.Control.ChangeAdress ~= 'No' then return end
local inAdr = m_simpleTV.Control.CurrentAdress
if not inAdr then return end
if not inAdr:match('^https?://www%.hdkinoteatr%.com')
and not inAdr:match('^https?://kinogo%.cc')
then return end
m_simpleTV.Control.ChangeAdress = 'Yes'
m_simpleTV.Control.CurrentAdress = ''
local session = m_simpleTV.Http.New('Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.2785.143 Safari/537.36')
if not session then return end
m_simpleTV.Http.SetTimeout(session, 8000)
local function getConfigVal(key)
return m_simpleTV.Config.GetValue(key,"LiteConf.ini")
end
local function setConfigVal(key,val)
m_simpleTV.Config.SetValue(key,val,"LiteConf.ini")
end
local rc, answer = m_simpleTV.Http.Request(session, {url = inAdr})
m_simpleTV.Http.Close(session)
if rc ~= 200 then
m_simpleTV.OSD.ShowMessage_UTF8('hdkinoteatr ошибка[1]-' .. rc, 255, 5)
return
end
local title = answer:match('<font color="yellow">(.-)</font>') or answer:match('<title>(.-)</title>') or 'hdkinoteatr'
title = title:gsub('%).-$', ')')
local poster = answer:match('<meta property="og:image" content="(.-)"')
m_simpleTV.Control.CurrentTitle_UTF8 = title:gsub('/.+', ''):gsub('Смотреть ', '')
local background = answer:match('"url": "(.-)"') or poster
if m_simpleTV.Control.MainMode == 0 then
m_simpleTV.Interface.SetBackground({BackColor = 0, PictFileName = background, TypeBackColor = 0, UseLogo = 3, Once = 1})
m_simpleTV.Control.ChangeChannelLogo(poster, m_simpleTV.Control.ChannelID, 'CHANGE_IF_NOT_EQUAL')
m_simpleTV.Control.ChangeChannelName(title, m_simpleTV.Control.ChannelID, false)
end
local retAdr
local t,i = {},1
for w in answer:gmatch('<iframe src=.-</iframe>') do
adr = w:match('<iframe src=(.-) ')
if not adr or adr:match('/trailer/') or adr:match('token=') then break end
t[i] = {}
t[i].Address = adr:gsub('"',''):gsub('^//', 'http://'):gsub('/iframe%?.+', '/iframe'):gsub('vb17120ayeshajenkins','vb17121coramclean'):gsub('%?host=kinogo%.cc.-$','')
if adr:match('/embed/') then t[i].Name = 'Collaps' else t[i].Name = 'HDVB' end
i=i+1
end
local hash, res = {}, {}
for i = 1, #t do
t[i].Address = tostring(t[i].Address)
if not hash[t[i].Address] then
res[#res + 1] = t[i]
hash[t[i].Address] = true
end
end
for i = 1, #res do
res[i].Id = i
end
if #res and #res > 1 then
local ret, id = m_simpleTV.OSD.ShowSelect_UTF8('🎞 ' .. title, 0, res, 8000, 1 + 2)
id = id or 1
retAdr = res[id].Address
else
retAdr = res[1].Address
end
if not retAdr then
m_simpleTV.OSD.ShowMessage_UTF8('hdkinoteatr ошибка[2]', 255, 5)
return
end
if inAdr:match('kinogo%.cc') then
setConfigVal('info/kinogo',inAdr)
end
m_simpleTV.Control.ChangeAdress = 'No'
if inAdr:match('kinogo%.cc') then
m_simpleTV.Control.CurrentAdress = retAdr .. '&kinogo=' .. inAdr
else
m_simpleTV.Control.CurrentAdress = retAdr
end
dofile(m_simpleTV.MainScriptDir .. "user\\video\\video.lua")
-- debug_in_file(retAdr .. '\n') |
local cgm = gg.class.cgm
---功能: 安全停服
---@usage
---用法: stop
function cgm:stop(args)
local reason = args[1] or "gm"
game.stop(reason)
end
function cgm:saveall(args)
game.saveall()
end
---功能: 将某玩家踢下线
---@usage
---用法: kick 玩家ID [玩家ID]
function cgm:kick(args)
local isok,args = gg.checkargs(args,"int","*")
if not isok then
return self:say("用法: kick pid1 pid2 ...")
end
for i,v in ipairs(args) do
local pid = tonumber(v)
gg.playermgr:kick(pid,"gm")
end
end
---功能: 将所有玩家踢下线
---@usage
---用法: kickall
function cgm:kickall(args)
gg.playermgr:kickall("gm")
end
---功能: 执行一段lua脚本
---@usage
---用法: exec lua脚本
function cgm:exec(args)
local cmdline = table.concat(args," ")
local chunk = load(cmdline,"=(load)","bt")
return chunk()
end
cgm.runcmd = cgm.exec
---功能: 执行一个文件
---@usage
---用法: dofile lua文件 ...
---举例: dofile /tmp/run.lua
function cgm:dofile(args)
local isok,args = gg.checkargs(args,"string","*")
if not isok then
return self:say("用法: dofile lua文件")
end
local filename = args[1]
-- loadfile need execute skynet.cache.clear to reload
--local chunk = loadfile(filename,"bt")
local fd = io.open(filename,"rb")
local script = fd:read("*all")
fd:close()
return gg.eval(script,nil,table.unpack(args,2))
end
---功能: 热更新某模块
---@usage
---用法: hotfix 模块名 ...
function cgm:hotfix(args)
local hasCfg = false
local fails = {}
for i,path in ipairs(args) do
local isok,errmsg = gg.hotfix(path)
if not isok then
table.insert(fails,{path=path,errmsg=errmsg})
elseif string.find(path,"app.cfg.") then
hasCfg = true
end
end
if next(fails) then
return self:say("热更失败:\n" .. table.dump(fails))
end
if hasCfg then
gg.hotfix("app.cfg.init")
end
end
cgm.reload = cgm.hotfix
---功能: 设置/获取日志等级
---@usage
---用法: loglevel [日志等级]
---举例:
---loglevel <=> 查看日志等级
---loglevel debug/trace/info/warn/error/fatal <=> 设置对应日志等级
function cgm:loglevel(args)
local loglevel = args[1]
if not loglevel then
local loglevel,name = logger.check_loglevel(logger.loglevel)
return self:say(name)
else
local ok,loglevel,name = pcall(logger.check_loglevel,loglevel)
if not ok then
local errmsg = loglevel
return self:say(errmsg)
end
logger.setloglevel(loglevel)
return name
end
end
---功能: 设置/获取日期
---@usage
---用法: date [日期]
---举例: date <=> 获取当前日期
---举例: date 2019/11/28 10:10:10 <=> 将时间设置成2019/11/28 10:10:10
function cgm:date(args)
local date
if #args > 0 then
if not skynet.getenv("allow_modify_date") then
return self:say("本服务器不允许修改时间")
end
date = table.concat(args," ")
if not pcall(string.totime,date) then
return self:say(string.format("非法日期格式:%s",date))
end
local cmd = string.format("date -s '%s'",date)
local isok,errmsg,errno = os.execute(cmd)
if not isok then
return self:say(string.format("修改时间失败,errmsg=%s,errno=%s",errmsg,errno))
else
date = os.date("%Y/%m/%d %H:%M:%S")
end
else
date = os.date("%Y/%m/%d %H:%M:%S")
end
self:say(string.format("当前日期:%s",date))
self:say("恢复当前时间可用指令ntpdate")
return date
end
---功能: 恢复当前时间
---@usage
---用法: ntpdate
---举例: ntpdate <=> 校正服务器时间,恢复为当前时区自然时间
function cgm:ntpdate(args)
if not skynet.getenv("allow_modify_date") then
return self:say("本服务器不允许修改时间")
end
local cmd = string.format("/usr/sbin/ntpdate -u cn.ntp.org.cn")
self:say("系统时间恢复中...")
local isok,errmsg,errno = os.execute(cmd)
if isok then
local date = os.date("%Y/%m/%d %H:%M:%S")
return self:say(string.format("当前日期:%s",date))
else
return self:say(string.format("恢复时间失败,errmsg=%s,errno=%s",errmsg,errno))
end
end
function __hotfix(module)
gg.hotfix("app.game.gm.gm")
end
return cgm
|
local Circle = Component.create("Circle")
function Circle:initialize(radius)
self.radius = radius
end
|
ulx.common_kick_reasons = {}
function ulx.populateKickReasons( reasons )
table.Empty( ulx.common_kick_reasons )
table.Merge( ulx.common_kick_reasons, reasons )
end
ulx.maps = {}
function ulx.populateClMaps( maps )
table.Empty( ulx.maps )
table.Merge( ulx.maps, maps )
end
ulx.gamemodes = {}
function ulx.populateClGamemodes( gamemodes )
table.Empty( ulx.gamemodes )
table.Merge( ulx.gamemodes, gamemodes )
end
ulx.votemaps = {}
function ulx.populateClVotemaps( votemaps )
table.Empty( ulx.votemaps )
table.Merge( ulx.votemaps, votemaps )
end
function ulx.soundComplete( ply, args )
local targs = string.Trim( args )
local soundList = {}
local relpath = targs:GetPathFromFilename()
local sounds = file.Find( "sound/" .. relpath .. "*", "GAME" )
for _, sound in ipairs( sounds ) do
if targs:len() == 0 or (relpath .. sound):sub( 1, targs:len() ) == targs then
table.insert( soundList, relpath .. sound )
end
end
return soundList
end
function ulx.blindUser( bool, amt )
if bool then
local function blind()
draw.RoundedBox( 0, 0, 0, ScrW(), ScrH(), Color( 255, 255, 255, amt ) )
end
hook.Add( "HUDPaint", "ulx_blind", blind )
else
hook.Remove( "HUDPaint", "ulx_blind" )
end
end
local function rcvBlind( um )
local bool = um:ReadBool()
local amt = um:ReadShort()
ulx.blindUser( bool, amt )
end
usermessage.Hook( "ulx_blind", rcvBlind )
function ulx.gagUser( user_to_gag, should_gag )
if should_gag then
if user_to_gag.ulx_was_gagged == nil then user_to_gag.ulx_was_gagged = user_to_gag:IsMuted() end
if user_to_gag:IsMuted() then return end
user_to_gag:SetMuted( true )
else
local was_gagged = user_to_gag.ulx_was_gagged
user_to_gag.ulx_was_gagged = nil
if not user_to_gag:IsMuted() or was_gagged then return end
user_to_gag:SetMuted( true ) -- Toggle
end
end
local function rcvGag( um )
local user_to_gag = um:ReadEntity()
local gagged = um:ReadBool()
ulx.gagUser( user_to_gag, gagged )
end
usermessage.Hook( "ulx_gag", rcvGag )
local curVote
local function optionsDraw()
if not curVote then return end
local title = curVote.title
local options = curVote.options
local endtime = curVote.endtime
if CurTime() > endtime then return end -- Expired
surface.SetFont( "Default" )
local w, h = surface.GetTextSize( title )
w = math.max( 200, w )
local totalh = h * 12 + 20
draw.RoundedBox( 8, 10, ScrH()*0.4 - 10, w + 20, totalh, Color( 111, 124, 138, 200 ) )
optiontxt = ""
for i=1, 10 do
if options[ i ] and options[ i ] ~= "" then
optiontxt = optiontxt .. math.modf( i, 10 ) .. ". " .. options[ i ]
end
optiontxt = optiontxt .. "\n"
end
draw.DrawText( title .. "\n\n" .. optiontxt, "Default", 20, ScrH()*0.4, Color( 255, 255, 255, 255 ), TEXT_ALIGN_LEFT )
end
local function rcvVote( um )
local title = um:ReadString()
local timeout = um:ReadShort()
local options = ULib.umsgRcv( um )
local function callback( id )
if id == 0 then id = 10 end
if not options[ id ] then
return -- Returning nil will keep our hook
end
RunConsoleCommand( "ulx_vote", id )
curVote = nil
return true -- Let it know we're done here
end
LocalPlayer():AddPlayerOption( title, timeout, callback, optionsDraw )
curVote = { title=title, options=options, endtime=CurTime()+timeout }
end
usermessage.Hook( "ulx_vote", rcvVote )
function ulx.getVersion() -- This exists on the server as well, so feel free to use it!
if ulx.release then
version = string.format( "%.02f", ulx.version )
elseif ulx.revision > 0 then -- SVN version?
version = string.format( "<SVN> revision %i", ulx.revision )
else
version = string.format( "<SVN> unknown revision" )
end
return version, ulx.version, ulx.revision
end
function ulx.addToMenu( menuid, label, data ) -- TODO, remove
Msg( "Warning: ulx.addToMenu was called, which is being phased out!\n" )
end
-- Any language stuff for ULX should go here...
language.Add( "Undone_ulx_ent", "Undone ulx ent command" )
|
return {
{
id = 'dummy1',
foo = 123,
bar = 456,
},
{
id = 'dummy2',
foo = 789,
bar = 111,
}
}
|
---
-- @author wesen
-- @copyright 2020 wesen <[email protected]>
-- @release 0.1
-- @license MIT
--
-- Attempt to parse AssaultCube cgz header data
-- luarocks:
--
-- lua-struct
-- lzlib
-- bitop-lua
local struct = require "struct"
local zlib = require "zlib"
local bit = require "bit"
--[[
struct header // map file format header
{
char head[4]; // "CUBE"
int version; // any >8bit quantity is little endian
int headersize; // sizeof(header)
int sfactor; // in bits
int numents;
char maptitle[128];
uchar texlists[3][256];
int waterlevel;
uchar watercolor[4];
int maprevision;
int ambient;
int reserved[12];
//char mediareq[128]; // version 7 and 8 only.
};
--]]
--local ezlib = require 'ezlib'
--local cgzFile = gzip.open("3-min-gema-1.cgz", "rb")
local charSize = 1
local ucharSize = 1
local integerSize = 4
local headerSize = 19 * integerSize + (4 + 128) * charSize + (3 * 256 + 4) * ucharSize
local numberOfBytesToRead = 4-- headerSize - 16 * integerSize
local numberOfReadBytes = 0
--[[
local cgzContent = ""
local nextLine
repeat
nextLine = cgzFile:read()
if (nextLine) then
cgzContent = cgzContent .. nextLine
end
until (not nextLine)
--]]
--[[
for _, line in gzip.lines("3-min-gema-1.cgz") do
print(line)
end
--]]
--[[
local cgzLine
local cgzContent = ""
repeat
cgzLine = cgzFile:read()
if (cgzLine) then
cgzContent = cgzContent .. cgzLine
end
until (not cgzLine)
--]]
local cgzFile = io.open("gibbed-gema12.cgz", "rb")
--local cgzFile = io.open("3-min-gema-1.cgz", "rb")
--local cgzFile = io.open("verwesen-gema-1.cgz", "rb")
local stream = zlib.inflate(cgzFile)
print(stream)
local cgzContent = ""
for line in stream:lines() do
cgzContent = cgzContent .. line
end
print(cgzContent)
local header = cgzContent:sub(1, 923)
print(#header)
local structFormat = ">c4<iiiic128c256c256c256ic4iii12"
--.. string.rep("B", 256 * 3)
local structContent = { struct.unpack(structFormat, cgzContent) }
for k, v in pairs(structContent) do
print(k, v)
end
print("head: " .. structContent[1])
print("version: " .. structContent[2])
print("headersize: " .. structContent[3])
print("sfactor: " .. structContent[4])
print("numents: " .. structContent[5])
print("maptitle: " .. structContent[6])
local firstTexlist = ""
local secondTexlist = ""
local thirdTexlist = ""
--[[
for i = 7, 262, 1 do
firstTexlist = firstTexlist .. " " .. string.char(structContent[i])
end
for i = 263, 518, 1 do
secondTexlist = secondTexlist .. " " .. string.char(structContent[i])
end
for i = 519, 774, 1 do
thirdTexlist = thirdTexlist .. " " .. string.char(structContent[i])
end
--]]
print("texlists[0]: " .. structContent[7])
print("texlists[1]: " .. structContent[8])
print("texlists[2]: " .. structContent[9])
print("waterlevel: " .. structContent[10])
print("watercolor: " .. structContent[11])
print("maprevision: " .. structContent[12])
print("ambient: " .. structContent[13])
print("reserved: " .. structContent[14])
for k, v in pairs(structContent) do
--print(k, v)
end
--print(cgzContent)
--print(stream:read("*a"))
--print(#cgzContent)
--print(cgzContent)
--print(stream(cgzContent))
--print(stream())
--print(stream())
--print(stream())
--print(stream())
--print(stream())
--print(stream())
--print(stream())
--print(stream())
--print(stream())
--print(cgzContent)
--print(stream)
--[[
local nextCharacter, nextByte
repeat
nextCharacter = cgzFile:read(1)
if (nextCharacter) then
nextByte = cgzFile:read(1)
nextByteThing = nextByteThing .. nextByte
nextByte = string.byte(nextByte)
print(nextByte)
print(string.char(nextByte))
-- string.char
end
numberOfReadBytes = numberOfReadBytes + 1
until (numberOfReadBytes == numberOfBytesToRead)
--]]
--[[
for byte in string.gfind(nextByteThing, ".") do
print(string.char(string.byte(byte)))
end
print(nextByteThing)
--]]
--[[
print()
print(string.rep("-", 100))
local nextLine
repeat
nextLine = cgzFile:read()
if (nextLine) then
print(nextLine)
end
until (not nextLine)
--]]
--print("NONONONOO: " .. numberOfBytesToRead)
--[[
bool load_world(char *mname) // still supports all map formats that have existed since the earliest cube betas!
{
advancemaprevision = 1;
setnames(mname);
maploaded = getfilesize(ocgzname);
if(maploaded > 0)
{
copystring(cgzname, ocgzname);
copystring(mcfname, omcfname);
}
else maploaded = getfilesize(cgzname);
if(!validmapname(mapname))
{
conoutf("\f3Invalid map name. It must only contain letters, digits, '-', '_' and be less than %d characters long", MAXMAPNAMELEN);
return false;
}
stream *f = opengzfile(cgzname, "rb");
if(!f) { conoutf("\f3could not read map %s", cgzname); return false; }
header tmp;
memset(&tmp, 0, sizeof(header));
if(f->read(&tmp, sizeof(header)-sizeof(int)*16)!=sizeof(header)-sizeof(int)*16) { conoutf("\f3while reading map: header malformatted"); delete f; return false; }
lilswap(&tmp.version, 4);
if(strncmp(tmp.head, "CUBE", 4)!=0 && strncmp(tmp.head, "ACMP",4)!=0) { conoutf("\f3while reading map: header malformatted"); delete f; return false; }
if(tmp.version>MAPVERSION) { conoutf("\f3this map requires a newer version of AssaultCube"); delete f; return false; }
if(tmp.sfactor<SMALLEST_FACTOR || tmp.sfactor>LARGEST_FACTOR || tmp.numents > MAXENTITIES) { conoutf("\f3illegal map size"); delete f; return false; }
if(tmp.version>=4 && f->read(&tmp.waterlevel, sizeof(int)*16)!=sizeof(int)*16) { conoutf("\f3while reading map: header malformatted"); delete f; return false; }
if((tmp.version==7 || tmp.version==8) && !f->seek(sizeof(char)*128, SEEK_CUR)) { conoutf("\f3while reading map: header malformatted"); delete f; return false; }
hdr = tmp;
loadingscreen("%s", hdr.maptitle);
resetmap();
if(hdr.version>=4)
{
lilswap(&hdr.waterlevel, 1);
if(!hdr.watercolor[3]) setwatercolor();
lilswap(&hdr.maprevision, 2);
curmaprevision = hdr.maprevision;
}
else
{
hdr.waterlevel = -100000;
hdr.ambient = 0;
}
ents.shrink(0);
loopi(3) numspawn[i] = 0;
loopi(2) numflagspawn[i] = 0;
loopi(hdr.numents)
{
entity &e = ents.add();
f->read(&e, sizeof(persistent_entity));
lilswap((short *)&e, 4);
e.spawned = false;
TRANSFORMOLDENTITIES(hdr)
if(e.type == PLAYERSTART && (e.attr2 == 0 || e.attr2 == 1 || e.attr2 == 100))
{
if(e.attr2 == 100)
numspawn[2]++;
else
numspawn[e.attr2]++;
}
if(e.type == CTF_FLAG && (e.attr2 == 0 || e.attr2 == 1)) numflagspawn[e.attr2]++;
}
delete[] world;
setupworld(hdr.sfactor);
DELETEA(mlayout);
mlayout = new char[cubicsize + 256];
memset(mlayout, 0, cubicsize * sizeof(char));
int diff = 0;
Mv = Ma = Hhits = 0;
if(!mapinfo.numelems || (mapinfo.access(mname) && !cmpf(cgzname, mapinfo[mname]))) world = (sqr *)ents.getbuf();
-- cgzname
-- hdr.maprevision
-- hdr.maptitle
}
--]]
|
require 'nn'
require 'audio'
require 'Mapper'
require 'UtilsMultiGPU'
local cmd = torch.CmdLine()
cmd:option('-modelPath', 'deepspeech.t7', 'Path of model to load')
cmd:option('-audioPath', '', 'Path to the input audio to predict on')
cmd:option('-dictionaryPath', './dictionary', 'File containing the dictionary to use')
cmd:option('-windowSize', 0.02, 'Window Size of audio')
cmd:option('-stride', 0.01, 'Stride of audio')
cmd:option('-sampleRate', 16000, 'Rate of audio (default 16khz)')
cmd:option('-nGPU', 1)
local opt = cmd:parse(arg)
if opt.nGPU > 0 then
require 'cunn'
require 'cudnn'
require 'BatchBRNNReLU'
end
local model = loadDataParallel(opt.modelPath, opt.nGPU)
local mapper = Mapper(opt.dictionaryPath)
local wave = audio.load(opt.audioPath)
local spect = audio.spectrogram(wave, opt.windowSize * opt.sampleRate, 'hamming', opt.stride * opt.sampleRate):float() -- freq-by-frames tensor
-- normalize the data
local mean = spect:mean()
local std = spect:std()
spect:add(-mean)
spect:div(std)
spect = spect:view(1, 1, spect:size(1), spect:size(2))
if opt.nGPU > 0 then
spect = spect:cuda()
model = model:cuda()
end
model:evaluate()
local predictions = model:forward(spect)
local tokens = mapper:decodeOutput(predictions[1])
local text = mapper:tokensToText(tokens)
print(text) |
local diff = {
["axisDiffs"] = {
["a2004cdnil"] = {
["added"] = {
[1] = {
["key"] = "JOY_Z",
},
},
["name"] = "Thrust",
["removed"] = {
[1] = {
["key"] = "JOY_SLIDER1",
},
},
},
},
}
return diff |
att.PrintName = "Range Suppressor"
att.Icon = Material("snowysnowtime/2k/ico/h3/smg_sil.png")
att.Description = "Suppressor attachment often used by special forces."
att.Desc_Pros = {
}
att.Desc_Cons = {
}
att.SortOrder = 997
att.Slot = "barrel_smgho"
att.Silencer = true
att.Override_MuzzleEffect = "astw2_halo_3_muzzle_SMG_ODST"
att.Override_MuzzleEffectAttachment = "1"
att.IsMuzzleDevice = true
att.AutoStats = true
att.Mult_ShootPitch = 1
att.Mult_ShootVol = 0.7
att.Mult_Recoil = 0.85
att.Mult_Precision = 0.95
att.Mult_SightTime = 1.2
att.Mult_SightedSpeedMult = 0.95
att.Add_BarrelLength = 5
att.AttachSound = "attch/snow/halo/h3/x_button.wav"
att.DetachSound = "attch/snow/halo/h3/b_button.wav"
att.ActivateElements = {"rng_barrel"} |
local template = require 'charon.template'
local test = {}
test.should_return_function = function()
template.mtime = {}
local result = template.execute("util/template/example-equal-char.tpl", {}, {}, true)
assert( result == 'Hello World !!!', result )
end
test.should_reload_with_flag = function()
template.cache["util/template/example-equal-char.tpl"] = function(self, helper)
return "Hello..."
end
local result = template.execute("util/template/example-equal-char.tpl", {})
assert( result == 'Hello...', result )
template.mtime["util/template/example-equal-char.tpl"] = 0
local result = template.execute("util/template/example-equal-char.tpl", {}, {}, true)
assert( result == 'Hello World !!!', result )
end
return test
|
local _M = {
[1] = "Pack",
[2] = "Error",
[3] = "Operation",
[4] = "CreateRole",
[5] = "EnterChapter",
[31] = "OpenBox",
[32] = "GainBox",
[11] = "Delete",
[101] = "Role",
[1071] = "Prop",
[107] = "Props",
[1021] = "Chapter",
[102] = "Chapters",
[51] = "FinishMission",
[53] = "FinishAchv",
[52] = "MissionEvent",
[1051] = "MissionItem",
[105] = "MissionList",
[1091] = "AchvItem",
[109] = "AchvList",
[1061] = "Box",
[106] = "Boxes",
[108] = "Rewards",
[110] = "Talents",
[54] = "TalentUnlock",
[12] = "SigninRecord",
[13] = "SigninGet",
[22] = "ShopBuy",
[21] = "ShopRecord",
[15] = "MapRecordSave",
}
return _M |
--
-- EFCReport by Cubenicke aka Yrrol@vanillagaming
-- Thx for the good looking graphics lanevegame!
--
EFCReport = CreateFrame('Frame', "EFCReport", UIParent)
EFCReport.enabled = false
EFCReport.created = false
EFCReport:RegisterEvent("ADDON_LOADED")
EFCReport:RegisterEvent("PLAYER_ENTERING_WORLD")
EFCReport:RegisterEvent("ZONE_CHANGED_NEW_AREA")
SLASH_EFCReport1 = '/efcr'
SLASH_EFCReport2 = '/EFCR'
if not EFCRSaves then
EFCRSaves = { scale = 0, x = 0, y = 0, dim = false }
end
function EFCReport:GetButtons()
local faction = UnitFactionGroup("player") == "Horde" and "H" or "A"
local fcPrefix = "Going >>> "
local efcPrefix = "EFC @ "
local ourPrefix = ""
local enemyPrefix = "E"
local locs = {
["gy"] = "GY",
["fr"] = "FR",
["balc"] = "BALC",
["ramp"] = "RAMP",
["leaf"] = "LEAF",
["fence"] = "FENCE/TOT",
["tun"] = "TUN",
["zerk"] = "ZERK",
["roof"] = "ROOF",
}
local buttons = {
{ x = {2,2}, y = {-2,-2}, w = 32, h = 32, tex = "repic28", text = "=== REPICK ===" },
{ faction = "A", loc = locs.roof, x = {34,34}, y = faction == "H" and {-2,-194} or {-194,-2}, w = 64, h = 32, tex = "aroof.blp" },
{ x = {98,98}, y = {-2,-2}, w = 32, h = 32, tex = "cap28", text = "=== CAP ===" },
{ faction = "A", loc = locs.gy, x = faction == "H" and {2,98} or {98,2}, y = faction == "H" and {-34,-162} or {-162,-34}, w = 32, h = 32, tex = "agy.blp" },
{ faction = "A", loc = locs.fr, x = faction == "H" and {34,66} or {66,34}, y = faction == "H" and {-34,-162} or {-162,-34}, w =32, h = 32, tex = "afr.blp" },
{ faction = "A", loc = locs.balc, x = faction == "H" and {66,34} or {34,66}, y = faction == "H" and {-34,-162} or {-162,-34}, w = 32, h = 32, tex = "abalc.blp" },
{ faction = "A", loc = locs.ramp, x = faction == "H" and {98,2} or {2,98}, y = faction == "H" and {-34,-162} or {-162,-34}, w = 32, h = 32, tex = "aramp.blp" },
{ faction = "A", loc = locs.leaf, x = faction == "H" and {2,98} or {98,2}, y = faction == "H" and {-66,-130} or {-130,-66}, w = 32, h = 32, tex = "aresto.blp" },
{ faction = "A", loc = locs.fence, x = faction == "H" and {34,66} or {66,34}, y = faction == "H" and {-66,-130} or {-130,-66}, w = 32, h = 32, tex = "afence.blp" },
{ faction = "A", loc = locs.tun, x = faction == "H" and {66,34} or {34,66}, y = faction == "H" and {-66,-130} or {-130,-66}, w = 32, h = 32, tex = "atun.blp" },
{ faction = "A", loc = locs.zerk, x = faction == "H" and {98,2} or {2,98}, y = faction == "H" and {-66,-130} or {-130,-66}, w = 32, h = 32, tex = "azerk.blp" },
{ loc = "WEST", x = faction == "H" and {18,18} or {82,82}, y={-98,-98}, w=32, h=32, tex = faction == "H" and "west.blp" or "east.blp"},
{ loc = "MID", x = {50,50}, y={-98,-98}, w=32, h=32, tex = "mid.blp", text = "MID"},
{ loc = "EAST", x = faction == "H" and {82,82} or {18,18}, y={-98,-98}, w=32, h=32, tex = faction == "H" and "east.blp" or "west.blp"},
{ faction = "H", loc = locs.zerk, x= faction == "H" and {2,98} or {98,2}, y= faction == "H" and {-130,-66} or {-66,-130}, w=32, h=32, tex = "hzerk.blp"},
{ faction = "H", loc = locs.tun, x= faction == "H" and {34,66} or {66,34}, y= faction == "H" and {-130,-66} or {-66,-130}, w=32, h=32, tex = "htun.blp"},
{ faction = "H", loc = locs.fence, x= faction == "H" and {66,34} or {34,66}, y= faction == "H" and {-130,-66} or {-66,-130}, w=32, h=32, tex = "hfence.blp"},
{ faction = "H", loc = locs.leaf, x= faction == "H" and {98,2} or {2,98}, y= faction == "H" and {-130,-66} or {-66,-130}, w=32, h=32, tex = "hresto.blp"},
{ faction = "H", loc = locs.ramp, x= faction == "H" and {2,98} or {98,2}, y= faction == "H" and {-162,-34} or {-34,-162}, w=32, h=32, tex = "hramp.blp"},
{ faction = "H", loc = locs.balc, x= faction == "H" and {34,66} or {66,34}, y= faction == "H" and {-162,-34} or {-34,-162}, w=32, h=32, tex = "hbalc.blp"},
{ faction = "H", loc = locs.fr, x= faction == "H" and {66,34} or {34,66}, y= faction == "H" and {-162,-34} or {-34,-162}, w=32, h=32, tex = "hfr.blp"},
{ faction = "H", loc = locs.gy, x= faction == "H" and {98,2} or {2,98}, y= faction == "H" and {-162,-34} or {-34,-162}, w=32, h=32, tex = "hgy.blp"},
{ faction = "H", loc = locs.roof, x={34,34}, y= faction == "H" and {-194,-2} or {-2, -194}, w=64, h=32, tex = "hroof.blp"},
}
for i,btn in pairs(buttons) do
if btn.loc ~= nil then
local loc = btn.loc
if btn.faction ~= nil then
loc = (btn.faction == faction and ourPrefix or enemyPrefix) .. btn.loc
end
btn.fcText = fcPrefix .. " " .. loc
btn.efcText = efcPrefix .. " " .. loc
end
end
return buttons;
end
local iconPath = "Interface\\Addons\\EFCReport\\Icons\\"
function Print(arg1)
DEFAULT_CHAT_FRAME:AddMessage("|cffCC121D EFCR|r "..(arg1 or ""))
end
-- Show the dialog when entering WSG
function EFCReport:OnEvent()
if event == "ADDON_LOADED" and arg1 == "EFCReport" then
Print("Loaded")
elseif event == 'PLAYER_ENTERING_WORLD' or event == 'ZONE_CHANGED_NEW_AREA' then
if GetRealZoneText() == "Warsong Gulch" then
EFCReport.create()
EFCReport.EFCFrame:Show()
EFCReport.enabled = true
elseif EFCReport.enabled then
EFCReport.enabled = false
EFCReport.EFCFrame:Hide()
end
end
end
EFCReport:SetScript("OnEvent", EFCReport.OnEvent)
-- Hanlde slash commands
-- /efcr
-- /efcr scale <0 - 1>
-- /efcr xy <x> <Y>
-- /efcr x <x>
-- /efcr y <y>
SlashCmdList['EFCReport'] = function (msg)
local _, _, cmd, args = string.find(msg or "", "([%w%p]+)%s*(.*)$")
if cmd == "" or cmd == nil then
if EFCReport.enabled then
EFCReport.enabled = false
EFCReport.EFCFrame:Hide()
else
EFCReport.create()
EFCReport.EFCFrame:Show()
EFCReport.enabled = true
end
elseif cmd == "scale" then
EFCRSaves.scale = tonumber(args)
Print("Setting Scale "..args)
if EFCReport.EFCFrame then
EFCReport.EFCFrame:SetScale(EFCRSaves.scale)
end
elseif cmd == "xy" or cmd == "pos" then
local x, y = string.find(args,"(.*)%s*(.*)")
EFCRSaves.x = x or 0
EFCRSaves.y = y or 0
EFCReport.EFCFrame:SetPoint("TOPLEFT", nil, "TOPLEFT", EFCRSaves.x, -EFCRSaves.y)
elseif cmd == "x" then
EFCRSaves.x = tonumber(args) or 0
EFCReport.EFCFrame:SetPoint("TOPLEFT", nil, "TOPLEFT", EFCRSaves.x, -EFCRSaves.y)
elseif cmd == "y" then
EFCRSaves.y = tonumber(args) or 0
EFCReport.EFCFrame:SetPoint("TOPLEFT", nil, "TOPLEFT", EFCRSaves.x, -EFCRSaves.y)
elseif cmd == "dim" then
if EFCRSaves.dim then
EFCReport.EFCFrame:SetAlpha(1)
EFCRSaves.dim = false
else
EFCReport.EFCFrame:SetAlpha(0.4)
EFCRSaves.dim = true
end
else
Print("Unknown command "..cmd)
end
end
function EFCReport_OnEnter()
if EFCRSaves.dim then
EFCReport.EFCFrame:SetAlpha(1)
end
end
function EFCReport_OnLeave()
if EFCRSaves.dim then
EFCReport.EFCFrame:SetAlpha(0.4)
end
end
-- Create the EFCReport dialog
function EFCReport:create()
if (EFCReport.EFCFrame ~= nil) then
EFCReport.EFCFrame:Hide()
EFCReport.enabled = false
end
-- Option Frame
local frame = CreateFrame("Frame", "EFCRFrame")
local ix = 1
EFCReport.EFCFrame = frame
tinsert(UISpecialFrames,"EFCReport")
EFCReport.Language = 'Common'
local numSkills = GetNumSkillLines();
for i = 1, numSkills do
local skill = GetSkillLineInfo(i);
if string.find(skill, 'Orcish') then
EFCReport.Language = 'Orcish'
end
end
-- Set scale, size and position
frame:SetWidth(132)
frame:SetHeight(228)
if EFCRSaves.scale > 0 then
frame:SetScale(EFCRSaves.scale)
end
if not (EFCRSaves.x > 0 and EFCRSaves.y > 0) then
EFCRSaves.x = 400
EFCRSaves.y = 50
end
-- Background on entire frame
frame:SetPoint("TOPLEFT", nil, "TOPLEFT", EFCRSaves.x, -EFCRSaves.y)
frame:SetBackdrop( {
bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Background",
tile = true,
tileSize = 32,
edgeSize = 2,
insets = { left = 2, right = 2, top = 2, bottom = 2 }
} );
frame:SetBackdropColor(0, 0, 0, .91)
frame:SetBackdropBorderColor(0.3, 0.3, 0.3, 1)
-- Make it moveable
frame:SetMovable(true)
frame:EnableMouse(true)
frame:SetClampedToScreen(false)
if EFCRSaves.dim then
frame:SetAlpha(0.4)
end
frame:Hide()
-- Handle drag of window
frame:SetScript("OnMouseDown", function()
if arg1 == "LeftButton" and not this.isMoving then
this:StartMoving();
this.isMoving = true;
end
end)
frame:SetScript("OnMouseUp", function()
if arg1 == "LeftButton" and this.isMoving then
local _,_,_,x,y = this:GetPoint()
EFCRSaves.x = x
EFCRSaves.y = -y
this:StopMovingOrSizing();
this.isMoving = false;
end
end)
frame:SetScript("OnHide", function()
if this.isMoving then
this:StopMovingOrSizing();
this.isMoving = false;
end
end)
frame:SetScript("OnEnter", EFCReport_OnEnter)
frame:SetScript("OnLeave", EFCReport_OnLeave)
-- Create the buttons
local buttons = EFCReport:GetButtons()
for i,btn in pairs(buttons) do
local btn_frame = CreateFrame("Button", btn.text, frame)
btn_frame:SetPoint("TOPLEFT", frame, "TOPLEFT", btn.x[ix], btn.y[ix])
btn_frame.id = i
btn_frame:SetWidth(btn.w)
btn_frame:SetHeight(btn.h)
-- Left click: EFC report
btn_frame:RegisterForClicks("LeftButtonUp", "RightButtonUp")
btn_frame:SetScript("OnClick", function()
local b = buttons[this.id]
local text = (arg1 == "LeftButton" and b.efcText or b.fcText) or b.text
faction = UnitFactionGroup
if (IsRaidLeader() or IsRaidOfficer()) then
SendChatMessage(text,"RAID_WARNING" , EFCReport.Language)
else
SendChatMessage(text,"BATTLEGROUND" , EFCReport.Language)
end
end)
btn_frame:SetBackdrop( {
bgFile = iconPath..btn.tex,
} );
btn_frame:SetScript("OnEnter", EFCReport_OnEnter)
btn_frame:SetScript("OnLeave", EFCReport_OnLeave)
end
EFCReport.created = true
end |
--------------------------------------
-- Spell: Sandstorm
-- Changes the weather around target party member to "dusty."
--------------------------------------
require("scripts/globals/magic")
require("scripts/globals/status")
--------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
target:delStatusEffectSilent(tpz.effect.FIRESTORM)
target:delStatusEffectSilent(tpz.effect.SANDSTORM)
target:delStatusEffectSilent(tpz.effect.RAINSTORM)
target:delStatusEffectSilent(tpz.effect.WINDSTORM)
target:delStatusEffectSilent(tpz.effect.HAILSTORM)
target:delStatusEffectSilent(tpz.effect.THUNDERSTORM)
target:delStatusEffectSilent(tpz.effect.AURORASTORM)
target:delStatusEffectSilent(tpz.effect.VOIDSTORM)
local duration = calculateDuration(180, spell:getSkillType(), spell:getSpellGroup(), caster, target)
duration = calculateDurationForLvl(duration, 41, target:getMainLvl())
local merit = caster:getMerit(tpz.merit.STORMSURGE)
local power = 0
if merit > 0 then
power = merit + caster:getMod(tpz.mod.STORMSURGE_EFFECT) + 2
end
target:addStatusEffect(tpz.effect.SANDSTORM, power, 0, duration)
return tpz.effect.SANDSTORM
end |
-- Copyright (c) 2020 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
describe("game.ui.layouts.message_layout", function()
require "game.ui"
it("is takes a title and internal content for rendering", function()
local layout = moonpie.ui.components.message_layout({
title = "An important event!",
content = {
{ id = "some-internal-thing" }
}
})
assert.equals("An important event!", layout:find_by_id("screen_title_heading").text)
assert.not_nil(layout:find_by_id("some-internal-thing"))
end)
it("can render out the actions section for buttons and widgets", function()
local layout = moonpie.ui.components.message_layout({
title = "Things",
content = {},
actions = {
{ id = "some-button" }
}
})
assert.not_nil(layout:find_by_id("some-button"))
end)
end) |
PLUGIN.name = "탄약 저장 (Save Ammo)"
PLUGIN.author = "Chessnut / 번역자 : Tensa"
PLUGIN.desc = "플레이어의 탄약을 저장합니다."
PLUGIN.base = true;
local AMMO_TYPES = {
"ar2",
"alyxgun",
"pistol",
"smg1",
"357",
"xbowbolt",
"buckshot",
"rpg_round",
"smg1_grenade",
"sniperround",
"sniperpenetratedround",
"grenade",
"thumper",
"gravity",
"battery",
"gaussenergy",
"combinecannon",
"airboatgun",
"striderminigun",
"helicoptergun",
"ar2altfire",
"slam"
}
function PLUGIN:CharacterSave(client)
local ammo = {}
local weapon = client:GetActiveWeapon()
for k, v in pairs(AMMO_TYPES) do
local count = client:GetAmmoCount(v)
if (count > 0) then
ammo[v] = count
end
end
client.character:SetData("ammo", ammo)
if(!IsValid(weapon) and IsValid(weapon.Clip1)) then
client.character:SetData("clip1", weapon:Clip1());
else
client.character:SetData("clip1", 0);
end;
end
function PLUGIN:PlayerFirstLoaded(client)
client:RemoveAllAmmo()
local ammo = client.character:GetData("ammo")
local weapon = client:GetActiveWeapon()
if (IsValid(weapon)) then
weapon:SetClip1(client.character:GetData("clip1"))
end
if (ammo) then
for ammoType, amount in pairs(ammo) do
client:SetAmmo(tonumber(amount) or 0, ammoType)
end
client.character:SetData("ammo", {})
end
end |
--[[
© 2016-2017 TeslaCloud Studios
See license in LICENSE.txt.
--]]
AddCSLuaFile()
AddCSLuaFile("sh_utility.lua")
include("sh_utility.lua")
util.Include("cl_client_utils.lua")
util.Include("sh_hex.lua")
util.Include("sh_string.lua")
util.Include("sh_table.lua")
util.Include("sh_color.lua")
util.Include("sh_easing.lua")
util.Include("sh_player.lua") |
------------------------------------------------------------------------------------
-- CSG
-- v1.0
-- ppEvent_c.luac (client-side)
-- Armored Truck Event
-- Priyen Patel
------------------------------------------------------------------------------------
local blips = {}
local truck = ""
local sentWanted = false
local bags = ""
local monitorBlipVisibilityTimer = ""
function rec(t,s,water)
inWater=water
bags = t
for k,v in pairs(t) do
setElementCollisionsEnabled(v[1],false)
rx,ry,rz = getElementRotation(v[1])
if inWater == true then ry = 45 end
setElementRotation(v[1],rx,ry,rz)
end
addEventHandler("onClientRender",root,rotateBags)
setTimer(function() sentWanted = false removeEventHandler("onClientRender",root,rotateBags) inWater=false end,s,1)
end
addEvent("CSGarmoredEventRecBags",true)
addEventHandler("CSGarmoredEventRecBags",localPlayer,rec)
function rotateBags()
for k,v in pairs(bags) do
if isElement(v[1]) == false then return end
local rx,ry,rz = getElementRotation(v[1])
rz=rz+1
if rz > 360 then rz = rz-360 end
setElementRotation(v[1],rx,ry,rz)
end
end
function makeBlip(x,y,z,id,teams)
if x == 0 then return end
if isTimer(monitorBlipVisibilityTimer) == false then monitorBlipVisibilityTimer = setTimer(monitorBlipVisibility,1000,0) end
local blip = ""
local team = getPlayerTeam(localPlayer)
local myTeam = ""
--[[if team == false then
myTeam = "notLaw"
else
myTeam = getTeamName(team)
end]]
if isLaw(localPlayer) then
myTeam = getTeamName(team)
end
--[[ for k,v in pairs(teams) do
if v == myTeam then blip=createBlip(x,y,z,id) break end
end --]]
table.insert(blips,{blip,teams,x,y,z,id})
end
addEvent("CSGarmoredEventMakeBlip",true)
addEventHandler("CSGarmoredEventMakeBlip",localPlayer,makeBlip)
function monitorBlipVisibility()
if getPlayerTeam(localPlayer) then
local myTeam = getTeamName(getPlayerTeam(localPlayer))
for k,v in pairs(blips) do
for k2,v2 in pairs(v[2]) do
if v2 == myTeam then
if v[1] == "" then
blip=createBlip(v[3],v[4],v[5],v[6]) blips[k][1] = blip
return
else
return
end
end
end
if isElement(v[1]) then destroyElement(v[1]) blips[k][1] = "" end
end
end
end
local lawTeams = {
"Military Forces",
"GIGN",
"Police"
}
function isLaw(e)
local team = getTeamName(getPlayerTeam(e))
for k,v in pairs(lawTeams) do if v == team then return true end end
return false
end
function destroyBlip(x,y,z)
for k,v in pairs(blips) do
local x2,y2,z2 = getElementPosition(v[1])
if x == x2 and y == y2 and z == z2 then
destroyElement(v[1])
table.remove(blips,k)
end
end
end
addEvent("CSGarmoredEventDestroyBlip",true)
addEventHandler("CSGarmoredEventDestroyBlip",localPlayer,destroyBlip)
function endEvent()
if isTimer(monitorBlipVisibilityTimer) == true then killTimer(monitorBlipVisibilityTimer) end
end
addEvent("CSGarmoredEventEnd",true)
addEventHandler("CSGarmoredEventEnd",localPlayer,endEvent)
timeUntilEvent = 1
function recTime(tim)
timeUntilEvent = tim
end
addEvent("CSGarmoredEventRecTime",true)
addEventHandler("CSGarmoredEventRecTime",localPlayer,recTime)
function decrease()
if timeUntilEvent > 0 then
timeUntilEvent = timeUntilEvent-1
end
end
setTimer(decrease,1000,0)
function getTimeUntilEvent()
return timeUntilEvent*1000
end
function waterCheck(x,y,z)
local result = getWaterLevel(x,y,z)
triggerServerEvent("CSGarmoredEventRecWaterCheckResult",localPlayer,result)
end
addEvent("CSGarmoredEventDoWaterCheck",true)
addEventHandler("CSGarmoredEventDoWaterCheck",localPlayer,waterCheck)
function rect(truckE)
truck = truckE
end
addEvent("CSGarmoredEventRecTruck",true)
addEventHandler("CSGarmoredEventRecTruck",localPlayer,rect)
function fire(wep,am,clip,x,y,z,el)
if source ~= localPlayer then return end
if el == truck then
if sentWanted == false then
sentWanted = true
triggerServerEvent("CSGarmoredEventHitTruck",localPlayer)
end
end
end
|
-- Internal glossary for enumeration, lookups, constants and so on.
local Glossary = {}
-- Dictionary.
Glossary.Resources = require("data/glossary/resources")
Glossary.Weapons = require("data/glossary/weapons")
Glossary.Clothing = require("data/glossary/clothing")
Glossary.Cyberware = require("data/glossary/cyberware")
Glossary.Quickhacks = require("data/glossary/quickhacks")
Glossary.Mods = require("data/glossary/mods")
Glossary.Attachments = require("data/glossary/attachments")
Glossary.Recipes = require("data/glossary/recipes")
Glossary.Perks = require("data/glossary/perks")
Glossary.Traits = require("data/glossary/traits")
Glossary.Vehicles = require("data/glossary/vehicles")
-- Enumerations.
Glossary.Attributes = {
Level = "Level",
StreetCred = "StreetCred",
Annihilation = "Demolition",
Athletics = "Athletics",
Assault = "Assault",
Blades = "Kenjutsu",
BreachProtocol = "Hacking",
ColdBlood = "ColdBlood",
Crafting = "Crafting",
Engineering = "Engineering",
Handguns = "Gunslinger",
Quickhacking = "CombatHacking",
Stealth = "Stealth",
StreetBrawler = "Brawling"
}
Glossary.AttributesRank = {
[1] = Glossary.Attributes.Level,
[2] = Glossary.Attributes.StreetCred,
[3] = Glossary.Attributes.Annihilation,
[4] = Glossary.Attributes.Athletics,
[5] = Glossary.Attributes.Assault,
[6] = Glossary.Attributes.Blades,
[7] = Glossary.Attributes.BreachProtocol,
[8] = Glossary.Attributes.ColdBlood,
[9] = Glossary.Attributes.Crafting,
[10] = Glossary.Attributes.Engineering,
[11] = Glossary.Attributes.Handguns,
[12] = Glossary.Attributes.Quickhacking,
[13] = Glossary.Attributes.Stealth,
[14] = Glossary.Attributes.StreetBrawler
}
Glossary.DevelopmentTypes = {
Primary = "Primary",
Attribute = "Attribute"
}
Glossary.Quality = {
Common = "Common",
Uncommon = "Uncommon",
Rare = "Rare",
Epic = "Epic",
Legendary = "Legendary"
}
Glossary.QualityNum = {
Common = 0,
Uncommon = 1,
Rare = 2,
Epic = 3,
Legendary = 4
}
Glossary.QualityRank = {
[1] = Glossary.Quality.Common,
[2] = Glossary.Quality.Uncommon,
[3] = Glossary.Quality.Rare,
[4] = Glossary.Quality.Epic,
[5] = Glossary.Quality.Legendary
}
Glossary.Stats = {
-- This list is likely still incomplete.
-- On dump the numerical value of each enumeration is also returned.
-- Some numbers are skipped depending on item type and other factors.
Accuracy = "Accuracy",
AimFOV = "AimFOV",
AimOffset = "AimOffset",
AimInTime = "AimInTime", -- Value expected to be negative on order of ~0.02.
AimOutTime = "AimOutTime",
Armor = "Armor",
AttackSpeed = "AttackSpeed", -- Not sure what this does. Maximum between 0 and 2 for some reason?
AttacksNumber = "AttacksNumber", -- Seems mostly tied to melee weapons. Number of attacks in a "combo" perhaps?
AttacksPerSecondBase = "AttacksPerSecondBase", -- Probably inherited from weapon type. Recommend not modifying this one.
AttacksPerSecond = "AttacksPerSecond",
AttackPenetration = "AttackPenetration", -- Is this a resistance or armour penetration value?
BaseDamage = "BaseDamage", -- Recommend modifying base damage modifiers where possible.
BaseDamageMin = "BaseDamageMin", -- Minimum and maximum damage ranges are computed as +/- 10% of base.
BaseDamageMax = "BaseDamageMax",
BleedChance = "BleedingApplicationRate",
BlockLocomotionWhenLeaningOutOfCover = "BlockLocomotionWhenLeaningOutOfCover",
BlockFactor = "BlockFactor", -- Used for melee weapon blocking. Unsure what exactly this value repesents.
BonusRicochetDamage = "BonusRicochetDamage",
BulletMagnetismDefaultAngle = "BulletMagnetismDefaultAngle",
BulletMagnetismHighVelocityAngle = "BulletMagnetismHighVelocityAngle",
BurnChance = "BurningApplicationRate",
Charge = "Charge", -- Not entirely sure what this represents.
BaseChargeTime = "BaseChargeTime", -- Appears to be in seconds.
CanSilentKill = "CanSilentKill", -- Boolean so that silencer not needed to kill while retaining stealth.
CanWeaponBlock = "CanWeaponBlock",
CanWeaponCriticallyHit = "CanWeaponCriticallyHit",
CanWeaponDeflect = "CanWeaponDeflect", -- More of a melee thing.
CanWeaponIgnoreArmor = "CanWeaponIgnoreArmor",
ChargeTime = "ChargeTime", -- Pure value seen on weapon. Likely to be seconds to maximum charge.
ChargeMaxTimeInChargedState = "ChargeMaxTimeInChargedState", -- Time before automatic discharge.
ChargeDischargeTime = "ChargeDischargeTime", -- Cooldown until can be charged again?
ChargeMultiplier = "ChargeMultiplier", -- Damage multiplier to charged damage.
ChargeFullMultiplier = "ChargeFullMultiplier", -- Separate modifier for fully-charged state.
ChargeReadyPercentage = "ChargeReadyPercentage",
ChemicalDamage = "ChemicalDamage",
ChemicalDamageMin = "ChemicalDamageMin",
ChemicalDamageMax = "ChemicalDamageMax",
ChemicalResistance = "ChemicalResistance",
CraftingBonusWeaponDamage = "CraftingBonusWeaponDamage", -- Additive multiplier due to weapon being crafted.
CycleTimeBase = "CycleTimeBase", -- Unsure what this refers to. Time between shots for pump actions, perhaps?
CycleTimeBonus = "CycleTimeBonus",
CycleTime = "CycleTime",
CycleTimeBurstMaxCharge = "CycleTime_BurstMaxCharge",
ClipTimesCycleBase = "ClipTimesCycleBase",
ClipTimesCycle = "ClipTimesCycle",
ClipTimesCyclePlusReload = "ClipTimesCyclePlusReload",
ClipTimesCyclePlusReloadBase = "ClipTimesCyclePlusReloadBase",
CritChance = "CritChance",
CritDamage = "CritDamage",
CritChanceTimesCritDamage = "CritChanceTimeCritDamage", -- Product of chance and damage maybe. Not sure where this is used.
CritDPSBonus = "CritDPSBonus", -- Likely to be visual only. Used for calculating in-inventory damage.
DPS = "DPS", -- Surely this is visual only.
DamagePerHit = "DamagePerHit", -- Probably also visual.
DamageFalloffDisabled = "DamageFalloffDisabled", -- Boolean flag. No range penalty for damage?
DealsChemicalDamage = "DealsChemicalDamage", -- Boolean flags for damage type.
DealsElectricalDamage = "DealsElectricDamage",
DealsPhysicalDamage = "DealsPhysicalDamage",
DealsThermalDamage = "DealsThermalDamage",
EffectiveDPS = "EffectiveDPS", -- Suspect these values are computed.
EffectiveDamagePerHit = "EffectiveDamagePerHit",
EffectiveDamagePerHitMin = "EffectiveDamagePerHitMin",
EffectiveDamagePerHitMax = "EffectiveDamagePerHitMax",
EffectiveDamagePerHitTimesAttacksPerSecond = "EffectiveDamagePerHitTimesAttacksPerSecond",
EffectiveRange = "EffectiveRange",
ElectricalDamage = "ElectricDamage",
ElectricalDamageMin = "ElectricDamageMin",
ElectricalDamageMax = "ElectricDamageMax",
ElectricalResistance = "ElectricResistance",
ShockChance = "ElectrocutedApplicationRate",
EmptyReloadTime = "EmptyReloadTime", -- Self-explanatory, really.
EquipDuration = "EquipDuration", -- No idea what these are used for.
EquipDurationFirst = "EquipDuration_First",
HeadshotDamageMultiplier = "HeadshotDamageMultiplier",
HasSmartLink = "HasSmartLink", -- Boolean value. Use this to make smart weapons be usable even without a link!
HitDismembermentFactor = "HitDismembermentFactor", -- Not too sure what these control but they sound fun to play with.
HitReactionFactor = "HitReactionFactor",
HitWoundsFactor = "HitWoundsFactor",
HoldEnterDuration = "HoldEnterDuration", -- Time taken to enter into blocking stance?
IconicItemUpgraded = "IconicItemUpgraded", -- Checks if this iconic weapon is the result of a previous upgrade?
IsItemCrafted = "IsItemCrafted", -- Booleans to set or unset craft flag.
IsItemIconic = "IsItemIconic", -- Similar for iconic flag.
ItemArmor = "ItemArmor",
ItemLevel = "ItemLevel",
ItemRequiresSmartLink = "ItemRequiresSmartLink", -- This is a boolean value.
KnockdownImpulse = "KnockdownImpulse", -- Physics value for knockdowns? Sounds fun!
Level = "Level", -- Matches power level but doesn't set requirement.
MagazineCapacityBase = "MagazineCapacityBase",
MagazineCapacityBonus = "MagazineCapacityBonus",
MagazineCapacity = "MagazineCapacity", -- Might be a computed value. Try modifying bonus.
MeleeAttackDuration = "MeleeAttackDuration",
NumShotsInBurstMaxCharge = "NumShotsInBurstMaxCharge", -- For tech weapons with burst fire on charge.
NumShotsToFire = "NumShotsToFire", -- Does not do what you think it does.
PartArmor = "PartArmor", -- Armor value from clothing mods. Typically composed of a base additive and an additive multiplier.
PhysicalDamage = "PhysicalDamage",
PhysicalDamageMin = "PhysicalDamageMin",
PhysicalDamageMax = "PhysicalDamageMax",
PhysicalImpulse = "PhysicalImpulse", -- Physics value for other ragdolling? Sounds fun!
PhysicalResistance = "PhysicalResistance",
PoisonChance = "PoisonedApplicationRate",
PowerLevel = "PowerLevel",
ProjectilesPerShotBase = "ProjectilesPerShotBase", -- Tech weapons or shotguns use this.
ProjectilesPerShotBonus = "ProjectilesPerShotBonus", -- Best to modify bonus rather than base (likely inherited from weapon type).
ProjectilesPerShot = "ProjectilesPerShot", -- May be a computed value. Needs testing.
Quality = "Quality",
Quantity = "Quantity", -- Unsure how this is used for non-stackable items. Value is not always one. Avoid!
RandomCurveInput = "RandomCurveInput",
Range = "Range", -- This should be interesting for melee weapons.
Recoil = "Recoil",
RecoilAngle = "RecoilAngle",
RecoilAnimation = "RecoilAnimation",
RecoilDelay = "RecoilDelay",
RecoilDir = "RecoilDir", -- Angle could be changed to force recoil direction.
RecoilDirADS = "RecoilDirADS",
RecoilDriftRandomRangeMin = "RecoilDriftRandomRangeMin",
RecoilDriftRandomRangeMax = "RecoilDriftRandomRangeMax",
RecoilEnableLinearX = "RecoilEnableLinearX",
RecoilEnableLinearXADS = "RecoilEnableLinearXADS",
RecoilEnableLinearY = "RecoilEnableLinearY",
RecoilEnableLinearYADS = "RecoilEnableLinearYADS",
RecoilFullChargeMult = "RecoilFullChargeMult",
RecoilHoldDuration = "RecoilHoldDuration",
RecoilHoldDurationADS = "RecoilHoldDurationADS",
RecoilKickMin = "RecoilKickMin",
RecoilKickMinADS = "RecoilKickMinADS",
RecoilKickMax = "RecoilKickMax",
RecoilKickMaxADS = "RecoilKickMaxADS",
RecoilMagForFullDrift = "RecoilMagForFullDrift",
RecoilMaxLength = "RecoilMaxLength",
RecoilRecoveryMinSpeed = "RecoilRecoveryMinSpeed",
RecoilRecoveryTime = "RecoilRecoveryTime",
RecoilRecoveryTimeADS = "RecoilRecoveryTimeADS",
RecoilTime = "RecoilTime",
RecoilTimeADS = "RecoilTimeADS",
RecoilUseDifferentStatsInADS = "RecoilUseDifferentStatsInADS", -- Boolean flag. Usually for rifles like snipers.
ReloadAmount = "ReloadAmount", -- For shotguns or items loaded shot-by-shot.
ReloadTimeBase = "ReloadTimeBase", -- Likely should modify base or bonus values. Only affects non-empty magazine reloads?
ReloadTimeBonus = "ReloadTimeBonus",
ReloadTime = "ReloadTime",
RicochetChance = "RicochetChance",
RicochetCount = "RicochetCount",
RicochetMinAngle = "RicochetMinAngle", -- Change these to make bouncy bullets?
RicochetMaxAngle = "RicochetMaxAngle",
RicochetTargetSearchAngle = "RicochetTargetSearchAngle", -- Automatically tries to guide to a target for hit.
ScopeFOV = "ScopeFOV",
ScopeOffset = "ScopeOffset",
ShotDelay = "ShotDelay", -- This is mainly a sniper rifle thing.
SlideWhenLeaningOutOfCover = "SlideWhenLeaningOutOfCover",
SmartGunAddSpiralTrajectory = "SmartGunAddSpiralTrajectory",
SmartGunAdsLockingAnglePitch = "SmartGunAdsLockingAnglePitch", -- Unsure what the locking angles control.
SmartGunAdsLockingAngleYaw = "SmartGunAdsLockingAngleYaw",
SmartGunAdsMaxLockedTargets = "SmartGunAdsMaxLockedTargets", -- Ooh baby.
SmartGunAdsTargetableAnglePitch = "SmartGunAdsTargetableAnglePitch",
SmartGunAdsTargetableAngleYaw = "SmartGunAdsTargetableAngleYaw",
SmartGunAdsTimeToLock = "SmartGunAdsTimeToLock", -- Appears to be in seconds.
SmartGunAdsTimeToUnlock = "SmartGunAdsTimeToUnlock", -- Usually set to zero.
SmartGunHipLockingAnglePitch = "SmartGunHipLockingAnglePitch",
SmartGunHipLockingAngleYaw = "SmartGunHipLockingAngleYaw",
SmartGunHipMaxLockedTargets = "SmartGunHipMaxLockedTargets", -- As with aim-down-sights variant.
SmartGunHipTargetableAnglePitch = "SmartGunHipTargetableAnglePitch",
SmartGunHipTargetableAngleYaw = "SmartGunHipTargetableAngleYaw",
SmartGunHipTimeToLock = "SmartGunHipTimeToLock",
SmartGunHipTimeToUnlock = "SmartGunHipTimeToUnlock",
SmartGunHitProbability = "SmartGunHitProbability", -- Values between zero and one. Why is it even possible for shots to miss?
SmartGunMissDelay = "SmartGunMissDelay",
SmartGunMissRadius = "SmartGunMissRadius",
SmartGunPlayerProjectileVelocity = "SmartGunPlayerProjectileVelocity", -- Default values are pretty low (~25) while max is very high (9999).
SmartGunProjectileVelocityVariance = "SmartGunProjectileVelocityVariance",
SmartGunSpiralCycleTimeMin = "SmartGunSpiralCycleTimeMin", -- Unsure what the spiral cycle times represent.
SmartGunSpiralCycleTimeMax = "SmartGunSpiralCycleTimeMax",
SmartGunSpiralRadius = "SmartGunSpiralRadius",
SmartGunSpiralRampDistanceStart = "SmartGunSpiralRampDistanceStart",
SmartGunSpiralRampDistanceEnd = "SmartGunSpiralRampDistanceEnd",
SmartGunSpiralRandomizeDirection = "SmartGunSpiralRandomizeDirection", -- This is a boolean flag.
SmartGunSpreadMultiplier = "SmartGunSpreadMultiplier",
SmartGunStartingAccuracy = "SmartGunStartingAccuracy", -- Default gun accuracy. For weapons that improve accuracy as they remain locked.
SmartGunTargetAcquisitionRange = "SmartGunTargetAcquisitionRange", -- Usually quite low (~20) while max is much higher (1000).
SmartGunTimeToMaxAccuracy = "SmartGunTimeToMaxAccuracy",
SmartGunTimeToRemoveOccludedTarget = "SmartGunTimeToRemoveOccludedTarget", -- You could use this to keep track through walls.
SmartGunTrackAllBodyparts = "SmartGunTrackAllBodyparts", -- Disable this to track only heads?
SmartGunUseEvenDistributionTargeting = "SmartGunUseEvenDistributionTargeting",
SmartGunUseTimeBasedAccuracy = "SmartGunUseTimeBasedAccuracy", -- Boolean flag.
Spread = "Spread", -- Here comes all the bullet spread stuff.
SpreadAdsChangePerShot = "SpreadAdsChangePerShot",
SpreadAdsChargeMult = "SpreadAdsChargeMult",
SpreadAdsDefaultX = "SpreadAdsDefaultX",
SpreadAdsFastSpeedMin = "SpreadAdsFastSpeedMin",
SpreadAdsFastSpeedMinAdd = "SpreadAdsFastSpeedMinAdd",
SpreadAdsFastSpeedMax = "SpreadAdsFastSpeedMax",
SpreadAdsFastSpeedMaxAdd = "SpreadAdsFastSpeedMaxAdd",
SpreadAdsFullChargeMult = "SpreadAdsFullChargeMult",
SpreadAdsMinX = "SpreadAdsMinX",
SpreadAdsMinY = "SpreadAdsMinY",
SpreadAdsMaxX = "SpreadAdsMaxX",
-- SpreadAdsMaxY = "SpreadAdsMaxY", -- Haven't seen this in any weapon dumps yet.
SpreadAnimation = "SpreadAnimation",
SpreadChangePerShot = "SpreadChangePerShot",
SpreadChargeMult = "SpreadChargeMult",
SpreadCrouchDefaultMult = "SpreadCrouchDefaultMult",
SpreadCrouchMaxMult = "SpreadCrouchMaxMult",
SpreadDefaultX = "SpreadDefaultX",
SpreadEvenDistributionJitterSize = "SpreadEvenDistributionJitterSize",
SpreadEvenDistributionRowCount = "SpreadEvenDistributionRowCount",
SpreadFastSpeedMin = "SpreadFastSpeedMin",
SpreadFastSpeedMinAdd = "SpreadFastSpeedMinAdd",
SpreadFastSpeedMax = "SpreadFastSpeedMax",
SpreadFastSpeedMaxAdd = "SpreadFastSpeedMaxAdd",
SpreadFullChargeMult = "SpreadFullChargeMult",
SpreadMinX = "SpreadMinX",
SpreadMaxX = "SpreadMaxX",
SpreadMinY = "SpreadMinY",
-- SpreadMaxY = "SpreadMaxY", -- Haven't seen this in any weapon dumps yet.
SpreadRandomizeOriginPoint = "SpreadRandomizeOriginPoint",
SpreadResetSpeed = "SpreadResetSpeed",
SpreadResetTimeThreshold = "SpreadResetTimeThreshold",
SpreadUseCircularSpread = "SpreadUseCircularSpread", -- This is a boolean. Common for tech weapons.
SpreadUseEvenDistribution = "SpreadUseEvenDistribution", -- This is a boolean. Common for tech weapons.
SpreadUseInAds = "SpreadUseInAds", -- This is a boolean.
StaminaCostToBlock = "StaminaCostToBlock",
StaminaDamage = "StaminaDamage", -- Is this damage done to your own stamina (i.e. cost to melee)?
StreetCred = "StreetCred",
Strength = "Strength", -- No idea what this represents.
SwayCenterMaximumAngleOffset = "SwayCenterMaximumAngleOffset",
SwayCurvatureMinimumFactor = "SwayCurvatureMinimumFactor",
SwayCurvatureMaximumFactor = "SwayCurvatureMaximumFactor",
SwayInitialOffsetRandomFactor = "SwayInitialOffsetRandomFactor",
SwayResetOnAimStart = "SwayResetOnAimStart",
SwaySideBottomAngleLimit = "SwaySideBottomAngleLimit",
SwaySideMinimumAngleDistance = "SwaySideMinimumAngleDistance",
SwaySideMaximumAngleDistance = "SwaySideMaximumAngleDistance",
SwaySideStepChangeMinimumFactor = "SwaySideStepChangeMinimumFactor",
SwaySideStepChangeMaximumFactor = "SwaySideStepChangeMaximumFactor",
SwaySideTopAngleLimit = "SwaySideTopAngleLimit",
SwayStartBlendTime = "SwayStartBlendTime",
SwayStartDelay = "SwayStartDelay",
SwayTraversalTime = "SwayTraversalTime",
TechPierceChargeLevel = "TechPierceChargeLevel", -- This is a threshold value of charge that must be exceeded to allow pierce.
TechPierceEnabled = "TechPierceEnabled", -- This is a boolean flag. Can set to allow piercing.
ThermalDamage = "ThermalDamage",
ThermalDamageMin = "ThermalDamageMin",
ThermalDamageMax = "ThermalDamageMax",
ThermalResistance = "ThermalResistance",
UnequipDuration = "UnequipDuration",
WasItemUpgraded = "WasItemUpgraded", -- Boolean or counter that tracks how to scale upgrade recipe?
Weight = "Weight",
ZoomLevel = "ZoomLevel"
}
Glossary.Inspect = {
Glossary.Stats.Level,
Glossary.Stats.ItemLevel,
Glossary.Stats.PowerLevel,
Glossary.Stats.IsItemIconic,
Glossary.Stats.IsItemCrafted,
Glossary.Stats.Armor,
Glossary.Stats.ItemArmor,
Glossary.Stats.PartArmor,
Glossary.Stats.BaseDamage,
Glossary.Stats.PhysicalDamage,
Glossary.Stats.BleedChance,
Glossary.Stats.ThermalDamage,
Glossary.Stats.BurnChance,
Glossary.Stats.ElectricalDamage,
Glossary.Stats.ShockChance,
Glossary.Stats.ChemicalDamage,
Glossary.Stats.PoisonChance,
Glossary.Stats.CritChance,
Glossary.Stats.CritDamage,
Glossary.Stats.HeadshotDamageMultiplier,
Glossary.Stats.ProjectilesPerShot,
Glossary.Stats.MagazineCapacity,
Glossary.Stats.CycleTime,
Glossary.Stats.RicochetChance,
Glossary.Stats.RicochetCount,
Glossary.Stats.BonusRicochetDamage,
Glossary.Stats.RicochetMinAngle,
Glossary.Stats.RicochetMaxAngle,
Glossary.Stats.RicochetTargetSearchAngle,
Glossary.Stats.TechPierceEnabled,
Glossary.Stats.TechPierceChargeLevel,
Glossary.Stats.ChargeMultiplier,
Glossary.Stats.ChargeFullMultiplier,
Glossary.Stats.BaseChargeTime,
Glossary.Stats.ChargeTime,
Glossary.Stats.NumShotsInBurstMaxCharge,
Glossary.Stats.HasSmartLink,
Glossary.Stats.SmartGunHitProbability,
Glossary.Stats.SmartGunAdsMaxLockedTargets,
Glossary.Stats.SmartGunHipMaxLockedTargets,
Glossary.Stats.SmartGunTrackAllBodyparts
}
Glossary.Calculation = {
Additive = "Additive",
Multiplicative = "Multiply",
Both = "AdditiveMultiplier" -- Represents a (1 + x) times multiplier.
}
Glossary.Tags = {
Quest = "Quest",
UnequipBlocked = "UnequipBlocked",
DummyPart = "DummyPart"
}
Glossary.EquipSlots = {
Face = 1,
Feet = 1,
Heads = 1,
InnerChest = 1,
Legs = 1,
OuterChest = 1,
Weapon = 3,
Outfit = 1
}
Glossary.WeaponSlots = {
[1] = "Weapon 1",
[2] = "Weapon 2",
[3] = "Weapon 3"
}
Glossary.ClothingSlots = {
[1] = "Head",
[2] = "Face",
[3] = "Inner Torso",
[4] = "Outer Torso",
[5] = "Legs",
[6] = "Feet"
}
Glossary.ClothingSlotsInv = {
["Head"] = "Heads",
["Face"] = "Face",
["Inner Torso"] = "InnerChest",
["Outer Torso"] = "OuterChest",
["Legs"] = "Legs",
["Feet"] = "Feet"
}
Glossary.PartSlots = {
Weapon = {
Generic = {
Ranged = {
"AttachmentSlots.GenericWeaponMod1",
"AttachmentSlots.GenericWeaponMod2",
"AttachmentSlots.GenericWeaponMod3",
"AttachmentSlots.GenericWeaponMod4"
},
Melee = {
"AttachmentSlots.MeleeWeaponMod1",
"AttachmentSlots.MeleeWeaponMod2",
"AttachmentSlots.MeleeWeaponMod3"
}
},
Scope = {
Small = "AttachmentSlots.Scope",
Rail = "AttachmentSlots.ScopeRail"
},
Muzzle = "AttachmentSlots.PowerModule",
Iconic = {
Melee = "AttachmentSlots.IconicMeleeWeaponMod1",
Ranged = "AttachmentSlots.IconicWeaponModLegendary"
},
Power = {
Rare = "AttachmentSlots.PowerWeaponModRare",
Epic = "AttachmentSlots.PowerWeaponModEpic",
Legendary = "AttachmentSlots.PowerWeaponModLegendary"
},
Tech = {
Rare = "AttachmentSlots.TechWeaponModRare",
Epic = "AttachmentSlots.TechWeaponModEpic",
Legendary = "AttachmentSlots.TechWeaponModLegendary"
},
Smart = {
Rare = "AttachmentSlots.SmartWeaponModRare",
Epic = "AttachmentSlots.SmartWeaponModEpic",
Legendary = "AttachmentSlots.SmartWeaponModLegendary"
}
},
Clothing = {
Face = {
"AttachmentSlots.FaceFabricEnhancer1",
"AttachmentSlots.FaceFabricEnhancer2",
"AttachmentSlots.FaceFabricEnhancer3",
"AttachmentSlots.FaceFabricEnhancer4"
},
Feet = {
"AttachmentSlots.FootFabricEnhancer1",
"AttachmentSlots.FootFabricEnhancer2",
"AttachmentSlots.FootFabricEnhancer3",
"AttachmentSlots.FootFabricEnhancer4"
},
Head = {
"AttachmentSlots.HeadFabricEnhancer1",
"AttachmentSlots.HeadFabricEnhancer2",
"AttachmentSlots.HeadFabricEnhancer3",
"AttachmentSlots.HeadFabricEnhancer4"
},
InnerChest = {
"AttachmentSlots.InnerChestFabricEnhancer1",
"AttachmentSlots.InnerChestFabricEnhancer2",
"AttachmentSlots.InnerChestFabricEnhancer3",
"AttachmentSlots.InnerChestFabricEnhancer4"
},
Legs = {
"AttachmentSlots.LegsFabricEnhancer1",
"AttachmentSlots.LegsFabricEnhancer2",
"AttachmentSlots.LegsFabricEnhancer3",
"AttachmentSlots.LegsFabricEnhancer4"
},
OuterChest = {
"AttachmentSlots.OuterChestFabricEnhancer1",
"AttachmentSlots.OuterChestFabricEnhancer2",
"AttachmentSlots.OuterChestFabricEnhancer3",
"AttachmentSlots.OuterChestFabricEnhancer4"
}
}
}
-- Property Lookups
Glossary.ForcedQuality = {
-- Keys should match those in item quality.
-- Let this be a lesson for anyone who doesn't want to learn object-oriented programming.
Legendary = {
Glossary.Weapons.Ranged.Achilles.Iconic.WidowMaker.Legendary,
Glossary.Weapons.Ranged.Ajax.Iconic.MoronLabe.Legendary,
Glossary.Weapons.Ranged.Burya.Iconic.ComradesHammer.Legendary,
Glossary.Weapons.Ranged.Carnage.Iconic.Mox.Legendary,
Glossary.Weapons.Ranged.Copperhead.Iconic.Psalm.Legendary,
Glossary.Weapons.Ranged.Dian.Iconic.YingLong.Legendary,
Glossary.Weapons.Ranged.Grad.Iconic.OFive.Legendary,
Glossary.Weapons.Ranged.Grad.Iconic.Overwatch.Legendary,
Glossary.Weapons.Ranged.Igla.Iconic.Sovereign.Legendary,
Glossary.Weapons.Ranged.Kenshin.Iconic.Apparition.Legendary,
Glossary.Weapons.Ranged.Kenshin.Iconic.Chaos.Legendary,
Glossary.Weapons.Ranged.Lexington.Iconic.DyingNight.Legendary,
Glossary.Weapons.Ranged.Liberty.Iconic.Kongou.Legendary,
Glossary.Weapons.Ranged.Liberty.Iconic.PlanB.Legendary,
Glossary.Weapons.Ranged.Liberty.Iconic.Pride.Legendary,
Glossary.Weapons.Ranged.Masamune.Iconic.Prejudice.Legendary,
Glossary.Weapons.Ranged.Nekomata.Iconic.Breakthrough.Legendary,
Glossary.Weapons.Ranged.Nova.Iconic.DoomDoom.Legendary,
Glossary.Weapons.Ranged.Nue.Iconic.ChingonaDorada.Legendary,
Glossary.Weapons.Ranged.Nue.Iconic.DeathTaxes.Legendary,
Glossary.Weapons.Ranged.Omaha.Iconic.Lizzie.Legendary,
Glossary.Weapons.Ranged.Overture.Iconic.Amnesty.Legendary,
Glossary.Weapons.Ranged.Overture.Iconic.Archangel.Legendary,
Glossary.Weapons.Ranged.Overture.Iconic.Crash.Legendary,
Glossary.Weapons.Ranged.Pulsar.Iconic.Buzzsaw.Legendary,
Glossary.Weapons.Ranged.Saratoga.Iconic.Fenrir.Legendary,
Glossary.Weapons.Ranged.Saratoga.Iconic.ProblemSolver.Legendary,
Glossary.Weapons.Ranged.Shingen.Iconic.Prototype.Legendary,
Glossary.Weapons.Ranged.Sidewinder.Iconic.DividedWeStand.Legendary,
Glossary.Weapons.Ranged.Silverhand.Legendary,
Glossary.Weapons.Ranged.Tactician.Iconic.Headsman.Legendary,
Glossary.Weapons.Ranged.Yukimara.Iconic.Genjiroh.Legendary,
Glossary.Weapons.Melee.BaseballBat.Iconic.GoldPlated.Legendary,
Glossary.Weapons.Melee.Baton.Iconic.TinkerBell.Legendary,
Glossary.Weapons.Melee.Cane.Iconic.Cottonmouth.Legendary,
Glossary.Weapons.Melee.Dildo.Iconic.Phallustiff.Legendary,
Glossary.Weapons.Melee.Katana.Iconic.BlackUnicorn.Legendary,
Glossary.Weapons.Melee.Katana.Iconic.Cocktail.Legendary,
Glossary.Weapons.Melee.Katana.Iconic.JinchuMaru.Legendary,
Glossary.Weapons.Melee.Katana.Iconic.Satori.Legendary,
Glossary.Weapons.Melee.Katana.Iconic.Scalpel.Legendary,
Glossary.Weapons.Melee.Katana.Iconic.Tsumetogi.Legendary,
Glossary.Weapons.Melee.Knife.Iconic.Stinger.Legendary,
Glossary.Weapons.Melee.Shovel.Iconic.Caretaker.Legendary,
Glossary.Weapons.Grenades.Ozob,
Glossary.Clothing.Face.Special.Police,
Glossary.Clothing.Face.Special.Corpo,
Glossary.Clothing.Face.Special.Fixer,
Glossary.Clothing.Face.Special.Media,
Glossary.Clothing.Face.Special.Techie,
Glossary.Clothing.Face.Special.Rocker,
Glossary.Clothing.Face.Special.Netrunner,
Glossary.Clothing.Face.Special.Nomad,
Glossary.Clothing.Face.Special.Solo,
Glossary.Clothing.Face.Special.Johnny.Legendary,
Glossary.Clothing.Head.Special.Media,
Glossary.Clothing.Head.Special.Techie,
Glossary.Clothing.Feet.Special.Police,
Glossary.Clothing.Feet.Special.Corpo,
Glossary.Clothing.Feet.Special.Fixer,
Glossary.Clothing.Feet.Special.Media,
Glossary.Clothing.Feet.Special.Netrunner,
Glossary.Clothing.Feet.Special.Nomad,
Glossary.Clothing.Feet.Special.Rocker,
Glossary.Clothing.Feet.Special.Solo,
Glossary.Clothing.Feet.Special.Techie,
Glossary.Clothing.Feet.Special.Johnny.Legendary,
Glossary.Clothing.Legs.Special.Police,
Glossary.Clothing.Legs.Special.Corpo,
Glossary.Clothing.Legs.Special.Fixer,
Glossary.Clothing.Legs.Special.Media,
Glossary.Clothing.Legs.Special.Netrunner,
Glossary.Clothing.Legs.Special.Nomad,
Glossary.Clothing.Legs.Special.Rocker,
Glossary.Clothing.Legs.Special.Solo,
Glossary.Clothing.Legs.Special.Techie,
Glossary.Clothing.Legs.Special.Johnny.Legendary,
Glossary.Clothing.OuterTorso.Special.Aldecaldo,
Glossary.Clothing.OuterTorso.Special.Corpo,
Glossary.Clothing.OuterTorso.Special.Fixer,
Glossary.Clothing.OuterTorso.Special.Media,
Glossary.Clothing.OuterTorso.Special.Nomad,
Glossary.Clothing.OuterTorso.Special.Police,
Glossary.Clothing.OuterTorso.Special.Rocker,
Glossary.Clothing.OuterTorso.Special.Johnny.Legendary,
Glossary.Clothing.OuterTorso.Special.Solo,
Glossary.Clothing.OuterTorso.Special.Techie,
Glossary.Clothing.OuterTorso.Special.Wolf.Legendary,
Glossary.Clothing.InnerTorso.Special.Corpo,
Glossary.Clothing.InnerTorso.Special.Fixer,
Glossary.Clothing.InnerTorso.Special.Media,
Glossary.Clothing.InnerTorso.Special.Netrunner,
Glossary.Clothing.InnerTorso.Special.Nomad,
Glossary.Clothing.InnerTorso.Special.Rocker,
Glossary.Clothing.InnerTorso.Special.Solo,
Glossary.Clothing.InnerTorso.Special.Techie,
Glossary.Clothing.InnerTorso.Special.Johnny.Legendary,
Glossary.Clothing.InnerTorso.Special.Wolf.Legendary,
Glossary.Clothing.InnerTorso.Special.Galaxy.Legendary,
Glossary.Cyberware.Arms.MantisBlades.Legendary,
Glossary.Cyberware.Arms.Monowire.Legendary,
Glossary.Cyberware.Arms.ProjectileLauncher.Legendary,
Glossary.Cyberware.Arms.GorillaArms.Legendary,
Glossary.Cyberware.Circulatory.AdrenalineBooster.Legendary,
Glossary.Cyberware.Circulatory.Bioconductor.Legendary,
Glossary.Cyberware.Circulatory.Biomonitor.Legendary,
Glossary.Cyberware.Circulatory.BloodPump.Legendary,
Glossary.Cyberware.Circulatory.BloodVessels.Legendary,
Glossary.Cyberware.Circulatory.FeedbackCircuit.Legendary,
Glossary.Cyberware.Circulatory.MicroGenerator.Legendary,
Glossary.Cyberware.Circulatory.SecondHeart.Legendary,
Glossary.Cyberware.Circulatory.SynLungs.Legendary,
Glossary.Cyberware.Deck.Arasaka.Legendary,
Glossary.Cyberware.Deck.Biodyne.Berserk.Legendary,
Glossary.Cyberware.Deck.Dynalay.Legendary,
Glossary.Cyberware.Deck.Fuyutsui.Iconic,
Glossary.Cyberware.Deck.Militech.Berserk.Iconic,
Glossary.Cyberware.Deck.Militech.Sandevistan.Iconic,
Glossary.Cyberware.Deck.Netwatch.Iconic,
Glossary.Cyberware.Deck.Qiant.Legendary,
Glossary.Cyberware.Deck.Qiant.Iconic,
Glossary.Cyberware.Deck.Raven.Legendary,
Glossary.Cyberware.Deck.Stephenson.Legendary,
Glossary.Cyberware.Deck.Tetratonic.Legendary,
Glossary.Cyberware.Deck.Zetatech.Berserk.Legendary,
Glossary.Cyberware.Deck.Zetatech.Berserk.Iconic,
Glossary.Cyberware.FrontalCortex.Camillo.Legendary,
Glossary.Cyberware.FrontalCortex.ExDisk.Legendary,
Glossary.Cyberware.FrontalCortex.HealOnKill.Legendary,
Glossary.Cyberware.FrontalCortex.Limbic.Legendary,
Glossary.Cyberware.FrontalCortex.Mechatronic.Legendary,
Glossary.Cyberware.FrontalCortex.SelfICE.Legendary,
Glossary.Cyberware.FrontalCortex.VisualCortex.Legendary,
Glossary.Cyberware.Hands.Ballistic.Legendary,
Glossary.Cyberware.Hands.SmartLink.Legendary,
Glossary.Cyberware.Immune.Cataresist.Legendary,
Glossary.Cyberware.Immune.PainEditor.Legendary,
Glossary.Cyberware.Immune.ShockAwe.Legendary,
Glossary.Cyberware.Integumentary.SubdermalArmor.Legendary,
Glossary.Cyberware.Nervous.Kerenzikov.Legendary,
Glossary.Cyberware.Nervous.Neofiber.Legendary,
Glossary.Cyberware.Nervous.ReflexTuner.Legendary,
Glossary.Cyberware.Nervous.SynapticAccel.Legendary,
Glossary.Cyberware.Skeleton.BionicLungs.Legendary,
Glossary.Cyberware.Skeleton.Microrotors.Legendary,
Glossary.Cyberware.Skeleton.MicroVibrationGen.Legendary,
Glossary.Cyberware.Skeleton.SynapticSignal.Legendary,
Glossary.Quickhacks.Contagion.Legendary,
Glossary.Quickhacks.CrippleMovement.Legendary,
Glossary.Quickhacks.Cyberpsychosis.Legendary,
Glossary.Quickhacks.DetonateGrenade.Legendary,
Glossary.Quickhacks.Overheat.Legendary,
Glossary.Quickhacks.Ping.Legendary,
Glossary.Quickhacks.RebootOptics.Legendary,
Glossary.Quickhacks.ShortCircuit.Legendary,
Glossary.Quickhacks.SonicShock.Legendary,
Glossary.Quickhacks.Suicide.Legendary,
Glossary.Quickhacks.SynapseBurnout.Legendary,
Glossary.Quickhacks.SystemReset.Legendary,
Glossary.Quickhacks.WeaponGlitch.Legendary,
Glossary.Mods.Clothing.Bully,
Glossary.Mods.Clothing.CoolIt,
Glossary.Mods.Clothing.DeadEye,
Glossary.Mods.Clothing.Fortuna,
Glossary.Mods.Clothing.Panacea,
Glossary.Mods.Clothing.Predator,
-- Glossary.Mods.Ranged.BeSmart, -- Disabled as this mod doesn't appear to actually be usable.
Glossary.Mods.Cyberware.Arms.GorillaArms.Battery.BlackMarket,
Glossary.Mods.Cyberware.Arms.GorillaArms.Battery.Rin3u,
Glossary.Mods.Cyberware.Arms.GorillaArms.Knuckles.Animals,
Glossary.Mods.Cyberware.Arms.MantisBlades.Rotor.Haming8,
Glossary.Mods.Cyberware.Deck.Berserk.BeastMode,
Glossary.Mods.Cyberware.Deck.Sandevistan.Arasaka,
Glossary.Mods.Cyberware.Deck.Sandevistan.MicroAmplifier,
Glossary.Mods.Cyberware.Eyes.TrajectoryAnalysis
},
Epic = {
Glossary.Weapons.Ranged.Achilles.Iconic.WidowMaker.Epic,
Glossary.Weapons.Ranged.Ajax.Iconic.MoronLabe.Epic,
Glossary.Weapons.Ranged.Burya.Iconic.ComradesHammer.Epic,
Glossary.Weapons.Ranged.Carnage.Iconic.Mox.Epic,
Glossary.Weapons.Ranged.Copperhead.Iconic.Psalm.Epic,
Glossary.Weapons.Ranged.Grad.Iconic.OFive.Epic,
Glossary.Weapons.Ranged.Grad.Iconic.Overwatch.Epic,
Glossary.Weapons.Ranged.Igla.Iconic.Sovereign.Epic,
Glossary.Weapons.Ranged.Kenshin.Iconic.Apparition.Epic,
Glossary.Weapons.Ranged.Kenshin.Iconic.Chaos.Epic,
Glossary.Weapons.Ranged.Lexington.Iconic.DyingNight.Epic,
Glossary.Weapons.Ranged.Liberty.Iconic.Kongou.Epic,
Glossary.Weapons.Ranged.Liberty.Iconic.PlanB.Epic,
Glossary.Weapons.Ranged.Nekomata.Iconic.Breakthrough.Epic,
Glossary.Weapons.Ranged.Nova.Iconic.DoomDoom.Epic,
Glossary.Weapons.Ranged.Nue.Iconic.ChingonaDorada.Epic,
Glossary.Weapons.Ranged.Nue.Iconic.DeathTaxes.Epic,
Glossary.Weapons.Ranged.Omaha.Iconic.Lizzie.Epic,
Glossary.Weapons.Ranged.Overture.Iconic.Amnesty.Epic,
Glossary.Weapons.Ranged.Overture.Iconic.Archangel.Epic,
Glossary.Weapons.Ranged.Overture.Iconic.Crash.Epic,
Glossary.Weapons.Ranged.Pulsar.Iconic.Buzzsaw.Epic,
Glossary.Weapons.Ranged.Saratoga.Iconic.Fenrir.Epic,
Glossary.Weapons.Ranged.Saratoga.Iconic.ProblemSolver.Epic,
Glossary.Weapons.Ranged.Sidewinder.Iconic.DividedWeStand.Epic,
Glossary.Weapons.Ranged.Tactician.Iconic.Headsman.Epic,
Glossary.Weapons.Ranged.Yukimara.Iconic.Genjiroh.Epic,
Glossary.Weapons.Ranged.Yukimara.Iconic.Skippy.Epic,
Glossary.Weapons.Melee.BaseballBat.Iconic.GoldPlated.Epic,
Glossary.Weapons.Melee.Baton.Iconic.TinkerBell.Epic,
Glossary.Weapons.Melee.Cane.Iconic.Cottonmouth.Epic,
Glossary.Weapons.Melee.Dildo.Iconic.Phallustiff.Epic,
Glossary.Weapons.Melee.Katana.Iconic.BlackUnicorn.Epic,
Glossary.Weapons.Melee.Katana.Iconic.Cocktail.Epic,
Glossary.Weapons.Melee.Katana.Iconic.JinchuMaru.Epic,
Glossary.Weapons.Melee.Katana.Iconic.Satori.Epic,
Glossary.Weapons.Melee.Katana.Iconic.Scalpel.Epic,
Glossary.Weapons.Melee.Katana.Iconic.Tsumetogi.Epic,
Glossary.Weapons.Melee.Knife.Iconic.Stinger.Epic,
Glossary.Weapons.Grenades.EMP.Homing,
Glossary.Weapons.Grenades.Gash,
Glossary.Weapons.Grenades.Incendiary.Homing,
Glossary.Clothing.Face.Special.Johnny.Epic,
Glossary.Clothing.Feet.Special.Johnny.Epic,
Glossary.Clothing.Legs.Special.Johnny.Epic,
Glossary.Clothing.OuterTorso.Special.Johnny.Epic,
Glossary.Clothing.OuterTorso.Special.Wolf.Epic,
Glossary.Clothing.InnerTorso.Special.Johnny.Epic,
Glossary.Clothing.InnerTorso.Special.Wolf.Epic,
Glossary.Clothing.InnerTorso.Special.Galaxy.Epic,
Glossary.Cyberware.Arms.MantisBlades.Epic,
Glossary.Cyberware.Arms.Monowire.Epic,
Glossary.Cyberware.Arms.ProjectileLauncher.Epic,
Glossary.Cyberware.Arms.GorillaArms.Epic,
Glossary.Cyberware.Circulatory.AdrenalineBooster.Epic,
Glossary.Cyberware.Circulatory.Bioconductor.Epic,
Glossary.Cyberware.Circulatory.Biomonitor.Epic,
Glossary.Cyberware.Circulatory.BloodPump.Epic,
Glossary.Cyberware.Circulatory.BloodVessels.Epic,
Glossary.Cyberware.Circulatory.FeedbackCircuit.Epic,
Glossary.Cyberware.Circulatory.MicroGenerator.Epic,
Glossary.Cyberware.Circulatory.SynLungs.Epic,
Glossary.Cyberware.Deck.Arasaka.Epic,
Glossary.Cyberware.Deck.Biodyne.Berserk.Epic,
Glossary.Cyberware.Deck.Biotech.Epic,
Glossary.Cyberware.Deck.Dynalay.Epic,
Glossary.Cyberware.Deck.MooreTech.Epic,
Glossary.Cyberware.Deck.Raven.Epic,
Glossary.Cyberware.Deck.Stephenson.Epic,
Glossary.Cyberware.Deck.Tetratonic.Epic,
Glossary.Cyberware.Deck.Zetatech.Sandevistan.Epic,
Glossary.Cyberware.FrontalCortex.Camillo.Epic,
Glossary.Cyberware.FrontalCortex.ExDisk.Epic,
Glossary.Cyberware.FrontalCortex.HealOnKill.Epic,
Glossary.Cyberware.FrontalCortex.Mechatronic.Epic,
Glossary.Cyberware.FrontalCortex.MemoryBoost.Epic,
Glossary.Cyberware.FrontalCortex.VisualCortex.Epic,
Glossary.Cyberware.Hands.Ballistic.Epic,
Glossary.Cyberware.Hands.SmartLink.Epic,
Glossary.Cyberware.Immune.Cataresist.Epic,
Glossary.Cyberware.Immune.Inductor.Epic,
Glossary.Cyberware.Immune.Metabolic.Epic,
Glossary.Cyberware.Immune.ShockAwe.Epic,
Glossary.Cyberware.Integumentary.HeatConverter.Epic,
Glossary.Cyberware.Integumentary.SubdermalArmor.Epic,
Glossary.Cyberware.Legs.FortifiedAnkles.Epic,
Glossary.Cyberware.Legs.LynxPaws.Epic,
Glossary.Cyberware.Nervous.Kerenzikov.Epic,
Glossary.Cyberware.Nervous.Nanorelays.Epic,
Glossary.Cyberware.Nervous.Neofiber.Epic,
Glossary.Cyberware.Nervous.SynapticAccel.Epic,
Glossary.Cyberware.Ocular.Kiroshi.Epic,
Glossary.Cyberware.Skeleton.BionicJoints.Epic,
Glossary.Cyberware.Skeleton.BionicLungs.Epic,
Glossary.Cyberware.Skeleton.DenseMarrow.Epic,
Glossary.Cyberware.Skeleton.Microrotors.Epic,
Glossary.Cyberware.Skeleton.SynapticSignal.Epic,
Glossary.Quickhacks.Contagion.Epic,
Glossary.Quickhacks.CrippleMovement.Epic,
Glossary.Quickhacks.Cyberpsychosis.Epic,
Glossary.Quickhacks.CyberwareMalfunction.Epic,
Glossary.Quickhacks.DetonateGrenade.Epic,
Glossary.Quickhacks.MemoryWipe.Epic,
Glossary.Quickhacks.Overheat.Epic,
Glossary.Quickhacks.Ping.Epic,
Glossary.Quickhacks.RebootOptics.Epic,
Glossary.Quickhacks.RequestBackup.Epic,
Glossary.Quickhacks.ShortCircuit.Epic,
Glossary.Quickhacks.SonicShock.Epic,
Glossary.Quickhacks.Suicide.Epic,
Glossary.Quickhacks.SynapseBurnout.Epic,
Glossary.Quickhacks.SystemReset.Epic,
Glossary.Quickhacks.WeaponGlitch.Epic,
Glossary.Quickhacks.Whistle.Epic,
Glossary.Mods.Clothing.AntiVenom,
Glossary.Mods.Clothing.CutItOut,
Glossary.Mods.Clothing.SoftSole,
Glossary.Mods.Clothing.SuperInsulator,
-- Glossary.Mods.Ranged.Bouncy, -- Disabled as this mod doesn't appear to actually be usable.
-- Glossary.Mods.Ranged.ChargeSpike, -- Disabled as this mod doesn't appear to actually be usable.
Glossary.Mods.Ranged.CounterMass,
Glossary.Mods.Ranged.Iconic.Archangel,
Glossary.Mods.Ranged.Iconic.Amnesty,
Glossary.Mods.Ranged.Iconic.Apparition,
Glossary.Mods.Ranged.Iconic.BaXingChong,
Glossary.Mods.Ranged.Iconic.Breakthrough,
Glossary.Mods.Ranged.Iconic.Buzzsaw,
Glossary.Mods.Ranged.Iconic.Chaos,
Glossary.Mods.Ranged.Iconic.ChingonaDorada,
Glossary.Mods.Ranged.Iconic.ComradesHammer,
Glossary.Mods.Ranged.Iconic.Crash,
Glossary.Mods.Ranged.Iconic.DeathTaxes,
Glossary.Mods.Ranged.Iconic.DividedWeStand,
Glossary.Mods.Ranged.Iconic.DoomDoom,
Glossary.Mods.Ranged.Iconic.DyingNight,
Glossary.Mods.Ranged.Iconic.Fenrir,
Glossary.Mods.Ranged.Iconic.Genjiroh,
Glossary.Mods.Ranged.Iconic.Headsman,
Glossary.Mods.Ranged.Iconic.Kongou,
Glossary.Mods.Ranged.Iconic.Lizzie,
Glossary.Mods.Ranged.Iconic.MoronLabe,
Glossary.Mods.Ranged.Iconic.Mox,
Glossary.Mods.Ranged.Iconic.OFive,
Glossary.Mods.Ranged.Iconic.Overwatch,
Glossary.Mods.Ranged.Iconic.PlanB,
Glossary.Mods.Ranged.Iconic.Prejudice,
Glossary.Mods.Ranged.Iconic.Pride,
Glossary.Mods.Ranged.Iconic.Psalm,
Glossary.Mods.Ranged.Iconic.ProblemSolver,
Glossary.Mods.Ranged.Iconic.Shingen,
Glossary.Mods.Ranged.Iconic.Sovereign,
Glossary.Mods.Ranged.Iconic.WidowMaker,
Glossary.Mods.Ranged.Iconic.YingLong,
Glossary.Mods.Melee.Iconic.Caretaker,
Glossary.Mods.Melee.Iconic.Cocktail,
Glossary.Mods.Melee.Iconic.Cottonmouth,
Glossary.Mods.Melee.Iconic.GoldPlated,
Glossary.Mods.Melee.Iconic.JinchuMaru,
Glossary.Mods.Melee.Iconic.Phallustiff,
Glossary.Mods.Melee.Iconic.Satori,
Glossary.Mods.Melee.Iconic.Scalpel,
Glossary.Mods.Melee.Iconic.Stinger,
Glossary.Mods.Melee.Iconic.TinkerBell,
Glossary.Mods.Melee.Iconic.Tsumetogi,
Glossary.Mods.Cyberware.Arms.GorillaArms.Battery.High,
Glossary.Mods.Cyberware.Arms.GorillaArms.Battery.Medium,
Glossary.Mods.Cyberware.Arms.MantisBlades.Rotor.Fast,
Glossary.Mods.Cyberware.Arms.Monowire.Battery.High,
Glossary.Mods.Cyberware.Arms.Monowire.Battery.Medium,
Glossary.Mods.Cyberware.Arms.ProjectileLauncher.Plating.Titanium,
Glossary.Mods.Cyberware.Deck.Sandevistan.RapidBull,
Glossary.Mods.Cyberware.Deck.Sandevistan.TygerPaw
},
Rare = {
Glossary.Weapons.Ranged.Achilles.Iconic.WidowMaker.Rare,
Glossary.Weapons.Ranged.Carnage.Iconic.Mox.Rare,
Glossary.Weapons.Ranged.Copperhead.Iconic.Psalm.Rare,
Glossary.Weapons.Ranged.Grad.Iconic.Overwatch.Rare,
Glossary.Weapons.Ranged.Kenshin.Iconic.Chaos.Rare,
Glossary.Weapons.Ranged.Lexington.Iconic.DyingNight.Rare,
Glossary.Weapons.Ranged.Liberty.Iconic.Kongou.Rare,
Glossary.Weapons.Ranged.Liberty.Iconic.PlanB.Rare,
Glossary.Weapons.Ranged.Nova.Iconic.DoomDoom.Rare,
Glossary.Weapons.Ranged.Nue.Iconic.ChingonaDorada.Rare,
Glossary.Weapons.Ranged.Nue.Iconic.DeathTaxes.Rare,
Glossary.Weapons.Ranged.Omaha.Iconic.Lizzie.Rare,
Glossary.Weapons.Ranged.Overture.Iconic.Archangel.Rare,
Glossary.Weapons.Ranged.Pulsar.Iconic.Buzzsaw.Rare,
Glossary.Weapons.Ranged.Saratoga.Iconic.Fenrir.Rare,
Glossary.Weapons.Ranged.Saratoga.Iconic.ProblemSolver.Rare,
Glossary.Weapons.Ranged.Sidewinder.Iconic.DividedWeStand.Rare,
Glossary.Weapons.Melee.BaseballBat.Iconic.GoldPlated.Rare,
Glossary.Weapons.Melee.Baton.Iconic.TinkerBell.Rare,
Glossary.Weapons.Melee.Cane.Iconic.Cottonmouth.Rare,
Glossary.Weapons.Melee.Dildo.Iconic.Phallustiff.Rare,
Glossary.Weapons.Melee.Katana.Iconic.BlackUnicorn.Rare,
Glossary.Weapons.Melee.Katana.Iconic.Cocktail.Rare,
Glossary.Weapons.Melee.Katana.Iconic.Satori.Rare,
Glossary.Weapons.Melee.Katana.Iconic.Scalpel.Rare,
Glossary.Weapons.Melee.Katana.Iconic.Tsumetogi.Rare,
Glossary.Weapons.Melee.Knife.Iconic.Stinger.Rare,
Glossary.Weapons.Grenades.Biohazard.Homing,
Glossary.Weapons.Grenades.EMP.Sticky,
Glossary.Weapons.Grenades.Flash.Homing,
Glossary.Weapons.Grenades.Frag.Homing,
Glossary.Weapons.Grenades.Incendiary.Sticky,
Glossary.Clothing.Face.Special.Johnny.Rare,
Glossary.Clothing.Feet.Special.Johnny.Rare,
Glossary.Clothing.Legs.Special.Johnny.Rare,
Glossary.Clothing.OuterTorso.Special.Johnny.Rare,
Glossary.Clothing.OuterTorso.Special.Wolf.Rare,
Glossary.Clothing.InnerTorso.Special.Johnny.Rare,
Glossary.Clothing.InnerTorso.Special.Wolf.Rare,
Glossary.Clothing.InnerTorso.Special.Galaxy.Rare,
Glossary.Cyberware.Arms.MantisBlades.Rare,
Glossary.Cyberware.Arms.Monowire.Rare,
Glossary.Cyberware.Arms.ProjectileLauncher.Rare,
Glossary.Cyberware.Arms.GorillaArms.Rare,
Glossary.Cyberware.Circulatory.AdrenalineBooster.Rare,
Glossary.Cyberware.Circulatory.Bioconductor.Rare,
Glossary.Cyberware.Circulatory.Biomonitor.Rare,
Glossary.Cyberware.Circulatory.BloodPump.Rare,
Glossary.Cyberware.Circulatory.BloodVessels.Rare,
Glossary.Cyberware.Circulatory.FeedbackCircuit.Rare,
Glossary.Cyberware.Circulatory.MicroGenerator.Rare,
Glossary.Cyberware.Circulatory.SynLungs.Rare,
Glossary.Cyberware.Deck.Biodyne.Rare,
Glossary.Cyberware.Deck.Biodyne.Berserk.Rare,
Glossary.Cyberware.Deck.Biotech.Rare,
Glossary.Cyberware.Deck.Dynalay.Rare,
Glossary.Cyberware.Deck.MooreTech.Rare,
Glossary.Cyberware.Deck.Seocho.Rare,
Glossary.Cyberware.Deck.Stephenson.Rare,
Glossary.Cyberware.Deck.Tetratonic.Rare,
Glossary.Cyberware.Deck.Zetatech.Sandevistan.Rare,
Glossary.Cyberware.FrontalCortex.ExDisk.Rare,
Glossary.Cyberware.FrontalCortex.Limbic.Rare,
Glossary.Cyberware.FrontalCortex.Mechatronic.Rare,
Glossary.Cyberware.FrontalCortex.MemoryBoost.Rare,
Glossary.Cyberware.FrontalCortex.RAMUpgrade.Rare,
Glossary.Cyberware.Hands.Ballistic.Rare,
Glossary.Cyberware.Hands.SmartLink.Rare,
Glossary.Cyberware.Immune.Detoxifier.Rare,
Glossary.Cyberware.Integumentary.FireproofCoating.Rare,
Glossary.Cyberware.Integumentary.GroundingPlating.Rare,
Glossary.Cyberware.Integumentary.SubdermalArmor.Rare,
Glossary.Cyberware.Integumentary.SupraDermalWeave.Rare,
Glossary.Cyberware.Legs.BoostedTendons.Rare,
Glossary.Cyberware.Legs.FortifiedAnkles.Rare,
Glossary.Cyberware.Nervous.Kerenzikov.Rare,
Glossary.Cyberware.Nervous.Maneuvering.Rare,
Glossary.Cyberware.Nervous.Nanorelays.Rare,
Glossary.Cyberware.Nervous.Neofiber.Rare,
Glossary.Cyberware.Nervous.ReflexTuner.Rare,
Glossary.Cyberware.Nervous.SynapticAccel.Rare,
Glossary.Cyberware.Ocular.Kiroshi.Rare,
Glossary.Cyberware.Skeleton.BionicJoints.Rare,
Glossary.Cyberware.Skeleton.BionicLungs.Rare,
Glossary.Cyberware.Skeleton.DenseMarrow.Rare,
Glossary.Cyberware.Skeleton.Microrotors.Rare,
Glossary.Cyberware.Skeleton.MicroVibrationGen.Rare,
Glossary.Cyberware.Skeleton.SynapticSignal.Rare,
Glossary.Cyberware.Skeleton.TitaniumBones.Rare,
Glossary.Quickhacks.Contagion.Rare,
Glossary.Quickhacks.CrippleMovement.Rare,
Glossary.Quickhacks.CyberwareMalfunction.Rare,
Glossary.Quickhacks.MemoryWipe.Rare,
Glossary.Quickhacks.Overheat.Rare,
Glossary.Quickhacks.Ping.Rare,
Glossary.Quickhacks.RebootOptics.Rare,
Glossary.Quickhacks.ShortCircuit.Rare,
Glossary.Quickhacks.SonicShock.Rare,
Glossary.Quickhacks.SynapseBurnout.Rare,
Glossary.Quickhacks.WeaponGlitch.Rare,
Glossary.Quickhacks.Whistle.Rare,
Glossary.Mods.Ranged.Autoloader,
Glossary.Mods.Ranged.CombatAmplifier,
Glossary.Mods.Ranged.Phantom,
Glossary.Mods.Ranged.NeonArrow,
Glossary.Mods.Ranged.Vendetta,
Glossary.Mods.Ranged.Weaken,
Glossary.Mods.Melee.ColdShoulder,
Glossary.Mods.Melee.Kunai,
Glossary.Mods.Melee.Scourge,
Glossary.Mods.Melee.WhiteKnuckled,
Glossary.Mods.Cyberware.Arms.GorillaArms.Battery.Low,
Glossary.Mods.Cyberware.Arms.GorillaArms.Knuckles.Chemical,
Glossary.Mods.Cyberware.Arms.GorillaArms.Knuckles.Electrical,
Glossary.Mods.Cyberware.Arms.GorillaArms.Knuckles.Physical,
Glossary.Mods.Cyberware.Arms.GorillaArms.Knuckles.Thermal,
Glossary.Mods.Cyberware.Arms.MantisBlades.Edge.Chemical,
Glossary.Mods.Cyberware.Arms.MantisBlades.Edge.Electrical,
Glossary.Mods.Cyberware.Arms.MantisBlades.Edge.Physical,
Glossary.Mods.Cyberware.Arms.MantisBlades.Edge.Thermal,
Glossary.Mods.Cyberware.Arms.MantisBlades.Rotor.Slow,
Glossary.Mods.Cyberware.Arms.Monowire.Cable.Chemical,
Glossary.Mods.Cyberware.Arms.Monowire.Cable.Electrical,
Glossary.Mods.Cyberware.Arms.Monowire.Cable.Physical,
Glossary.Mods.Cyberware.Arms.Monowire.Cable.Thermal,
Glossary.Mods.Cyberware.Arms.ProjectileLauncher.Round.Chemical,
Glossary.Mods.Cyberware.Arms.ProjectileLauncher.Round.Electrical,
Glossary.Mods.Cyberware.Arms.ProjectileLauncher.Round.Explosive,
Glossary.Mods.Cyberware.Arms.ProjectileLauncher.Round.Incendiary,
Glossary.Mods.Cyberware.Arms.ProjectileLauncher.Round.Thermal,
Glossary.Mods.Cyberware.Arms.ProjectileLauncher.Round.Tranquilizer,
Glossary.Mods.Cyberware.Arms.ProjectileLauncher.Plating.Metal,
Glossary.Mods.Cyberware.Arms.ProjectileLauncher.Plating.Neoplastic,
Glossary.Mods.Cyberware.Arms.Universal.SensoryAmplifier.Armor,
Glossary.Mods.Cyberware.Arms.Universal.SensoryAmplifier.CritChance,
Glossary.Mods.Cyberware.Arms.Universal.SensoryAmplifier.CritDamage,
Glossary.Mods.Cyberware.Arms.Universal.SensoryAmplifier.Health,
Glossary.Mods.Cyberware.Deck.Berserk.Devastating,
Glossary.Mods.Cyberware.Deck.Berserk.Sharpened,
Glossary.Mods.Cyberware.Deck.Sandevistan.NeuroTransmitters,
Glossary.Mods.Cyberware.Deck.Sandevistan.Prototype,
Glossary.Mods.Cyberware.Eyes.TargetAnalysis,
Glossary.Mods.Cyberware.Eyes.ThreatDetector,
Glossary.Attachments.Silencer.Alecto
},
Uncommon = {
Glossary.Weapons.Ranged.Lexington.Iconic.DyingNight.Uncommon,
Glossary.Weapons.Grenades.Biohazard.Regular,
Glossary.Weapons.Grenades.EMP.Regular,
Glossary.Weapons.Grenades.Frag.Sticky,
Glossary.Weapons.Grenades.Incendiary.Regular,
Glossary.Weapons.Grenades.Recon.Regular,
Glossary.Weapons.Grenades.Recon.Sticky,
Glossary.Cyberware.Circulatory.AdrenalineBooster.Uncommon,
Glossary.Cyberware.Circulatory.Biomonitor.Uncommon,
Glossary.Cyberware.Circulatory.BloodPump.Uncommon,
Glossary.Cyberware.Circulatory.BloodVessels.Uncommon,
Glossary.Cyberware.Circulatory.MicroGenerator.Uncommon,
Glossary.Cyberware.Circulatory.SynLungs.Uncommon,
Glossary.Cyberware.Circulatory.TyrosineInjector.Uncommon,
Glossary.Cyberware.Deck.Biodyne.Uncommon,
Glossary.Cyberware.Deck.Biodyne.Berserk.Uncommon,
Glossary.Cyberware.Deck.Biotech.Uncommon,
Glossary.Cyberware.Deck.Dynalay.Uncommon,
Glossary.Cyberware.Deck.MooreTech.Uncommon,
Glossary.Cyberware.Deck.Seocho.Uncommon,
Glossary.Cyberware.Deck.Tetratonic.Uncommon,
Glossary.Cyberware.Deck.Zetatech.Sandevistan.Uncommon,
Glossary.Cyberware.FrontalCortex.HealOnKill.Uncommon,
Glossary.Cyberware.FrontalCortex.Mechatronic.Uncommon,
Glossary.Cyberware.FrontalCortex.MemoryBoost.Uncommon,
Glossary.Cyberware.FrontalCortex.RAMUpgrade.Uncommon,
Glossary.Cyberware.FrontalCortex.VisualCortex.Uncommon,
Glossary.Cyberware.Immune.Cataresist.Uncommon,
Glossary.Cyberware.Immune.ShockAwe.Uncommon,
Glossary.Cyberware.Integumentary.SubdermalArmor.Uncommon,
Glossary.Cyberware.Nervous.Kerenzikov.Uncommon,
Glossary.Cyberware.Nervous.Nanorelays.Uncommon,
Glossary.Cyberware.Nervous.Neofiber.Uncommon,
Glossary.Cyberware.Nervous.ReflexTuner.Uncommon,
Glossary.Cyberware.Nervous.SynapticAccel.Uncommon,
Glossary.Cyberware.Skeleton.BionicLungs.Uncommon,
Glossary.Cyberware.Skeleton.DenseMarrow.Uncommon,
Glossary.Cyberware.Skeleton.Microrotors.Uncommon,
Glossary.Cyberware.Skeleton.MicroVibrationGen.Uncommon,
Glossary.Cyberware.Skeleton.SynapticSignal.Uncommon,
Glossary.Cyberware.Skeleton.TitaniumBones.Uncommon,
Glossary.Quickhacks.Contagion.Uncommon,
Glossary.Quickhacks.CrippleMovement.Uncommon,
Glossary.Quickhacks.CyberwareMalfunction.Uncommon,
Glossary.Quickhacks.Overheat.Uncommon,
Glossary.Quickhacks.Ping.Uncommon,
Glossary.Quickhacks.RebootOptics.Uncommon,
Glossary.Quickhacks.RequestBackup.Uncommon,
Glossary.Quickhacks.ShortCircuit.Uncommon,
Glossary.Quickhacks.SonicShock.Uncommon,
Glossary.Quickhacks.WeaponGlitch.Uncommon,
Glossary.Quickhacks.Whistle.Uncommon,
Glossary.Mods.Ranged.Pax,
Glossary.Mods.Ranged.Pulverize,
Glossary.Mods.Cyberware.Deck.Sandevistan.Heatsink,
Glossary.Mods.Cyberware.Eyes.ExplosiveAnalysis,
Glossary.Mods.Cyberware.Eyes.TrajectoryGenerator,
Glossary.Mods.Cyberware.Eyes.WeakspotDetection,
Glossary.Attachments.Silencer.Cetus,
Glossary.Attachments.Silencer.Strix
},
Common = {
Glossary.Weapons.Grenades.Flash.Regular,
Glossary.Weapons.Grenades.Frag.Regular,
Glossary.Cyberware.Circulatory.AdrenalineBooster.Common,
Glossary.Cyberware.Circulatory.Biomonitor.Common,
Glossary.Cyberware.Circulatory.BloodPump.Common,
Glossary.Cyberware.Circulatory.BloodVessels.Common,
Glossary.Cyberware.Circulatory.MicroGenerator.Common,
Glossary.Cyberware.Circulatory.SynLungs.Common,
Glossary.Cyberware.Deck.Fuyutsui.Common,
Glossary.Cyberware.Deck.Militech.Common,
Glossary.Cyberware.FrontalCortex.HealOnKill.Common,
Glossary.Cyberware.FrontalCortex.Limbic.Common,
Glossary.Cyberware.FrontalCortex.Mechatronic.Common,
Glossary.Cyberware.FrontalCortex.MemoryBoost.Common,
Glossary.Cyberware.FrontalCortex.RAMUpgrade.Common,
Glossary.Cyberware.FrontalCortex.VisualCortex.Common,
Glossary.Cyberware.Immune.Cataresist.Common,
Glossary.Cyberware.Immune.ShockAwe.Common,
Glossary.Cyberware.Integumentary.SubdermalArmor.Common,
Glossary.Cyberware.Nervous.Kerenzikov.Common,
Glossary.Cyberware.Nervous.Neofiber.Common,
Glossary.Cyberware.Nervous.ReflexTuner.Common,
Glossary.Cyberware.Nervous.SynapticAccel.Common,
Glossary.Cyberware.Ocular.Kiroshi.Common,
Glossary.Cyberware.Skeleton.BionicLungs.Common,
Glossary.Cyberware.Skeleton.Microrotors.Common,
Glossary.Cyberware.Skeleton.SynapticSignal.Common,
Glossary.Cyberware.Skeleton.TitaniumBones.Common,
Glossary.Attachments.Silencer.Taipan
}
}
-- This also implies the item cannot be levelled.
Glossary.IsStackable = {
Glossary.Resources.Money,
Glossary.Resources.Ammo.Handgun,
Glossary.Resources.Ammo.Rifle,
Glossary.Resources.Ammo.Shotgun,
Glossary.Resources.Ammo.SniperRifle,
Glossary.Resources.Ammo.Special,
Glossary.Resources.Components.Crafting.Legendary,
Glossary.Resources.Components.Crafting.Epic,
Glossary.Resources.Components.Crafting.Rare,
Glossary.Resources.Components.Crafting.Uncommon,
Glossary.Resources.Components.Crafting.Common,
Glossary.Resources.Components.Upgrade.Legendary,
Glossary.Resources.Components.Upgrade.Epic,
Glossary.Resources.Components.Upgrade.Rare,
Glossary.Resources.Components.Quickhack.Legendary,
Glossary.Resources.Components.Quickhack.Epic,
Glossary.Resources.Components.Quickhack.Rare,
Glossary.Resources.Components.Quickhack.Uncommon,
Glossary.Resources.Consumables.Booster.Capacity,
Glossary.Resources.Consumables.Booster.Health,
Glossary.Resources.Consumables.Booster.Oxygen,
Glossary.Resources.Consumables.Booster.Stamina,
Glossary.Resources.Consumables.Booster.Armor,
Glossary.Resources.Medicine.MaxDoc.Uncommon,
Glossary.Resources.Medicine.MaxDoc.Rare,
Glossary.Resources.Medicine.MaxDoc.Epic,
Glossary.Resources.Medicine.BounceBack.Common,
Glossary.Resources.Medicine.BounceBack.Uncommon,
Glossary.Resources.Medicine.BounceBack.Rare,
Glossary.Weapons.Grenades.Biohazard.Homing,
Glossary.Weapons.Grenades.Biohazard.Regular,
Glossary.Weapons.Grenades.EMP.Homing,
Glossary.Weapons.Grenades.EMP.Regular,
Glossary.Weapons.Grenades.EMP.Sticky,
Glossary.Weapons.Grenades.Flash.Homing,
Glossary.Weapons.Grenades.Flash.Regular,
Glossary.Weapons.Grenades.Frag.Homing,
Glossary.Weapons.Grenades.Frag.Regular,
Glossary.Weapons.Grenades.Frag.Sticky,
Glossary.Weapons.Grenades.Gash,
Glossary.Weapons.Grenades.Incendiary.Homing,
Glossary.Weapons.Grenades.Incendiary.Regular,
Glossary.Weapons.Grenades.Incendiary.Sticky,
Glossary.Weapons.Grenades.Recon.Regular,
Glossary.Weapons.Grenades.Recon.Sticky,
Glossary.Weapons.Grenades.Ozob
}
Glossary.CannotBeLevelled = {
Glossary.Cyberware.Arms.MantisBlades.Legendary,
Glossary.Cyberware.Arms.Monowire.Legendary,
Glossary.Cyberware.Arms.ProjectileLauncher.Legendary,
Glossary.Cyberware.Arms.GorillaArms.Legendary,
Glossary.Cyberware.Circulatory.AdrenalineBooster.Legendary,
Glossary.Cyberware.Circulatory.Bioconductor.Legendary,
Glossary.Cyberware.Circulatory.Biomonitor.Legendary,
Glossary.Cyberware.Circulatory.BloodPump.Legendary,
Glossary.Cyberware.Circulatory.BloodVessels.Legendary,
Glossary.Cyberware.Circulatory.FeedbackCircuit.Legendary,
Glossary.Cyberware.Circulatory.MicroGenerator.Legendary,
Glossary.Cyberware.Circulatory.SecondHeart.Legendary,
Glossary.Cyberware.Circulatory.SynLungs.Legendary,
Glossary.Cyberware.Deck.Arasaka.Legendary,
Glossary.Cyberware.Deck.Biodyne.Berserk.Legendary,
Glossary.Cyberware.Deck.Dynalay.Legendary,
Glossary.Cyberware.Deck.Fuyutsui.Iconic,
Glossary.Cyberware.Deck.Militech.Berserk.Iconic,
Glossary.Cyberware.Deck.Militech.Sandevistan.Iconic,
Glossary.Cyberware.Deck.Netwatch.Iconic,
Glossary.Cyberware.Deck.Qiant.Legendary,
Glossary.Cyberware.Deck.Qiant.Iconic,
Glossary.Cyberware.Deck.Raven.Legendary,
Glossary.Cyberware.Deck.Stephenson.Legendary,
Glossary.Cyberware.Deck.Tetratonic.Legendary,
Glossary.Cyberware.Deck.Zetatech.Berserk.Legendary,
Glossary.Cyberware.Deck.Zetatech.Berserk.Iconic,
Glossary.Cyberware.FrontalCortex.Camillo.Legendary,
Glossary.Cyberware.FrontalCortex.ExDisk.Legendary,
Glossary.Cyberware.FrontalCortex.HealOnKill.Legendary,
Glossary.Cyberware.FrontalCortex.Limbic.Legendary,
Glossary.Cyberware.FrontalCortex.Mechatronic.Legendary,
Glossary.Cyberware.FrontalCortex.SelfICE.Legendary,
Glossary.Cyberware.FrontalCortex.VisualCortex.Legendary,
Glossary.Cyberware.Hands.Ballistic.Legendary,
Glossary.Cyberware.Hands.SmartLink.Legendary,
Glossary.Cyberware.Immune.Cataresist.Legendary,
Glossary.Cyberware.Immune.PainEditor.Legendary,
Glossary.Cyberware.Immune.ShockAwe.Legendary,
Glossary.Cyberware.Integumentary.SubdermalArmor.Legendary,
Glossary.Cyberware.Nervous.Kerenzikov.Legendary,
Glossary.Cyberware.Nervous.Neofiber.Legendary,
Glossary.Cyberware.Nervous.ReflexTuner.Legendary,
Glossary.Cyberware.Nervous.SynapticAccel.Legendary,
Glossary.Cyberware.Skeleton.BionicLungs.Legendary,
Glossary.Cyberware.Skeleton.Microrotors.Legendary,
Glossary.Cyberware.Skeleton.MicroVibrationGen.Legendary,
Glossary.Cyberware.Skeleton.SynapticSignal.Legendary,
Glossary.Cyberware.Arms.MantisBlades.Epic,
Glossary.Cyberware.Arms.Monowire.Epic,
Glossary.Cyberware.Arms.ProjectileLauncher.Epic,
Glossary.Cyberware.Arms.GorillaArms.Epic,
Glossary.Cyberware.Circulatory.AdrenalineBooster.Epic,
Glossary.Cyberware.Circulatory.Bioconductor.Epic,
Glossary.Cyberware.Circulatory.Biomonitor.Epic,
Glossary.Cyberware.Circulatory.BloodPump.Epic,
Glossary.Cyberware.Circulatory.BloodVessels.Epic,
Glossary.Cyberware.Circulatory.FeedbackCircuit.Epic,
Glossary.Cyberware.Circulatory.MicroGenerator.Epic,
Glossary.Cyberware.Circulatory.SynLungs.Epic,
Glossary.Cyberware.Deck.Arasaka.Epic,
Glossary.Cyberware.Deck.Biodyne.Berserk.Epic,
Glossary.Cyberware.Deck.Biotech.Epic,
Glossary.Cyberware.Deck.Dynalay.Epic,
Glossary.Cyberware.Deck.MooreTech.Epic,
Glossary.Cyberware.Deck.Raven.Epic,
Glossary.Cyberware.Deck.Stephenson.Epic,
Glossary.Cyberware.Deck.Tetratonic.Epic,
Glossary.Cyberware.Deck.Zetatech.Sandevistan.Epic,
Glossary.Cyberware.FrontalCortex.Camillo.Epic,
Glossary.Cyberware.FrontalCortex.ExDisk.Epic,
Glossary.Cyberware.FrontalCortex.HealOnKill.Epic,
Glossary.Cyberware.FrontalCortex.Limbic.Epic,
Glossary.Cyberware.FrontalCortex.Mechatronic.Epic,
Glossary.Cyberware.FrontalCortex.MemoryBoost.Epic,
Glossary.Cyberware.FrontalCortex.VisualCortex.Epic,
Glossary.Cyberware.Hands.Ballistic.Epic,
Glossary.Cyberware.Hands.SmartLink.Epic,
Glossary.Cyberware.Immune.Cataresist.Epic,
Glossary.Cyberware.Immune.Inductor.Epic,
Glossary.Cyberware.Immune.Metabolic.Epic,
Glossary.Cyberware.Immune.ShockAwe.Epic,
Glossary.Cyberware.Integumentary.HeatConverter.Epic,
Glossary.Cyberware.Integumentary.SubdermalArmor.Epic,
Glossary.Cyberware.Legs.FortifiedAnkles.Epic,
Glossary.Cyberware.Legs.LynxPaws.Epic,
Glossary.Cyberware.Nervous.Kerenzikov.Epic,
Glossary.Cyberware.Nervous.Nanorelays.Epic,
Glossary.Cyberware.Nervous.Neofiber.Epic,
Glossary.Cyberware.Nervous.SynapticAccel.Epic,
Glossary.Cyberware.Ocular.Kiroshi.Epic,
Glossary.Cyberware.Skeleton.BionicJoints.Epic,
Glossary.Cyberware.Skeleton.BionicLungs.Epic,
Glossary.Cyberware.Skeleton.DenseMarrow.Epic,
Glossary.Cyberware.Skeleton.Microrotors.Epic,
Glossary.Cyberware.Skeleton.SynapticSignal.Epic,
Glossary.Cyberware.Arms.MantisBlades.Rare,
Glossary.Cyberware.Arms.Monowire.Rare,
Glossary.Cyberware.Arms.ProjectileLauncher.Rare,
Glossary.Cyberware.Arms.GorillaArms.Rare,
Glossary.Cyberware.Circulatory.AdrenalineBooster.Rare,
Glossary.Cyberware.Circulatory.Bioconductor.Rare,
Glossary.Cyberware.Circulatory.Biomonitor.Rare,
Glossary.Cyberware.Circulatory.BloodPump.Rare,
Glossary.Cyberware.Circulatory.BloodVessels.Rare,
Glossary.Cyberware.Circulatory.FeedbackCircuit.Rare,
Glossary.Cyberware.Circulatory.MicroGenerator.Rare,
Glossary.Cyberware.Circulatory.SynLungs.Rare,
Glossary.Cyberware.Deck.Biodyne.Rare,
Glossary.Cyberware.Deck.Biodyne.Berserk.Rare,
Glossary.Cyberware.Deck.Biotech.Rare,
Glossary.Cyberware.Deck.Dynalay.Rare,
Glossary.Cyberware.Deck.MooreTech.Rare,
Glossary.Cyberware.Deck.Seocho.Rare,
Glossary.Cyberware.Deck.Stephenson.Rare,
Glossary.Cyberware.Deck.Tetratonic.Rare,
Glossary.Cyberware.Deck.Zetatech.Sandevistan.Rare,
Glossary.Cyberware.FrontalCortex.ExDisk.Rare,
Glossary.Cyberware.FrontalCortex.Limbic.Rare,
Glossary.Cyberware.FrontalCortex.Mechatronic.Rare,
Glossary.Cyberware.FrontalCortex.MemoryBoost.Rare,
Glossary.Cyberware.FrontalCortex.RAMUpgrade.Rare,
Glossary.Cyberware.Hands.Ballistic.Rare,
Glossary.Cyberware.Hands.SmartLink.Rare,
Glossary.Cyberware.Immune.Detoxifier.Rare,
Glossary.Cyberware.Integumentary.FireproofCoating.Rare,
Glossary.Cyberware.Integumentary.GroundingPlating.Rare,
Glossary.Cyberware.Integumentary.SubdermalArmor.Rare,
Glossary.Cyberware.Integumentary.SupraDermalWeave.Rare,
Glossary.Cyberware.Legs.BoostedTendons.Rare,
Glossary.Cyberware.Legs.FortifiedAnkles.Rare,
Glossary.Cyberware.Nervous.Kerenzikov.Rare,
Glossary.Cyberware.Nervous.Maneuvering.Rare,
Glossary.Cyberware.Nervous.Nanorelays.Rare,
Glossary.Cyberware.Nervous.Neofiber.Rare,
Glossary.Cyberware.Nervous.ReflexTuner.Rare,
Glossary.Cyberware.Nervous.SynapticAccel.Rare,
Glossary.Cyberware.Ocular.Kiroshi.Rare,
Glossary.Cyberware.Skeleton.BionicJoints.Rare,
Glossary.Cyberware.Skeleton.BionicLungs.Rare,
Glossary.Cyberware.Skeleton.DenseMarrow.Rare,
Glossary.Cyberware.Skeleton.Microrotors.Rare,
Glossary.Cyberware.Skeleton.MicroVibrationGen.Rare,
Glossary.Cyberware.Skeleton.SynapticSignal.Rare,
Glossary.Cyberware.Skeleton.TitaniumBones.Rare,
Glossary.Cyberware.Circulatory.AdrenalineBooster.Uncommon,
Glossary.Cyberware.Circulatory.Biomonitor.Uncommon,
Glossary.Cyberware.Circulatory.BloodPump.Uncommon,
Glossary.Cyberware.Circulatory.BloodVessels.Uncommon,
Glossary.Cyberware.Circulatory.MicroGenerator.Uncommon,
Glossary.Cyberware.Circulatory.SynLungs.Uncommon,
Glossary.Cyberware.Circulatory.TyrosineInjector.Uncommon,
Glossary.Cyberware.Deck.Biodyne.Uncommon,
Glossary.Cyberware.Deck.Biodyne.Berserk.Uncommon,
Glossary.Cyberware.Deck.Biotech.Uncommon,
Glossary.Cyberware.Deck.Dynalay.Uncommon,
Glossary.Cyberware.Deck.MooreTech.Uncommon,
Glossary.Cyberware.Deck.Seocho.Uncommon,
Glossary.Cyberware.Deck.Tetratonic.Uncommon,
Glossary.Cyberware.Deck.Zetatech.Sandevistan.Uncommon,
Glossary.Cyberware.FrontalCortex.HealOnKill.Uncommon,
Glossary.Cyberware.FrontalCortex.Mechatronic.Uncommon,
Glossary.Cyberware.FrontalCortex.MemoryBoost.Uncommon,
Glossary.Cyberware.FrontalCortex.RAMUpgrade.Uncommon,
Glossary.Cyberware.FrontalCortex.VisualCortex.Uncommon,
Glossary.Cyberware.Immune.Cataresist.Uncommon,
Glossary.Cyberware.Immune.ShockAwe.Uncommon,
Glossary.Cyberware.Integumentary.SubdermalArmor.Uncommon,
Glossary.Cyberware.Nervous.Kerenzikov.Uncommon,
Glossary.Cyberware.Nervous.Nanorelays.Uncommon,
Glossary.Cyberware.Nervous.Neofiber.Uncommon,
Glossary.Cyberware.Nervous.ReflexTuner.Uncommon,
Glossary.Cyberware.Nervous.SynapticAccel.Uncommon,
Glossary.Cyberware.Skeleton.BionicLungs.Uncommon,
Glossary.Cyberware.Skeleton.DenseMarrow.Uncommon,
Glossary.Cyberware.Skeleton.Microrotors.Uncommon,
Glossary.Cyberware.Skeleton.MicroVibrationGen.Uncommon,
Glossary.Cyberware.Skeleton.SynapticSignal.Uncommon,
Glossary.Cyberware.Skeleton.TitaniumBones.Uncommon,
Glossary.Cyberware.Circulatory.AdrenalineBooster.Common,
Glossary.Cyberware.Circulatory.Biomonitor.Common,
Glossary.Cyberware.Circulatory.BloodPump.Common,
Glossary.Cyberware.Circulatory.BloodVessels.Common,
Glossary.Cyberware.Circulatory.MicroGenerator.Common,
Glossary.Cyberware.Circulatory.SynLungs.Common,
Glossary.Cyberware.Deck.Fuyutsui.Common,
Glossary.Cyberware.Deck.Militech.Common,
Glossary.Cyberware.FrontalCortex.HealOnKill.Common,
Glossary.Cyberware.FrontalCortex.Limbic.Common,
Glossary.Cyberware.FrontalCortex.Mechatronic.Common,
Glossary.Cyberware.FrontalCortex.MemoryBoost.Common,
Glossary.Cyberware.FrontalCortex.RAMUpgrade.Common,
Glossary.Cyberware.FrontalCortex.VisualCortex.Common,
Glossary.Cyberware.Immune.Cataresist.Common,
Glossary.Cyberware.Immune.ShockAwe.Common,
Glossary.Cyberware.Integumentary.SubdermalArmor.Common,
Glossary.Cyberware.Nervous.Kerenzikov.Common,
Glossary.Cyberware.Nervous.Neofiber.Common,
Glossary.Cyberware.Nervous.ReflexTuner.Common,
Glossary.Cyberware.Nervous.SynapticAccel.Common,
Glossary.Cyberware.Ocular.Kiroshi.Common,
Glossary.Cyberware.Skeleton.BionicLungs.Common,
Glossary.Cyberware.Skeleton.Microrotors.Common,
Glossary.Cyberware.Skeleton.SynapticSignal.Common,
Glossary.Cyberware.Skeleton.TitaniumBones.Common
}
Glossary.Searchable = {
Resources = Glossary.Resources,
Weapons = Glossary.Weapons,
Clothing = Glossary.Clothing,
Cyberware = Glossary.Cyberware,
Quickhacks = Glossary.Quickhacks,
Mods = Glossary.Mods,
Attachments = Glossary.Attachments
-- Recipes = Glossary.Recipes
}
return Glossary |
OverworldMixedMode = SurrogateItem:extend()
function OverworldMixedMode:init(isAlt)
self.baseCode = "ow_mixed"
self.label = "Overworld Tile Swap"
self:initSuffix(isAlt)
self:initCode()
self:setCount(4)
self:setState(0)
end
function OverworldMixedMode:onLeftClick()
self.clicked = true
if self:getState() == 3 then
self:setState(1)
else
self:setState((self:getState() + 1) % self:getCount())
end
end
function OverworldMixedMode:onRightClick()
if self:getState() > 0 then
self.clicked = true
if self:getState() == 3 then
self:setState(1)
else
self:setState((self:getState() - 1) % self:getCount())
end
end
end
function OverworldMixedMode:providesCode(code)
if self.suffix == "" then
if code == "ow_mixed_off" and self:getState() == 0 then
return 1
elseif code == "ow_mixed_on" and self:getState() > 0 then
return 1
end
end
return 0
end
function OverworldMixedMode:updateIcon()
if self:getState() == 0 then
self.ItemInstance.Icon = ImageReference:FromPackRelativePath("images/modes/ow_mixed" .. self.suffix .. ".png", "@disabled")
else
if self.suffix == "" or self:getState() == 1 then
self.ItemInstance.Icon = ImageReference:FromPackRelativePath("images/modes/ow_mixed" .. self.suffix .. ".png")
elseif self:getState() == 2 then
self.ItemInstance.Icon = ImageReference:FromPackRelativePath("images/modes/ow_mixed_edit.png")
else
self.ItemInstance.Icon = ImageReference:FromPackRelativePath("images/modes/ow_mixed_editlocked.png")
end
end
end
function OverworldMixedMode:updateItem()
for i = 1, #DATA.OverworldIds do
local item = Tracker:FindObjectForCode("ow_swapped_" .. string.format("%02x", DATA.OverworldIds[i])).ItemState
if not item.modified then
item:setState(self:getState() == 0 and OBJ_WORLDSTATE:getState() or (OBJ_WORLDSTATE:getState() == 0 and 3 or 2))
end
end
end
function OverworldMixedMode:postUpdate()
if CONFIG.PREFERENCE_ENABLE_DEBUG_LOGGING then
print("OW Mixed updated")
end
Layout:FindLayout("map").Root.HitTestVisible = self:getState() < 2
end
|
--- === bit.mouse.highlight ===
---
--- (only works with https://github.com/lodestone/hyper-hacks)
mouse = {}
local canvas = require "hs.canvas"
local timer = require "hs.timer"
require "hs.mouse"
local function createCrosshair(middlePosition, size)
local frame = {
x = middlePosition.x + 3 - size/2,
y = middlePosition.y + 6 - size/2,
w = size,
h = size
}
return canvas.new(frame):appendElements({
action = "build",
type = "rectangle",
frame = {x = "0%", y = "0%", w = "40%", h = "40%"},
},{
action = "build",
type = "rectangle",
frame = {x = "60%", y = "0%", w = "40%", h = "40%"},
},{
action = "build",
type = "rectangle",
frame = {x = "0%", y = "60%", w = "40%", h = "40%"},
},{
action = "clip",
type = "rectangle",
frame = {x = "60%", y = "60%", w = "40%", h = "40%"},
},{
action = "stroke",
padding = 10,
type = "rectangle",
frame = {x = "0%", y = "0%", w = "100%", h = "100%"},
roundedRectRadii = {xRadius = 10, yRadius= 10},
strokeColor = {red = 1, alpha = 1},
strokeWidth = 5,
withShadow = true,
strokeCapStyle = "round"
}):show()
end
local function showHighlight(position, size, time, fn)
local highlight = createCrosshair(position, size)
timer.doAfter(time, function() highlight:delete() if fn then fn() end end)
end
mouse.highlight = function()
local target = hs.mouse.getAbsolutePosition()
showHighlight(target, 180, 0.35, function()
showHighlight(target, 130, 0.35, function()
showHighlight(target, 80, 1, nil)
end)
end)
end
return mouse
|
ACF.RegisterFuelTankClass("FTS_6", {
Name = "Size 6 Container",
Description = "Size 6 fuel containers, required for engines to work.",
})
do
ACF.RegisterFuelTank("Tank_6x6x1","FTS_6", {
Name = "6x6x1 Container",
Description = "Got gas?",
Model = "models/fueltank/fueltank_6x6x1.mdl",
SurfaceArea = 9405.2,
Volume = 37278.5,
})
ACF.RegisterFuelTank("Tank_6x6x2","FTS_6", {
Name = "6x6x2 Container",
Description = "Drive across the desert without a fuck to give.",
Model = "models/fueltank/fueltank_6x6x2.mdl",
SurfaceArea = 11514.5,
Volume = 73606.2,
})
ACF.RegisterFuelTank("Tank_6x6x4","FTS_6", {
Name = "6x6x4 Container",
Description = "May contain Mesozoic ghosts.",
Model = "models/fueltank/fueltank_6x6x4.mdl",
SurfaceArea = 16028.8,
Volume = 143269,
})
ACF.RegisterFuelTank("Tank_6x8x1","FTS_6", {
Name = "6x8x1 Container",
Description = "Conformal fuel tank, does what all its friends do.",
Model = "models/fueltank/fueltank_6x8x1.mdl",
SurfaceArea = 12131.1,
Volume = 48480.2,
})
ACF.RegisterFuelTank("Tank_6x8x2","FTS_6", {
Name = "6x8x2 Container",
Description = "Certified 100% dinosaur juice.",
Model = "models/fueltank/fueltank_6x8x2.mdl",
SurfaceArea = 14403.8,
Volume = 95065.5,
})
ACF.RegisterFuelTank("Tank_6x8x4","FTS_6", {
Name = "6x8x4 Container",
Description = "Will last you a while.",
Model = "models/fueltank/fueltank_6x8x4.mdl",
SurfaceArea = 19592.4,
Volume = 187296.4,
})
end
|
hp = 3500
attack = 850
defense = 550
speed = 100
mdefense = 600
luck = 85
strength = ELEMENT_NONE
weakness = ELEMENT_NONE
function initId(id)
myId = id
end
function start()
end
function get_action(step)
return COMBAT_ATTACKING, 1, getRandomPlayer()
end
function die()
end
|
local Hook = {}
Hook.debug = false
local hooks = {}
local function _print( ... )
if not Hook.debug then return end
print( ... )
end
-- > Hook: methods
function Hook.Add( event, id, func )
if not event or not type(event) == "string" then error( "#1 argument must be valid and be a string", 2 ) end
if not id or not type(id) == "string" then error( "#2 argument must be valid and be a string", 2 ) end
if not func or not type(func) == "function" then error( "#3 argument must be valid", 2 ) end
if not hooks[event] then hooks[event] = {} end
hooks[event][id] = func
_print( ("Add hook with event '%s' and id '%s'"):format( event, id ) )
end
function Hook.Remove( event, id )
if not event or not type(event) == "string" then error( "#1 argument must be valid and be a string", 2 ) end
if not id or not type(id) == "string" then error( "#2 argument must be valid and be a string", 2 ) end
if not hooks[event] or not hooks[event][id] then return _print( ( "Hook with event '%s' and id '%s' doesn't exists" ):format( event, id ) ) end
hooks[event][id] = nil
_print( ("Remove hook with event '%s' and id '%s'"):format( event, id ) )
end
function Hook.Call( event, id, ... )
if not event or not type(event) == "string" then error( "#1 argument must be valid and be a string", 2 ) end
if not hooks[event] then return _print( ( "Hooks with event '%s' don't exists" ):format( event ) ) end
if hooks[event][id] then
hooks[event][id]( ... )
_print( ("Call hook with event '%s' and id '%s'"):format( event, id ) )
elseif not id then
_print( ("Call hooks with event '%s'"):format( event ) )
for _, v in pairs( hooks[event] ) do
v( ... )
end
else
_print( ("There is no hooks with event '%s' and id '%s'"):format( event, id ) )
end
end
function Hook.SetDebug( state )
if state == nil or not type(state) == "boolean" then error( "#1 argument must be valid and be a boolean", 2 ) end
Hook.debug = state
end
return Hook |
local zmq = require "lzmq"
local zthreads = require "lzmq.threads"
local zauth = {} do
zauth.__index = zauth
function zauth:new(ctx)
local o = setmetatable({
private_ = {
ctx = assert(ctx);
}
}, self)
return o
end
function zauth:destroy()
if self.private_ then
self:stop()
self.private_ = nil
end
end
zauth.__gc = zauth.destroy
function zauth:started()
return not not self.private_.thread
end
function zauth:context()
return self.private_.ctx
end
function zauth:start()
local proc = string.dump(function(...)
local pipe = ...
local ctx = pipe:context()
local ok, err = pcall(function(...)
require "lzmq.impl.auth_zap"(...)
end, ...)
if not ok then
if not pipe:closed() then
pipe:sendx("ERROR", tostring(err))
end
ctx:destroy(200)
end
end)
if not self:started() then
local thread, pipe = zthreads.fork(self.private_.ctx, proc)
if not thread then return nil, pipe end
thread:start()
local ok, err = pipe:recvx()
if not ok then -- thread terminate
if not pipe:closed() then
pipe:send('TERMINATE') -- just in case
end
thread:join()
pipe:close()
return nil, err
end
if ok == 'ERROR' then
thread:join()
pipe:close()
return nil, err
end
assert(ok == 'OK')
self.private_.thread, self.private_.pipe = thread, pipe
end
return true
end
function zauth:stop()
local thread, pipe = self.private_.thread, self.private_.pipe
if thread then
pipe:send('TERMINATE')
thread:join()
pipe:close()
self.private_.thread, self.private_.pipe = nil
end
end
function zauth:allow(address)
local pipe = self.private_.pipe
pipe:sendx('ALLOW', address)
return pipe:recv()
end
function zauth:deny(address)
local pipe = self.private_.pipe
pipe:sendx('DENY', address)
return pipe:recv()
end
function zauth:verbose(...)
local pipe = self.private_.pipe
local enable = ...
if select("#", ...) == 0 then enable = true end
pipe:sendx('VERBOSE', enable and '1' or '0')
return pipe:recv()
end
function zauth:configure_plain(...)
local domain, passwords
if select('#', ...) < 2 then passwords = ...
else domain, passwords = ... end
domain = domain or '*'
assert(passwords)
local pipe = self.private_.pipe
pipe:sendx('PLAIN', domain, passwords)
return pipe:recv()
end
function zauth:configure_curve(...)
local domain, location
if select('#', ...) < 2 then location = ...
else domain, location = ... end
domain = domain or '*'
assert(location)
local pipe = self.private_.pipe
pipe:sendx('CURVE', domain or '*', location)
return pipe:recv()
end
end
local selftest do
local ZSOCKET_DYNFROM = 0xc000
local ZSOCKET_DYNTO = 0xffff
local function dyn_bind (sok, address)
local ok, err
for port = ZSOCKET_DYNFROM, ZSOCKET_DYNTO do
ok, err = sok:bind(address .. ":" .. tostring(port))
if ok then return port end
end
return nil, err
end
local function s_can_connect(ctx, server, client)
local port_nbr = zmq.assert(dyn_bind(server, "tcp://127.0.0.1"))
assert(client:connect("tcp://127.0.0.1:" .. tostring(port_nbr)))
server:send("Hello, World")
client:set_rcvtimeo(200)
local success = (client:recv() == "Hello, World")
client:close()
server:close()
return success, ctx:socket(zmq.PUSH),ctx:socket(zmq.PULL)
end
local TESTDIR = ".test_zauth"
local function test_impl(auth, verbose)
local path = require "path"
local zcert = require "lzmq.cert"
local ctx = assert(auth:context())
assert(auth:start())
auth:verbose(verbose)
local a2 = zauth:new(ctx)
local ok, err = a2:start()
assert( not ok )
a2:destroy()
local server = ctx:socket(zmq.PUSH)
local client = ctx:socket(zmq.PULL)
local success
-- A default NULL connection should always success, and not
-- go through our authentication infrastructure at all.
success, server, client = s_can_connect(ctx, server, client)
assert(success)
-- When we set a domain on the server, we switch on authentication
-- for NULL sockets, but with no policies, the client connection
-- will be allowed.
server:set_zap_domain("global")
success, server, client = s_can_connect(ctx, server, client)
assert(success)
-- Blacklist 127.0.0.1, connection should fail
server:set_zap_domain("global")
auth:deny("127.0.0.1")
success, server, client = s_can_connect(ctx, server, client)
assert(not success)
-- Whitelist our address, which overrides the blacklist
server:set_zap_domain("global")
auth:deny("127.0.0.1")
auth:allow("127.0.0.1")
success, server, client = s_can_connect(ctx, server, client)
assert(success)
-- Try PLAIN authentication
server:set_plain_server(1)
client:set_plain_username("admin")
client:set_plain_password("Password")
success, server, client = s_can_connect(ctx, server, client)
assert(not success)
local pass_path = path.join(TESTDIR, "/password-file")
local password = assert(io.open(pass_path, "w+"))
password:write("admin=Password\n")
password:close()
server:set_plain_server(1)
client:set_plain_username("admin")
client:set_plain_password("Password")
auth:configure_plain("*", pass_path);
success, server, client = s_can_connect(ctx, server, client)
assert(success)
server:set_plain_server(1)
client:set_plain_username("admin")
client:set_plain_password("Bogus")
auth:configure_plain("*", pass_path);
success, server, client = s_can_connect(ctx, server, client)
assert(not success)
-- Try CURVE authentication
-- We'll create two new certificates and save the client public
-- certificate on disk; in a real case we'd transfer this securely
-- from the client machine to the server machine.
local server_cert = zcert.new()
local client_cert = zcert.new()
local server_key = server_cert:public_key(true)
-- Test without setting-up any authentication
server_cert:apply(server)
client_cert:apply(client)
server:set_curve_server(1)
client:set_curve_serverkey(server_key)
success, server, client = s_can_connect(ctx, server, client)
assert(not success)
-- Test full client authentication using certificates
server_cert:apply(server)
client_cert:apply(client)
server:set_curve_server(1)
client:set_curve_serverkey(server_key)
client_cert:save_public(path.join(TESTDIR, "mycert.key"))
auth:configure_curve("*", TESTDIR)
success, server, client = s_can_connect(ctx, server, client)
assert(success)
end
selftest = function(verbose)
io.write (" * zauth: ")
local path = require "path"
path.mkdir(TESTDIR)
assert(path.isdir(TESTDIR))
local auth = zauth:new(zmq.context())
assert(pcall(test_impl, auth, verbose))
auth:stop()
auth:context():destroy()
path.each(path.join(TESTDIR, "*.*"), path.remove)
-- path.each with lfs <1.6 close dir iterator only on gc.
collectgarbage("collect") collectgarbage("collect")
path.rmdir(TESTDIR)
io.write(" OK\n")
end
end
return {
new = function(...) return zauth:new(...) end;
}
|
local L = BigWigs:NewBossLocale("Maw of Souls Trash", "itIT")
if not L then return end
if L then
L.soulguard = "Guardia dell'Anima Fradicia"
L.champion = "Campione Helarjar"
L.mariner = "Marinaio dei Guardiani della Notte"
L.swiftblade = "Lamalesta Maledetto"
L.mistmender = "Curatrice delle Nebbie Maledetta"
L.mistcaller = "Evocanebbie Helarjar"
L.skjal = "Skjal"
end
|
ZO_CreateStringId("SI_BUI_INV_ITEM_ALL","Inventory")
ZO_CreateStringId("SI_BUI_INV_ITEM_MATERIALS","Materials")
ZO_CreateStringId("SI_BUI_INV_ITEM_QUICKSLOT","|cFF6600Quickslot|r")
ZO_CreateStringId("SI_BUI_INV_ITEM_WEAPONS","Weapons")
ZO_CreateStringId("SI_BUI_INV_ITEM_APPAREL","Apparel")
ZO_CreateStringId("SI_BUI_INV_ITEM_CONSUMABLE","Quickslot")
ZO_CreateStringId("SI_BUI_INV_ITEM_MISC","Miscellaneous")
ZO_CreateStringId("SI_BUI_INV_ITEM_JUNK","Junk")
ZO_CreateStringId("SI_BUI_INV_EQUIPSLOT_TITLE","Equipping item...")
ZO_CreateStringId("SI_BUI_INV_EQUIPSLOT_PROMPT","Which hand should it go into?")
ZO_CreateStringId("SI_BUI_INV_EQUIPSLOT_MAIN","Main")
ZO_CreateStringId("SI_BUI_INV_EQUIPSLOT_OFF","Off")
ZO_CreateStringId("SI_BUI_INV_EQUIP_PROMPT_MAIN","Main Hand")
ZO_CreateStringId("SI_BUI_INV_EQUIP_PROMPT_BACKUP","Off Hand")
ZO_CreateStringId("SI_BUI_INV_EQUIP_PROMPT_CANCEL","Cancel")
ZO_CreateStringId("SI_BUI_INV_SWITCH_EQUIPSLOT","Switch Weapons")
ZO_CreateStringId("SI_BUI_INV_ACTION_QUICKSLOT_ASSIGN","Assign Quickslot")
ZO_CreateStringId("SI_BUI_INV_EQUIPSLOT_MAIN","Main")
ZO_CreateStringId("SI_BUI_INV_EQUIPSLOT_BACKUP","Backup")
ZO_CreateStringId("SI_BUI_BANKING_WITHDRAW","Withdraw")
ZO_CreateStringId("SI_BUI_BANKING_DEPOSIT","Deposit")
ZO_CreateStringId("SI_BUI_BANKING_BUYSPACE","Buy More Space (<<1>>)")
ZO_CreateStringId("SI_BUI_INV_ACTION_TO_TEMPLATE","Go To <<1>>")
ZO_CreateStringId("SI_BUI_INV_ACTION_CB","Crafting Bag")
ZO_CreateStringId("SI_BUI_INV_ACTION_INV","Inventory")
-- A little patch to correct the scaling of items displaying the incorrect CP values
ZO_CreateStringId("SI_ITEM_ABILITY_SCALING_CHAMPION_POINTS_RANGE","Scaling from <<X:1>> <<2>> to <<X:1>> <<3>>")
|
local g = vim.g -- a table to access global variables
-- see https://github.com/numToStr/Comment.nvim/issues/14#issuecomment-939230851
-- visual comment with custom keyboard shortcut
local Ut = require('Comment.utils')
local Op = require('Comment.opfunc')
function _G.__toggle_visual(vmode)
local lcs, rcs = Ut.unwrap_cstr(vim.bo.commentstring)
local srow, erow, lines = Ut.get_lines(vmode, Ut.ctype.line)
Op.linewise({
cfg = { padding = true, ignore = nil },
cmode = Ut.cmode.toggle,
lines = lines,
lcs = lcs,
rcs = rcs,
srow = srow,
erow = erow,
})
end
-- end visual comment
local function map(mode, lhs, rhs, opts)
local options = { noremap = true }
if opts then
options = vim.tbl_extend('force', options, opts)
end
vim.api.nvim_set_keymap(mode, lhs, rhs, options)
end
function _G.set_terminal_keymaps()
local opts = { noremap = true }
vim.api.nvim_buf_set_keymap(0, 't', '<esc>', [[<C-\><C-n>]], opts)
vim.api.nvim_buf_set_keymap(0, 't', 'jk', [[<C-\><C-n>]], opts)
vim.api.nvim_buf_set_keymap(0, 't', '<C-h>', [[<C-\><C-n><C-W>h]], opts)
vim.api.nvim_buf_set_keymap(0, 't', '<C-j>', [[<C-\><C-n><C-W>j]], opts)
vim.api.nvim_buf_set_keymap(0, 't', '<C-k>', [[<C-\><C-n><C-W>k]], opts)
vim.api.nvim_buf_set_keymap(0, 't', '<C-l>', [[<C-\><C-n><C-W>l]], opts)
end
-- toggle showing whitespace
map('n', '<leader>s', ':set nolist!<cr>', { silent = true })
map('n', 'J', '<c-d>')
map('x', 'J', '<c-d>')
map('n', 'K', '<c-u>')
map('x', 'K', '<c-u>')
-- up/down work as expected with word wrapping on
map('n', 'j', 'gj')
map('n', 'k', 'gk')
map('n', 'gj', 'j')
map('n', 'gj', 'j')
map('', 'H', '^')
map('', 'L', '$')
-- clear search highlighting
map('n', '<esc>', ':nohlsearch<cr><esc>', { silent = true })
if not g.vscode then
map('', '\\\\', '<esc><cmd>lua __toggle_visual(vim.fn.visualmode())<cr>', { silent = true })
map('', '<c-l>', ':Telescope buffers<cr>')
map('', '<c-p>', ':Telescope find_files<cr>')
map('n', '<S-l>', ':BufferLineCycleNext<CR>')
map('n', '<S-h>', ':BufferLineCyclePrev<CR>')
vim.cmd('autocmd! TermOpen term://* lua set_terminal_keymaps()')
local wk = require('which-key')
wk.register({
f = { '<cmd>Telescope live_grep<cr>', 'Live ripgrep search' },
r = { '<cmd>Telescope oldfiles<cr>', 'Find recently opened files' },
d = { '<cmd>NvimTreeToggle<cr>', 'Toggle directory tree' },
-- Packer
p = {
name = 'Packer',
c = { '<cmd>PackerCompile<cr>', 'Compile' },
i = { '<cmd>PackerInstall<cr>', 'Install' },
r = { "<cmd>lua require('lvim.plugin-loader').recompile()<cr>", 'Re-compile' },
s = { '<cmd>PackerSync<cr>', 'Sync' },
S = { '<cmd>PackerStatus<cr>', 'Status' },
u = { '<cmd>PackerUpdate<cr>', 'Update' },
},
-- Git
g = {
name = 'Git',
j = { "<cmd>lua require 'gitsigns'.next_hunk()<cr>", 'Next Hunk' },
k = { "<cmd>lua require 'gitsigns'.prev_hunk()<cr>", 'Prev Hunk' },
l = { "<cmd>lua require 'gitsigns'.blame_line()<cr>", 'Blame' },
p = { "<cmd>lua require 'gitsigns'.preview_hunk()<cr>", 'Preview Hunk' },
r = { "<cmd>lua require 'gitsigns'.reset_hunk()<cr>", 'Reset Hunk' },
R = { "<cmd>lua require 'gitsigns'.reset_buffer()<cr>", 'Reset Buffer' },
s = { "<cmd>lua require 'gitsigns'.stage_hunk()<cr>", 'Stage Hunk' },
u = {
"<cmd>lua require 'gitsigns'.undo_stage_hunk()<cr>",
'Undo Stage Hunk',
},
o = { '<cmd>Telescope git_status<cr>', 'Open changed file' },
b = { '<cmd>Telescope git_branches<cr>', 'Checkout branch' },
c = { '<cmd>Telescope git_commits<cr>', 'Checkout commit' },
C = {
'<cmd>Telescope git_bcommits<cr>',
'Checkout commit(for current file)',
},
d = {
'<cmd>Gitsigns diffthis HEAD<cr>',
'Git Diff',
},
},
-- LSP
l = {
name = 'LSP',
a = { "<cmd>lua require('lvim.core.telescope').code_actions()<cr>", 'Code Action' },
d = {
'<cmd>Telescope lsp_document_diagnostics<cr>',
'Document Diagnostics',
},
w = {
'<cmd>Telescope lsp_workspace_diagnostics<cr>',
'Workspace Diagnostics',
},
f = { '<cmd>lua vim.lsp.buf.formatting()<cr>', 'Format' },
i = { '<cmd>LspInfo<cr>', 'Info' },
I = { '<cmd>LspInstallInfo<cr>', 'Installer Info' },
j = {
'<cmd>lua vim.lsp.diagnostic.goto_next({popup_opts = {border = lvim.lsp.popup_border}})<cr>',
'Next Diagnostic',
},
k = {
'<cmd>lua vim.lsp.diagnostic.goto_prev({popup_opts = {border = lvim.lsp.popup_border}})<cr>',
'Prev Diagnostic',
},
l = { '<cmd>lua vim.lsp.codelens.run()<cr>', 'CodeLens Action' },
p = {
name = 'Peek',
d = { "<cmd>lua require('lvim.lsp.peek').Peek('definition')<cr>", 'Definition' },
t = { "<cmd>lua require('lvim.lsp.peek').Peek('typeDefinition')<cr>", 'Type Definition' },
i = { "<cmd>lua require('lvim.lsp.peek').Peek('implementation')<cr>", 'Implementation' },
},
q = { '<cmd>lua vim.lsp.diagnostic.set_loclist()<cr>', 'Quickfix' },
r = { '<cmd>lua vim.lsp.buf.rename()<cr>', 'Rename' },
s = { '<cmd>Telescope lsp_document_symbols<cr>', 'Document Symbols' },
S = {
'<cmd>Telescope lsp_dynamic_workspace_symbols<cr>',
'Workspace Symbols',
},
},
-- Trouble toggling
t = {
name = 'Diagnostics',
t = { '<cmd>TroubleToggle<cr>', 'trouble' },
w = { '<cmd>TroubleToggle lsp_workspace_diagnostics<cr>', 'workspace' },
d = { '<cmd>TroubleToggle lsp_document_diagnostics<cr>', 'document' },
q = { '<cmd>TroubleToggle quickfix<cr>', 'quickfix' },
l = { '<cmd>TroubleToggle loclist<cr>', 'loclist' },
r = { '<cmd>TroubleToggle lsp_references<cr>', 'references' },
},
}, {
prefix = '<leader>',
})
end
|
--[[
-- This script converts the outputted aseprite json animation files
-- to Lua tables that the game engine can load.
--
-- It uses hardcoded paths, so that should be refactored at some point
--]]
local json = require "assets/scripts/json"
local serpent = require "assets/scripts/serpent"
require "lfs"
function readAll(file)
local f = assert(io.open(file, "rb"))
local content = f:read("*all")
f:close()
return content
end
function string:split(delimiter)
local result = { }
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
end
table.insert( result, string.sub( self, from ) )
return result
end
function isN(a)
return tonumber(a) ~= nil
end
for file in lfs.dir "assets/images/" do
local dest = string.find(file, ".", 1, true)
local ext = string.sub(file, dest+1, #file)
local name = string.sub(file, 1, dest-1)
if ext == "json" then
local jdata = readAll("assets/images/"..file)
local ltable = json.decode(jdata)
local final = {[name] = {
playback = "forward",
repeated = true,
frames = {},
}}
for key, i in pairs(ltable.frames) do
--bird 3.aseprite
local period = string.find(key, ".", 1, true)
local index = period - 1
while index >= 1 and isN(key:sub(index, index)) do
index = index - 1
end
local num = tonumber(string.sub(key, index+1, period-1)) + 1
final[name].frames[num] = {
{i.frame.x, i.frame.y, i.frame.w, i.frame.h},
duration = i.duration
}
end
local outfile = io.open("assets/data/animations/" .. name .. ".lua", "w")
outfile:write("return " .. serpent.block(final, {comment=false, compact=true}))
outfile:close()
end
end
|
--- Lake script to install script wrappers in bin
local exec, join = utils.execute, path.join
if arg[1] or LUA53 then
lua = 'lua53'
soar = 'soar53'
print 'installing Lua 5.3'
else
lua = 'lua52'
soar = 'soar52'
end
-- some platform-dependent swearing...
if WINDOWS then
bat_ext, all_args, shebang = '.bat',' %*', '@echo off\n'
else
bat_ext, all_args, shebang = '',' $*','#!/bin/sh\n'
end
local function bin_dir(f) return join('bin',f) end
local function make_wrapper(target,exe,name)
if not name then
local _
_, name = path.splitpath(target)
name = path.splitext(name)
end
target = path.abs(target)
if not exe then
exe = path.abs(bin_dir(lua))
end
local wrap = bin_dir (name)..bat_ext
file.write(wrap,shebang..exe..' '..target..all_args..'\n')
if not WINDOWS then
exec('chmod +x '..wrap)
end
end
make_wrapper ('tools/soar.lua')
make_wrapper ('tools/srlua.lua','lake')
make_wrapper 'lake'
|
-- ------------------------------------------------------------------------
-- This project is developed by Marco Mastropaolo (Xanathar)
-- as a personal project and is in no way affiliated with Almost Human.
-- You can use this scripts in any Legend of Grimrock dungeon you want;
-- credits are appreciated though not necessary.
-- ------------------------------------------------------------------------
-- If you want to use this code in a Lua project outside Grimrock,
-- please refer to the files and license included
-- at http://code.google.com/p/lualinq/
-- ------------------------------------------------------------------------
---------------------------------------------------------------------------
-- CONFIGURATION OPTIONS --
---------------------------------------------------------------------------
-- change this if you don't want all secrets to be "auto"
AUTO_ALL_SECRETS = true
-- how much log information is printed: 3 => verbose, 2 => info, 1 => only warning and errors, 0 => only errors, -1 => silent
LOG_LEVEL = 1
-- prefix for the printed logs
LOG_PREFIX = "GrimQ: "
-- set this to false when the allEntities bug gets fixed for faster iterations
PATCH_ALLENTITIES_BUG = true
---------------------------------------------------------------------------
-- IMPLEMENTATION BELOW, DO NOT CHANGE
---------------------------------------------------------------------------
VERSION_SUFFIX = ""
MAXLEVEL = 1
CONTAINERITEM_MAXSLOTS = 10
-- ============================================================
-- DEBUG TRACER
-- ============================================================
LIB_VERSION_TEXT = "1.5.2"
LIB_VERSION = 152
function setLogLevel(level)
LOG_LEVEL = level;
end
function _log(level, prefix, text)
if (level <= LOG_LEVEL) then
print(prefix .. LOG_PREFIX .. text)
end
end
function logq(self, method)
if (LOG_LEVEL >= 3) then
logv("after " .. method .. " => " .. #self.m_Data .. " items : " .. _dumpData(self))
end
end
function _dumpData(self)
local items = #self.m_Data
local dumpdata = "q{ "
for i = 1, 3 do
if (i <= items) then
if (i ~= 1) then
dumpdata = dumpdata .. ", "
end
dumpdata = dumpdata .. tostring(self.m_Data[i])
end
end
if (items > 3) then
dumpdata = dumpdata .. ", ..." .. items .. " }"
else
dumpdata = dumpdata .. " }"
end
return dumpdata
end
function logv(txt)
_log(3, "[..] ", txt)
end
function logi(txt)
_log(2, "[ii] ", txt)
end
function logw(txt)
_log(1, "[W?] ", txt)
end
function loge(txt)
_log(0, "[E!] ", txt)
end
-- ============================================================
-- CONSTRUCTOR
-- ============================================================
-- [private] Creates a linq data structure from an array without copying the data for efficiency
function _new_lualinq(method, collection)
local self = { }
self.classid_71cd970f_a742_4316_938d_1998df001335 = 2
self.m_Data = collection
self.concat = _concat
self.select = _select
self.selectMany = _selectMany
self.where = _where
self.whereIndex = _whereIndex
self.take = _take
self.skip = _skip
self.zip = _zip
self.distinct = _distinct
self.union = _union
self.except = _except
self.intersection = _intersection
self.exceptby = _exceptby
self.intersectionby = _intersectionby
self.exceptBy = _exceptby
self.intersectionBy = _intersectionby
self.first = _first
self.last = _last
self.min = _min
self.max = _max
self.random = _random
self.any = _any
self.all = _all
self.contains = _contains
self.count = _count
self.sum = _sum
self.average = _average
self.dump = _dump
self.map = _map
self.foreach = _foreach
self.xmap = _xmap
self.toArray = _toArray
self.toDictionary = _toDictionary
self.toIterator = _toIterator
self.toTuple = _toTuple
-- shortcuts
self.each = _foreach
self.intersect = _intersection
self.intersectby = _intersectionby
self.intersectBy = _intersectionby
logq(self, "from")
return self
end
-- ============================================================
-- GENERATORS
-- ============================================================
-- Tries to autodetect input type and uses the appropriate from method
function from(auto)
if (auto == nil) then
return fromNothing()
elseif (type(auto) == "function") then
return fromIterator(auto)
elseif (type(auto) == "table") then
if (auto["classid_71cd970f_a742_4316_938d_1998df001335"] ~= nil) then
return auto
elseif (auto[1] == nil) then
return fromDictionary(auto)
elseif (type(auto[1]) == "function") then
return fromIteratorsArray(auto)
else
return fromArrayInstance(auto)
end
end
return fromNothing()
end
-- Creates a linq data structure from an array without copying the data for efficiency
function fromArrayInstance(collection)
return _new_lualinq("fromArrayInstance", collection)
end
-- Creates a linq data structure from an array copying the data first (so that changes in the original
-- table do not reflect here)
function fromArray(array)
local collection = { }
for k,v in ipairs(array) do
table.insert(collection, v)
end
return _new_lualinq("fromArray", collection)
end
-- Creates a linq data structure from a dictionary (table with non-consecutive-integer keys)
function fromDictionary(dictionary)
local collection = { }
for k,v in pairs(dictionary) do
local kvp = {}
kvp.key = k
kvp.value = v
table.insert(collection, kvp)
end
return _new_lualinq("fromDictionary", collection)
end
-- Creates a linq data structure from an iterator returning single items
function fromIterator(iterator)
local collection = { }
for s in iterator do
table.insert(collection, s)
end
return _new_lualinq("fromIterator", collection)
end
-- Creates a linq data structure from an array of iterators each returning single items
function fromIteratorsArray(iteratorArray)
local collection = { }
for _, iterator in ipairs(iteratorArray) do
for s in iterator do
table.insert(collection, s)
end
end
return _new_lualinq("fromIteratorsArray", collection)
end
-- Creates a linq data structure from a table of keys, values ignored
function fromSet(set)
local collection = { }
for k,v in pairs(set) do
table.insert(collection, k)
end
return _new_lualinq("fromIteratorsArray", collection)
end
-- Creates an empty linq data structure
function fromNothing()
return _new_lualinq("fromNothing", { } )
end
-- ============================================================
-- QUERY METHODS
-- ============================================================
-- Concatenates two collections together
function _concat(self, otherlinq)
local result = { }
for idx, value in ipairs(self.m_Data) do
table.insert(result, value)
end
for idx, value in ipairs(otherlinq.m_Data) do
table.insert(result, value)
end
return _new_lualinq(":concat", result)
end
-- Replaces items with those returned by the selector function or properties with name selector
function _select(self, selector)
local result = { }
if (type(selector) == "function") then
for idx, value in ipairs(self.m_Data) do
local newvalue = selector(value)
if (newvalue ~= nil) then
table.insert(result, newvalue)
end
end
elseif (type(selector) == "string") then
for idx, value in ipairs(self.m_Data) do
local newvalue = value[selector]
if (newvalue ~= nil) then
table.insert(result, newvalue)
end
end
else
loge("select called with unknown predicate type");
end
return _new_lualinq(":select", result)
end
-- Replaces items with those contained in arrays returned by the selector function
function _selectMany(self, selector)
local result = { }
for idx, value in ipairs(self.m_Data) do
local newvalue = selector(value)
if (newvalue ~= nil) then
for ii, vv in ipairs(newvalue) do
if (vv ~= nil) then
table.insert(result, vv)
end
end
end
end
return _new_lualinq(":selectMany", result)
end
-- Returns a linq data structure where only items for whose the predicate has returned true are included
function _where(self, predicate, refvalue, ...)
local result = { }
if (type(predicate) == "function") then
for idx, value in ipairs(self.m_Data) do
if (predicate(value, refvalue, from({...}):toTuple())) then
table.insert(result, value)
end
end
elseif (type(predicate) == "string") then
local refvals = {...}
if (#refvals > 0) then
table.insert(refvals, refvalue);
return _intersectionby(self, predicate, refvals);
elseif (refvalue ~= nil) then
for idx, value in ipairs(self.m_Data) do
if (value[predicate] == refvalue) then
table.insert(result, value)
end
end
else
for idx, value in ipairs(self.m_Data) do
if (value[predicate] ~= nil) then
table.insert(result, value)
end
end
end
else
loge("where called with unknown predicate type");
end
return _new_lualinq(":where", result)
end
-- Returns a linq data structure where only items for whose the predicate has returned true are included, indexed version
function _whereIndex(self, predicate)
local result = { }
for idx, value in ipairs(self.m_Data) do
if (predicate(idx, value)) then
table.insert(result, value)
end
end
return _new_lualinq(":whereIndex", result)
end
-- Return a linq data structure with at most the first howmany elements
function _take(self, howmany)
return self:whereIndex(function(i, v) return i <= howmany; end)
end
-- Return a linq data structure skipping the first howmany elements
function _skip(self, howmany)
return self:whereIndex(function(i, v) return i > howmany; end)
end
-- Zips two collections together, using the specified join function
function _zip(self, otherlinq, joiner)
otherlinq = from(otherlinq)
local thismax = #self.m_Data
local thatmax = #otherlinq.m_Data
local result = {}
if (thatmax < thismax) then thismax = thatmax; end
for i = 1, thismax do
result[i] = joiner(self.m_Data[i], otherlinq.m_Data[i]);
end
return _new_lualinq(":zip", result)
end
-- Returns only distinct items, using an optional comparator
function _distinct(self, comparator)
local result = {}
comparator = comparator or function (v1, v2) return v1 == v2; end
for idx, value in ipairs(self.m_Data) do
local found = false
for _, value2 in ipairs(result) do
if (comparator(value, value2)) then
found = true
end
end
if (not found) then
table.insert(result, value)
end
end
return _new_lualinq(":distinct", result)
end
-- Returns the union of two collections, using an optional comparator
function _union(self, other, comparator)
return self:concat(from(other)):distinct(comparator)
end
-- Returns the difference of two collections, using an optional comparator
function _except(self, other, comparator)
other = from(other)
return self:where(function (v) return not other:contains(v, comparator) end)
end
-- Returns the intersection of two collections, using an optional comparator
function _intersection(self, other, comparator)
other = from(other)
return self:where(function (v) return other:contains(v, comparator) end)
end
-- Returns the difference of two collections, using a property accessor
function _exceptby(self, property, other)
other = from(other)
return self:where(function (v) return not other:contains(v[property]) end)
end
-- Returns the intersection of two collections, using a property accessor
function _intersectionby(self, property, other)
other = from(other)
return self:where(function (v) return other:contains(v[property]) end)
end
-- ============================================================
-- CONVERSION METHODS
-- ============================================================
-- Converts the collection to an array
function _toIterator(self)
local i = 0
local n = #self.m_Data
return function ()
i = i + 1
if i <= n then return self.m_Data[i] end
end
end
-- Converts the collection to an array
function _toArray(self)
return self.m_Data
end
-- Converts the collection to a table using a selector functions which returns key and value for each item
function _toDictionary(self, keyValueSelector)
local result = { }
for idx, value in ipairs(self.m_Data) do
local key, value = keyValueSelector(value)
if (key ~= nil) then
result[key] = value
end
end
return result
end
-- Converts the lualinq struct to a tuple
function _toTuple(self)
return unpack(self.m_Data)
end
-- ============================================================
-- TERMINATING METHODS
-- ============================================================
-- Return the first item or default if no items in the colelction
function _first(self, default)
if (#self.m_Data > 0) then
return self.m_Data[1]
else
return default
end
end
-- Return the last item or default if no items in the colelction
function _last(self, default)
if (#self.m_Data > 0) then
return self.m_Data[#self.m_Data]
else
return default
end
end
-- Returns true if any item satisfies the predicate. If predicate is null, it returns true if the collection has at least one item.
function _any(self, predicate)
if (predicate == nil) then return #self.m_Data > 0; end
for idx, value in ipairs(self.m_Data) do
if (predicate(value)) then
return true
end
end
return false
end
-- Returns true if all items satisfy the predicate. If predicate is null, it returns true if the collection is empty.
function _all(self, predicate)
if (predicate == nil) then return #self.m_Data == 0; end
for idx, value in ipairs(self.m_Data) do
if (not predicate(value)) then
return false
end
end
return true
end
-- Returns the number of items satisfying the predicate. If predicate is null, it returns the number of items in the collection.
function _count(self, predicate)
if (predicate == nil) then return #self.m_Data; end
local result = 0
for idx, value in ipairs(self.m_Data) do
if (predicate(value)) then
result = result + 1
end
end
return result
end
-- Prints debug data.
function _dump(self)
print(_dumpData(self));
end
-- Returns a random item in the collection, or default if no items are present
function _random(self, default)
if (#self.m_Data == 0) then return default; end
return self.m_Data[math.random(1, #self.m_Data)]
end
-- Returns true if the collection contains the specified item
function _contains(self, item, comparator)
comparator = comparator or function (v1, v2) return v1 == v2; end
for idx, value in ipairs(self.m_Data) do
if (comparator(value, item)) then return true; end
end
return false
end
-- Calls the action for each item in the collection. Action takes 1 parameter: the item value.
-- If the action is a string, it calls that method with the additional parameters
function _foreach(self, action, ...)
if (type(action) == "function") then
for idx, value in ipairs(self.m_Data) do
action(value, from({...}):toTuple())
end
elseif (type(action) == "string") then
for idx, value in ipairs(self.m_Data) do
value[action](value, from({...}):toTuple())
end
else
loge("foreach called with unknown action type");
end
return self
end
-- Calls the accumulator for each item in the collection. Accumulator takes 2 parameters: value and the previous result of
-- the accumulator itself (firstvalue for the first call) and returns a new result.
function _map(self, accumulator, firstvalue)
local result = firstvalue
for idx, value in ipairs(self.m_Data) do
result = accumulator(value, result)
end
return result
end
-- Calls the accumulator for each item in the collection. Accumulator takes 3 parameters: value, the previous result of
-- the accumulator itself (nil on first call) and the previous associated-result of the accumulator(firstvalue for the first call)
-- and returns a new result and a new associated-result.
function _xmap(self, accumulator, firstvalue)
local result = nil
local lastval = firstvalue
for idx, value in ipairs(self.m_Data) do
result, lastval = accumulator(value, result, lastval)
end
return result
end
-- Returns the max of a collection. Selector is called with values and should return a number. Can be nil if collection is of numbers.
function _max(self, selector)
if (selector == nil) then
selector = function(n) return n; end
end
return self:xmap(function(v, r, l) local res = selector(v); if (l == nil or res > l) then return v, res; else return r, l; end; end, nil)
end
-- Returns the min of a collection. Selector is called with values and should return a number. Can be nil if collection is of numbers.
function _min(self, selector)
if (selector == nil) then
selector = function(n) return n; end
end
return self:xmap(function(v, r, l) local res = selector(v); if (l == nil or res < l) then return v, res; else return r, l; end; end, nil)
end
-- Returns the sum of a collection. Selector is called with values and should return a number. Can be nil if collection is of numbers.
function _sum(self, selector)
if (selector == nil) then
selector = function(n) return n; end
end
return self:map(function(n, r) r = r + selector(n); return r; end, 0)
end
-- Returns the average of a collection. Selector is called with values and should return a number. Can be nil if collection is of numbers.
function _average(self, selector)
local count = self:count()
if (count > 0) then
return self:sum(selector) / count
else
return 0
end
end
-- ============================================================
-- ENUMERATIONS
-- ============================================================
-- Enumeration of all the inventory slots
inventory =
{
head = 1,
torso = 2,
legs = 3,
feet = 4,
cloak = 5,
neck = 6,
handl = 7,
handr = 8,
gauntlets = 9,
bracers = 10,
hands = { 7, 8 },
backpack = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 },
armor = { 1, 2, 3, 4, 5, 6, 9 },
all = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 },
}
-- Enumeration of all the direction/facing values
facing =
{
north = 0,
east = 1,
south = 2,
west = 3
}
-- ============================================================
-- LUALINQ GENERATORS
-- ============================================================
-- Returns a grimq structure filled with names of entities contained
-- in one of the fw sets.
function fromFwSet(listname, sublistname)
local set = fw.lists[listname];
if (set ~= nil) and (sublistname ~= nil) then
set = set[sublistname];
end
return fromSet(set);
end
-- Returns a grimq structure containing all champions
function fromChampions()
local collection = { }
for i = 1, 4 do
collection[i] = party:getChampion(i)
end
return fromArrayInstance(collection)
end
-- Returns a grimq structure containing all enabled and alive champions
function fromAliveChampions()
local collection = { }
for i = 1, 4 do
local c = party:getChampion(i)
if (c:isAlive() and c:getEnabled()) then
table.insert(collection, c) -- fixed in 1.5
end
end
return fromArrayInstance(collection)
end
-- Returns a grimq structure containing all the items in the champion's inventory
-- champion => the specified champion to which the inventory is returned
-- [recurseIntoContainers] => true, to recurse into sacks, crates, etc.
-- [inventorySlots] => nil, or a table of integers to limit the search to the specified slots
-- [includeMouse] => if true, the mouse item is included in the search
function fromChampionInventory(champion, recurseIntoContainers, inventorySlots, includeMouse)
return fromChampionInventoryEx(champion, recurseIntoContainers, inventorySlots, includeMouse)
:select("entity")
end
-- Returns a grimq structure containing all the items in the party inventory
-- [recurseIntoContainers] => true, to recurse into sacks, crates, etc.
-- [inventorySlots] => nil, or a table of integers to limit the search to the specified slots
-- [includeMouse] => if true, the mouse item is included in the search
function fromPartyInventory(recurseIntoContainers, inventorySlots, includeMouse)
return fromChampions():selectMany(function(v) return fromChampionInventory(v, recurseIntoContainers, inventorySlots, includeMouse):toArray(); end)
end
-- [private] Creates an extended object
function _createExtEntity(_slotnumber, _entity, _champion, _container, _ismouse, _containerSlot, _alcove, _isworld)
return {
slot = _slotnumber,
entity = _entity,
item = _entity, -- this is for backward compatibilty only!!
champion = _champion,
container = _container,
ismouse = _ismouse,
containerSlot = _containerSlot,
alcove = _alcove,
isworld = _isworld,
destroy = function(self)
if (self.entity == party) then
gameover()
elseif (self.container ~= nil) then
self.container:removeItem(self.slot)
elseif (self.slot >= 0) then
self.champion:removeItem(self.slot)
elseif (self.ismouse) then
setMouseItem(nil)
else
self.entity:destroy()
end
end,
replaceCallback = function(self, constructor)
local obj = nil
if (self.entity == party) then
gameover()
elseif (self.container ~= nil) then
self.container:removeItem(self.slot)
obj = constructor()
self.container:insertItem(self.slot, obj)
elseif (self.slot >= 0) then
self.champion:removeItem(self.slot)
obj = constructor()
self.champion:insertItem(self.slot, obj)
elseif (self.ismouse) then
setMouseItem(nil)
obj = constructor()
setMouseItem(obj)
elseif (self.alcove ~= nil) then
self.entity:destroy()
obj = constructor()
self.alcove:addItem(obj)
elseif (self.isworld) then
local l = self.entity.level
local x = self.entity.x
local y = self.entity.y
local f = self.entity.facing
self.entity:destroy()
obj = constructor(l, x, y, f)
else
logw("itemobject.replaceCallback fallback on incompatible default")
end
return obj
end,
replace = function(self, itemname, desiredid)
return self:replaceCallback(function(l,x,y,f) return spawn(itemname, l, x, y, f, desiredid); end)
end,
debug = function(self)
local obj = nil
if (self.entity == party) then
print("=> entity is party")
elseif (self.container ~= nil) then
print("=> entity is slot " .. self.slot .. " of cont " .. self.container.id)
elseif (self.slot >= 0) then
print("=> entity is slot " .. self.slot .. " of champion ord#" .. self.champion:getOrdinal())
elseif (self.ismouse) then
print("=> entity is on mouse")
elseif (self.alcove ~= nil) then
print("=> entity is in alcove " .. self.alcove.id)
elseif (self.isworld) then
local l = self.entity.level
local x = self.entity.x
local y = self.entity.y
local f = self.entity.facing
print("=> entity is in world at level=".. l, " pos = (" .. x .. "," .. y .. ") facing=" .. f)
else
logw("itemobject.replaceCallback fallback on incompatible default")
end
return obj
end,
}
end
function _appendContainerItem(collection, item, champion, containerslot)
--print("appending contents of container " .. item.id)
for j = 1, CONTAINERITEM_MAXSLOTS do
if (item:getItem(j) ~= nil) then
--print(" appended " .. item:getItem(j).id)
table.insert(collection, _createExtEntity(j, item:getItem(j), champion, item, false, containerslot))
_appendContainerItem(collection, item:getItem(j), nil, j)
end
end
end
-- Returns a grimq structure containing item objects in the champion's inventory
-- champion => the specified champion to which the inventory is returned
-- [recurseIntoContainers] => true, to recurse into sacks, crates, etc.
-- [inventorySlots] => nil, or a table of integers to limit the search to the specified slots
-- [includeMouse] => if true, the mouse item is included in the search
function fromChampionInventoryEx(champion, recurseIntoContainers, inventorySlots, includeMouse)
if (inventorySlots == nil) then
inventorySlots = inventory.all
end
local collection = { }
for idx = 1, #inventorySlots do
local i = inventorySlots[idx];
local item = champion:getItem(i)
if (item ~= nil) then
table.insert(collection, _createExtEntity(i, item, champion, nil, false, -1))
if (recurseIntoContainers) then
_appendContainerItem(collection, item, champion, i)
end
end
end
if (includeMouse and (getMouseItem() ~= nil)) then
local item = getMouseItem()
table.insert(collection, _createExtEntity(-1, item, nil, nil, true, -1))
if (recurseIntoContainers) then
_appendContainerItem(collection, item, nil, -1)
end
end
return fromArrayInstance(collection)
end
-- Returns a grimq structure filled with extended entities of the contents of a container
function fromContainerItemEx(item)
local collection = { }
_appendContainerItem(collection, item, nil, -1)
return fromArrayInstance(collection)
end
-- Returns a grimq structure containing all the item-objects in the party inventory
-- [recurseIntoContainers] => true, to recurse into sacks, crates, etc.
-- [inventorySlots] => nil, or a table of integers to limit the search to the specified slots
-- [includeMouse] => if true, the mouse item is included in the search
function fromPartyInventoryEx(recurseIntoContainers, inventorySlots, includeMouse)
return fromChampions():selectMany(function(v) return fromChampionInventoryEx(v, recurseIntoContainers, inventorySlots, includeMouse):toArray(); end)
end
-- Returns a grimq structure cotaining all the entities in the dungeon respecting a given *optional* condition
function fromAllEntitiesInWorld(predicate, refvalue, ...)
local result = { }
if (predicate == nil) then
for lvl = 1, MAXLEVEL do
for value in fromAllEntities(lvl):toIterator() do
table.insert(result, value)
end
end
elseif (type(predicate) == "function") then
for lvl = 1, MAXLEVEL do
for value in fromAllEntities(lvl):toIterator() do
if (predicate(value)) then
table.insert(result, value)
end
end
end
else
local refvals = {...}
if (#refvals > 0) then
local refset = { }
for _, l in ipairs(refvals) do refset[l] = true; end
refset[refvalue] = true;
for lvl = 1, MAXLEVEL do
for value in fromAllEntities(lvl):toIterator() do
if (refset[value[predicate]]) then
table.insert(result, value)
end
end
end
else
for lvl = 1, MAXLEVEL do
for value in fromAllEntities(lvl):toIterator() do
if (value[predicate] == refvalue) then
table.insert(result, value)
end
end
end
end
end
return fromArrayInstance(result)
end
-- Returns a grimq structure cotaining all the entities in an area
function fromEntitiesInArea(level, x1, y1, x2, y2, skipx, skipy)
local itercoll = { }
if (skipx == nil) then skipx = -10000; end
if (skipy == nil) then skipy = -10000; end
local stepx = 1
if (x1 > x2) then stepx = -1; end
local stepy = 1
if (y1 > y2) then stepy = -1; end
for x = x1, x2, stepx do
for y = y1, y2, stepy do
if (skipx ~= x) or (skipy ~= y) then
table.insert(itercoll, entitiesAt(level, x, y))
end
end
end
return fromIteratorsArray(itercoll)
end
function fromEntitiesAround(level, x, y, radius, includecenter)
if (radius == nil) then radius = 1; end
if (includecenter == nil) or (not includecenter) then
return fromEntitiesInArea(level, x - radius, y - radius, x + radius, y + radius, x, y)
else
return fromEntitiesInArea(level, x - radius, y - radius, x + radius, y + radius)
end
end
function fromEntitiesForward(level, x, y, facing, distance, includeorigin)
if (distance == nil) then distance = 1; end
local dx, dy = getForward(facing)
local dx = dx * distance
local dy = dy * distance
if (includeorigin == nil) or (not includeorigin) then
return fromEntitiesInArea(level, x, y, x + dx, y + dy, x, y)
else
return fromEntitiesInArea(level, x, y, x + dx, y + dy, nil, nil)
end
end
function fromAllEntities(level)
if (PATCH_ALLENTITIES_BUG) then
local result = { }
for i=0,31 do
for j=0,31 do
for k in entitiesAt(level,i,j) do
table.insert(result, k)
end
end
end
return fromArrayInstance(result)
else
return grimq.from(allEntities(level))
end
end
-- ============================================================
-- PREDICATES
-- ============================================================
function isMonster(entity)
return entity.setAIState ~= nil
end
function isItem(entity)
return entity.getWeight ~= nil
end
function isAlcoveOrAltar(entity)
return entity.getItemCount ~= nil
end
function isContainerOrAlcove(entity)
return entity.containedItems ~= nil
end
function isDoor(entity)
return (entity.setDoorState ~= nil)
end
function isLever()
return (entity.getLeverState ~= nil)
end
function isLock(entity)
return (entity.setOpenedBy ~= nil) and (entity.setDoorState == nil)
end
function isPit(entity)
return (entity.setPitState ~= nil)
end
function isSpawner(entity)
return (entity.setSpawnedEntity ~= nil)
end
function isScript(entity)
return (entity.setSource ~= nil)
end
function isPressurePlate(entity)
return (entity.isDown ~= nil)
end
function isTeleport(entity)
return (entity.setChangeFacing ~= nil)
end
function isTimer(entity)
return (entity.setTimerInterval ~= nil)
end
function isTorchHolder(entity)
return (entity.hasTorch ~= nil)
end
function isWallText(entity)
return (entity.getWallText ~= nil)
end
function match(attribute, namepattern)
return function(entity)
return string.find(entity[attribute], namepattern) ~= nil
end
end
function has(attribute, value)
return function(entity)
return entity[attribute] == value
end
end
-- ============================================================
-- UTILITY FUNCTIONS
-- ============================================================
-- saves an item into the table
function saveItem(item, slot)
local itemTable = { }
itemTable.id = item.id
itemTable.name = item.name
itemTable.stackSize = item:getStackSize()
itemTable.fuel = item:getFuel()
itemTable.charges = item:getCharges()
itemTable.scrollText = item:getScrollText()
itemTable.scrollImage = item:getScrollImage()
itemTable.slot = slot
for j = 1, CONTAINERITEM_MAXSLOTS do
if (item:getItem(j) ~= nil) then
if (itemTable.subItems == nil) then itemTable.subItems = {}; end
table.insert(itemTable.subItems, saveItem(item:getItem(j), j))
end
end
return itemTable
end
-- loads an item from the table
function loadItem(itemTable, level, x, y, facing, id, restoresubids)
if (tonumber(id) ~= nil) then
id = nil
end
local spitem = nil
if (level ~= nil) then
spitem = spawn(itemTable.name, level, x, y, facing, id)
else
spitem = spawn(itemTable.name, nil, nil, nil, nil, id)
end
if itemTable.stackSize > 0 then
spitem:setStackSize(itemTable.stackSize)
end
if itemTable.charges > 0 then
spitem:setCharges(itemTable.charges)
end
if itemTable.scrollText ~= nil then
spitem:setScrollText(itemTable.scrollText)
end
if itemTable.scrollImage ~= nil then
spitem:setScrollImage(itemTable.scrollImage)
end
spitem:setFuel(itemTable.fuel)
if (itemTable.subItems ~= nil) then
for _, subTable in pairs(itemTable.subItems) do
local subid = nil
if (restoresubids) then
subid = subTable.id
end
local subItem = loadItem(subTable, nil, nil, nil, nil, subid, restoresubids)
if (subTable.slot ~= nil) then
spitem:insertItem(subTable.slot, subItem)
else
spitem:addItem(subItem)
end
end
end
return spitem
end
-- Creates a copy of an item
function copyItem(item)
return loadItem(saveItem(item))
end
-- Moves an item, preserving id
function moveItem(item, level, x, y, facing)
local saved = saveItem(item)
destroy(item)
return loadItem(saved, level, x, y, facing, saved.id, true)
end
-- Moves an item, preserving id, faster version if we know the item is in the world
function moveItemFromFloor(item, level, x, y, facing)
local saved = saveItem(item)
item:destroy()
return loadItem(saved, level, x, y, facing, saved.id, true)
end
-- Moves an item to a container/alcove
-- New 1.4: preserves ids
function moveFromFloorToContainer(alcove, item)
alcove:addItem(moveItemFromFloor(item))
end
-- New 1.4: preserves ids
function moveItemsFromTileToAlcove(alcove)
from(entitiesAt(alcove.level, alcove.x, alcove.y))
:where(isItem)
:foreach(function(i)
moveFromFloorToContainer(alcove, i)
end)
end
g_ToorumMode = nil
function isToorumMode()
if (g_ToorumMode == nil) then
local rangerDetected = fromChampions():where(function(c) return (c:getClass() == "Ranger"); end):count()
local zombieDetected = fromChampions():where(function(c) return ((not c:getEnabled()) and (c:getStatMax("health") == 0)); end):count()
g_ToorumMode = (rangerDetected >= 1) and (zombieDetected == 3)
end
return g_ToorumMode
end
function dezombifyParty()
local portraits = { "human_female_01", "human_female_02", "human_male_01", "human_male_02" }
local genders = { "female", "female", "male", "male" }
local names = { "Sylyna", "Yennica", "Contar", "Sancsaron" }
for c in fromChampions():where(function(c) return ((not c:getEnabled()) and (c:getStatMax("health") == 0)); end):toIterator() do
c:setStatMax("health", 25)
c:setStatMax("energy", 10)
c:setPortrait("assets/textures/portraits/" .. portraits[i] .. ".tga")
c:setName(names[i])
c:setSex(genders[i])
end
end
function reverseFacing(facing)
return (facing + 2) % 4;
end
function getChampionFromOrdinal(ord)
return grimq.fromChampions():where(function(c) return c:getOrdinal() == ord; end):first()
end
function setLogLevel(level)
LOG_LEVEL = level
end
-- 1.3
function directionFromPos(fromx, fromy, tox, toy)
local dx = tox - fromx
local dy = toy - fromy
return directionFromDelta(dx, dy)
end
function directionFromDelta(dx, dy)
if (dx > dy) then dy = 0; else dx = 0; end
if (dy < 0) then return 0;
elseif (dx > 0) then return 1;
elseif (dy > 0) then return 2;
else return 3; end
end
function find(id, ignoreCornerCases)
local entity = findEntity(id)
if (entity ~= nil) then return entity; end
entity = fromPartyInventory(true, inventory.all, true):where("id", id):first()
if (entity ~= nil) then return entity; end
if (not ignoreCornerCases) then
local containers = fromAllEntitiesInWorld(isItem)
:selectMany(function(i) return from(i:containedItems()):toArray(); end)
entity = containers
:where(function(ii) return ii.id == id; end)
:first()
if (entity ~= nil) then return entity; end
entity = containers
:selectMany(function(i) return from(i:containedItems()):toArray(); end)
:where(function(ii) return ii.id == id; end)
:first()
end
return entity
end
function getEx(entity)
-- entity isn't in world, try inventory
local itemInInv = fromPartyInventoryEx(true, inventory.all, true)
:where(function(i) return i.entity == entity; end)
:first()
if (itemInInv ~= nil) then
return itemInInv
end
-- inventory failed, we try alcoves and containers
-- if we don't have an entity level, we in an obscure "item in sack in alcove" scenario
if (entity.level == nil) then
local topcontainers = fromAllEntitiesInWorld(isContainerOrAlcove)
local container = topcontainers
:where(function(a) return from(a:containedItems()):where(function(ii) return ii == entity; end):any(); end)
:first()
if (container ~= nil) then
local itemInInv = fromContainerItemEx(container)
:where(function(i) return i.entity == entity; end)
:first()
return itemInInv
end
container = topcontainers
:selectMany(function(i) return from(i:containedItems()):toArray(); end)
:where(function(a) return from(a:containedItems()):where(function(ii) return ii == entity; end):any(); end)
:first()
if (container ~= nil) then
local itemInInv = fromContainerItemEx(container)
:where(function(i) return i.entity == entity; end)
:first()
return itemInInv
else
logw("findAndCallback can't find item " .. entity.id)
return
end
end
-- we are in classic alcove or container scenario here
local alcoveOrContainer = from(entitiesAt(entity.level, entity.x, entity.y))
:where(isContainerOrAlcove)
:where(function(a) return from(a:containedItems()):where(function(ii) return ii == entity; end):any(); end)
:first()
if (alcoveOrContainer ~= nil) then
if (isAlcoveOrAltar(alcoveOrContainer)) then
return _createExtEntity(-1, entity, nil, nil, false, -1, alcoveOrContainer, nil)
else
local itemInInv = fromContainerItemEx(alcoveOrContainer)
:where(function(i) return i.entity == entity; end)
:first()
return itemInInv
end
end
-- the simplest case sadly happens last
local wentity = findEntity(entity.id)
if (wentity ~= nil) then
return _createExtEntity(-1, entity, nil, nil, false, -1, nil, true)
end
logw("findAndCallback can't find entity " .. entityid)
end
function gameover()
damageTile(party.level, party.x, party.y, party.facing, 64, "physical", 100000000)
end
function findEx(entityid)
local entity = find(entityid)
if (entity == nil) then
return nil
end
return getEx(entity)
end
function replace(entity, entityToSpawn, desiredId)
local ex = getEx(entity)
if (ex ~= nil) then
ex:replace(entityToSpawn, desiredId)
end
end
function destroy(entity)
local ex = getEx(entity)
if (ex ~= nil) then
ex:destroy()
end
end
function partyGainExp(amount)
grimq.fromAliveChampions():foreach(function(c) c:gainExp(amount); end)
end
function shuffleCoords(l, x, y, f, max)
local m = 17 * l + 5 * x + 13 * y - 7 * f
return (m % max) + 1
end
function randomReplacer(name, listOfReplace)
for o in fromAllEntitiesInWorld("name", name) do
local newname = listOfReplace[math.random(1, #listOfReplace)]
if (newname ~= "") then
spawn(newname, o.level, o.x, o.y, o.facing)
end
o:destroy()
end
end
function decorateWalls(level, listOfDecorations, useRandomNumbers)
for x = -1, 32 do
for y = -1, 32 do
if (x < 0 or x > 31 or y < 0 or y > 31 or isWall(level, x, y)) then
for f = 0, 3 do
local dx, dy = getForward(f)
if (not isWall(level, x + dx, y + dy)) then
local rf = (f + 2) % 4
local hasdeco = grimq.from(entitiesAt(level, x + dx, y + dy)):where(function(o)
return ((o.facing == rf) or (string.find(o.name, "stairs") ~= nil)) and (not grimq.isItem(o)) and (not grimq.isMonster(o)) end):any()
if (not hasdeco) then
local index = 1
if (useRandomNumbers) then
index = math.random(1, #listOfDecorations)
else
index = shuffleCoords(level, x + dx, y + dy, rf, #listOfDecorations)
end
local newname = listOfDecorations[index]
if (newname ~= "") then
if (type(newname) == "table") then
for _, w in ipairs(newname) do
spawn(w, level, x+dx, y+dy, rf)
end
else
spawn(newname, level, x+dx, y+dy, rf)
end
end
end
end
end
end
end
end
end
function decorateOver(level, nameOverWhich, listOfDecorations, useRandomNumbers)
grimq.fromAllEntities(level):where("name", nameOverWhich):foreach(function(o)
local index = 1
if (useRandomNumbers) then
index = math.random(1, #listOfDecorations)
else
index = shuffleCoords(level, o.x, o.y, o.facing, #listOfDecorations)
end
local newname = listOfDecorations[index]
if (newname ~= "") then
if (type(newname) == "table") then
for _, w in ipairs(newname) do
spawn(w, level, o.x, o.y, o.facing)
end
else
spawn(newname, level, o.x, o.y, o.facing)
end
end
end)
end
function partyDist(x, y)
return math.abs(party.x - x) + math.abs(party.y - y)
end
function spawnSmart(level, spawners, spawnedEntityNames, maxEntities, minDistance)
minDistance = minDistance or 7;
local count = grimq.fromAllEntities(level)
:where(grimq.isMonster)
:intersectionby("name", spawnedEntityNames)
:count();
if count >= maxEntities then
return 0;
end
local spawner = spawners[math.random(1, #spawners)]
local dist = partyDist(spawner.x, spawner.y)
if dist < minDistance then
return 0;
end
spawner:activate()
return 1;
end
function replaceMonster(m, newname)
local x = m.x
local y = m.y
local f = m.facing
local l = m.level
local id = m.id
local hp = m:getHealth()
local lvl = m:getLevel()
if (tonumber(id) ~= nil) then
id = nil
end
if (hp > 0) then
m:destroy()
spawn(newname, l, x, y, f, id)
:setLevel(lvl)
:setHealth(hp)
end
end
function spawnOver(entity, spawnname, overridefacing)
local facing = overridefacing or entity.facing;
spawn(spawnname, entity.level, entity.x, entity.y, facing);
end
-- ============================================================
-- STRING FUNCTIONS
-- ============================================================
-- $1.. $9 -> replaces with func parameters
-- $champ1..$champ4 -> replaces with name of champion of slot x
-- $CHAMP1..$CHAMP4 -> replaces with name of champion in ordinal x
-- $rchamp -> random champion, any
-- $RCHAMP -> random champion, alive
function strformat(text, ...)
local args = {...}
for i, v in ipairs(args) do
text = string.gsub(text, "$" .. i, tostring(v))
end
for i = 1, 4 do
local c = party:getChampion(i)
local name = c:getName()
text = string.gsub(text, "$champ" .. i, name)
local ord = c:getOrdinal()
text = string.gsub(text, "$CHAMP" .. ord, name)
end
text = string.gsub(text, "$rchamp", fromChampions():select(function(c) return c:getName(); end):random())
text = string.gsub(text, "$RCHAMP", fromAliveChampions():select(function(c) return c:getName(); end):random())
return text
end
-- see http://lua-users.org/wiki/StringRecipes
function strstarts(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
-- see http://lua-users.org/wiki/StringRecipes
function strends(String,End)
return End=='' or string.sub(String,-string.len(End))==End
end
function strmatch(value, pattern)
return string.find(value, pattern) ~= nil
end
function strlines(str)
local count = 0
local byte_char = string.byte("\n")
for i = 1, #str do
if string.byte(str, i) == byte_char then
count = count + 1
end
end
return count + 1
end
-- ============================================================
-- AUTO-OBJECTS
-- ============================================================
function _activateAutos()
-- cache is toorum mode result, so that we remember being toorum after party is manipulated
local toorummode = isToorumMode()
logv("Toorum mode: ".. tostring(toorummode))
logv("Starting auto-secrets... (AUTO_ALL_SECRETS is " .. tostring(AUTO_ALL_SECRETS) .. ")")
if (AUTO_ALL_SECRETS) then
fromAllEntitiesInWorld("name", "secret"):foreach(_initializeAutoSecret)
else
fromAllEntitiesInWorld(match("id", "^auto_secret")):foreach(_initializeAutoSecret)
end
logv("Starting auto-printers...")
fromAllEntitiesInWorld("name", "auto_printer"):foreach(_initializeAutoHudPrinter)
logv("Starting auto-torches...")
fromAllEntitiesInWorld(isTorchHolder):where(match("name", "^auto_")):foreach(function(auto) if (not auto:hasTorch()) then auto:addTorch(); end; end)
logv("Starting auto-alcoves...")
fromAllEntitiesInWorld(isAlcoveOrAltar):where(match("name", "^auto_")):foreach(moveItemsFromTileToAlcove)
logv("Starting autoexec scripts...")
fromAllEntitiesInWorld(isScript):foreach(_initializeAutoScript)
logi("Started.")
end
function _initializeAutoSecret(auto)
local plate = spawn("pressure_plate_hidden", auto.level, auto.x, auto.y, auto.facing)
:setTriggeredByParty(true)
:setTriggeredByMonster(false)
:setTriggeredByItem(false)
:setSilent(true)
:setActivateOnce(true)
:addConnector("activate", auto.id, "activate")
end
function _initializeAutoHudPrinter(auto)
local plate = spawn("pressure_plate_hidden", auto.level, auto.x, auto.y, auto.facing)
:setTriggeredByParty(true)
:setTriggeredByMonster(false)
:setTriggeredByItem(false)
:setSilent(true)
:setActivateOnce(true)
:addConnector("activate", "grimq", "execHudPrinter")
g_HudPrinters[plate.id] = auto:getScrollText()
auto:destroy()
end
g_HudPrinters = { }
g_HudPrintFunction = nil
function setFunctionForHudPrint(fn)
g_HudPrintFunction = fn
end
function printHud(text)
if (g_HudPrintFunction == nil) then
hudPrint(strformat(text))
else
g_HudPrintFunction(strformat(text))
end
end
function execHudPrinter(source)
logv("Executing hudprinter " .. source.id)
local text = g_HudPrinters[source.id]
if (text ~= nil) then
printHud(text)
else
logw("Auto-hud-printer not found in hudprinters list: " .. source.id)
end
end
-- NEW
function _initializeAutoScript(ntt)
if (ntt.autoexec ~= nil) then
logv("Executing autoexec of " .. ntt.id .. "...)")
ntt:autoexec();
end
if (ntt.auto_onStep ~= nil) then
logv("Install auto_onStep hook for " .. ntt.id .. "...)")
spawn("pressure_plate_hidden", ntt.level, ntt.x, ntt.y, ntt.facing)
:setTriggeredByParty(true)
:setTriggeredByMonster(false)
:setTriggeredByItem(false)
:setSilent(true)
:setActivateOnce(false)
:addConnector("activate", ntt.id, "auto_onStep")
end
if (ntt.auto_onStepOnce ~= nil) then
logv("Install auto_onStepOnce hook for " .. ntt.id .. "...)")
spawn("pressure_plate_hidden", ntt.level, ntt.x, ntt.y, ntt.facing)
:setTriggeredByParty(true)
:setTriggeredByMonster(false)
:setTriggeredByItem(false)
:setSilent(true)
:setActivateOnce(true)
:addConnector("activate", ntt.id, "auto_onStepOnce")
end
end
function _initializeAutoHooks(ntt)
if (ntt.autoexecfw ~= nil) then
logv("Executing autoexecfw of " .. ntt.id .. "...)")
ntt:autoexecfw();
end
local autohook = ntt.autohook;
if (autohook == nil) then
autohook = ntt.autohooks;
end
if (autohook ~= nil) then
if (fw == nil) then
loge("_initializeAutoHooks called with nil fw ???.")
return
end
for hooktable in from(autohook):toIterator() do
local target = hooktable.key
local hooks = from(hooktable.value)
for hook in hooks:toIterator() do
local hookname = hook.key
local hookfn = hook.value
if (type(hookfn) == "function") then
logi("Adding *DEPRECATED* hook for: ".. ntt.id .. "." .. hookname .. " for target " .. target .. " ...")
fw.addHooks(target, ntt.id .. "_" .. target .. "_" .. hookname, { [hookname] = hook.value } )
logw("Hook: ".. ntt.id .. "." .. hookname .. " for target " .. target .. " is a function -- *DEPRECATED* use.")
elseif (type(hookfn) == "string") then
_installAutoHook(ntt, hookname, target, {fn = hookfn});
elseif (type(hookfn) == "table") then
_installAutoHook(ntt, hookname, target, hookfn);
else
loge("Hook: ".. ntt.id .. "." .. hookname .. " for target " .. target .. " is an unsupported type. Must be string or table.")
end
end
end
end
end
function _installAutoHook(ntt, hookname, target, hooktable)
local hookId = ntt.id .. "_" .. target .. "_" .. hookname;
logi("Adding hook for: ".. ntt.id .. "." .. hookname .. " for target " .. target .. " ...")
if (hooktable.vars == nil) then
hooktable.vars = { };
end
hooktable.vars._hook_entity = ntt.id;
hooktable.vars._hook_method = hooktable.fn;
fw.setHookVars(target, hookId, hookname, hooktable.vars)
fw.addHooks(target, hookId,
{
[hookname] = function(p1, p2, p3, p4, p5, p6, p7, p8, p9)
local vars = fw.getHookVars();
local ntt = findEntity(vars._hook_entity);
if (ntt == nil) then
loge("Can't find entity ".. vars._hook_entity);
else
return ntt[vars._hook_method](p1, p2, p3, p4, p5, p6, p7, p8, p9);
end
end,
}
, hooktable.ordinal
);
end
function _activateJKosFw()
fromAllEntitiesInWorld(isScript):foreach(_initializeAutoHooks)
end
-- ============================================================
-- BOOTSTRAP CODE
-- ============================================================
function _banner()
logi("GrimQ Version " .. LIB_VERSION_TEXT .. VERSION_SUFFIX .. " - Marco Mastropaolo (Xanathar)")
end
-- added by JKos -- note: as of v1.5 grimq *REQUIRES* jkos fw.
function activate()
logi("Starting with jkos-fw bootstrap...")
grimq._activateAutos()
grimq._activateJKosFw()
end
_banner()
MAXLEVEL = getMaxLevels()
if (isWall == nil) then
loge("This version of GrimQ requires Legend of Grimrock 1.3.6 or later!")
end
|
--[[
Copyright 2018 American Megatrends Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local RedfishHandler = require("redfish-handler")
-- The default handler that reports as missing resource
local DefaultHandler = class("DefaultHandler", RedfishHandler)
-- Default GET resource missing handler function
function DefaultHandler:get(url)
self:error_resource_missing_at_uri()
end
-- Default POST resource missing handler function
function DefaultHandler:post()
self:error_resource_missing_at_uri()
end
-- Default PUT resource missing handler function
function DefaultHandler:put()
self:error_resource_missing_at_uri()
end
-- Default PATCH resource missing handler function
function DefaultHandler:patch()
self:error_resource_missing_at_uri()
end
-- Default DELETE resource missing handler function
function DefaultHandler:delete()
self:error_resource_missing_at_uri()
end
return DefaultHandler |
local Plugin = script.Parent.Parent
local Roact = require(Plugin.Vendor.Roact)
local StudioComponents = require(Plugin.Vendor.StudioComponents)
local withTheme = StudioComponents.withTheme
local TabButton = Roact.Component:extend("TabButton")
function TabButton:init()
self:setState({ Hover = false })
self.onInputBegan = function(_, input)
if self.props.Disabled then
return
end
if input.UserInputType == Enum.UserInputType.MouseMovement then
self:setState({ Hover = true })
end
end
self.onInputEnded = function(_, input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
self:setState({ Hover = false })
end
end
end
function TabButton:render()
local modifier = Enum.StudioStyleGuideModifier.Default
if self.props.Disabled then
modifier = Enum.StudioStyleGuideModifier.Disabled
elseif self.props.Selected then
modifier = Enum.StudioStyleGuideModifier.Pressed
elseif self.state.Hover then
modifier = Enum.StudioStyleGuideModifier.Hover
end
return withTheme(function(theme)
return Roact.createElement("TextButton", {
AutoButtonColor = false,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Button, modifier),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border, modifier),
LayoutOrder = self.props.LayoutOrder,
Size = self.props.Size,
Text = self.props.Text,
Font = Enum.Font.SourceSans,
TextColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainText, modifier),
TextTruncate = Enum.TextTruncate.AtEnd,
TextSize = 14,
[Roact.Event.InputBegan] = self.onInputBegan,
[Roact.Event.InputEnded] = self.onInputEnded,
[Roact.Event.Activated] = function()
if not self.props.Disabled then
self.props.OnActivated()
end
end,
}, {
Top = Roact.createElement("Frame", {
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border, modifier),
BorderSizePixel = 0,
Size = UDim2.new(1, 0, 0, 1),
}),
Indicator = self.props.Selected and Roact.createElement("Frame", {
AnchorPoint = Vector2.new(0, 1),
BackgroundColor3 = Color3.fromRGB(0, 162, 255),
BackgroundTransparency = self.props.Disabled and 0.8 or 0,
BorderSizePixel = 0,
Position = UDim2.fromScale(0, 1),
Size = UDim2.new(1, 0, 0, 2),
}),
})
end)
end
return TabButton
|
require 'sys'
require 'gfx.go'
sys.sleep(1)
N = 1000
n = torch.Tensor(N,2):normal(0,1)
u = torch.Tensor(N,2):uniform(-1,1)
gfx.chart({
{values=n, key='Normal'},
{values=u, key='Uniform'},
}, {
width = 1024,
height = 768,
chart = 'scatter',
})
|
os.loadAPI("ws/Client.lua"); local Client = _G["Client.lua"]
if select("#", ...) == 0 then
print("Usage UpdateSafeZone [start|end]")
return
end
local cmd = select(1, ...)
local x, y, z = gps.locate()
if cmd == "start" then
sendMessage("setSafeStart " .. x .. ", " .. z)
elseif cmd == "end" then
sendMessage("setSafeEnd " .. x .. ", " .. z)
end
--print(response.x .. ", " .. response.y)
--
--local response = Client.sendMessage("getSafeEnd")
--print(response.x .. ", " .. response.y) |
require 'dpnn'
require 'nn'
require 'optim'
if cuda then
require 'cunn'
require 'cutorch'
-- require 'inn'
end
if cuda_nn then
require 'cudnn'
end
require 'accuracy'
require 'batcher'
require 'batcherT'
ConvNet = {}
function ConvNet:__init()
obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
----------------------------------------------------------------
-- adjust_final
--
-- Reset the final layer for new targets.
----------------------------------------------------------------
function ConvNet:adjust_final(num_targets, target_type)
-- re-specify num targets
self.num_targets = num_targets
-- re-specify target_type
local target_type_seed = self.target_type
self.target_type = target_type or self.target_type
-- remove nonlinearity
if target_type_seed == "binary" or target_type_seed == "positive" then
self.model:remove()
end
-- save input size
local hidden_in = self.model.modules[#self.model].weight:size(2)
-- remove Linear
self.model:remove()
-- add final linear
self.model:add(nn.Linear(hidden_in, self.num_targets))
if self.target_type == "binary" then
-- add final nonlinearity
self.model:add(nn.Sigmoid())
-- binary cross-entropy loss
self.criterion = nn.BCECriterion()
elseif self.target_type == "positive" then
-- binary cross-entropy loss
self.model:add(nn.ReLU())
-- mean-squared error loss
self.criterion = nn.MSECriterion()
else
-- mean-squared error loss
self.criterion = nn.MSECriterion()
end
self.criterion.sizeAverage = false
-- cuda
if cuda then
print("Running on GPU.")
self.model:cuda()
self.criterion:cuda()
end
if cuda_nn then
self.model = cudnn.convert(self.model, cudnn)
end
-- retrieve parameters and gradients
self.parameters, self.gradParameters = self.model:getParameters()
-- print model summary
print(self.model)
end
----------------------------------------------------------------
-- adjust_optim
--
-- Reset the optim state and set optimization hyper-params
----------------------------------------------------------------
function ConvNet:adjust_optim(job)
-- number of examples per weight update
self.batch_size = job.batch_size or 128
-- base learning rate
self.learning_rate = job.learning_rate or 0.002
self.optim_state.learningRate = self.learning_rate
if self.optimization == "rmsprop" then
-- reset state
self.optim_state.m = nil
-- gradient momentum
self.momentum = job.momentum or 0.98
self.optim_state.alpha = self.momentum
elseif self.optimization == "adam" then
-- reset state
self.optim_state.t = nil
self.optim_state.m = nil
self.optim_state.v = nil
self.optim_state.denom = nil
-- gradients momentum
self.beta1 = job.beta1 or 0.9
self.optim_state.beta1 = self.beta1
self.beta2 = job.beta2 or 0.999
self.optim_state.beta2 = self.beta2
else
print("Unrecognized optimization algorithm")
exit(1)
end
end
----------------------------------------------------------------
-- build
--
-- Build the network using the job parameters and data
-- attributes.
----------------------------------------------------------------
function ConvNet:build(job, init_depth, init_len, num_targets)
-- parse network structure parameters
self:setStructureParams(job)
-- initialize model sequential
self.model = nn.Sequential()
-- store useful values
self.num_targets = num_targets
local depth = init_depth
local seq_len = init_len
-- convolution layers
for i = 1,self.conv_layers do
-- convolution
if i == 1 or self.conv_conn[i-1] == 1 then
-- TEMP padding
out_width = math.ceil(seq_len / self.conv_filter_strides[i])
pad_width = (out_width-1) * self.conv_filter_strides[i] + self.conv_filter_sizes[i] - seq_len
pad_left = math.floor(pad_width / 2)
print(string.format("seq_len: %d, filter_size: %d, pad_width: %d", seq_len, self.conv_filter_sizes[i], pad_width))
-- fully connected convolution
-- self.model:add(nn.SpatialConvolution(depth, self.conv_filters[i], self.conv_filter_sizes[i], 1))
self.model:add(nn.SpatialConvolution(depth, self.conv_filters[i], self.conv_filter_sizes[i], 1, self.conv_filter_strides[i], 1, pad_left, 0))
else
-- randomly connected convolution
num_to = torch.round(depth*self.conv_conn[i-1])
conn_matrix = nn.tables.random(depth, self.conv_filters[i], num_to)
self.model:add(nn.SpatialConvolutionMap(conn_matrix, self.conv_filter_sizes[i], 1))
end
-- TEMP: padding instead
-- update sequence length for filter pass
-- seq_len = seq_len - self.conv_filter_sizes[i] + 1
-- batch normalization (need to figure out how to ditch the bias above)
if self.batch_normalize then
self.model:add(nn.SpatialBatchNormalization(self.conv_filters[i]))
end
-- nonlinearity
self.model:add(nn.ReLU())
-- pooling
if self.pool_width[i] > 1 then
if self.pool_op == "max" then
-- trimming the seq
pseq_len = math.ceil(seq_len / self.pool_width[i])
pool_mod = nn.SpatialMaxPooling(self.pool_width[i], 1)
pool_mod:ceil()
self.model:add(pool_mod)
else
pseq_len = math.floor(seq_len / self.pool_width[i])
self.model:add(inn.SpatialStochasticPooling(self.pool_width[i],1))
end
seq_len = pseq_len
end
-- dropout
if self.conv_dropouts[i] > 0 then
self.model:add(nn.Dropout(self.conv_dropouts[i]))
end
-- update helper
depth = self.conv_filters[i]
end
-- too much pooling
if seq_len <= 0 then
return false
end
-- prep for fully connected layers
hidden_in = depth*seq_len
self.model:add(nn.Reshape(hidden_in))
-- fully connected hidden layers
for i =1,self.hidden_layers do
-- linear transform
self.model:add(nn.Linear(hidden_in, self.hidden_units[i]))
-- batch normalization (need to figure out how to ditch the bias above)
if self.batch_normalize then
self.model:add(nn.BatchNormalization(self.hidden_units[i]))
end
-- nonlinearity
self.model:add(nn.ReLU())
-- dropout
if self.hidden_dropouts[i] > 0 then
self.model:add(nn.Dropout(self.hidden_dropouts[i]))
end
-- update helper
hidden_in = self.hidden_units[i]
end
if self.target_type == "binary" then
-- final layer w/ target priors as initial biases
final_linear = nn.Linear(hidden_in, self.num_targets)
-- target_priors = targets:mean(1):squeeze()
-- biases_init = -torch.log(torch.pow(target_priors, -1) - 1)
-- final_linear.bias = biases_init
self.model:add(final_linear)
self.model:add(nn.Sigmoid())
-- binary cross-entropy loss
self.criterion = nn.BCECriterion()
elseif self.target_type == "positive" then
-- final layer
self.model:add(nn.Linear(hidden_in, self.num_targets))
self.model:add(nn.ReLU())
-- mean-squared error loss
self.criterion = nn.MSECriterion()
else
-- final layer
self.model:add(nn.Linear(hidden_in, self.num_targets))
-- mean-squared error loss
self.criterion = nn.MSECriterion()
end
self.criterion.sizeAverage = false
-- cuda
if cuda then
print("Running on GPU.")
self.model:cuda()
self.criterion:cuda()
end
if cuda_nn then
self.model = cudnn.convert(self.model, cudnn)
end
-- retrieve parameters and gradients
self.parameters, self.gradParameters = self.model:getParameters()
-- print model summary
print(self.model)
-- the following code breaks the program, but
-- it's interesting to see those counts!
-- print(string.format("Sum: %7d parameters",(#self.parameters)[1]))
-- for i = 1,(#self.model) do
-- local layer_params = self.model.modules[i]:getParameters()
-- local np = 0
-- if layer_params:nDimension() > 0 then
-- np = (#layer_params)[1]
-- end
-- print(string.format("Layer %2d: %7d", i, np))
-- end
return true
end
----------------------------------------------------------------
-- cuda
--
-- Move the model to the GPU. Untested.
----------------------------------------------------------------
function ConvNet:cuda()
if self.optimization == "rmsprop" then
self.optim_state.m = self.optim_state.m:cuda()
self.optim_state.tmp = self.optim_state.tmp:cuda()
elseif self.optimization == "adam" then
self.optim_state.m = self.optim_state.m:cuda()
self.optim_state.v = self.optim_state.v:cuda()
self.optim_state.denom = self.optim_state.denom:cuda()
end
self.criterion:cuda()
self.model:cuda()
if cuda_nn then
cudnn.convert(self.model, cudnn)
end
self.parameters, self.gradParameters = self.model:getParameters()
-- self.parameters = self.parameters:double()
-- self.gradParameters = self.gradParameters:double()
cuda = true
end
----------------------------------------------------------------
-- decuda
--
-- Move the model back to the CPU.
----------------------------------------------------------------
function ConvNet:decuda()
if self.optimization == "rmsprop" then
self.optim_state.m = self.optim_state.m:double()
self.optim_state.tmp = self.optim_state.tmp:double()
elseif self.optimization == "adam" then
self.optim_state.m = self.optim_state.m:double()
self.optim_state.v = self.optim_state.v:double()
self.optim_state.denom = self.optim_state.denom:double()
end
self.criterion:double()
if cuda_nn then
cudnn.convert(self.model, nn)
end
self.model:double()
self.parameters, self.gradParameters = self.model:getParameters()
-- self.parameters = self.parameters:double()
-- self.gradParameters = self.gradParameters:double()
cuda = false
end
----------------------------------------------------------------
-- drop_rate
--
-- Decrease the optimization learning_rate by a multiplier
----------------------------------------------------------------
function ConvNet:drop_rate()
self.learning_rate = self.learning_rate * 2/3
self.optim_state.learningRate = self.learning_rate
end
----------------------------------------------------------------
-- evaluate_mc
--
-- Change only the batch normalization layers to evaluate.
----------------------------------------------------------------
function ConvNet:evaluate_mc()
self.model:training()
mi = 1
while mi <= #(self.model.modules) do
-- print(torch.typename(self.model.modules[mi]))
if torch.typename(self.model.modules[mi]) == "cudnn.SpatialBatchNormalization" then
self.model.modules[mi]:evaluate()
-- print("eval")
end
if torch.typename(self.model.modules[mi]) == "cudnn.BatchNormalization" then
self.model.modules[mi]:evaluate()
-- print("eval")
end
mi = mi + 1
end
end
----------------------------------------------------------------
-- get_nonlinearity
--
-- Return the module representing nonlinearity x.
----------------------------------------------------------------
function ConvNet:get_nonlinearity(x)
local nl_modules = self.model:findModules('nn.ReLU')
return nl_modules[x]
end
function ConvNet:get_nonlinears(pool)
local relu_name = 'nn.ReLU'
if cuda_nn then
relu_name = 'cudnn.ReLU'
end
local nl_modules = {}
local ni = 1
local mi = 1
local conv_name
local conv_layers = self.conv_layers
if pool then
conv_name = 'nn.SpatialMaxPooling'
if self.pool_width[1] == 1 then
conv_layers = self.conv_layers - 1
end
else
conv_name = relu_name
end
-- add convolutions
for c = 1,conv_layers do
while mi <= #self.model.modules and torch.typename(self.model.modules[mi]) ~= conv_name do
mi = mi + 1
end
if torch.typename(self.model.modules[mi]) ~= conv_name then
error("Cannot find convolution modules " .. conv_name)
end
nl_modules[ni] = self.model.modules[mi]
ni = ni + 1
mi = mi + 1
end
-- add fully connected
while mi <= #(self.model.modules) do
if torch.typename(self.model.modules[mi]) == relu_name then
nl_modules[ni] = self.model.modules[mi]
ni = ni + 1
end
mi = mi + 1
end
return nl_modules
end
----------------------------------------------------------------
-- get_final
--
-- Return the module representing the final layer.
----------------------------------------------------------------
function ConvNet:get_final()
local layers = #self.model
return self.model.modules[layers-1]
end
function ConvNet:load(cnn)
for k, v in pairs(cnn) do
self[k] = v
end
end
----------------------------------------------------------------
-- predict
--
-- Predict targets for a new set of sequences.
----------------------------------------------------------------
function ConvNet:predict(Xf, batch_size, Xtens, rc_avg)
local bs = batch_size or self.batch_size
local batcher
if Xtens then
batcher = BatcherT:__init(Xf, nil, bs)
else
batcher = Batcher:__init(Xf, nil, bs)
end
-- find final model layer
local final_i = #self.model.modules - 1
if self.target_type == "continuous" then
final_i = final_i + 1
end
-- track predictions across batches
local preds = torch.FloatTensor(batcher.num_seqs, self.num_targets)
local scores = torch.FloatTensor(batcher.num_seqs, self.num_targets)
local pi = 1
-- collect garbage occasionaly
local cgi = 0
-- get first batch
local Xb = batcher:next()
-- while batches remain
while Xb ~= nil do
-- cuda
if cuda then
Xb = Xb:cuda()
end
-- predict
local preds_batch = self.model:forward(Xb)
local scores_batch = self.model.modules[final_i].output
if rc_avg then
-- save the forward orientation
local preds_batch_fwd = preds_batch:clone()
local scores_batch_fwd = scores_batch:clone()
-- reverse complement the sequences
local Xb_rc = self:rc_seqs(Xb)
-- predict. preds_batch now holds the reverse
self.model:forward(Xb_rc)
-- so add back the forward, and average
preds_batch = (preds_batch + preds_batch_fwd) / 2
scores_batch = (scores_batch + scores_batch_fwd) / 2
end
-- copy into larger Tensor
for i = 1,(#preds_batch)[1] do
preds[{pi,{}}] = preds_batch[{i,{}}]:float()
scores[{pi,{}}] = scores_batch[{i,{}}]:float()
pi = pi + 1
end
-- next batch
Xb = batcher:next()
-- collect garbage occasionaly
cgi = cgi + 1
if cgi % 100 == 0 then
collectgarbage()
end
end
return preds, scores
end
----------------------------------------------------------------
-- predict_mc
--
-- Predict targets for a new set of sequences.
----------------------------------------------------------------
function ConvNet:predict_mc(Xf, mc_n, batch_size, Xtens, rc_too)
local bs = batch_size or self.batch_size
local batcher
if Xtens then
batcher = BatcherT:__init(Xf, nil, bs)
else
batcher = Batcher:__init(Xf, nil, bs)
end
-- find final model layer
local final_i = #self.model.modules - 1
if self.target_type == "continuous" then
final_i = final_i + 1
end
-- track predictions across batches
local preds = torch.FloatTensor(batcher.num_seqs, self.num_targets)
local scores = torch.FloatTensor(batcher.num_seqs, self.num_targets)
local pi = 1
-- collect garbage occasionaly
local cgi = 0
-- get first batch
local Xb = batcher:next()
-- while batches remain
while Xb ~= nil do
-- cuda
if cuda then
Xb = Xb:cuda()
end
-- predict
local preds_batch = self.model:forward(Xb)
local scores_batch = self.model.modules[final_i].output
for mi = 2,mc_n do
local preds_batch_mc = self.model:forward(Xb)
local scores_batch_mc = self.model.modules[final_i].output
preds_batch = preds_batch + preds_batch_mc
scores_batch = scores_batch + scores_batch_mc
end
if rc_too then
-- reverse complement the sequences
local Xb_rc = self:rc_seqs(Xb)
for mi = 1,mc_n do
local preds_batch_mc = self.model:forward(Xb_rc)
local scores_batch_mc = self.model.modules[final_i].output
preds_batch = preds_batch + preds_batch_mc
scores_batch = scores_batch + scores_batch_mc
end
end
if rc_too then
preds_batch = preds_batch / (2*mc_n)
scores_batch = scores_batch / (2*mc_n)
else
preds_batch = preds_batch / mc_n
scores_batch = scores_batch / mc_n
end
-- copy into larger Tensor
for i = 1,(#preds_batch)[1] do
preds[{pi,{}}] = preds_batch[{i,{}}]:float()
scores[{pi,{}}] = scores_batch[{i,{}}]:float()
pi = pi + 1
end
-- next batch
Xb = batcher:next()
-- collect garbage occasionaly
cgi = cgi + 1
if cgi % 100 == 0 then
collectgarbage()
end
end
return preds, scores
end
----------------------------------------------------------------
-- predict_finalrep
--
-- Args:
--
-- Predict representations for a new set of sequences.
----------------------------------------------------------------
function ConvNet:predict_finalrepr(Xf, batch_size, Xtens)
local bs = batch_size or self.batch_size
local batcher
if Xtens then
batcher = BatcherT:__init(Xf, nil, bs)
else
batcher = Batcher:__init(Xf, nil, bs)
end
-- representation data structure
local init_repr = true
local repr
-- final modules
local nl_modules = self:get_nonlinears(pool)
local final_module = nl_modules[#nl_modules]
local bi = 1
-- get first batch
local Xb = batcher:next()
-- while batches remain
while Xb ~= nil do
-- cuda
if cuda then
Xb = Xb:cuda()
end
-- predict
self.model:forward(Xb)
-- get batch repr
local repr_batch = final_module.output
-- initialize reprs
if init_repr then
repr = torch.FloatTensor(batcher.num_seqs, (#repr_batch)[2])
init_repr = false
end
-- copy into larger tensor
local pi = bi
for i = 1,(#repr_batch)[1] do
repr[{pi,{}}] = repr_batch[{i,{}}]:float()
pi = pi + 1
end
-- next batch
Xb = batcher:next()
bi = bi + (#repr_batch)[1]
collectgarbage()
end
return repr
end
----------------------------------------------------------------
-- predict_reprs
--
-- Args:
-- repr_layers
-- Predict representations for a new set of sequences.
----------------------------------------------------------------
function ConvNet:predict_reprs(Xf, batch_size, Xtens, pool, repr_layers)
local bs = batch_size or self.batch_size
local batcher
if Xtens then
batcher = BatcherT:__init(Xf, nil, bs)
else
batcher = Batcher:__init(Xf, nil, bs)
end
-- find final model layer
local final_i = #self.model.modules - 1
if self.target_type == "continuous" then
final_i = final_i + 1
end
-- track predictions across batches
local preds = torch.FloatTensor(batcher.num_seqs, self.num_targets)
local scores = torch.FloatTensor(batcher.num_seqs, self.num_targets)
local reprs = {}
local init_reprs = true
local nl_modules = self:get_nonlinears(pool)
if repr_layers == nil then
repr_layers = {}
for li=1,#nl_modules do
repr_layers[li] = li
end
end
local bi = 1
-- get first batch
local Xb = batcher:next()
-- while batches remain
while Xb ~= nil do
-- cuda
if cuda then
Xb = Xb:cuda()
end
-- predict
local preds_batch = self.model:forward(Xb)
local scores_batch = self.model.modules[final_i].output
-- copy into larger tensor
local pi = bi
for i = 1,(#preds_batch)[1] do
preds[{pi,{}}] = preds_batch[{i,{}}]:float()
scores[{pi,{}}] = scores_batch[{i,{}}]:float()
pi = pi + 1
end
for li,l in ipairs(repr_layers) do
-- get batch repr
local reprs_batch = nl_modules[l].output
-- initialize reprs
if init_reprs then
if reprs_batch:nDimension() == 2 then
-- fully connected
reprs[l] = torch.FloatTensor(batcher.num_seqs, (#reprs_batch)[2], 1)
else
-- convolution
reprs[l] = torch.FloatTensor(batcher.num_seqs, (#reprs_batch)[2], (#reprs_batch)[4])
end
end
-- copy into larger tensor
local pi = bi
for i = 1,(#reprs_batch)[1] do
if reprs_batch:nDimension() == 2 then
-- fully connected
reprs[l][{pi,{}, 1}] = reprs_batch[{i,{}}]:float()
else
-- convolution
reprs[l][{pi,{},{}}] = reprs_batch[{i,{},{}}]:float():squeeze()
end
pi = pi + 1
end
end
-- reprs initialized
init_reprs = false
-- next batch
Xb = batcher:next()
bi = bi + (#preds_batch)[1]
collectgarbage()
end
return preds, scores, reprs
end
----------------------------------------------------------------
-- rc_seqs
--
-- Reverse complement a batch of sequences.
----------------------------------------------------------------
function ConvNet:rc_seqs(seqs)
local rc_seqs = seqs:clone()
local seq_len = (#seqs)[4]
for li=1,seq_len do
rc_seqs[{{},1,1,li}] = seqs[{{},4,1,seq_len-li+1}]
rc_seqs[{{},2,1,li}] = seqs[{{},3,1,seq_len-li+1}]
rc_seqs[{{},3,1,li}] = seqs[{{},2,1,seq_len-li+1}]
rc_seqs[{{},4,1,li}] = seqs[{{},1,1,seq_len-li+1}]
end
return rc_seqs
end
----------------------------------------------------------------
-- sanitize
--
-- Clear the intermediate states in the model before
-- saving to disk.
----------------------------------------------------------------
function ConvNet:sanitize()
local module_list = self.model:listModules()
for _,val in ipairs(module_list) do
for name,field in pairs(val) do
if torch.type(field) == 'cdata' then val[name] = nil end
if name == 'homeGradBuffers' then val[name] = nil end
if name == 'input_gpu' then val['input_gpu'] = {} end
if name == 'gradOutput_gpu' then val['gradOutput_gpu'] = {} end
if name == 'gradInput_gpu' then val['gradInput_gpu'] = {} end
if name == 'output' or name == 'gradInput' then
val[name] = field.new()
end
-- batch normalization
if name == 'buffer' or name == 'normalized' or name == 'centered' then
val[name] = field.new()
end
-- max pooling
if name == 'indices' then
val[name] = field.new()
end
end
end
end
----------------------------------------------------------------
-- setStructureParams
--
----------------------------------------------------------------
function ConvNet:setStructureParams(job)
---------------------------------------------
-- training
---------------------------------------------
-- number of examples per weight update
self.batch_size = job.batch_size or 128
-- optimization algorithm
self.optimization = job.optimization or "rmsprop"
-- base learning rate
self.learning_rate = job.learning_rate or 0.002
-- gradient update momentum
self.momentum = job.momentum or 0.98
-- adam momentums
self.beta1 = job.beta1 or 0.9
self.beta2 = job.beta2 or 0.999
-- batch normaliztion
if job.batch_normalize == nil then
self.batch_normalize = true
else
self.batch_normalize = job.batch_normalize
end
-- leaky ReLU leak parameter
-- self.leak = job.leak or 0.01
-- self.conv_leak = job.conv_leak or self.leak
-- self.final_leak = job.final_leak or self.leak
-- normalize weight vectors to this max
self.weight_norm = job.weight_norm or 10
---------------------------------------------
-- network structure
---------------------------------------------
-- number of filters per layer
self.conv_filters = job.conv_filters or {10}
if type(self.conv_filters) == "number" then
self.conv_filters = {self.conv_filters}
end
-- or determine via scaling
if job.conv_layers and job.conv_filters_scale then
self.conv_layers = job.conv_layers
for i=2,self.conv_layers do
self.conv_filters[i] = math.ceil(job.conv_filters_scale * self.conv_filters[i-1])
end
end
-- determine number of convolution layers
self.conv_layers = #self.conv_filters
-- convolution filter sizes
if job.conv_filter1_size == nil then
self.conv_filter_sizes = job.conv_filter_sizes or {10}
if type(self.conv_filter_sizes) == "number" then
self.conv_filter_sizes = {self.conv_filter_sizes}
end
else
self.conv_filter_sizes = {job.conv_filter1_size}
local l = 2
while job[string.format("conv_filter%d_size",l)] ~= nil do
self.conv_filter_sizes[l] = job[string.format("conv_filter%d_size",l)]
l = l + 1
end
end
-- or determine via scaling
if job.conv_layers and job.conv_size_scale then
for i=2,job.conv_layers do
self.conv_filter_sizes[i] = math.ceil(job.conv_size_scale * self.conv_filter_sizes[i-1])
end
end
-- convolution filter strides
self.conv_filter_strides = table_ext(job.conv_filter_strides, 1, self.conv_layers)
-- pooling widths
self.pool_width = table_ext(job.pool_width, 1, self.conv_layers)
-- or determine via scaling
if job.conv_layers and job.pool_width_scale then
for i=2,job.conv_layers do
self.pool_width[i] = math.ceil(job.pool_width_scale * self.pool_width[i-1])
end
end
-- pooling operation ("max", "stochastic")
self.pool_op = job.pool_op or "max"
-- random connections (need to test this with one layer, where it becomes irrelevant)
self.conv_conn = table_ext(job.conv_conn, 1, self.conv_layers-1)
-- number of hidden units in the final fully connected layers
self.hidden_units = table_ext(job.hidden_units, 500, 1)
-- number of fully connected final layers
self.hidden_layers = #self.hidden_units
-- target value type ("binary", "continuous", "positive")
self.target_type = job.target_type or "binary"
---------------------------------------------
-- regularization
---------------------------------------------
-- input dropout probability
-- self.input_dropout = job.input_dropout or 0
-- convolution dropout probabilities
self.conv_dropouts = table_ext(job.conv_dropouts, 0, self.conv_layers)
-- convolution gaussian noise stdev
self.conv_gauss = table_ext(job.conv_gauss, 0, self.conv_layers)
-- final dropout probabilities
self.hidden_dropouts = table_ext(job.hidden_dropouts, 0, self.hidden_layers)
-- final gaussian noise stdev
self.hidden_gauss = table_ext(job.hidden_gauss, 0, self.hidden_layers)
-- L2 parameter norm
self.coef_l2 = job.coef_l2 or 0
-- L1 parameter norm
self.coef_l1 = job.coef_l1 or 0
end
---------------------------------------------------------------
-- train_epoch
--
-- Train the model for one epoch through the data specified by
-- batcher.
----------------------------------------------------------------
function ConvNet:train_epoch(batcher, fwdrc)
local total_loss = 0
-- collect garbage occasionaly
collectgarbage()
local cgi = 0
-- get first batch
local inputs, targets = batcher:next()
-- while batches remain
while inputs ~= nil do
-- cuda
if cuda then
inputs = inputs:cuda()
targets = targets:cuda()
end
-- reverse complement the sequences
if not fwdrc then
inputs = self:rc_seqs(inputs)
end
-- create closure to evaluate f(X) and df/dX
local feval = function(x)
-- get new parameters
if x ~= self.parameters then
self.parameters:copy(x)
end
-- reset gradients
self.gradParameters:zero()
-- evaluate function for mini batch
local outputs = self.model:forward(inputs)
local f = self.criterion:forward(outputs, targets)
-- estimate df/dW
local df_do = self.criterion:backward(outputs, targets)
self.model:backward(inputs, df_do)
-- penalties
if self.coef_l2 > 0 then
-- add to loss
f = f + self.coef_l2 * torch.norm(self.parameters,2)^2/2
-- add to gradient
self.gradParameters:add(self.coef_l2, self.parameters)
end
if self.coef_l1 > 0 then
-- add to loss
f = f + self.coef_l1 * torch.norm(self.parameters,1)
-- add to gradient
self.gradParameters:add(torch.sign(self.parameters):mul(self.coef_l1))
end
-- return f and df/dX
return f, self.gradParameters
end
-- perform RMSprop step
if self.optimization == "rmsprop" then
self.optim_state = self.optim_state or {
learningRate = self.learning_rate,
alpha = self.momentum
}
optim.rmsprop(feval, self.parameters, self.optim_state)
elseif self.optimization == "adam" then
self.optim_state = self.optim_state or {
learningRate = self.learning_rate,
beta1 = self.beta1,
beta2 = self.beta2
}
optim.adam(feval, self.parameters, self.optim_state)
else
print("Unrecognized optimization algorithm")
exit(1)
end
-- cap weight paramaters
self.model:maxParamNorm(self.weight_norm)
-- accumulate loss
total_loss = total_loss + self.criterion.output
-- next batch
inputs, targets = batcher:next()
-- collect garbage occasionaly
cgi = cgi + 1
if cgi % 100 == 0 then
collectgarbage()
end
end
-- reset batcher
batcher:reset()
-- mean loss over examples
avg_loss = total_loss / batcher.num_seqs
return avg_loss
end
----------------------------------------------------------------
-- test
--
-- Predict targets for X and compare to Y.
----------------------------------------------------------------
function ConvNet:test(Xf, Yf, batch_size, rc_avg)
-- track the loss across batches
local loss = 0
-- collect garbage occasionaly
local cgi = 0
-- create a batcher to help
local batch_size = batch_size or self.batch_size
local batcher = Batcher:__init(Xf, Yf, batch_size)
-- track predictions across batches
local preds = torch.FloatTensor(batcher.num_seqs, self.num_targets)
local pi = 1
-- get first batch
local inputs, targets = batcher:next()
-- while batches remain
while inputs ~= nil do
-- cuda
if cuda then
inputs = inputs:cuda()
targets = targets:cuda()
end
-- predict
local preds_batch = self.model:forward(inputs)
if rc_avg then
-- save the forward orientation
local preds_batch_fwd = preds_batch:clone()
-- reverse complement the sequences
local rc_inputs = self:rc_seqs(inputs)
-- predict. preds_batch now holds the reverse
self.model:forward(rc_inputs)
-- so add back the forward, and average
preds_batch = (preds_batch + preds_batch_fwd) / 2
end
-- accumulate loss
loss = loss + self.criterion:forward(preds_batch, targets)
-- copy into larger Tensor
for i = 1,(#preds_batch)[1] do
preds[{pi,{}}] = preds_batch[{i,{}}]:float()
pi = pi + 1
end
-- next batch
inputs, targets = batcher:next()
-- collect garbage occasionaly
cgi = cgi + 1
if cgi % 100 == 0 then
collectgarbage()
end
end
-- mean loss over examples
local avg_loss = loss / batcher.num_seqs
-- save pred means and stds
self.pred_means = preds:mean(1):squeeze()
self.pred_stds = preds:std(1):squeeze()
local Ydim = batcher.num_targets
if self.target_type == "binary" then
-- compute AUC
local AUCs = torch.Tensor(Ydim)
local roc_points = {}
for yi = 1,Ydim do
-- read Yi from file
local Yi = Yf:partial({1,batcher.num_seqs},{yi,yi}):squeeze()
if(Yi:sum() == 0) then
roc_points[yi] = nil
AUCs[yi] = 1.0
else
-- compute ROC points
roc_points[yi] = ROC.points(preds[{{},yi}], Yi)
-- compute AUCs
AUCs[yi] = ROC.area(roc_points[yi])
end
collectgarbage()
end
return avg_loss, AUCs, roc_points
else
-- compute R2
local R2s = variance_explained(Yf, preds)
local cors = spearmanr(Yf, preds)
return avg_loss, R2s, cors
end
end
----------------------------------------------------------------
-- test_mc
--
-- Predict targets for X and compare to Y.
----------------------------------------------------------------
function ConvNet:test_mc(Xf, Yf, mc_n, batch_size, rc_too)
-- requires stochasticity
-- self.model:training()
-- track the loss across batches
local loss = 0
-- collect garbage occasionaly
local cgi = 0
-- create a batcher to help
local batch_size = batch_size or self.batch_size
local batcher = Batcher:__init(Xf, Yf, batch_size)
-- track predictions across batches
local preds = torch.FloatTensor(batcher.num_seqs, self.num_targets)
local pi = 1
-- get first batch
local inputs, targets = batcher:next()
-- while batches remain
while inputs ~= nil do
-- cuda
if cuda then
inputs = inputs:cuda()
targets = targets:cuda()
end
-- predict
local preds_batch = self.model:forward(inputs)
for mi = 2,mc_n do
local preds_batch_mc = self.model:forward(inputs)
preds_batch = preds_batch + preds_batch_mc
end
if rc_too then
-- reverse complement the sequences
local rc_inputs = self:rc_seqs(inputs)
for mi = 1,mc_n do
local preds_batch_mc = self.model:forward(rc_inputs)
preds_batch = preds_batch + preds_batch_mc
end
end
if rc_too then
preds_batch = preds_batch / (2*mc_n)
else
preds_batch = preds_batch / mc_n
end
-- accumulate loss
loss = loss + self.criterion:forward(preds_batch, targets)
-- copy into larger Tensor
for i = 1,(#preds_batch)[1] do
preds[{pi,{}}] = preds_batch[{i,{}}]:float()
pi = pi + 1
end
-- next batch
inputs, targets = batcher:next()
-- collect garbage occasionaly
cgi = cgi + 1
if cgi % 100 == 0 then
collectgarbage()
end
end
-- mean loss over examples
local avg_loss = loss / batcher.num_seqs
-- save pred means and stds
self.pred_means = preds:mean(1):squeeze()
self.pred_stds = preds:std(1):squeeze()
local Ydim = batcher.num_targets
if self.target_type == "binary" then
-- compute AUC
local AUCs = torch.Tensor(Ydim)
local roc_points = {}
for yi = 1,Ydim do
-- read Yi from file
local Yi = Yf:partial({1,batcher.num_seqs},{yi,yi}):squeeze()
if(Yi:sum() == 0) then
roc_points[yi] = nil
AUCs[yi] = 1.0
else
-- compute ROC points
roc_points[yi] = ROC.points(preds[{{},yi}], Yi)
-- compute AUCs
AUCs[yi] = ROC.area(roc_points[yi])
end
collectgarbage()
end
return avg_loss, AUCs, roc_points
else
-- compute R2
local R2s = variance_explained(Yf, preds)
return avg_loss, R2s
end
end
----------------------------------------------------------------
-- table_ext
--
-- Extend the table to be the given size, adding in the default
-- value to fill it.
----------------------------------------------------------------
function table_ext(try, default, size)
-- set var to try if available or default otherwise
var = try or default
-- if it was a number
if type(var) == "number" then
-- change default to the number
default = var
-- make it a table
var = {var}
end
-- extend the table if too small
for i = 2,size do
if i > #var then
var[i] = default
end
end
return var
end
|
solution = ""
ind = math.random(9)
for i = 0, 9 do
if i < ind then
solution = solution.."solution["..tostring(i).."]=1;"
else
solution = solution.."solution["..tostring(i).."]=0;"
end
end
out = "sum(result) == " .. ind
if (ITEM == 1) then
style = blue_style
image = "circle"
end
if (ITEM == 2) then
style = red_style
image = "triangle"
end
if (ITEM == 3) then
style = green_style
image = "square"
end
if (ind == 1) then
quest = name[1]
else
if (ind < 5) then
quest = name[2]
else
quest = name[3]
end
end
|
local turkishmode = {}
local core = require('turkishmode.core')
local api = vim.api
function turkishmode.deasciify_current_line()
local cur_line = api.nvim_get_current_line()
local deasciified = core.deasciify(cur_line)
api.nvim_set_current_line(deasciified)
end
function turkishmode.asciify_current_line()
local cur_line = api.nvim_get_current_line()
local asciified = core.asciify(cur_line)
api.nvim_set_current_line(asciified)
end
function turkishmode.deasciify_buffer(bufnr)
bufnr = bufnr or api.nvim_get_current_buf()
local lines = api.nvim_buf_get_lines(bufnr, 0, -1, true)
local buf_text = table.concat(lines, '\n')
local deasciified = core.deasciify(buf_text)
api.nvim_buf_set_lines(bufnr, 0, -1, true, vim.split(deasciified, '\n'))
end
function turkishmode.asciify_buffer(bufnr)
bufnr = bufnr or api.nvim_get_current_buf()
local lines = api.nvim_buf_get_lines(bufnr, 0, -1, true)
for i = 1, #lines do lines[i] = core.asciify(lines[i]) end
api.nvim_buf_set_lines(bufnr, 0, -1, true, lines)
end
function turkishmode.timeit()
local f = io.open('masal.txt', 'r')
local str = f:read('*a')
local start = os.clock()
core.deasciify(str)
local finish = os.clock()
print('time:', finish - start)
f:close()
end
function turkishmode.attach() end
function turkishmode.flush() end
function turkishmode.detach() end
return turkishmode
|
--default_lang.lua - default language
-- This file is under copyright, and is bound to the agreement stated in the EULA.
-- Any 3rd party content has been used as either public domain or with permission.
-- © Copyright 2016-2017 Aritz Beobide-Cardinal All rights reserved.
ARCSlots.Msgs = ARCSlots.Msgs or {}
ARCSlots.Msgs.Time = ARCSlots.Msgs.Time or {}
ARCSlots.Msgs.AdminMenu = ARCSlots.Msgs.AdminMenu or {}
ARCSlots.Msgs.Commands = ARCSlots.Msgs.Commands or {}
ARCSlots.Msgs.CommandOutput = ARCSlots.Msgs.CommandOutput or {}
ARCSlots.Msgs.Items = ARCSlots.Msgs.Items or {}
ARCSlots.Msgs.LogMsgs = ARCSlots.Msgs.LogMsgs or {}
ARCSlots.Msgs.Notifications = ARCSlots.Msgs.Notifications or {}
ARCSlots.Msgs.SlotMsgs = ARCSlots.Msgs.SlotMsgs or {}
ARCSlots.Msgs.VaultMsgs = ARCSlots.Msgs.VaultMsgs or {}
ARCSLOTS_ERRORSTRINGS = ARCPHONE_ERRORSTRINGS or {}
ARCSlots.SettingsDesc = ARCSlots.SettingsDesc or {}
--[[
____ ___ _ _ ___ _____ _____ ____ ___ _____ _____ _ _ _____ _ _ _ _ _____ ___ _ _____ _
| _ \ / _ \ | \ | |/ _ \_ _| | ____| _ \_ _|_ _| |_ _| | | | ____| | | | | | | / \ | ___|_ _| | | ____| |
| | | | | | | | \| | | | || | | _| | | | | | | | | | | |_| | _| | | | | | |/ _ \ | |_ | || | | _| | |
| |_| | |_| | | |\ | |_| || | | |___| |_| | | | | | | | _ | |___ | |__| |_| / ___ \ | _| | || |___| |___|_|
|____/ \___/ |_| \_|\___/ |_| |_____|____/___| |_| |_| |_| |_|_____| |_____\___/_/ \_\ |_| |___|_____|_____(_)
____ ___ _ _ ___ _____ _____ ____ ___ _____ _____ _ _ _____ _ _ _ _ _____ ___ _ _____ _
| _ \ / _ \ | \ | |/ _ \_ _| | ____| _ \_ _|_ _| |_ _| | | | ____| | | | | | | / \ | ___|_ _| | | ____| |
| | | | | | | | \| | | | || | | _| | | | | | | | | | | |_| | _| | | | | | |/ _ \ | |_ | || | | _| | |
| |_| | |_| | | |\ | |_| || | | |___| |_| | | | | | | | _ | |___ | |__| |_| / ___ \ | _| | || |___| |___|_|
|____/ \___/ |_| \_|\___/ |_| |_____|____/___| |_| |_| |_| |_|_____| |_____\___/_/ \_\ |_| |___|_____|_____(_)
____ ___ _ _ ___ _____ _____ ____ ___ _____ _____ _ _ _____ _ _ _ _ _____ ___ _ _____ _
| _ \ / _ \ | \ | |/ _ \_ _| | ____| _ \_ _|_ _| |_ _| | | | ____| | | | | | | / \ | ___|_ _| | | ____| |
| | | | | | | | \| | | | || | | _| | | | | | | | | | | |_| | _| | | | | | |/ _ \ | |_ | || | | _| | |
| |_| | |_| | | |\ | |_| || | | |___| |_| | | | | | | | _ | |___ | |__| |_| / ___ \ | _| | || |___| |___|_|
|____/ \___/ |_| \_|\___/ |_| |_____|____/___| |_| |_| |_| |_|_____| |_____\___/_/ \_\ |_| |___|_____|_____(_)
These are the default values in order to prevent you from screwing it up!
For a tutorial on how to create your own custom language, READ THE README!
There's even a command that lets you select from a range of pre-loaded languages!
type "arcslots settings language (lang)" in console
(lang) can be the following:
en -- English
fr -- French
ger -- German
pt_br -- Brazilian Portuguese
sp -- Spanish
]]
ARCSLOTS_ERRORSTRINGS[0] = "GIVE YOUR MONEY"
ARCSlots.Msgs.CommandOutput.SysReset = "System reset required! Please enter \"arcslots reset\""
ARCSlots.Msgs.CommandOutput.SysSetting = "%SETTING% has been changed to %VALUE%"
ARCSlots.Msgs.CommandOutput.AdminCommand = "You must be one of these ranks to use this command: %RANKS%"
ARCSlots.Msgs.CommandOutput.SettingsSaved = "Settings have been saved!"
ARCSlots.Msgs.CommandOutput.AdvSettingsSaved = "Advanced setting %SETTING% saved."
ARCSlots.Msgs.CommandOutput.SettingsError = "Error saving settings."
ARCSlots.Msgs.CommandOutput.ResetYes = "System reset!"
ARCSlots.Msgs.CommandOutput.ResetNo = "Error. Check server console for details. Or look at the latest system log located in garrysmod/data/_arcslots on the server."
ARCSlots.Msgs.CommandOutput.SaveSlots = "Slot Machines saved!"
ARCSlots.Msgs.CommandOutput.SaveSlotsNo = "Error while saving slot machines."
ARCSlots.Msgs.CommandOutput.UnSaveSlots = "Slot Machines detached from map!"
ARCSlots.Msgs.CommandOutput.UnSaveSlotsNo = "An error occurred while detaching Slot Machines from map."
ARCSlots.Msgs.CommandOutput.SpawnSlots = "Map-Based Slot Machines Spawned!"
ARCSlots.Msgs.CommandOutput.SpawnSlotsNo = "No Slot Machines associated with this map. (Non-existent/Corrupt file)"
ARCSlots.Msgs.CommandOutput.SaveVault = "Casino Vault and alarms saved!"
ARCSlots.Msgs.CommandOutput.SaveVaultNo = "Error while saving vault and alarms."
ARCSlots.Msgs.CommandOutput.UnSaveVault = "Casino Vault and alarms detached from map"
ARCSlots.Msgs.CommandOutput.UnSaveVaultNo = "An error occurred while detaching the Casino Vault from map."
ARCSlots.Msgs.Items.SlotMachine = "Slot Machine"
ARCSlots.Msgs.Time.nd = "and"
ARCSlots.Msgs.Time.second = "second"
ARCSlots.Msgs.Time.seconds = "seconds"
ARCSlots.Msgs.Time.minute = "minute"
ARCSlots.Msgs.Time.minutes = "minutes"
ARCSlots.Msgs.Time.hour = "hour"
ARCSlots.Msgs.Time.hours = "hours"
ARCSlots.Msgs.Time.day = "day"
ARCSlots.Msgs.Time.days = "days"
ARCSlots.Msgs.Time.forever = "forever"
ARCSlots.Msgs.Time.now = "now"
ARCSlots.Msgs.AdminMenu.Remove = "Remove"
ARCSlots.Msgs.AdminMenu.Add = "Add"
ARCSlots.Msgs.AdminMenu.Description = "Description:"
ARCSlots.Msgs.AdminMenu.Enable = "Enable"
ARCSlots.Msgs.AdminMenu.Settings = "Settings"
ARCSlots.Msgs.AdminMenu.AdvSettings = "Advanced Settings"
ARCSlots.Msgs.AdminMenu.ChooseSetting = "Choose setting"
ARCSlots.Msgs.AdminMenu.Commands = "Commands"
ARCSlots.Msgs.AdminMenu.SaveSettings = "Save Settings"
ARCSlots.Msgs.AdminMenu.Logs = "System Logs"
ARCSlots.Msgs.AdminMenu.Unavailable = "This feature is currently unavailable"
ARCSlots.Msgs.AdminMenu.SlotConfig = "Slot machine configuration menu"
ARCSlots.Msgs.AdminMenu.SlotIncome = "Income multiplier:"
ARCSlots.Msgs.AdminMenu.FreeSpin = "Free spin percent chance:"
ARCSlots.Msgs.AdminMenu.SlotPrize = "Prize:"
ARCSlots.Msgs.AdminMenu.SlotChance = "Chances:"
ARCSlots.Msgs.AdminMenu.Explination = "Some of these setting options are counter-intuitive and require explination. Would you like to see the explination?"
ARCSlots.Msgs.Notifications.NoMoney = "You do not have enough cash!"
ARCSlots.Msgs.Notifications.Pocket = "No matter how hard to try, you can't fit this giant thing in your pants!"
ARCSlots.Msgs.Notifications.AlarmVault = "You cannot spawn an alarm without a vault"
ARCSlots.Msgs.Notifications.VaultOne = "There can only be one vault"
ARCSlots.Msgs.Notifications.VaultARCBank = "The vault requires ARCBank v1.4.0 or later (the paid version)"
ARCSlots.Msgs.SlotMsgs.Yes = "Yes"
ARCSlots.Msgs.SlotMsgs.No = "No"
ARCSlots.Msgs.SlotMsgs.Lucky = "Feeling lucky today?"
ARCSlots.Msgs.SlotMsgs.Win = "YOU WON %AMOUNT%"
ARCSlots.Msgs.SlotMsgs.MegaWin = "WOW YOU WON %AMOUNT%"
ARCSlots.Msgs.SlotMsgs.Jackpot = "CONGRATULATIONS YOU HAVE WON THE MEGA JACKPOT *** YOU WON %AMOUNT%"
ARCSlots.Msgs.SlotMsgs.LooseMock = "HA HA HA NOT TODAY"
ARCSlots.Msgs.SlotMsgs.Loose = "BETTER LUCK NEXT TIME"
ARCSlots.Msgs.SlotMsgs.FreeSpins = "%AMOUNT% FREE SPINS!"
ARCSlots.Msgs.SlotMsgs.Bet = "bet"
ARCSlots.Msgs.SlotMsgs.BadLuck = "Being broke is bad Luck! If you get that bad card, you loose!"
ARCSlots.Msgs.SlotMsgs.Wild = "The WILD card can substitute for any other symbol!"
ARCSlots.Msgs.SlotMsgs.MaxPrize = "MAX PRIZE: %AMOUNT%"
ARCSlots.Msgs.SlotMsgs.BetMsg = "Select the amount you wish to bet:"
ARCSlots.Msgs.VaultMsgs.Funds = "VAULT FUNDS:"
ARCSlots.Msgs.VaultMsgs.TotalFunds = "TOTAL FUNDS:"
ARCSlots.Msgs.VaultMsgs.Status = "VAULT STATUS:"
ARCSlots.Msgs.VaultMsgs.Secure = "**SECURE**"
ARCSlots.Msgs.VaultMsgs.Warning = "** WARNING **"
ARCSlots.Msgs.VaultMsgs.Insecure = "**BREACHED**"
ARCSlots.Msgs.VaultMsgs.GettingCash = "You are entitled to receiving casino profits for the next %TIME%."
ARCSlots.Msgs.VaultMsgs.WithdrawAmount = "You can currently withdraw %AMOUNT%"
ARCSlots.Msgs.VaultMsgs.NotGettingCash = "You are currently not receiving casino profits."
ARCSlots.Msgs.VaultMsgs.PleaseCheckIn = "Please authenticate to start receiving casino profits"
ARCSlots.Msgs.VaultMsgs.CheckIn = "Authenticate as manager"
ARCSlots.Msgs.VaultMsgs.Exit = "Exit"
ARCSlots.Msgs.VaultMsgs.WithdrawCash = "Withdraw earnings as cash"
ARCSlots.Msgs.VaultMsgs.WithdrawBank = "Transfer earnings to bank account"
ARCSlots.Msgs.VaultMsgs.NotManager = "You are not a casino manager"
ARCSlots.Msgs.VaultMsgs.NoCash = "You cannot withdraw that much money"
ARCSlots.Msgs.VaultMsgs.NotAuthed = "You are not authenticated"
ARCSlots.Msgs.VaultMsgs.MaxManagers = "There are already the maximum amount of managers"
ARCSlots.Msgs.VaultMsgs.WhichAccount = "Which account would you like to send your funds to?"
ARCSlots.Msgs.VaultMsgs.Robbed = "The vault was robbed while you were on duty. You may not authenticate until your previous authentication expires or you regained the casino's profits."
ARCSlots.Msgs.Commands["slots_save"] = "Save all Slot machines"
ARCSlots.Msgs.Commands["slots_unsave"] = "Unsave all Slot machines"
ARCSlots.Msgs.Commands["slots_respawn"] = "Respawn Slot machines"
ARCSlots.Msgs.Commands["vault_save"] = "Save the vault"
ARCSlots.Msgs.Commands["vault_unsave"] = "Unsave the vault"
ARCSlots.SettingsDesc["name"] = "The displayed \"short\" name of the addon."
ARCSlots.SettingsDesc["name_long"] = "The displayed \"long\" name of the addon."
ARCSlots.SettingsDesc["slots_max_bet"] = "The maximum people can bet on the Slot Machines"
ARCSlots.SettingsDesc["slots_min_bet"] = "The minimum people can bet on the Slot Machines"
ARCSlots.SettingsDesc["slots_idle_text"] = "Text to display while the slot machine is idle"
ARCSlots.SettingsDesc["vault_steal_rate"] = "The amount of money a player can take from the vault per second."
ARCSlots.SettingsDesc["slots_incr"] = "How much the bet should increase by when the + button is pressed"
ARCSlots.SettingsDesc["slots_incr_big"] = "How much the bet should increase by when the ++ button is pressed"
ARCSlots.SettingsDesc["slots_handle"] = "If enabled, the slot machines will have the pull lever on their side"
ARCSlots.SettingsDesc["language"] = "Which language to use. If you want a custom language, create your own file in SERVER/garrysmod/data/_arcbank/languages"
ARCSlots.SettingsDesc["slots_volume"] = "How loud the slot machines should be (Between 0 and 1)"
ARCSlots.SettingsDesc["money_symbol"] = "The symbol of currency to display"
ARCSlots.SettingsDesc["legacy_bet_interface"] = "If enabled, the slot machines will use a popup window to select the bet instead of the immsersive interface."
ARCSlots.SettingsDesc["admins"] = "List of in game rank(s) that can use the admin GUI and the admin commands."
ARCSlots.SettingsDesc["vault_hack_max"] = "The maximum amount of money that can be taken from the vault by hacking it."
ARCSlots.SettingsDesc["vault_hack_min"] = "The minumum amount of money that can be taken from the vault by hacking it."
ARCSlots.SettingsDesc["vault_hack_time_max"] = "The maximum amount of time it takes to hack the vault."
ARCSlots.SettingsDesc["vault_hack_time_min"] = "The minimum amount of time it takes to hack the vault."
ARCSlots.SettingsDesc["vault_hack_time_stealth_rate"] = "Setting the ATM Hacker to \"stealth mode\" will multiply the hacking time by this amount"
ARCSlots.SettingsDesc["vault_hack_time_curve"] = "Please see aritzcracker.ca/uploads/aritz/atm_hack_time_curve.png"
ARCSlots.SettingsDesc["manager_auth_time"] = "The amount of minutes a casino manager will recieve profits after authenticating"
ARCSlots.SettingsDesc["manager_auth_teams"] = "People in these teams will be considered potential casino managers"
|
local function mult(x, y) return x * y end
local function mult_fold(elems)
local tot = 1
for _, v in pairs(elems) do
tot = tot * v
end
return tot
end
food_effects.eye_height_monoid = player_monoids.make_monoid({
combine = mult,
fold = mult_fold,
identity = 1,
apply = function(multiplier, player)
player:set_properties({
eye_height = 1.625 * multiplier
})
end,
})
|
--Castlevania: Rondo of Blood
fill = 0x64FFC8C8
line = 0xFFFFC8C8
function drawObjInfo()
for i = 0,88 do
objX = mainmemory.read_u8(0xBC8+i)
objY = mainmemory.read_u8(0xCD0+i)
objVisibleX = mainmemory.read_u8(0xB70+i)*255
objVisibleY = mainmemory.read_u8(0xC78+i)*255
objDamage = mainmemory.read_u8(0x1300+i) --how much damage it will do if it collides with you
objHealth = mainmemory.read_u8(0x12A8+i-2) --something is wrong, -2 makes it right in some cases but makes others wrong
objStatus = mainmemory.read_u8(0x1250+i) --collision status
adjustedX = objX - objVisibleX
adjustedY = objY - objVisibleY
--clipping
if(adjustedX > 0 and adjustedY > 0) then
gui.text(
adjustedX * xmult,
adjustedY * ymult,
objX
.. " " .. objY
-- .. " " .. "#" .. i
-- .. " D" .. objDamage
-- .. " HP" .. objHealth
-- .. " S" .. objStatus
)
end
end
end
function drawHitBoxes()
for i = 0,88 do
objX = mainmemory.read_u8(0xBC8+i)
objY = mainmemory.read_u8(0xCD0+i)
objVisibleX = mainmemory.read_u8(0xB70+i)*255
objVisibleY = mainmemory.read_u8(0xC78+i)*255
adjustedX = objX - objVisibleX
adjustedY = objY - objVisibleY
objOffsetX = mainmemory.read_u8(0x1930+i)
objDirection = mainmemory.read_u8(0xAC0+i)
objUnknownY = mainmemory.read_u8(0x19E0+i)
hitSizeX = mainmemory.read_u8(0x1988+i)
hitSizeY = mainmemory.read_u8(0x1A38+i)
if(objDirection == 1) then --9484
objOffsetX = bit.bxor(0xFF,objOffsetX) --9488
objOffsetX = objOffsetX+1 --948A
end
off00 = 0 --942B
if (bit.band(0x80, objOffsetX) == 128) then --942F
of00=bit.band(0xFF,(off00-1)) --9431
end
hitBoxCornerX = bit.band(0xFF,(objX + objOffsetX)) --9434
hitBoxCornerY = bit.band(0xFF,(objY + objUnknownY)) --944F
objStatus = mainmemory.read_u8(0x1250+i)-- generally: 0 inert, 1 benign, 2 damageable/possibly damaging
if(objStatus == 0) then
fill = 0x600000FF
line = 0xC0000000
elseif(objStatus == 1) then
fill = 0x3C00FF00
line = 0x8000FF00
elseif(objStatus == 2) then
fill = 0x50FF0000
line = 0x80FF0000
end
--clipping
if(adjustedX > 0 and adjustedY > 0) then
gui.drawBox(
hitBoxCornerX-hitSizeX,
hitBoxCornerY+hitSizeY,
hitBoxCornerX+hitSizeX,
hitBoxCornerY-hitSizeY,
line,
fill
)
end
end
end
function dispProperties(num)
fill = 0x80FFC8C8
ObjDamageInfo = {
0x13b0,--5 means is being damaged
0x1a90,--invulnerability countdown
0xf90,--if 0, animate. seems to be used as a counter to temporarily freeze objs when damaged
0xb18,--flashing if equal to 0x10, white if equal to 0x86
0x1ae8,
0x1f18,
0x11f8,
0x12a8--health
}
for i = 1,8 do
gui.text((10+(i*20)) * xmult ,100 * ymult, mainmemory.read_u8(ObjDamageInfo[i]+num))
end
hitBoxInfo = {
0x1988,
0x1A38,
0x1930,
0xAC0
}
for i = 1,4 do
gui.text((10+(i*20)) * xmult,120 * ymult, mainmemory.read_u8(hitBoxInfo[i]+num))
end
ObjPositionInfo = {
0xB70, --offscreen or not
0xBC8, --x position
0xC20,
0xC78,
0xCD0, --y position
0xD28,
}
for i = 1,6 do
gui.text((10+(i*20)) * xmult,140 * ymult, mainmemory.read_u8(ObjPositionInfo[i]+num))
end
collisionInfo = {
0x710, --compensated x
0x720, --compensated y
0x730 --compensated "visible"
}
for i = 1,3 do
gui.text((10+(i*20)) * xmult,160 * ymult, mainmemory.read_u8(collisionInfo[i]+num))
end
end
while true do
--Multiplier for text rendering
xmult = client.screenwidth() / 256
ymult = client.screenheight() / 225
line = 0xFFFFC8C8
--display info about a given object
--dispProperties(0)
drawHitBoxes()
drawObjInfo()
emu.frameadvance()
--invincibility cheat
-- memory.writebyte(0x13B0, 0)
end
--[[ Notes
--Object Damage
A1ED LDY $33B0,X ;"can damage"
A1F0 LDA $A26D,Y
A1F3 STA $3A90,X ;invulnerability countdown
A1F6 LDA $A27D,X
A1F9 STA $2F90,X ;whether to animate the obj or not
A1FC LDA $2B18,X ;flashing or not
A1FF STA $3AE8,X
A202 LDA #$86 ;make the palette white
A204 STA $2B18,X
A207 LDA $3F18,X
A20A ORA #$03
A20C STA $31F8,X
A20F LDA $32A8,X
A212 SEC
A213 SBC $00 ;subtract the amount of damage to do
A215 STA $32A8,X ;x is the object slot to modify
--Where the player's health is decremented
A1F2 LDA $33B0 ;check if the player is vulnerable
A1F5 BEQ $A234
A1F7 LDA $33B0
A1FA bit.band #$07
A1FC CMP #$05
A1FE BNE $A20B
A200 LDA $36D3
A203 BNE $A20B
A205 STZ $33B0
A20B LDA $98 ;player health
A20D SEC
A20E SBC $32A8 ;subtract amount of damage received
A211 STA $98
--Where the damage received (32A8) is set
9546 STA $33B0,X
9549 LDA $33B0
954C BNE $955A
954E LDA $3358,X
9551 STA $33B0
9554 LDA $3300,X ;the amount of damage an object will deal to you
9557 STA $32A8
--Where the hitbox offset is calculated
9413 LDX #$00
9415 LDA $3250,X ;load the hitbox type
9418 BEQ $9460 ;we quit if type 0
941A LDA $3930,X ;x offset
941D STA $01 ;store it in 01
941F LDA $2AC0,X ;direction facing, left is 1, right is 0
9422 BEQ $942B ;we are facing...
9424 LDA $01 ;left, load offset
9426 EOR #$FF
9428 INC
9429 STA $01 ;store the altered offset
942B STZ $00
942D LDA $01 ;get the either altered or unaltered offset
942F BPL $9433
9431 DEC $00
9433 CLC
9434 ADC $2BC8,X ;add x position to either altered or unaltered offset
9437 STA $2710,X ;store that as the hitbox corner
943A LDA $2B70,X ;is the object visible
943D ADC $00 ;correct it depending on the altered x offset
943F STA $2730,X
9442 STZ $00
9444 LDA $39E0,X
9447 BPL $944B
9449 DEC $00
944B LDA $2CD0,X ;y position
944E CLC
944F ADC $39E0,X
9452 STA $2720,X ;store hitbox y corner
9455 LDA $2C78,X ;indicator that the object is y visible
9458 ADC $00
945A ORA $2730,X
945D STA $2730,X
9460 INX
9461 CPX #$10 ;we can only do 16 objects
9463 BCC $9415 ;start again if we have objects left
9465 RTS
9466 STZ $33B0,X ;zero the "can damage" byte
9469 LDA $3250,X ;objStatus / collision status
946C BNE $9471 ;if the status is 0 we continue
946E JMP $9507 ;otherwise we quit
--X and Y represent our two objects
9471 LDA $3988,X ;x hitbox size
9474 ORA $3A38,X ;y hitbox size
9477 BNE $947C
9479 JMP $9507
947C LDA $3930,X ;x offset
947F STA $01
9481 LDA $2AC0,X ;objDirection
9484 BEQ $948D ;branch if we are facing right
9486 LDA $01 ;left
9488 EOR #$FF
948A INC
948B STA $01
948D STZ $00 ;right, zero our temp byte
948F LDA $01 ;load the possibly manipulated offset
9491 BPL $9495
9493 DEC $00
9495 CLC
9496 ADC $2BC8,X ;add object x position to the possibly manipulated offset
9499 STA $26FF
949C LDA $2B70,X ;objVisibleX
949F ADC $00
94A1 BNE $9507 ;quit if the result is non-zero
94A3 STZ $00
94A5 LDA $39E0,X ;y related
94A8 BPL $94AC
94AA DEC $00
94AC CLC
94AD ADC $2CD0,X ;obj y position
94B0 STA $2700
94B3 LDA $2C78,X ;objVisibleY
94B6 ADC $00
94B8 BNE $9507
94BA LDA $3250,X ;objStatus / collision status
94BD BPL $94C2
94BF CLY
94C0 BRA $94C4
94C2 LDY #$0F ;16 objects max
94C4 LDA $3250,Y ;objStatus / collision status
94C7 BEQ $9504 ;if objStatus is zero, go to the next object
94C9 LDA $2730,Y ;compensated "visible"
94CC BNE $9504
94CE LDA $3988,X ;x hitbox size of 1st object
94D1 CLC
94D2 ADC $3988,Y ;x hitbox size of 2nd object
94D5 STA $2701
94D8 LDA $3A38,X ;y hitbox size of 1st object
94DB CLC
94DC ADC $3A38,Y ;y hitbox size of 2nd object
94DF STA $2702
94E2 LDA $26FF
94E5 SEC
94E6 SBC $2710,Y ;subtract compensated x position for the current object
94E9 BCS $94EE
94EB EOR #$FF
94ED INC
94EE CMP $2701
94F1 BCS $9504
94F3 LDA $2700
94F6 SEC
94F7 SBC $2720,Y ;subtract compensated y position for the current object
94FA BCS $94FF
94FC EOR #$FF
94FE INC
94FF CMP $2702
9502 BCC $9508
9504 DEY
9505 BPL $94C4
9507 RTS
]] |
---@type TestTableArraysTemplate
local TestTableArraysTemplateFieldsIndex ={
Id = 1,
Weapons = 2,
born_position = 3,
TestTypes = 4,
LinkId = 5,
Model = 6,
Icon = 7,
MachineTypes = 8,
MapType = 9,
}
local Position3dFieldsIndex ={
x = 1,
y = 2,
z = 3,
}
local TestType_FieldsIndex ={
types = 1,
id = 2,
}
local TestTableArraysTemplateCustom ={
born_position = {0,Position3dFieldsIndex},
TestTypes = {1,TestType_FieldsIndex},
}
local T = {}
function T.T1()
return {1,{2,1,3},nil,nil,1,"hero_chushi","chushi",nil,"222.0"}
end
function T.T2()
return {2,{2,1,4},nil,{{nil,2},{{1},3}},1,"hero_chushi","chushi",{"防御"},"平原"}
end
function T.T3()
return {3,{2,1,5},nil,{{{1},2},{{1},4}},1,"hero_chushi","chushi",{"防御"},"平原"}
end
function T.T4()
return {4,{2,1,6},nil,{{nil,0},{nil,0}},1,"hero_chushi","chushi",{"防御"},"平原"}
end
function T.T5()
return {5,{2,1,7},{1.0,2.0,3.0},{{{1},2},{{1},6}},1,"hero_chushi","chushi",{"防御"},"平原"}
end
function T.T6()
return {6,{2,1,8},{1.0,2.0,4.0},{{{1},2},{{1},7}},1,"hero_chushi","chushi",{"防御"},"平原"}
end
function T.T7()
return {7,{2,1,9},{1.0,2.0,5.0},{{{1},2},{{1},8}},1,"hero_chushi","chushi",{"防御"},"平原"}
end
function T.T8()
return {8,{2,1,10},{1.0,2.0,6.0},{{{1},2},{{1},9}},1,"hero_chushi","chushi",{"防御"},"平原"}
end
function T.T9()
return {9,{2,1,11},{1.0,2.0,7.0},{{{1},2},{{1},10}},1,"hero_chushi","chushi",{"防御"},"平原"}
end
function T.T10()
return {10,{2,1,12},{1.0,2.0,8.0},{{{1},2},{{1},11}},1,"hero_chushi","chushi",{"防御"},"平原"}
end
local function table_read_only(t)
local temp= {}
local mt = {
__index = t,
__newindex = function(t, k, v)
error('error write to a read-only table with key = ' .. tostring(k)..', value ='..tostring(v))
end
}
setmetatable(temp, mt)
return temp
end
local function New(data,tableIndexes)
local t = {}
for k,v in pairs(tableIndexes) do
local c = TestTableArraysTemplateCustom[k]
local d = data[v]
if c == nil then
t[k]= d
else
if c[1] == 1 then
local t_c = {}
for index = 1,#d do
table.insert(t_c, New(d[index],c[2]))
end
t[k] = t_c
else
t[k] = New(d,c[2])
end
end
end
return table_read_only(t)
end
local TestTableArraysTemplate = {
Values = {}
}
---@return TestTableArrayTemplate
function TestTableArraysTemplate.GetTableByIndex(index)
if TestTableArraysTemplate.Values[index]==nil then
TestTableArraysTemplate.Values[index]=New(T['T'..index](),TestTableArraysTemplateFieldsIndex)
end
return TestTableArraysTemplate.Values[index]
end
function TestTableArraysTemplate.GetLength()
return 10
end
function TestTableArraysTemplate.Dispose()
TestTableArraysTemplate.Values={}
end
return TestTableArraysTemplate |
return {'zelateur','zelatrice','zelden','zeldzaam','zeldzaamheid','zeldzaamheidswaarde','zelf','zelfaanvaarding','zelfacceptatie','zelfachting','zelfanalyse','zelfbedacht','zelfbediening','zelfbedieningsapparatuur','zelfbedieningsgroothandel','zelfbedieningsprincipe','zelfbedieningsrestaurant','zelfbedieningswinkel','zelfbedieningszaak','zelfbedrog','zelfbedwang','zelfbeeld','zelfbegoocheling','zelfbehaaglijk','zelfbehagen','zelfbeheer','zelfbeheersing','zelfbehoud','zelfbeklag','zelfbeoordeling','zelfbeperking','zelfbescherming','zelfbeschikking','zelfbeschikkingsrecht','zelfbeschouwing','zelfbeschuldiging','zelfbespiegeling','zelfbestuiving','zelfbesturend','zelfbestuur','zelfbevestiging','zelfbevlekking','zelfbevrediging','zelfbevrijding','zelfbevruchting','zelfbewoning','zelfbewust','zelfbewustheid','zelfbewustzijn','zelfbinder','zelfbouw','zelfbouwer','zelfcensuur','zelfcontrole','zelfcorrectie','zelfcorrigerend','zelfde','zelfdenkend','zelfdestructie','zelfdestructief','zelfdiscipline','zelfdoding','zelfdoener','zelfdragend','zelfevaluatie','zelfevaluatiemodel','zelfexpressie','zelfgebakken','zelfgebouwd','zelfgecreeerde','zelfgefabriceerde','zelfgegraven','zelfgekozen','zelfgemaakt','zelfgenererend','zelfgenoegzaam','zelfgenoegzaamheid','zelfgeschapen','zelfgeschreven','zelfgevoel','zelfhaat','zelfhandhaving','zelfheid','zelfhulp','zelfhulpboek','zelfhulpgroep','zelfhypnose','zelfinductie','zelfingenomen','zelfingenomenheid','zelfinzicht','zelfironie','zelfkant','zelfkanten','zelfkastijding','zelfkennis','zelfklevend','zelfklever','zelfkritiek','zelfkritisch','zelfkwelling','zelflerende','zelfmedelijden','zelfmedicatie','zelfmoord','zelfmoordaanslag','zelfmoordaanval','zelfmoordactie','zelfmoordbriefje','zelfmoordcommando','zelfmoorddrama','zelfmoorden','zelfmoordenaar','zelfmoordenares','zelfmoordgedachte','zelfmoordneiging','zelfmoordneigingen','zelfmoordpil','zelfmoordpiloot','zelfmoordplan','zelfmoordplannen','zelfmoordpoging','zelfmoordterrorist','zelfnoemfunctie','zelfonderricht','zelfonderzoek','zelfontbranding','zelfontplooiing','zelfontspanner','zelfontwikkeling','zelfontworpen','zelfopblaasbaar','zelfopofferend','zelfopoffering','zelforganisatie','zelfoverschatting','zelfoverwinning','zelfportret','zelfpromotie','zelfrealisatie','zelfredzaam','zelfredzaamheid','zelfreflectie','zelfregelend','zelfregistrerend','zelfregulatie','zelfregulerend','zelfregulering','zelfreinigend','zelfreiniging','zelfrelativering','zelfrespect','zelfrijzend','zelfs','zelfscholing','zelfselectie','zelfsmerend','zelfspot','zelfstandig','zelfstandige','zelfstandigenaftrek','zelfstandigenorganisatie','zelfstandigenstatuut','zelfstandigheid','zelfstandigheidsdrang','zelfstandigheidsstreven','zelfstrijd','zelfstrijkend','zelfstudie','zelfsturend','zelfsturing','zelfsuggestie','zelftest','zelftucht','zelftwijfel','zelfverachting','zelfverblinding','zelfverbranding','zelfverdediging','zelfverdedigingscursus','zelfvergroting','zelfverheerlijking','zelfverheffing','zelfverklaard','zelfverkozen','zelfverloochening','zelfverminking','zelfvernedering','zelfvernietiging','zelfverrijking','zelfvertrouwen','zelfverwerkelijking','zelfverwezenlijking','zelfverwijt','zelfverwonding','zelfverzekerd','zelfverzekerdheid','zelfverzonnen','zelfvoldaan','zelfvoldaanheid','zelfvoldoening','zelfvoorzienend','zelfvoorziening','zelfvoorzieningsgraad','zelfwaardering','zelfwerkend','zelfwerkzaamheden','zelfwerkzaamheid','zelfzeker','zelfzekerheid','zelfzorg','zelfzucht','zelfzuchtig','zelfzuchtige','zelfzuchtigheid','zelling','zeloot','zelve','zelftankstation','zelfbesef','zelfwaarneming','zelfontleding','zelfvervreemding','zelfvergoding','zelfbedieningspomp','zelfverdedigingssport','zelfwording','zelfmoordcijfer','zelfvernietigend','zelfmoordterrorisme','zelfhulpcursus','zelfhulpprogramma','zelfmoordpercentage','zelfmoordpreventie','zelfverdedigingswet','zelfmoordgedrag','zelfdoder','zele','zelem','zelenaar','zelhem','zelhemmer','zelhems','zellik','zelzaats','zelzate','zelzatenaar','zelda','zeldenrust','zeldenrijk','zeller','zelissen','zelis','zelfdoders','zelfkritische','zelateurs','zelatrices','zeldzaamheden','zeldzaamst','zeldzame','zeldzamer','zelen','zelfbedachte','zelfbedieningswinkels','zelfbedieningszaken','zelfbegoochelingen','zelfbenoemde','zelfbereide','zelfbeschuldigingen','zelfbewuste','zelfbewuster','zelfbinders','zelfdenkende','zelfdragende','zelfgebouwde','zelfgebreid','zelfgebreide','zelfgedraaide','zelfgegenereerde','zelfgemaakte','zelfgenererende','zelfgenoegzame','zelfgenoegzamer','zelfgeproclameerde','zelfgeproduceerde','zelfgestookte','zelfinducties','zelfkastijdingen','zelfkwellingen','zelfmoordaanslagen','zelfmoordacties','zelfmoordcijfers','zelfmoordcommandos','zelfmoordenaars','zelfmoordenaressen','zelfmoordpogingen','zelfmoordterroristen','zelfontwikkelde','zelfopgelegde','zelfopofferende','zelfoverwinningen','zelfportretten','zelfregelende','zelfregistrerende','zelfregulerende','zelfreinigende','zelfrijzende','zelfscheppende','zelfsmerende','zelfstandigen','zelfstandiger','zelfstandigere','zelfstandigheden','zelfstandigst','zelfstandigste','zelfsturende','zelftests','zelfvernietigende','zelfverzekerde','zelfverzekerder','zelfverzekerdere','zelfverzekerdst','zelfvoldane','zelfvoldaner','zelfwerkende','zelfzorggeneesmiddelen','zelfzorgmedicijnen','zelfzorgmiddelen','zelfzuchtiger','zelfzuchtigere','zelfzuchtigste','zellingen','zeloten','zeldzaams','zeldzaamste','zeldzamere','zelfbedieningsrestaurants','zelfbeelden','zelfbehaaglijke','zelfbesturende','zelfbouwers','zelfdestructieve','zelfdodingen','zelfhulpboeken','zelfhulpgroepen','zelfklevende','zelfklevers','zelfmoordaanvallen','zelfmoordgedachten','zelfmoordgedachtes','zelfmoordpiloten','zelfopblaasbare','zelforganisaties','zelfsuggesties','zelfverbrandingen','zelfverdedigingscursussen','zelfverklaarde','zelfverminkingen','zelfverwijten','zelfvoorzienende','zelfdoeners','zelfredzame','zelfgenoegzaamst','zelfzekere','zelfbespiegelingen','zelfontledingen','zelfontspanners','zelfstrijkende','zelftankstations','zelfverdedigingssporten','zeldas','zelfhulpboekjes','zelfbedieningswinkeltjes','zelfhulpprogrammas','zelfevaluaties'} |
local THNN = require 'nn.THNN'
local VolumetricDilatedMaxPooling, parent = torch.class('nn.VolumetricDilatedMaxPooling', 'nn.VolumetricMaxPooling')
function VolumetricDilatedMaxPooling:__init(kT, kW, kH, dT, dW, dH, padT, padW, padH, dilationT, dilationW, dilationH)
parent.__init(self, kT, kW, kH, dT, dW, dH, padT, padW, padH)
self.dilationT = dilationT or 1
self.dilationW = dilationW or 1
self.dilationH = dilationH or 1
end
function VolumetricDilatedMaxPooling:updateOutput(input)
local dims = input:dim()
self.itime = input:size(dims-2)
self.iheight = input:size(dims-1)
self.iwidth = input:size(dims)
self.indices = self.indices or torch.LongTensor()
if torch.typename(input):find('torch%.Cuda.*Tensor') then
self.indices = torch.CudaLongTensor and self.indices:cudaLong() or self.indices
else
self.indices = self.indices:long()
end
input.THNN.VolumetricDilatedMaxPooling_updateOutput(
input:cdata(),
self.output:cdata(),
self.indices:cdata(),
self.kT, self.kW, self.kH,
self.dT, self.dW, self.dH,
self.padT, self.padW, self.padH,
self.dilationT, self.dilationW, self.dilationH,
self.ceil_mode
)
return self.output
end
function VolumetricDilatedMaxPooling:updateGradInput(input, gradOutput)
input.THNN.VolumetricDilatedMaxPooling_updateGradInput(
input:cdata(),
gradOutput:cdata(),
self.gradInput:cdata(),
self.indices:cdata(),
self.kT, self.kW, self.kH,
self.dT, self.dW, self.dH,
self.padT, self.padW, self.padH,
self.dilationT, self.dilationW, self.dilationH,
self.ceil_mode
)
return self.gradInput
end
function VolumetricDilatedMaxPooling:clearState()
if self.indices then
self.indices:set()
end
return parent.clearState(self)
end
function VolumetricDilatedMaxPooling:__tostring__()
local s = string.format('%s(%dx%dx%d, %d,%d,%d', torch.type(self),
self.kT, self.kW, self.kH, self.dT, self.dW, self.dH)
if (self.padT or self.padW or self.padH) and
(self.padT ~= 0 or self.padW ~= 0 or self.padH ~= 0) then
s = s .. ', ' .. self.padT.. ',' .. self.padW .. ','.. self.padH
end
s = s .. ', ' .. self.dilationT .. ',' .. self.dilationW .. ',' .. self.dilationH
s = s .. ')'
return s
end
|
local exports = {}
local os = require('os')
local Date = require('../')
exports['strptime is sane'] = function (test)
--
local ts = os.time()
local s = os.date('%c %Z', ts)
test.equal(os.time(Date.strptime(s, '%c %Z')), ts)
--
ts = os.time()
s = os.date('%c %Z', ts)
local expected = os.date('*t', ts)
test.equal(Date.strptime(s, '%c %Z'), expected)
--
ts = os.time()
s = os.date('%c', ts)
test.equal(os.time(Date.strptime(s, '%c')), ts)
--
ts = os.time()
s = os.date('%c', ts)
expected = os.date('*t', ts)
test.equal(Date.strptime(s, '%c'), expected)
-- strptime reports same what os.date() reports
test.equal(os.date('*t', 1329820391), Date.strptime('1329820391', '%s'))
test.done()
end
exports['ISO date'] = function (test)
local date, err = Date.strptime(
'2012-02-21 01:02:03 -0300',
'%Y-%m-%d %H:%M:%S %z'
)
test.equal(date, d20120221010203)
date, err = Date.strptime(
'2012-02-21 01:02:03 GMT+03',
'%Y-%m-%d %H:%M:%S GMT'
)
test.equal(err, '+03')
test.equal(date, d20120221010203)
test.equal(Date.parse('2013-12-12T00:00:01').year, 2013)
test.done()
end
exports['unix date'] = function (test)
test.equal(Date.parse('Tue Feb 21 14:33:11 2012'), Date.parse(1329820391))
test.done()
end
exports['RFC6265 date'] = function (test)
test.equal(Date.parse('Tue, Feb 21 2012 01:02:03 GMT+04'), d20120221010203_m4)
test.equal(Date.parse('Tue, Feb 21 12 1:2:3'), d20120221010203)
test.equal(Date.parse('Sun, Dec 31 99 0:1:2 UTC+0400'), d19991231000102_m4)
test.equal(Date.parse('Sun, Dec 31 99 0:1:2 UTC+0400', true), d19991231000102_o4)
test.is_nil(Date.parse('Пн, Дек 31 99 0:1:2'))
test.done()
end
exports['RFC6265 date fallbacks to ISO'] = function (test)
test.equal(Date.parse('2012-12-31 23:59:59 GMT-0300'), d20121231235959_p3)
test.equal(Date.parse('2012-12-31 23:59:59 GMT+0300', true), d20121231235959_o3)
test.done()
end
exports['now() is sane'] = function (test)
local now = Date.now()
test.is_number(now)
test.done()
end
exports['diff() is sane'] = function (test)
test.equal(Date.diff('2013-12-12T00:00:01', 'Thu, Dec 12 2013 01:00:00'), 3599)
test.equal(Date.diff('Thu, Dec 12 2013 01:00:00', '2013-12-12T00:00:01'), -3599)
test.done()
end
exports['add() is sane'] = function (test)
local date = Date.add('2013-12-12T23:00:01', 100000)
date = os.date('*t', date)
test.equal(date.year, 2013)
test.equal(date.month, 12)
test.equal(date.day, 14)
test.equal(date.hour, 2)
test.equal(date.min, 46)
test.equal(date.sec, 41)
test.done()
end
exports['format() is sane'] = function (test)
test.equal(Date.format(d20121231235959_o3, '%Y%m%d%H%M%S%z'), '20121231235959+0000')
test.equal(Date.format(d19991231000102), 'Fri, 31 Dec 99 00:01:02 GMT')
-- FIXME: so, 31.12.1999 is Friday or Sunday?!
--test.equal(Date.parse('Fri, 31 Dec 99 00:01:02 GMT'), d19991231000102)
test.equal(Date.parse('Sun, 31 Dec 99 00:01:02 GMT'), d19991231000102)
test.done()
end
return exports
|
local state = {}
state._NAME = ...
require'hcm'
local vector = require'vector'
local util = require'util'
local movearm = require'movearm'
local libArmPlan = require 'libArmPlan'
local arm_planner = libArmPlan.new_planner()
local T = require'Transform'
--Initial hand angle
local lhand_rpy0 = {0,0*DEG_TO_RAD, -30*DEG_TO_RAD}
local rhand_rpy0 = {0,0*DEG_TO_RAD, 30*DEG_TO_RAD}
local trLArm0, trRArm0, trLArm1, trRArm1, qLArm0, qRarm0
local stage
local gripL, gripR = 1,1
function state.entry()
print(state._NAME..' Entry' )
-- Update the time of entry
local t_entry_prev = t_entry
t_entry = Body.get_time()
t_update = t_entry
mcm.set_arm_handoffset(Config.arm.handoffset.chopstick)
local qLArm = Body.get_larm_command_position()
local qRArm = Body.get_rarm_command_position()
qLArm0 = qLArm
qRArm0 = qRArm
trLArm0 = Body.get_forward_larm(qLArm0)
trRArm0 = Body.get_forward_rarm(qRArm0)
arm_planner:set_shoulder_yaw_target(nil,nil)
qLArm1 = Body.get_inverse_arm_given_wrist( qLArm, {0,0,0, unpack(lhand_rpy0)})
qRArm1 = Body.get_inverse_arm_given_wrist( qRArm, {0,0,0, unpack(rhand_rpy0)})
trLArm1 = Body.get_forward_larm(qLArm1)
trRArm1 = Body.get_forward_rarm(qRArm1)
hcm.set_wheel_model({0.50,0.0,0.02,0,0,0.18})
local wrist_seq = {{'wrist',trLArm1, trRArm1}}
if arm_planner:plan_arm_sequence(wrist_seq) then stage = "wristturn" end
end
function state.update()
-- print(state._NAME..' Update' )
-- Get the time of update
local t = Body.get_time()
local dt = t - t_update
-- Save this at the last update time
t_update = t
--if t-t_entry > timeout then return'timeout' end
local qLArm = Body.get_larm_command_position()
local qRArm = Body.get_rarm_command_position()
local trLArm = Body.get_forward_larm(qLArm)
local trRArm = Body.get_forward_rarm(qRArm)
if stage=="wristturn" then --Turn yaw angles first
gripL,doneL = util.approachTol(gripL,1,2,dt) --Close gripper
gripR,doneL = util.approachTol(gripR,1,2,dt) --Close gripper
Body.set_lgrip_percent(gripL*0.8)
Body.set_rgrip_percent(gripR*0.8)
if arm_planner:play_arm_sequence(t) then
if hcm.get_state_proceed()==1 then
local trLArmTarget={0.35,0.20,-0.15, unpack(lhand_rpy0)}
local trRArmTarget={0.35,-0.20,-0.15, unpack(rhand_rpy0)}
local arm_seq = {{'move',trLArmTarget, trRArmTarget}}
if arm_planner:plan_arm_sequence(arm_seq) then stage="armwide" end
elseif hcm.get_state_proceed()==-1 then
arm_planner:set_shoulder_yaw_target(qLArm0[3],qRArm0[3])
local wrist_seq = {{'wrist',trLArm0, trRArm0}}
if arm_planner:plan_arm_sequence(wrist_seq) then stage = "armbacktoinitpos" end
end
end
elseif stage=="armwide" then
Body.set_lgrip_percent(gripL*0.8)
Body.set_rgrip_percent(gripR*0.8)
if arm_planner:play_arm_sequence(t) then
if hcm.get_state_proceed()==1 then
local trLArmTarget, trRArmTarget = movearm.getLargeValvePosition(0,0,-0.08,-0.08)
print("TrL:",util.print_transform(trLArmTarget))
print("TrR:",util.print_transform(trRArmTarget))
local arm_seq = {{'move',trLArmTarget, trRArmTarget}}
if arm_planner:plan_arm_sequence(arm_seq) then stage="pregrip" end
elseif hcm.get_state_proceed()==-1 then
local arm_seq = {{'move',trLArm1, trRArm1}}
if arm_planner:plan_arm_sequence(arm_seq) then stage="wristturn" end
end
end
elseif stage=="pregrip" then
if arm_planner:play_arm_sequence(t) then
if hcm.get_state_proceed()==1 then --teleop signal
arm_planner:save_valveparam({0,0,0,0})
local trLArmTarget, trRArmTarget = movearm.getLargeValvePosition(0,0,0,0)
local arm_seq = {{'move',trLArmTarget, trRArmTarget}}
if arm_planner:plan_arm_sequence(arm_seq) then stage="inposition" end
elseif hcm.get_state_proceed(0)==-1 then
local trLArmTarget={0.25,0.15,-0.15, unpack(lhand_rpy0)}
local trRArmTarget={0.25,-0.15,-0.15, unpack(rhand_rpy0)}
local arm_seq = {{'move',trLArmTarget, trRArmTarget}}
if arm_planner:plan_arm_sequence(arm_seq) then stage="armwide" end
end
end
elseif stage=="inposition" then
if arm_planner:play_arm_sequence(t) then
if hcm.get_state_proceed()==1 then --teleop signal
--[[
local valve_seq={
{0,0,-0.08,0},
{-45*DEG_TO_RAD,45*DEG_TO_RAD,-0.08,0},
{-45*DEG_TO_RAD,45*DEG_TO_RAD,0,-0.08},
{5*DEG_TO_RAD,-5*DEG_TO_RAD, 0,-0.08},
{5*DEG_TO_RAD,-5*DEG_TO_RAD, -0.08,0},
{0,0,-0.08,0},
}
if arm_planner:plan_valve_sequence(valve_seq) then stage="inposition" end
--]]
local valve_seq={
{'valvetwoarm',0,0,-0.08,0},
{'valvetwoarm',-45*DEG_TO_RAD,45*DEG_TO_RAD,-0.08,0},
{'valvetwoarm',-45*DEG_TO_RAD,45*DEG_TO_RAD,0,-0.08},
{'valvetwoarm',5*DEG_TO_RAD,-5*DEG_TO_RAD, 0,-0.08},
{'valvetwoarm',5*DEG_TO_RAD,-5*DEG_TO_RAD, -0.08,0},
{'valvetwoarm',0,0,-0.08,0},
}
if arm_planner:plan_arm_sequence(valve_seq) then stage="inposition" end
elseif hcm.get_state_proceed()==-1 then
local trLArmTarget, trRArmTarget = movearm.getLargeValvePosition(0,0,-0.05,-0.05)
local arm_seq = {{'move',trLArmTarget, trRArmTarget}}
if arm_planner:plan_arm_sequence(arm_seq) then stage="pregrip" end
end
end
elseif stage=="valveturn" then
if arm_planner:play_arm_sequence(t) then
end
elseif stage=="armbacktoinitpos" then
if arm_planner:play_arm_sequence(t) then return "done" end
end
hcm.set_state_proceed(0)
end
function state.exit()
print(state._NAME..' Exit' )
end
return state
|
--Includes
require('libs.json')
require('modules.General.DataStructures')
require('modules.General.TableFunctions')
require('modules.General.Colors')
require('modules.General.Constants')
require('modules.Entities.Player')
require('modules.World.Rooms.TestRoom')
--LOVE Functions
function love.load()
--Setup Random Number Generator
local seed_val = love.timer.getTime()
love.math.setRandomSeed(seed_val)
--Basic Window Setup
love.window.setTitle('The Quaackening')
love.window.setMode(800,600,{resizable = true, minwidth = 800, minheight = 600})
love.keyboard.setKeyRepeat(true)
--Table to store globals
globals = {
win_width = love.graphics.getWidth(),
win_height = love.graphics.getHeight(),
max_bound = 1,
min_bound = 0,
game_state = 'play',
default_chars = {
player = 'x',
proj = 'o'
},
perm_objects = {},
temp_objects = {
bullets = {},
enemies = {},
menus = {},
},
next_id = 2,
colors = Colors(),
fire_rate = 10,
default_fonts = {
love_default = '/res/fonts/Vera.ttf',
player = '/res/fonts/origa___.ttf',
},
cursor = '/res/cursor.png',
load_info = {}
}
love.graphics.setBackgroundColor(globals.colors.black)
love.mouse.setCursor(love.mouse.newCursor(globals.cursor, 7, 7))
--Debug variables
debug = true
if(debug) then
debug_globals = {
current_dt = 0,
show_debug = false,
current_object_count = 1,
Grid = Grid(10,10, true),
}
end
globals.load_info.load_font = love.graphics.newFont(
globals.default_fonts.love_default,
80
)
globals.load_info.load_text = love.graphics.newText(globals.load_info.load_font, "LOADING")
--Generate Player once ready
globals.Player = CreatePlayer(
'x',
42,
love.math.random(),
love.math.random(),
1,
nil,
globals.default_fonts.player
)
globals.current_room = TestRoom()
end
function love.update(dt)
--Only update when window is focused and game is in play mode
if(love.window.hasFocus() and globals.game_state ~= 'paused') then
--Do updates for all permanent objects
for _,i in pairs(globals.perm_objects) do
i.update(dt)
end
--Iterates through all categories of temporary objects, then iterates over non-function members of those categories
for _,v in pairs(globals.temp_objects) do
if(type(v) == "table") then
for k,i in pairs(v) do
if type(k) =="number" then
i.update(dt)
end
end
end
end
globals.current_room.update(dt)
globals.Player.update(dt)
--Necessary debug globals updated here
if(debug) then
debug_globals.current_dt = dt
debug_globals.current_mem_usage = collectgarbage('count')
debug_globals.mouse_x_pos, debug_globals.mouse_y_pos = love.mouse.getPosition()
debug_globals.Grid.update()
end
end
end
function love.draw()
if(globals.game_state ~= 'loading') then
for _,i in pairs(globals.perm_objects) do
i.draw(i)
end
--Iterates through all categories of temporary objects besides menus, then iterates over non-function members of those categories
for k,v in pairs(globals.temp_objects) do
if(type(v) == "table" and k ~= 'menus') then
for k,i in pairs(v) do
if type(k) =="number" then
i.draw(i)
end
end
end
end
if(debug) then
debug_globals.Grid.draw()
end
globals.current_room.draw()
globals.Player.draw()
--Iterate over specifically menus since they should be on top
for k,v in pairs(globals.temp_objects) do
if(type(v) == "table" and k == 'menus') then
for k,i in pairs(v) do
if type(k) =="number" then
i.draw(i)
end
end
end
end
else
local load_text = globals.load_info.load_text
love.graphics.draw(
load_text,
globals.win_width/2 - load_text:getWidth()/2,
globals.win_height/2 - load_text:getHeight()/2
)
end
end
function love.resize(w, h)
globals.win_width = w
globals.win_height = h
if(debug) then
debug_globals.Grid.update_offsets()
end
for _,i in pairs(globals.perm_objects) do
i.update_offsets()
end
--Iterates through all categories of temporary objects, then iterates over non-function members of those categories (Allows for Special Data Structures)
for _,v in pairs(globals.temp_objects) do
if(type(v) == "table") then
for k,i in pairs(v) do
if type(k) =="number" then
i.update_offsets()
end
end
end
end
globals.current_room.update_offsets()
globals.Player.update_offsets()
end |
static t_socket getfd(lua_State *L) {
t_socket fd = SOCKET_INVALID;
lua_pushstring(L, "getfd");
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
lua_pushvalue(L, -2);
lua_call(L, 1, 1);
if (lua_isnumber(L, -1)) {
double numfd = lua_tonumber(L, -1);
fd = (numfd >= 0.0)? (t_socket) numfd: SOCKET_INVALID;
}
}
lua_pop(L, 1);
return fd;
}
static int dirty(lua_State *L) {
int is = 0;
lua_pushstring(L, "dirty");
lua_gettable(L, -2);
if (!lua_isnil(L, -1)) {
lua_pushvalue(L, -2);
lua_call(L, 1, 1);
is = lua_toboolean(L, -1);
}
lua_pop(L, 1);
return is;
}
static void collect_fd(lua_State *L, int tab, int itab, fd_set *set, t_socket *max_fd) {
int i = 1, n = 0;
/* nil is the same as an empty table */
if (lua_isnil(L, tab)) return;
/* otherwise we need it to be a table */
luaL_checktype(L, tab, LUA_TTABLE);
for ( ;; ) {
t_socket fd;
lua_pushnumber(L, i);
lua_gettable(L, tab);
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
break;
}
/* getfd figures out if this is a socket */
fd = getfd(L);
if (fd != SOCKET_INVALID) {
/* make sure we don't overflow the fd_set */
#ifdef _WIN32
if (n >= FD_SETSIZE)
luaL_argerror(L, tab, "too many sockets");
#else
if (fd >= FD_SETSIZE)
luaL_argerror(L, tab, "descriptor too large for set size");
#endif
FD_SET(fd, set);
n++;
/* keep track of the largest descriptor so far */
if (*max_fd == SOCKET_INVALID || *max_fd < fd)
*max_fd = fd;
/* make sure we can map back from descriptor to the object */
lua_pushnumber(L, (lua_Number) fd);
lua_pushvalue(L, -2);
lua_settable(L, itab);
}
lua_pop(L, 1);
i = i + 1;
}
}
static int check_dirty(lua_State *L, int tab, int dtab, fd_set *set) {
int ndirty = 0, i = 1;
if (lua_isnil(L, tab))
return 0;
for ( ;; ) {
t_socket fd;
lua_pushnumber(L, i);
lua_gettable(L, tab);
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
break;
}
fd = getfd(L);
if (fd != SOCKET_INVALID && dirty(L)) {
lua_pushnumber(L, ++ndirty);
lua_pushvalue(L, -2);
lua_settable(L, dtab);
FD_CLR(fd, set);
}
lua_pop(L, 1);
i = i + 1;
}
return ndirty;
}
static void return_fd(lua_State *L, fd_set *set, t_socket max_fd, int itab, int tab, int start) {
t_socket fd;
for (fd = 0; fd < max_fd; fd++) {
if (FD_ISSET(fd, set)) {
lua_pushnumber(L, ++start);
lua_pushnumber(L, (lua_Number) fd);
lua_gettable(L, itab);
lua_settable(L, tab);
}
}
}
local function return_fd()
end
static void make_assoc(lua_State *L, int tab) {
int i = 1, atab;
lua_newtable(L); atab = lua_gettop(L);
for ( ;; ) {
lua_pushnumber(L, i);
lua_gettable(L, tab);
if (!lua_isnil(L, -1)) {
lua_pushnumber(L, i);
lua_pushvalue(L, -2);
lua_settable(L, atab);
lua_pushnumber(L, i);
lua_settable(L, atab);
} else {
lua_pop(L, 1);
break;
}
i = i+1;
}
}
local function make_assoc()
end
return function(readt, writet, timeout)
int rtab, wtab, itab, ret, ndirty;
t_socket max_fd = SOCKET_INVALID;
fd_set rset, wset;
t_timeout tm;
double t = luaL_optnumber(L, 3, -1);
FD_ZERO(&rset); FD_ZERO(&wset);
lua_settop(L, 3);
lua_newtable(L); itab = lua_gettop(L);
lua_newtable(L); rtab = lua_gettop(L);
lua_newtable(L); wtab = lua_gettop(L);
collect_fd(L, 1, itab, &rset, &max_fd);
collect_fd(L, 2, itab, &wset, &max_fd);
ndirty = check_dirty(L, 1, rtab, &rset);
t = ndirty > 0? 0.0: t;
timeout_init(&tm, t, -1);
timeout_markstart(&tm);
ret = socket_select(max_fd+1, &rset, &wset, NULL, &tm);
if (ret > 0 || ndirty > 0) {
return_fd(L, &rset, max_fd+1, itab, rtab, ndirty);
return_fd(L, &wset, max_fd+1, itab, wtab, 0);
make_assoc(L, rtab);
make_assoc(L, wtab);
return 2;
} else if (ret == 0) {
lua_pushstring(L, "timeout");
return 3;
} else {
luaL_error(L, "select failed");
return 3;
}
end
|
local luatwitch = require('lua-twitch')
local myBot
io.stdout:setvbuf("no")
function love.load(arg)
myBot = luatwitch.new('your_username', 'oauth:your_oauth_key', '#channel_to_join')
end
local msg
function love.update(dt)
myBot:update(dt)
local msg = myBot:message()
if msg ~= nil then
print('<CHAT>', msg.nick, 'said: ', msg.message)
end
end
function love.keypressed(key, scancode)
if key == "k" then
myBot:sendMessage("[botmsg] oh boy i love watching %(VIDEOGAME)")
end
end |
-- Copyright 2012 by Till Tantau
--
-- This file may be distributed an/or modified
--
-- 1. under the LaTeX Project Public License and/or
-- 2. under the GNU Public License
--
-- See the file doc/generic/pgf/licenses/LICENSE for more information
-- @release $Header$
local key = require 'pgf.gd.doc'.key
local documentation = require 'pgf.gd.doc'.documentation
local summary = require 'pgf.gd.doc'.summary
local example = require 'pgf.gd.doc'.example
--------------------------------------------------------------------
key "tree layout"
summary "This layout uses the Reingold--Tilform method for drawing trees."
documentation
[[
The Reingold--Tilford method is a standard method for drawing
trees. It is described in:
%
\begin{itemize}
\item
E.~M.\ Reingold and J.~S.\ Tilford,
\newblock Tidier drawings of trees,
\newblock \emph{IEEE Transactions on Software Engineering,}
7(2), 223--228, 1981.
\end{itemize}
%
My implementation in |graphdrawing.trees| follows the following paper, which
introduces some nice extensions of the basic algorithm:
%
\begin{itemize}
\item
A.\ Br\"uggemann-Klein, D.\ Wood,
\newblock Drawing trees nicely with \TeX,
\emph{Electronic Publishing,} 2(2), 101--115, 1989.
\end{itemize}
%
As a historical remark, Br\"uggemann-Klein and Wood have implemented
their version of the Reingold--Tilford algorithm directly in \TeX\
(resulting in the Tree\TeX\ style). With the power of Lua\TeX\ at
our disposal, the 2012 implementation in the |graphdrawing.tree|
library is somewhat more powerful and cleaner, but it really was an
impressive achievement to implement this algorithm back in 1989
directly in \TeX.
The basic idea of the Reingold--Tilford algorithm is to use the
following rules to position the nodes of a tree (the following
description assumes that the tree grows downwards, other growth
directions are handled by the automatic orientation mechanisms of
the graph drawing library):
%
\begin{enumerate}
\item For a node, recursively compute a layout for each of its children.
\item Place the tree rooted at the first child somewhere on the page.
\item Place the tree rooted at the second child to the right of the
first one as near as possible so that no two nodes touch (and such
that the |sibling sep| padding is not violated).
\item Repeat for all subsequent children.
\item Then place the root above the child trees at the middle
position, that is, at the half-way point between the left-most and
the right-most child of the node.
\end{enumerate}
%
The standard keys |level distance|, |level sep|, |sibling distance|,
and |sibling sep|, as well as the |pre| and |post| versions of these
keys, as taken into consideration when nodes are positioned. See also
Section~\ref{subsection-gd-dist-pad} for details on these keys.
\noindent\textbf{Handling of Missing Children.}
As described in Section~\ref{section-gd-missing-children}, you can
specify that some child nodes are ``missing'' in the tree, but some
space should be reserved for them. This is exactly what happens:
When the subtrees of the children of a node are arranged, each
position with a missing child is treated as if a zero-width,
zero-height subtree were present at that positions:
%
\begin{codeexample}[preamble={\usetikzlibrary{graphs,graphdrawing}
\usegdlibrary{trees}}]
\tikz [tree layout, nodes={draw,circle}]
\node {r}
child { node {a}
child [missing]
child { node {b} }
}
child[missing];
\end{codeexample}
%
or in |graph| syntax:
%
\begin{codeexample}[preamble={\usetikzlibrary{graphs,graphdrawing}
\usegdlibrary{trees}}]
\tikz \graph [tree layout, nodes={draw,circle}]
{
r -> {
a -> {
, %missing
b},
% missing
}
};
\end{codeexample}
%
More than one child can go missing:
%
\begin{codeexample}[preamble={\usetikzlibrary{graphs,graphdrawing}
\usegdlibrary{trees}}]
\tikz \graph [tree layout, nodes={draw,circle}, sibling sep=0pt]
{ r -> { a, , ,b -> {c,d}, ,e} };
\end{codeexample}
%
Although missing children are taken into consideration for the
computation of the placement of the children of a root node relative
to one another and also for the computation of the position of the
root node, they are usually \emph{not} considered as part of the
``outline'' of a subtree (the \texttt{minimum number of children}
key ensures that |b|, |c|, |e|, and |f| all have a missing right
child):
%
\begin{codeexample}[preamble={\usetikzlibrary{graphs,graphdrawing}
\usegdlibrary{trees}}]
\tikz \graph [tree layout, minimum number of children=2,
nodes={draw,circle}]
{ a -> { b -> c -> d, e -> f -> g } };
\end{codeexample}
%
This behaviour of ``ignoring'' missing children in later stages of
the recursion can be changed using the key |missing nodes get space|.
\noindent\textbf{Significant Pairs of Siblings.}
Br\"uggemann-Klein and Wood have proposed an extension of the
Reingold--Tilford method that is intended to better highlight the
overall structure of a tree. Consider the following two trees:
%
\begin{codeexample}[preamble={\usetikzlibrary{graphs,graphdrawing}
\usegdlibrary{trees}}]
\tikz [baseline=(a.base), tree layout, minimum number of children=2,
sibling distance=5mm, level distance=5mm]
\graph [nodes={circle, inner sep=0pt, minimum size=2mm, fill, as=}]{
a -- { b -- c -- { d -- e, f -- { g, h }}, i -- j -- k[second] }
};\quad
\tikz [baseline=(a.base), tree layout, minimum number of children=2,
sibling distance=5mm, level distance=5mm]
\graph [nodes={circle, inner sep=0pt, minimum size=2mm, fill, as=}]{
a -- { b -- c -- d -- e, i -- j -- { f -- {g,h}, k } }
};
\end{codeexample}
%
As observed by Br\"uggemann-Klein and Wood, the two trees are
structurally quite different, but the Reingold--Tilford method
places the nodes at exactly the same positions and only one edge
``switches'' positions. In order to better highlight the differences
between the trees, they propose to add a little extra separation
between siblings that form a \emph{significant pair}. They define
such a pair as follows: Consider the subtrees of two adjacent
siblings. There will be one or more levels where these subtrees have
a minimum distance. For instance, the following two trees the
subtrees of the nodes |a| and |b| have a minimum distance only at
the top level in the left example, and in all levels in the second
example. A \emph{significant pair} is a pair of siblings where the
minimum distance is encountered on any level other than the first
level. Thus, in the first example there is no significant pair,
while in the second example |a| and |b| form such a pair.
%
\begin{codeexample}[preamble={\usetikzlibrary{graphs,graphdrawing}
\usegdlibrary{trees}}]
\tikz \graph [tree layout, minimum number of children=2,
level distance=5mm, nodes={circle,draw}]
{ / -> { a -> / -> /, b -> /[second] -> /[second] }};
\quad
\tikz \graph [tree layout, minimum number of children=2,
level distance=5mm, nodes={circle,draw}]
{ / -> { a -> / -> /, b -> / -> / }};
\end{codeexample}
%
Whenever the algorithm encounters a significant pair, it adds extra
space between the siblings as specified by the |significant sep|
key.
]]
example
[[
\tikz [tree layout, sibling distance=8mm]
\graph [nodes={circle, draw, inner sep=1.5pt}]{
1 -- { 2 -- 3 -- { 4 -- 5, 6 -- { 7, 8, 9 }}, 10 -- 11 -- { 12, 13 } }
};
]]
example
[[
\tikz [tree layout, grow=-30,
sibling distance=0mm, level distance=0mm,]
\graph [nodes={circle, draw, inner sep=1.5pt}]{
1 -- { 2 -- 3 -- { 4 -- 5, 6 -- { 7, 8, 9 }}, 10 -- 11 -- { 12, 13 } }
};
]]
--------------------------------------------------------------------
--------------------------------------------------------------------
key "missing nodes get space"
summary
[[
When set to true, missing children are treated as if they where
zero-width, zero-height nodes during the whole tree layout process.
]]
example
[[
\tikz \graph [tree layout, missing nodes get space,
minimum number of children=2, nodes={draw,circle}]
{ a -> { b -> c -> d, e -> f -> g } };
]]
--------------------------------------------------------------------
--------------------------------------------------------------------
key "significant sep"
summary
[[
This space is added to significant pairs by the modified
Reingold--Tilford algorithm.
]]
example
[[
\tikz [baseline=(a.base), tree layout, significant sep=1em,
minimum number of children=2,
sibling distance=5mm, level distance=5mm]
\graph [nodes={circle, inner sep=0pt, minimum size=2mm, fill, as=}]{
a -- { b -- c -- { d -- e, f -- { g, h }}, i -- j -- k[second] }
};\quad
\tikz [baseline=(a.base), tree layout, significant sep=1em,
minimum number of children=2,
sibling distance=5mm, level distance=5mm]
\graph [nodes={circle, inner sep=0pt, minimum size=2mm, fill, as=}]{
a -- { b -- c -- d -- e, i -- j -- { f -- {g,h}, k } }
};
]]
--------------------------------------------------------------------
--------------------------------------------------------------------
key "binary tree layout"
summary
[[
A layout based on the Reingold--Tilford method for drawing
binary trees.
]]
documentation
[[
This key executes:
%
\begin{enumerate}
\item |tree layout|, thereby selecting the Reingold--Tilford method,
\item |minimum number of children=2|, thereby ensuring the all nodes
have (at least) two children or none at all, and
\item |significant sep=10pt| to highlight significant pairs.
\end{enumerate}
%
In the examples, the last one is taken from the paper of
Br\"uggemann-Klein and Wood. It demonstrates nicely the
advantages of having the full power of \tikzname's anchoring and the
graph drawing engine's orientation mechanisms at one's disposal.
]]
example
[[
\tikz [grow'=up, binary tree layout, sibling distance=7mm, level distance=7mm]
\graph {
a -- { b -- c -- { d -- e, f -- { g, h }}, i -- j -- k[second] }
};
]]
--[[
% TODOsp: codeexamples: the next example needs the library `arrows.meta`
--]]
example
[[
\tikz \graph [binary tree layout] {
Knuth -> {
Beeton -> Kellermann [second] -> Carnes,
Tobin -> Plass -> { Lamport, Spivak }
}
};\qquad
\tikz [>={Stealth[round,sep]}]
\graph [binary tree layout, grow'=right, level sep=1.5em,
nodes={right, fill=blue!50, text=white, chamfered rectangle},
edges={decorate,decoration={snake, post length=5pt}}]
{
Knuth -> {
Beeton -> Kellermann [second] -> Carnes,
Tobin -> Plass -> { Lamport, Spivak }
}
};
]]
--------------------------------------------------------------------
--------------------------------------------------------------------
key "extended binary tree layout"
summary
[[
This algorithm is similar to |binary tree layout|, only the
option \texttt{missing nodes get space} is executed and the
\texttt{significant sep} is zero.
]]
example
[[
\tikz [grow'=up, extended binary tree layout,
sibling distance=7mm, level distance=7mm]
\graph {
a -- { b -- c -- { d -- e, f -- { g, h }}, i -- j -- k[second] }
};
]]
--------------------------------------------------------------------
|
setenv("LMOD_B_DIR", "/d/e/f")
|
local config = require("notify.config")
---@class Notification
---@field level string
---@field message string[]
---@field timeout number | nil
---@field title string[]
---@field icon string
---@field time number
---@field width number
---@field keep fun(): boolean
---@field on_open fun(win: number) | nil
---@field on_close fun(win: number) | nil
---@field render fun(buf: integer, notification: Notification, highlights: table<string, string>)
local Notification = {}
function Notification:new(message, level, opts)
opts = opts or {}
if type(level) == "number" then
level = vim.lsp.log_levels[level]
end
if type(message) == "string" then
message = vim.split(message, "\n")
end
level = vim.fn.toupper(level or "info")
local time = vim.fn.localtime()
local title = opts.title or ""
if type(title) == "string" then
title = { title, vim.fn.strftime("%H:%M", time) }
end
local notif = {
message = message,
title = title,
icon = opts.icon or config.icons()[level] or config.icons().INFO,
time = time,
timeout = opts.timeout,
level = level,
keep = opts.keep,
on_open = opts.on_open,
on_close = opts.on_close,
render = opts.render,
}
self.__index = self
setmetatable(notif, self)
return notif
end
function Notification:record()
return {
message = self.message,
level = self.level,
time = self.time,
title = self.title,
icon = self.icon,
render = self.render,
}
end
---@param message string | string[]
---@param level string | number
---@param opts NotifyOptions
return function(message, level, opts)
return Notification:new(message, level, opts)
end
|
----------------------------------
-- Area: Grauberg [S]
-- NPC: Indescript Markings
-- Type: Quest
-----------------------------------
local ID = require("scripts/zones/Grauberg_[S]/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/npc_util")
require("scripts/globals/status")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local gownQuestProgress = player:getCharVar("AF_SCH_BODY")
player:delStatusEffect(tpz.effect.SNEAK)
-- SCH AF Quest - Boots
if (gownQuestProgress > 0 and gownQuestProgress < 3 and not player:hasKeyItem(tpz.ki.SAMPLE_OF_GRAUBERG_CHERT)) then
npcUtil.giveKeyItem(player, tpz.ki.SAMPLE_OF_GRAUBERG_CHERT)
player:setCharVar("AF_SCH_BODY", gownQuestProgress + 1)
-- Move the markings around
local positions = {
[1] = {-517, -167, 209},
[2] = {-492, -168, 190},
[3] = {-464, -166, 241},
[4] = {-442, -156, 182},
[5] = {-433, -151, 162},
[6] = {-416, -143, 146},
[7] = {-535, -167, 227},
[8] = {-513, -170, 255}
}
local newPosition = npcUtil.pickNewPosition(npc:getID(), positions)
npc:setPos(newPosition.x, newPosition.y, newPosition.z)
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by hunzs.
--- DateTime: 2020/5/8 22:18
---
-- 全局秒钟
cj.TimerStart(cj.CreateTimer(), 1.00, true, htime.clock)
-- 预读 preread
local preread_u = cj.CreateUnit(hplayer.player_passive, hslk_global.unit_token, 0, 0, 0)
hattr.regAllAbility(preread_u)
hunit.del(preread_u)
-- register APM
hevent.pool('global', hevent_default_actions.player.apm, function(tgr)
for i = 1, bj_MAX_PLAYERS, 1 do
cj.TriggerRegisterPlayerUnitEvent(tgr, cj.Player(i - 1), EVENT_PLAYER_UNIT_ISSUED_TARGET_ORDER, nil)
cj.TriggerRegisterPlayerUnitEvent(tgr, cj.Player(i - 1), EVENT_PLAYER_UNIT_ISSUED_POINT_ORDER, nil)
cj.TriggerRegisterPlayerUnitEvent(tgr, cj.Player(i - 1), EVENT_PLAYER_UNIT_ISSUED_ORDER, nil)
end
end)
for i = 1, bj_MAX_PLAYERS, 1 do
hplayer.players[i] = cj.Player(i - 1)
-- 英雄模块初始化
hhero.player_allow_qty[i] = 1
hhero.player_heroes[i] = {}
cj.SetPlayerHandicapXP(hplayer.players[i], 0) -- 经验置0
hplayer.set(hplayer.players[i], "index", i)
hplayer.set(hplayer.players[i], "prevGold", 0)
hplayer.set(hplayer.players[i], "prevLumber", 0)
hplayer.set(hplayer.players[i], "totalGold", 0)
hplayer.set(hplayer.players[i], "totalGoldCost", 0)
hplayer.set(hplayer.players[i], "totalLumber", 0)
hplayer.set(hplayer.players[i], "totalLumberCost", 0)
hplayer.set(hplayer.players[i], "goldRatio", 100)
hplayer.set(hplayer.players[i], "lumberRatio", 100)
hplayer.set(hplayer.players[i], "expRatio", 100)
hplayer.set(hplayer.players[i], "sellRatio", 50)
hplayer.set(hplayer.players[i], "apm", 0)
hplayer.set(hplayer.players[i], "damage", 0)
hplayer.set(hplayer.players[i], "beDamage", 0)
hplayer.set(hplayer.players[i], "kill", 0)
if ((cj.GetPlayerController(hplayer.players[i]) == MAP_CONTROL_USER)
and (cj.GetPlayerSlotState(hplayer.players[i]) == PLAYER_SLOT_STATE_PLAYING)) then
--
hplayer.qty_current = hplayer.qty_current + 1
-- 默认开启自动换木
hplayer.setIsAutoConvert(hplayer.players[i], true)
hplayer.set(hplayer.players[i], "status", hplayer.player_status.gaming)
hevent.onChat(
hplayer.players[i], '+', false,
hevent_default_actions.player.command
)
hevent.onChat(
hplayer.players[i], '-', false,
hevent_default_actions.player.command
)
-- 玩家离开游戏
hevent.pool(hplayer.players[i], hevent_default_actions.player.leave, function(tgr)
cj.TriggerRegisterPlayerEvent(tgr, hplayer.players[i], EVENT_PLAYER_LEAVE)
end)
-- 玩家取消选择单位
hevent.onDeSelection(hplayer.players[i], function(evtData)
hplayer.set(evtData.triggerPlayer, "selection", nil)
end)
-- 玩家选中单位
hevent.pool(hplayer.players[i], hevent_default_actions.player.selection, function(tgr)
cj.TriggerRegisterPlayerUnitEvent(tgr, hplayer.players[i], EVENT_PLAYER_UNIT_SELECTED, nil)
end)
hevent.onSelection(hplayer.players[i], 1, function(evtData)
hplayer.set(evtData.triggerPlayer, "selection", evtData.triggerUnit)
end)
else
hplayer.set(hplayer.players[i], "status", hplayer.player_status.none)
end
end
-- 生命魔法恢复
htime.setInterval(
0.5,
function()
for agk, agu in ipairs(hRuntime.attributeGroup.life_back) do
if (his.deleted(agu) == true) then
table.remove(hRuntime.attributeGroup.life_back, agk)
else
if (his.alive(agu) and 100 > hunit.getCurLifePercent(agu)) then
local val = hattr.get(agu, "life_back") or 0
if (val ~= 0) then
hunit.addCurLife(agu, val * 0.5)
end
end
end
end
for agk, agu in ipairs(hRuntime.attributeGroup.mana_back) do
if (his.deleted(agu) == true) then
table.remove(hRuntime.attributeGroup.mana_back, agk)
else
if (his.alive(agu) and 100 > hunit.getCurManaPercent(agu)) then
local val = hattr.get(agu, "mana_back") or 0
if (val ~= 0) then
hunit.addCurMana(agu, val * 0.5)
end
end
end
end
end
)
-- 没收到伤害时,每1.5秒恢复1.5%硬直
htime.setInterval(
1.5,
function()
for agk, agu in ipairs(hRuntime.attributeGroup.punish) do
if (his.deleted(agu) == true) then
table.remove(hRuntime.attributeGroup.punish, agk)
elseif (his.alive(agu) == true and his.beDamaging(agu) == false) then
local punish_current = hattr.get(agu, "punish_current")
local punish = hattr.get(agu, "punish")
if (punish_current < punish) then
local val = math.floor(0.015 * punish)
if (punish_current + val > punish) then
hattr.set(agu, 0, { punish_current = "=" .. punish })
else
hattr.set(agu, 0, { punish_current = "+" .. val })
end
end
end
end
end
)
|
function string:split(delimiter)
local result = { }
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
end
table.insert( result, string.sub( self, from ) )
return result
end
computer_id = os.getComputerID()
computer_label = os.getComputerLabel()
computer_request_location = "http://127.0.0.1:5000/GPS_Setup?computer_id="..computer_id
http_request = http.get(computer_request_location)
computer_location = http_request.readAll()
location_table = computer_location:split(",")
-- Arrays start at 1
x = location_table[1]
y = location_table[2]
z = location_table[3]
shell.run("gps","host",x,y,z)
print(computer_location) |
--MoveCurve
--H_Yuzuru/curve_RushBack curve_RushBack
return
{
filePath = "H_Yuzuru/curve_RushBack",
startTime = Fixed64(0) --[[0]],
startRealTime = Fixed64(0) --[[0]],
endTime = Fixed64(74763472) --[[71.3]],
endRealTime = Fixed64(822399) --[[0.7843]],
isZoom = false,
isCompensate = false,
curve = {
[1] = {
time = 0 --[[0]],
value = 0 --[[0]],
inTangent = 2097152 --[[2]],
outTangent = 2097152 --[[2]],
},
[2] = {
time = 747634 --[[0.713]],
value = 4718592 --[[4.5]],
inTangent = 0 --[[0]],
outTangent = 0 --[[0]],
},
},
} |
---------------------------------------------
-- Tempest Wing
-- Family: Bahamut
-- Description: Turbulence deals Wind damage to enemies within a very wide area of effect. Additional effect: Knockback
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: Cone
-- Notes:
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (target:isBehind(mob, 55) == true) then
return 1
else
return 0
end
end
function onMobWeaponSkill(target, mob, skill)
local dmgmod = 1
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*4,tpz.magic.ele.WIND,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,tpz.attackType.MAGICAL,tpz.damageType.WIND,MOBPARAM_WIPE_SHADOWS)
target:takeDamage(dmg, mob, tpz.attackType.MAGICAL, tpz.damageType.WIND)
return dmg
end
|
--- GCC compiler implementation (C++ specialization)
-- @classmod configure.lang.cxx.compiler.gcc
local Compiler = table.update(
table.update({}, require('configure.lang.cxx.compiler.base')),
require('configure.lang.c.compiler.gcc')
)
Compiler.binary_names = {'g++', }
Compiler.lang = 'c++'
return Compiler
|
local HttpService = game:GetService("HttpService")
local Constants = require(script.Parent.Constants)
-- todo: SCOPES
local function makeInvalidTypeError(valueType)
return string.format(
"104: Cannot store %s in data store. Data stores can only accept valid UTF-8 characters.",
valueType
)
end
local function makeExceedsLimitError()
return "105: Serialized value exceeds 4MB limit."
end
local function assertValidStringValue(value)
if #value > Constants.MAX_DATA_LENGTH then
error(makeExceedsLimitError())
elseif utf8.len(value) == nil then
error(makeInvalidTypeError("string"))
end
end
local function getTableType(value)
local key = next(value)
if typeof(key) == "number" then
return "Array"
else
return "Dictionary"
end
end
local function isNumberValid(tableType, value)
if tableType == "Dictionary" then
return false, "cannot store mixed tables"
end
if value % 1 == 0 then
return false, "cannot store tables with non-integer indices"
end
if value == math.huge or value == -math.huge then
return false, "cannot store tables with (-)infinity indices"
end
return true
end
local function isValueValid(value, valueType)
if valueType == "userdata" or valueType == "function" or valueType == "thread" then
return false, string.format("cannot store '%s' of type %s", tostring(value), valueType)
end
if valueType == "string" and utf8.len(value) == nil then
return false, "cannot store strings that are invalid UTF-8"
end
return true
end
local function isValidTable(tbl, visited, path)
visited[tbl] = true
local tableType = getTableType(tbl)
local lastIndex = 0
for key, value in pairs(tbl) do
table.insert(path, tostring(key))
local keyType = typeof(key)
if keyType == "number" then
local isValidNumber, invalidNumberReason = isNumberValid(key)
if not isValidNumber then
return false, path, invalidNumberReason
end
end
if tableType == "Dictionary" and keyType ~= "string" then
return false, path, string.format("dictionaries cannot have keys of type %s", keyType)
end
if tableType == "Array" and keyType ~= "number" then
return false, path, "cannot store mixed tables"
end
if utf8.len(key) == nil then
return false, path, "dictionary has key that is invalid UTF-8"
end
if tableType == "Array" then
if lastIndex ~= key - 1 then
return false, path, "array has non-sequential indices"
end
lastIndex = key
end
local valueType = typeof(value)
local isValidValue, invalidValueReason = isValueValid(value)
if not isValidValue then
return isValidValue, path, invalidValueReason
end
if valueType == "table" then
if visited[value] then
return false, path
end
local isValid, invalidPath, reason = isValidTable(value, visited, path)
if not isValid then
return isValidTable, invalidPath, reason
end
end
table.remove(tbl)
end
return true, nil, nil
end
local function assertValidTableValue(value)
local isValid, invalidPath, reason = isValidTable(value, {}, { "root" })
if not isValid then
error(string.format("Table value has invalid entry at <%s>: %s", table.concat(invalidPath, "."), reason))
end
local ok, content = pcall(function()
return HttpService:JSONEncode(value)
end)
if not ok then
error("Could not encode table to JSON.")
elseif #content > Constants.MAX_DATA_LENGTH then
error(makeExceedsLimitError())
end
end
-- TODO: This really needs to be tested!
local function assertValidValue(value)
local valueType = typeof(value)
if valueType == "function" or valueType == "userdata" or valueType == "thread" then
error(makeInvalidTypeError(valueType))
end
if valueType == "string" then
assertValidStringValue(value)
elseif valueType == "table" then
assertValidTableValue(value)
end
end
return assertValidValue
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.