content
stringlengths 5
1.05M
|
---|
--! rocketnn
--@ commonstargets commonsweapons commons eventdriver firstrun weapontypes neuralnet secant shuffle debug
-- Neural net-based rocket turret predictor
Main = EventDriver.new()
NN = NeuralNet.new(1, 3, 1)
NN:Randomize()
TrainingSets = {}
TrainingSamplesCaptured = 0
TrainingEpoch = 0
TrainingSetIndex = 0
LastMaxRMS = 0
DummyPrediction = true
AddFirstRun(function (_)
Main:Schedule(0, RocketControl_Capture)
Main:Schedule(0, RocketControl_Update)
end)
function RocketControl_Train(I)
local Count = 0
repeat
local Set = TrainingSets[1+TrainingSetIndex]
NN:Run({ Set[1] })
local RMS = NN:Backprop({ Set[2] })
LastMaxRMS = math.max(LastMaxRMS, RMS)
Count = Count + 1
TrainingSetIndex = (TrainingSetIndex + 1) % #TrainingSets
until Count >= TrainingBatchSize or TrainingSetIndex == 0
if TrainingSetIndex == 0 then
TrainingEpoch = TrainingEpoch + 1
if (TrainingEpoch % 10) == 0 then
Log("Epoch #%d MaxRMS = %.03f", TrainingEpoch, LastMaxRMS)
end
if LastMaxRMS < DummyPredictionRMS then
DummyPrediction = false
end
if LastMaxRMS > TrainingMaxRMS then
if TrainingEpoch >= TrainingMaxEpochs then
I:LogToHud("Training failed, trying again!")
-- Try again with different weights
NN:Randomize()
TrainingEpoch = 0
DummyPrediction = true
end
shuffle(TrainingSets)
-- TrainingSetIndex already 0
LastMaxRMS = 0
Main:Schedule(1, RocketControl_Train)
else
I:LogToHud("Training complete!")
end
else
Main:Schedule(1, RocketControl_Train)
end
end
RocketControl_MissileStates = {}
function RocketControl_Capture(I)
local NewMissileStates = {}
for tindex = 0,I:GetLuaTransceiverCount()-1 do
local LaunchPad = I:GetLuaTransceiverInfo(tindex)
for mindex = 0,I:GetLuaControlledMissileCount(tindex)-1 do
local Missile = I:GetLuaControlledMissileInfo(tindex, mindex)
local MissileId = Missile.Id
local State = RocketControl_MissileStates[MissileId]
if not State then State = {} end
-- Copy state to next update
NewMissileStates[MissileId] = State
local Now = Missile.TimeSinceLaunch
local DataPoints = State.DataPoints
if not DataPoints then
DataPoints = {}
State.DataPoints = DataPoints
State.Submitted = false
-- DQ if too old
State.Disqualified = Now > 1
end
if Missile.Position.y < SampleMinAltitude then
-- Disqualify it
State.Disqualified = true
end
if not State.Disqualified then
if Now <= TimeScale then
-- Save data point
local Distance = (Missile.Position - LaunchPad.Position).magnitude
table.insert(DataPoints, { Now / TimeScale, Distance / DistanceScale })
else
-- Submit data for training if needed and it hasn't already been
if not State.Submitted and TrainingSamplesCaptured < TrainingSamplesNeeded then
-- Copy over to TrainingSets
for _,v in ipairs(DataPoints) do
table.insert(TrainingSets, v)
end
State.Submitted = true
TrainingSamplesCaptured = TrainingSamplesCaptured + 1
I:LogToHud(string.format("Sample #%d captured!", TrainingSamplesCaptured))
end
end
end
end
end
RocketControl_MissileStates = NewMissileStates
-- Keep capturing until we have enough samples, otherwise start training
if TrainingSamplesCaptured >= TrainingSamplesNeeded then
I:LogToHud(string.format("Starting training with %d sets!", #TrainingSets))
shuffle(TrainingSets)
Main:Schedule(1, RocketControl_Train)
else
Main:Schedule(Capture_UpdateRate, RocketControl_Capture)
end
end
function MissileDistance(t)
return NN:Run({ t / TimeScale })[1]*DistanceScale
end
-- Returns relative aim point for given weapon & target or nil
function RocketControl_Predict(Weapon, Target)
local AimPoint = Target.AimPoint
local ConstrainWaterline = RocketLimits.ConstrainWaterline
if ConstrainWaterline then
AimPoint = Vector3(AimPoint.x, math.max(ConstrainWaterline, AimPoint.y), AimPoint.z)
end
local RelativePosition = AimPoint - Weapon.Position
if DummyPrediction then
-- Just aim straight at target so we can fire and begin capturing data
return RelativePosition
end
-- Solve MissileDistance(t)^2 = (TP + TV*t)^2 for t
local TimeToTarget = Secant(function (t)
local TargetPosition = RelativePosition + Target.Velocity*t
return MissileDistance(t)^2 - Vector3.Dot(TargetPosition, TargetPosition)
end,
FirstGuess)
if TimeToTarget then
return RelativePosition + Target.Velocity*TimeToTarget
else
return nil
end
end
function RocketControl_Update(I)
-- Get highest-priority target within limits
local Target = nil
for _,T in ipairs(C:Targets()) do
local Altitude = T.AimPoint.y
if (T.Range >= RocketLimits.MinRange and T.Range <= RocketLimits.MaxRange and
Altitude >= RocketLimits.MinAltitude and Altitude <= RocketLimits.MaxAltitude) then
Target = T
break
end
end
if Target then
-- Aim & fire all turrets/missile controllers of the appropriate slot
for _,Weapon in pairs(C:WeaponControllers()) do
if Weapon.Slot == RocketWeaponSlot and (Weapon.Type == TURRET or Weapon.Type == MISSILECONTROL) and not Weapon.PlayerControl then
-- Calculate aim point
local AimPoint = RocketControl_Predict(Weapon, Target)
if AimPoint and I:AimWeaponInDirectionOnSubConstruct(Weapon.SubConstructId, Weapon.Index, AimPoint.x, AimPoint.y, AimPoint.z, RocketWeaponSlot) > 0 and Weapon.Type == MISSILECONTROL then
I:FireWeaponOnSubConstruct(Weapon.SubConstructId, Weapon.Index, RocketWeaponSlot)
end
end
end
end
Main:Schedule(1, RocketControl_Update)
end
function Update(I) -- luacheck: ignore 131
C = Commons.new(I)
FirstRun(I)
if not C:IsDocked() and ActivateWhen[I.AIMode] then
Main:Tick(I)
end
end
|
vim.opt.breakindent = true -- make wrapped lined match previous indentation
vim.opt.breakindentopt = "shift:2" -- emphasize broken lines by indenting them
vim.opt.clipboard = "unnamedplus" -- use system clipboard
vim.opt.colorcolumn = "80" -- display vertical gray line at 80 columns
vim.opt.cursorline = true -- enable cursorline
vim.opt.emoji = false -- don't assume double width emojis
vim.opt.equalalways = false -- don't resize my splits
vim.opt.expandtab = true -- expand tabs to spaces
-- vim.opt.foldlevel
vim.opt.inccommand = "split" -- show the effects of a command as you type
vim.opt.joinspaces = false -- don't insert two spaces after joining lines
vim.opt.linebreak = true -- wrap long lines on full word
vim.opt.list = true -- show whitespace
vim.opt.mouse = "a" -- enable mouse support
vim.opt.number = true -- show line numbers
vim.opt.relativenumber = true -- use relative line numbers
vim.opt.scrolloff = 10 -- start scrolling 10 lines before edge of viewport
vim.opt.shiftwidth = 2 -- spaces per tab when indenting
vim.opt.showmode = false -- don't show current mode, statusline does that
vim.opt.softtabstop = -1 -- use the value of "shiftwidth"
vim.opt.splitbelow = true -- open horizontal splits below
vim.opt.splitright = true -- open vertical splits to the right
vim.opt.tabstop = 2 -- use 2 spaces per when inserting tabs
vim.opt.textwidth = 80 -- wrap lines at 80 columns
vim.opt.undofile = true -- save undofiles
vim.opt.updatetime = 500 -- update signs etc. on cursor hold (default: 4000)
vim.opt.virtualedit = "block" -- allow cursor to move freely in visual mode
vim.opt.foldlevelstart = 99 -- start unfolded
vim.opt.showcmd = false -- don't show extra info at end of command line
vim.opt.showbreak = "↳ " -- DOWNWARDS ARROW WITH TIP RIGHTWARDS (U+21B3, UTF-8: E2 86 B3)
vim.opt.spellcapcheck = "" -- don't check for capital letters at start of sentence
vim.opt.synmaxcol = 200 -- don't bother syntax highlighting long lines
vim.opt.wildmode = 'longest:full,full' -- shell-like autocomplete to unambiguous portion
-- better completion experience
-- menuone: always display popup menu, even where there's only one completion
-- noinsert: do not insert any text until the user selects a match from the menu
-- noselect: do not automatically select a match from the menu
vim.opt.completeopt = "menuone,noinsert,noselect"
-- ignore these files and folders when completing paths etc.
vim.opt.wildignore = {
"*.class",
"*~",
"*.o",
".DS_Store"
}
-- show whitespace using these symbols
vim.opt.listchars = {
nbsp = "⦸", -- CIRCLED REVERSE SOLIDUS (U+29B8, UTF-8: E2 A6 B8)
tab = "▷┅", -- WHITE RIGHT-POINTING TRIANGLE (U+25B7, UTF-8: E2 96 B7) + MIDLINE HORIZONTAL ELLIPSIS (U+22EF, UTF-8: E2 8B AF)
extends = "»", -- RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK (U+00BB, UTF-8: C2 BB)
precedes = "«", -- LEFT-POINTING DOUBLE ANGLE QUOTATION MARK (U+00AB, UTF-8: C2 AB)
trail = "•" -- BULLET (U+2022, UTF-8: E2 80 A2)
}
vim.opt.formatoptions = vim.opt.formatoptions
+ "j" -- remove comment leader when joining comments
+ "n" -- smart auto indent in lists
- "o" -- don't insert comment leader when pressing "o" or "O"
vim.opt.shortmess = vim.opt.shortmess
+ "c" -- don't show insert completed messages
+ "I" -- disable intro messages
+ "W" -- don't show "written" or "[w]" when writing a file
+ "a" -- use abbreviated messages
+ "A" -- don't show waring about existing swapfile
- "F" -- needed for nvim-metals
-- enable termguicolors (needs to be set before packer loads any plugins)
vim.opt.termguicolors = true
|
local Objects = require ('map.file.objects')
local W3Q = {}
function W3Q.unpack (input)
return Objects.unpack (input, true)
end
function W3Q.pack (input)
return Objects.pack (input, true)
end
return W3Q
|
local Map = require("game.Map")
local Server = require("net.Server")
local TextButton = require("ui.TextButton")
local SelectButton = require("ui.SelectButton")
local TextBox = require("ui.TextBox")
local MenuScene = Object:extend()
function MenuScene:new(game, font)
self.ip = TextBox(game, font, "ENTER IP...", 4, 1, 6)
self.ip.change = function()
self.join.text = "JOIN"
end
self.join = TextButton(game, font, "JOIN", 10, 1, 2)
self.join.action = function()
local ip = self.ip.input:gsub("%s+", "")
local part = "%d%d?%d?"
if ip:match(part .. "." .. part .. "." .. part .. "." .. part) then
game.host:connect(ip .. ":" .. Server.PORT)
self.join.text = "..."
else
self.join.text = "!!!"
end
end
self.fullscreen = SelectButton(game, font, 3, 3, 4, {
"FLLSCRN: OFF",
"FLLSCRN: ON"
}, config.fullscreen)
self.fullscreen.change = function(index)
config.fullscreen = index
love.window.setFullscreen(index == 2)
end
self.msaa = SelectButton(game, font, 3, 5, 4, {
"MSAA: OFF",
"MSAA: LOW",
"MSAA: MED",
"MSAA: HIGH",
"MSAA: ULTRA"
}, config.msaa)
self.msaa.change = function(index)
config.msaa = index
game.post:resize()
end
self.bloom = SelectButton(game, font, 9, 3, 4, {
"BLOOM: OFF",
"BLOOM: LOW",
"BLOOM: MED",
"BLOOM: HIGH",
"BLOOM: ULTRA"
}, config.bloom)
self.bloom.change = function(index)
config.bloom = index
game.post:resize()
end
self.spark = SelectButton(game, font, 9, 5, 4, {
"SPARK: OFF",
"SPARK: LOW",
"SPARK: MED",
"SPARK: HIGH",
"SPARK: ULTRA"
}, config.spark)
self.spark.change = function(index)
config.spark = index
end
self.quit = TextButton(game, font, "QUIT", 6, 7, 4)
self.quit.action = function()
love.event.quit()
end
end
function MenuScene:update()
self.ip:update()
self.join:update()
self.fullscreen:update()
self.msaa:update()
self.bloom:update()
self.spark:update()
self.quit:update()
end
function MenuScene:draw()
love.graphics.setColor(0, 0, 0, 0.8)
love.graphics.rectangle("fill", 0, 0, Map.WIDTH, Map.HEIGHT)
love.graphics.setColor(1, 1, 1)
self.join:draw()
self.ip:draw()
self.fullscreen:draw()
self.msaa:draw()
self.bloom:draw()
self.spark:draw()
self.quit:draw()
end
function MenuScene:textinput(text)
self.ip:textinput(text)
end
return MenuScene |
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:28' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
local ZO_LootPickup_Gamepad = ZO_Loot_Gamepad_Base:Subclass()
function ZO_LootPickup_Gamepad:New(...)
return ZO_Loot_Gamepad_Base.New(self, ...)
end
function ZO_LootPickup_Gamepad:Initialize(control)
ZO_Loot_Gamepad_Base.Initialize(self, GAMEPAD_RIGHT_TOOLTIP)
control.owner = self
self.control = control
self.isInitialized = false
self.intialLootUpdate = true
local function OnStateChanged(oldState, newState)
if newState == SCENE_SHOWING then
self:OnShowing()
elseif(newState == SCENE_HIDING) then
EndLooting()
SCENE_MANAGER:RestoreHUDUIScene()
elseif newState == SCENE_HIDDEN then
self:OnHide()
end
end
LOOT_SCENE_GAMEPAD = ZO_LootScene:New("lootGamepad", SCENE_MANAGER)
LOOT_SCENE_GAMEPAD:RegisterCallback("StateChange", OnStateChanged)
SYSTEMS:RegisterGamepadRootScene("loot", LOOT_SCENE_GAMEPAD)
end
function ZO_LootPickup_Gamepad:DeferredInitialize()
self:InitializeKeybindStripDescriptors()
local contentContainer = self.control:GetNamedChild("Content")
local listContainer = contentContainer:GetNamedChild("List"):GetNamedChild("Container")
self.itemList = ZO_GamepadVerticalItemParametricScrollList:New(listContainer:GetNamedChild("List"))
self.itemList:SetAlignToScreenCenter(true)
self.itemList:AddDataTemplate("ZO_GamepadItemSubEntryTemplate", ZO_SharedGamepadEntry_OnSetup, ZO_GamepadMenuEntryTemplateParametricListFunction)
local function OnSelectionChanged(...)
self:OnSelectionChanged(...)
end
self.itemList:SetOnSelectedDataChangedCallback(OnSelectionChanged)
self.takeControl = contentContainer:GetNamedChild("KeybindContainer"):GetNamedChild("TakeContainer")
self.takeAllControl = contentContainer:GetNamedChild("KeybindContainer"):GetNamedChild("TakeAllContainer")
local SHOW_UNBOUND = true
local ALWAYS_PREFER_GAMEPAD_MODE = true
self.takeControl:SetKeybind(nil, SHOW_UNBOUND, "UI_SHORTCUT_PRIMARY", ALWAYS_PREFER_GAMEPAD_MODE)
self.takeAllControl:SetKeybind(nil, SHOW_UNBOUND, "UI_SHORTCUT_SECONDARY", ALWAYS_PREFER_GAMEPAD_MODE)
KEYBIND_STRIP:SetupButtonStyle(self.takeControl, KEYBIND_STRIP_GAMEPAD_STYLE)
KEYBIND_STRIP:SetupButtonStyle(self.takeAllControl, KEYBIND_STRIP_GAMEPAD_STYLE)
self.takeControl:SetText(GetString(SI_LOOT_TAKE))
self.takeAllControl:SetText(GetString(SI_LOOT_TAKE_ALL))
local MAX_TAKEALL_SINGLE_ROW_WIDTH = 135
local takeAllNameWidth = self.takeAllControl:GetNamedChild("NameLabel"):GetTextWidth()
if takeAllNameWidth > MAX_TAKEALL_SINGLE_ROW_WIDTH then
self.takeAllControl:ClearAnchors()
self.takeAllControl:SetAnchor(TOPLEFT, self.takeControl, BOTTOMLEFT)
end
self:InitializeHeader(GetString(SI_WINDOW_TITLE_LOOT))
local function OnPlayerDead()
if LOOT_SCENE_GAMEPAD:IsShowing() then
self:Hide()
EndLooting()
end
end
self.control:RegisterForEvent(EVENT_PLAYER_DEAD, OnPlayerDead)
self.isInitialized = true
end
function ZO_LootPickup_Gamepad:OnShowing()
local dontAutomaticallyExitScene = false
SCENE_MANAGER:SetHUDUIScene("lootGamepad", dontAutomaticallyExitScene)
KEYBIND_STRIP:RemoveDefaultExit()
KEYBIND_STRIP:AddKeybindButtonGroup(self.keybindStripDescriptor)
self.itemList:Activate()
self:OnSelectionChanged(self.itemList, self.itemList:GetTargetData())
end
function ZO_LootPickup_Gamepad:OnHide()
KEYBIND_STRIP:RemoveKeybindButtonGroup(self.keybindStripDescriptor)
self.itemList:Deactivate()
KEYBIND_STRIP:RestoreDefaultExit()
self.returnScene = nil
end
function ZO_LootPickup_Gamepad:SetTitle(title)
self.headerData.titleText = title
ZO_GamepadGenericHeader_Refresh(self.header, self.headerData)
end
function ZO_LootPickup_Gamepad:UpdateButtonTextOnSelection(selectedData)
if selectedData then
local actionStringId = selectedData.isStolen and SI_LOOT_STEAL or SI_LOOT_TAKE
self.takeControl:SetText(GetString(actionStringId))
end
end
function ZO_LootPickup_Gamepad:UpdateAllControlText()
if self.itemCount > 0 then
-- update the take all / steal all text depending on the situation
self.takeAllControl:SetText(GetString(self.nonStolenItemsPresent and SI_LOOT_TAKE_ALL or SI_LOOT_STEAL_ALL))
end
end
function ZO_LootPickup_Gamepad:Update(isOwned)
self:UpdateList()
end
function ZO_LootPickup_Gamepad:Hide()
if self.returnScene then
SCENE_MANAGER:Show(self.returnScene)
else
SCENE_MANAGER:RestoreHUDUIScene()
end
end
function ZO_LootPickup_Gamepad:Show()
if SCENE_MANAGER:IsShowingBaseScene() then
self.returnScene = nil
else
self.returnScene = SCENE_MANAGER:GetCurrentScene():GetName()
end
SCENE_MANAGER:Show("lootGamepad")
local OPEN_LOOT_WINDOW = false
ZO_PlayMonsterLootSound(OPEN_LOOT_WINDOW)
end
function ZO_LootPickup_Gamepad:InitializeKeybindStripDescriptors()
local ARE_ETHEREAL = true
self:InitializeKeybindStripDescriptorsMixin(ARE_ETHEREAL)
end
function ZO_LootPickup_Gamepad:InitializeHeader(title)
self.header = self.control:GetNamedChild("Content"):GetNamedChild("HeaderContainer"):GetNamedChild("Header")
ZO_GamepadGenericHeader_Initialize(self.header, ZO_GAMEPAD_HEADER_TABBAR_DONT_CREATE)
local function UpdateCapacityString()
local capacityString = zo_strformat(SI_GAMEPAD_INVENTORY_CAPACITY_FORMAT, self.numUsedBagSlots, self.numTotalBagSlots)
if self.bagFull then
capacityString = ZO_ERROR_COLOR:Colorize(capacityString)
end
return capacityString
end
self.headerData = {
titleText = title,
data1HeaderText = GetString(SI_GAMEPAD_LOOT_INVENTORY_CAPACITY),
data1Text = UpdateCapacityString,
}
end
--[[ Global Handlers ]]--
function ZO_LootPickup_Gamepad_Initialize(control)
LOOT_WINDOW_GAMEPAD = ZO_LootPickup_Gamepad:New(control)
end
|
minetest.register_node("yatm_decor:vent", {
description = "Vent",
groups = {cracky = 1},
tiles = {
"yatm_vents_vent.png",
},
paramtype = "none",
paramtype2 = "facedir",
sounds = yatm.node_sounds:build("metal"),
})
|
-- Decompiled using luadec 2.2 rev: for Lua 5.2 from https://github.com/viruscamp/luadec
-- Command line: A:\Steam\twd-definitive\scripteditor-10-31-20\definitive_lighting_improvements\WDC_pc_WalkingDead201_data\RiverWoods_temp.lua
-- params : ...
-- function num : 0 , upvalues : _ENV
local kScript = "RiverWoods"
local kScene = "adv_riverWoods"
local kClemTreeStruggleTime = 3.5
local multiAgents = {}
multiAgents.buckeye = {}
-- DECOMPILER ERROR at PC11: Confused about usage of register: R4 in 'UnsetPending'
;
(multiAgents.buckeye).agents = {"obj_acornBuckeyeWD", "obj_acornBuckeyeWD_clementine"}
-- DECOMPILER ERROR at PC13: Confused about usage of register: R4 in 'UnsetPending'
;
(multiAgents.buckeye).lastUpdateTime = -1
multiAgents.rock = {}
-- DECOMPILER ERROR at PC23: Confused about usage of register: R4 in 'UnsetPending'
;
(multiAgents.rock).agents = {"obj_rockWD", "obj_rockRiverWoods_clementineWristL", "obj_rockRiverWoods_clementine", "obj_rockRiverWoods"}
-- DECOMPILER ERROR at PC25: Confused about usage of register: R4 in 'UnsetPending'
;
(multiAgents.rock).lastUpdateTime = -1
multiAgents.branch = {}
-- DECOMPILER ERROR at PC33: Confused about usage of register: R4 in 'UnsetPending'
;
(multiAgents.branch).agents = {"obj_branchLogRiverWoods", "obj_branchLogRiverWoods_clementine"}
-- DECOMPILER ERROR at PC35: Confused about usage of register: R4 in 'UnsetPending'
;
(multiAgents.branch).lastUpdateTime = -1
local mBGdlgID = nil
local clemAttachedObjs = {"obj_branchLogRiverWoods_clementine", "obj_rockRiverWoods_clementine", "obj_rockRiverWoods_clementineWristL"}
local StartNodeDebugPrint = function(dialog, nodeID, instanceID, executionCount)
-- function num : 0_0 , upvalues : _ENV
print("Executing Start Node: " .. DlgGetNodeName(dialog, nodeID))
end
local PreloadAssets = function()
-- function num : 0_1 , upvalues : _ENV
PreLoad("adv_riverWoods_clementineHideAtRock.chore")
PreLoad("adv_riverWoods_clementineHideAtRock.chore")
PreLoad("adv_riverWoods_clementineDodgeZombieGround.chore")
PreLoad("adv_riverWoods_clementineDodgeZombieGround.chore")
PreLoad("env_riverWoods_use_rockLeft_1.chore")
PreLoad("env_riverWoods_use_rockRight_1.chore")
PreLoad("env_riverWoods_use_winstonThumb_1.chore")
PreLoad("env_riverWoods_timer_clemPulledLog_1.chore")
PreLoad("env_riverWoods_timer_winstonDragsClem_2_1.chore")
PreLoad("env_riverWoods_death_foundByVictor_1.chore")
PreLoad("env_riverWoods_use_winstonHands_1.chore")
PreLoad("env_riverWoods_timer_failState_winstonDrag_3.chore")
PreLoad("adv_riverWoods_clementineHoldTree.chore")
PreLoad("adv_riverWoods_clementineHoldTree.chore")
PreLoad("adv_riverWoods_zombieScavengerA_struggleZombieImpaled.chore")
PreLoad("adv_riverWoods_zombieScavengerA_struggleZombieImpaled.chore")
PreLoad("amb_riverWoods_struggle_thumb.chore")
PreLoad("adv_riverWoods_clementineTrappedAtDeadfall.chore")
PreLoad("adv_riverWoods_clementineTrappedAtDeadfall.chore")
PreLoad("env_riverWoods_cs_winstonAdjustsHold_2.chore")
PreLoad("env_riverWoods_cs_clemTackled_1.chore")
PreLoad("env_riverWoods_timer_clemDragged_1_1.chore")
PreLoad("env_riverWoods_timer_clemDragged_1b_1.chore")
PreLoad("env_riverWoods_fail_struggle_stumpZombie_1.chore")
PreLoad("env_riverWoods_cs_winstonShitsSelfLeft_1.chore")
PreLoad("env_riverWoods_cs_winstonShitsSelfCenter_1.chore")
PreLoad("env_riverWoods_fail_dodgeZombieGround_1.chore")
PreLoad("env_riverWoods_use_branch_1.chore")
PreLoad("adv_riverWoods_clementineTrappedAtDeadfall_Branch.chore")
PreLoad("adv_riverWoods_clementineTrappedAtDeadfall_Branch.chore")
PreLoad("env_riverWoods_cs_winstonAdjustsHold_1.chore")
PreLoad("env_riverWoods_peek_rightToTree_1.chore")
PreLoad("env_riverWoods_peek_rightToTree_1.chore")
PreLoad("env_riverWoods_peek_rightToTree_1.chore")
PreLoad("adv_riverWoods_clementineTrappedAtDeadfall.chore")
PreLoad("adv_riverWoods_clementineTrappedAtDeadfall.chore")
PreLoad("env_riverWoods_timer_clemGrabbedTreeZombie_1.chore")
PreLoad("adv_riverWoods_clementinePulledLog.chore")
PreLoad("adv_riverWoods_clementinePulledLog.chore")
PreLoad("env_riverWoods_kick_winston_3.chore")
PreLoad("env_riverWoods_timer_dodgeZombieGround_1.chore")
PreLoad("env_riverWoods_use_buckeye_1.chore")
PreLoad("adv_riverWoods_clementineHoldBuckeye.chore")
PreLoad("adv_riverWoods_clementineHoldBuckeye.chore")
PreLoad("env_riverWoods_cs_winstonShitsSelf_1.chore")
PreLoad("env_riverWoods_swing_rockWinston_1.chore")
PreLoad("env_riverWoods_cs_R-ratedThumb_1.chore")
PreLoad("env_riverWoods_timer_dodgeTreeZombie_1.chore")
PreLoad("env_riverWoods_cs_exit_1.chore")
PreLoad("env_riverWoods_fail_dodgeTreeZombie_1.chore")
PreLoad("env_riverWoods_fail_finalDodge_1.chore")
PreLoad("env_riverWoods_cs_enterClearing_1.chore")
PreLoad("env_riverWoods_move_zombieTumblesWinston_1.chore")
PreLoad("env_riverWoods_timer_WinstonBrokenNose_1.chore")
PreLoad("env_riverWoods_use_tree_1.chore")
PreLoad("env_riverWoods_fail_treeZombie_1.chore")
PreLoad("env_riverWoods_timer_clemHoldingBranch_1.chore")
PreLoad("env_riverWoods_fail_moveFromDeadfall_2.chore")
PreLoad("env_riverWoods_kick_winston_1.chore")
PreLoad("env_riverWoods_use_winstonHands_2.chore")
PreLoad("env_riverWoods_cs_winstonApproachesRock.chore")
PreLoad("env_riverWoods_cs_winstonAdjustsHold_3.chore")
PreLoad("env_riverWoods_fail_dodgeOnWayToDeadfall_1.chore")
PreLoad("env_riverWoods_cs_clemBacksUpToRiverBank_2.chore")
PreLoad("env_riverWoods_timer_throwRockAtMultipleZombies_1.chore")
PreLoad("env_riverWoods_cs_clemThrowsRockAtZombie_1.chore")
PreLoad("env_riverWoods_cs_clemThrowsRockAtZombie_2.chore")
PreLoad("env_riverWoods_cs_clemThrowsRockAtZombie_3.chore")
PreLoad("env_riverWoods_cs_clemThrowsRockAtZombie_4.chore")
PreLoad("env_riverWoods_cs_clemThrowsRockAtZombie_5.chore")
PreLoad("env_riverWoods_cs_clemThrowsRockAtZombie_6.chore")
PreLoad("env_riverWoods_fail_biteThumb_1.chore")
PreLoad("env_riverWoods_timer_dodgeOnWayToDeadfall_1.chore")
PreLoad("env_riverWoods_swing_branch_1.chore")
PreLoad("env_riverWoods_cs_clemYankedFromLog_1.chore")
PreLoad("env_riverWoods_kick_winston_2.chore")
PreLoad("env_riverWoods_timer_WinstonBlocksClem_1.chore")
PreLoad("env_riverWoods_fail_throwRock_1.chore")
PreLoad("env_riverWoods_cs_clemThrowsRockAtZombie_7.chore")
PreLoad("env_riverWoods_cs_fail_moveFromRock.chore")
PreLoad("env_riverWoods_cs_move_rightToTree.chore")
PreLoad("env_riverWoods_fail_moveFromDeadfall_1.chore")
PreLoad("env_riverWoods_cs_clemHides_1.chore")
PreLoad("env_riverWoods_timer_clemBiteThumb_1.chore")
PreLoad("env_riverWoods_death_foundByVictor_2.chore")
PreLoad("env_riverWoods_cs_move_rightToTree_2.chore")
PreLoad("env_riverWoods_fail_treeZombie_2.chore")
PreLoad("adv_riverWoods_zombieScavengerA_impaledZombie.chore")
PreLoad("adv_riverWoods_zombieScavengerA_impaledZombie.chore")
PreLoad("tile_barkOak.d3dtx")
PreLoad("env_leavesHiRiverWoods.d3dtx")
PreLoad("obj_rootRapidsRiverWoods_000.d3dtx")
PreLoad("Tile_forestWaterTowerTreeRoot.d3dtx")
PreLoad("obj_boulderRapidsRiverWoods_000.d3dtx")
PreLoad("obj_hatClementine200_detail.d3dtx")
PreLoad("obj_hatClementine200_nm.d3dtx")
PreLoad("obj_hatClementine200.d3dtx")
PreLoad("obj_treeDeadRiverShore_000.d3dtx")
PreLoad("adv_riverWoodsTile_meshesE_000.d3dtx")
PreLoad("adv_riverWoodsTile_meshesD_000.d3dtx")
PreLoad("obj_acornBuckeyeWD.d3dtx")
PreLoad("sk54_zombieScavengerC_head_detail.d3dtx")
PreLoad("sk54_zombieScavengerC_body_detail.d3dtx")
PreLoad("sk54_zombieScavengerC_head_nm.d3dtx")
PreLoad("sk54_zombieScavengerC_hair_nm.d3dtx")
PreLoad("sk54_zombieScavengerC_body_nm.d3dtx")
PreLoad("sk54_zombieScavengerC_head.d3dtx")
PreLoad("sk54_zombieScavengerC_hair.d3dtx")
PreLoad("sk54_zombieScavengerC_body.d3dtx")
PreLoad("obj_armZombieScavengerB_nm.d3dtx")
PreLoad("obj_armZombieScavengerB.d3dtx")
PreLoad("sk55_zombieScavengerB_bodyDamage_nm.d3dtx")
PreLoad("sk55_zombieScavengerB_bodyDamage.d3dtx")
PreLoad("sk55_zombieScavengerB_body_detail.d3dtx")
PreLoad("sk55_zombieScavengerB_body_nm.d3dtx")
PreLoad("sk55_zombieScavengerB_body.d3dtx")
PreLoad("sk55_zombieScavengerB_head_detail.d3dtx")
PreLoad("sk55_zombieScavengerB_head_nm.d3dtx")
PreLoad("sk55_zombieScavengerB_hair_nm.d3dtx")
PreLoad("sk55_zombieScavengerB_head.d3dtx")
PreLoad("sk55_zombieScavengerB_hair.d3dtx")
PreLoad("sk54_victor_head_detail.d3dtx")
PreLoad("sk54_victor_body_detail.d3dtx")
PreLoad("sk54_victor_head_nm.d3dtx")
PreLoad("sk54_victor_hair_nm.d3dtx")
PreLoad("sk54_victor_body_nm.d3dtx")
PreLoad("sk54_victor_head.d3dtx")
PreLoad("sk54_victor_hairAlpha.d3dtx")
PreLoad("sk54_victor_hair.d3dtx")
PreLoad("sk54_victor_body.d3dtx")
PreLoad("sk54_zombie200_neckGoreCap_nm.d3dtx")
PreLoad("sk54_zombie200_neckGoreCap.d3dtx")
PreLoad("sk54_zombie200_armFracture_Detail.d3dtx")
PreLoad("sk54_zombie200_armFracture_nm.d3dtx")
PreLoad("sk54_zombie200_armFracture.d3dtx")
PreLoad("sk54_zombie200_horseShoeHairA_nm.d3dtx")
PreLoad("sk54_zombie200_horseShoeHairAAlpha_nm.d3dtx")
PreLoad("sk54_zombie200_horseShoeHairAblackAlpha.d3dtx")
PreLoad("sk54_zombie200_horseShoeHairAblack.d3dtx")
PreLoad("sk54_zombie200_longHairA_nm.d3dtx")
PreLoad("sk54_zombie200_longHairAAlpha_nm.d3dtx")
PreLoad("sk54_zombie200_longHairABlackAlpha.d3dtx")
PreLoad("sk54_zombie200_longHairABlack.d3dtx")
PreLoad("map_gradiant_zombie200.d3dtx")
PreLoad("sk54_zombie200_spikeyHairA_nm.d3dtx")
PreLoad("sk54_zombie200_spikeyHairAAlpha_nm.d3dtx")
PreLoad("sk54_zombie200_spikeyHairAblackAlpha.d3dtx")
PreLoad("sk54_zombie200_spikeyHairAblack.d3dtx")
PreLoad("sk54_zombie200_stragglyHairAblackAlpha.d3dtx")
PreLoad("sk54_zombie200_fullArms_detail.d3dtx")
PreLoad("sk54_zombie200_fullArms_nm.d3dtx")
PreLoad("sk54_zombie200_fullArms.d3dtx")
PreLoad("sk54_zombie200_faceB_detail.d3dtx")
PreLoad("sk54_zombie200_faceB_nm.d3dtx")
PreLoad("sk54_zombie200_faceB.d3dtx")
PreLoad("sk54_zombie200_jacketABlue_Detail.d3dtx")
PreLoad("sk54_zombie200_jacketABlue_nm.d3dtx")
PreLoad("sk54_zombie200_jacketABlue.d3dtx")
PreLoad("sk54_zombie200_jacketB_Detail.d3dtx")
PreLoad("sk54_zombie200_jacketB_nm.d3dtx")
PreLoad("sk54_zombie200_jacketB.d3dtx")
PreLoad("sk54_zombie200_summerShirt_detail.d3dtx")
PreLoad("sk54_zombie200_summerShirt_nm.d3dtx")
PreLoad("sk54_zombie200_summerShirt.d3dtx")
PreLoad("sk54_zombie200_shirtA_detail.d3dtx")
PreLoad("sk54_zombie200_shirtA_nm.d3dtx")
PreLoad("sk54_zombie_alphaSketch.d3dtx")
PreLoad("sk54_zombie200_shirtA.d3dtx")
PreLoad("obj_gunGlockClip.d3dtx")
PreLoad("obj_gunGlock.d3dtx")
PreLoad("random_lookup.d3dtx")
PreLoad("smaa_area_lookup.d3dtx")
PreLoad("smaa_search_lookup.d3dtx")
PreLoad("sk55_zombieFem_hairStraggleyBlack.d3dtx")
PreLoad("sk55_zombieFem_hairStraggleyBlackAlpha.d3dtx")
PreLoad("fx_bloodSpurtDirRadBurst.d3dtx")
PreLoad("fx_bloodSpurtDirWdeA2.d3dtx")
PreLoad("sk54_winston_headThumbBite.d3dtx")
PreLoad("fx_bloodSpurtRadB2.d3dtx")
PreLoad("fx_splashWaterRiverFoam.d3dtx")
PreLoad("fx_bubbles.d3dtx")
PreLoad("sk56_clementine200FearB.ptable")
PreLoad("clementine200_phoneme_default_fearB.anm")
PreLoad("clementine200_phoneme_FV_fearB.anm")
PreLoad("clementine200_phoneme_I_fearB.anm")
PreLoad("clementine200_phoneme_LL_fearB.anm")
PreLoad("clementine200_phoneme_MM_fearB.anm")
PreLoad("clementine200_phoneme_NN_fearB.anm")
PreLoad("clementine200_phoneme_O_fearB.anm")
PreLoad("clementine200_phoneme_SH_fearB.anm")
PreLoad("clementine200_phoneme_TH_fearB.anm")
PreLoad("clementine200_phoneme_U_fearB.anm")
PreLoad("sk56_idle_clementine200FearCX.chore")
PreLoad("sk56_idle_clem200FearCX.anm")
PreLoad("sk56_clementine200FearCX.ptable")
PreLoad("clementine200_phoneme_AA_fearCX.anm")
PreLoad("clementine200_phoneme_default_fearCX.anm")
PreLoad("clementine200_phoneme_EE_fearCX.anm")
PreLoad("clementine200_phoneme_FV_fearCX.anm")
PreLoad("clementine200_phoneme_I_fearCX.anm")
PreLoad("clementine200_phoneme_LL_fearCX.anm")
PreLoad("clementine200_phoneme_MM_fearCX.anm")
PreLoad("clementine200_phoneme_NN_fearCX.anm")
PreLoad("clementine200_phoneme_O_fearCX.anm")
PreLoad("clementine200_phoneme_SH_fearCX.anm")
PreLoad("clementine200_phoneme_TH_fearCX.anm")
PreLoad("clementine200_phoneme_U_fearCX.anm")
PreLoad("fs_mud_run_step_6.wav")
PreLoad("fs_mud_run_step_7.wav")
PreLoad("fs_mud_run_step_8.wav")
PreLoad("fs_mud_run_step_9.wav")
PreLoad("fs_mud_run_step_10.wav")
PreLoad("sk56_idle_clementine200PainA.chore")
PreLoad("sk56_clementine200PainA.ptable")
PreLoad("clementine200_phoneme_AA_painA.anm")
PreLoad("clementine200_phoneme_default_painA.anm")
PreLoad("clementine200_phoneme_EE_painA.anm")
PreLoad("clementine200_phoneme_FV_painA.anm")
PreLoad("clementine200_phoneme_I_painA.anm")
PreLoad("clementine200_phoneme_LL_painA.anm")
PreLoad("clementine200_phoneme_MM_painA.anm")
PreLoad("clementine200_phoneme_NN_painA.anm")
PreLoad("clementine200_phoneme_O_painA.anm")
PreLoad("clementine200_phoneme_SH_painA.anm")
PreLoad("clementine200_phoneme_TH_painA.anm")
PreLoad("clementine200_phoneme_U_painA.anm")
PreLoad("mus_loop_Tense_24.wav")
PreLoad("sk54_idle_winstonAngryCX.chore")
PreLoad("sk54_winstonAngryCX.ptable")
PreLoad("winston_phoneme_AA_angryCX.anm")
PreLoad("winston_phoneme_default_angryCX.anm")
PreLoad("winston_phoneme_EE_angryCX.anm")
PreLoad("winston_phoneme_FV_angryCX.anm")
PreLoad("winston_phoneme_I_angryCX.anm")
PreLoad("winston_phoneme_LL_angryCX.anm")
PreLoad("winston_phoneme_MM_angryCX.anm")
PreLoad("winston_phoneme_NN_angryCX.anm")
PreLoad("winston_phoneme_O_angryCX.anm")
PreLoad("winston_phoneme_SH_angryCX.anm")
PreLoad("winston_phoneme_TH_angryCX.anm")
PreLoad("winston_phoneme_U_angryCX.anm")
PreLoad("sk54_idle_winstonAngryC.chore")
PreLoad("sk54_winstonAngryC.ptable")
PreLoad("winston_phoneme_AA_angryC.anm")
PreLoad("winston_phoneme_default_angryC.anm")
PreLoad("winston_phoneme_EE_angryC.anm")
PreLoad("winston_phoneme_FV_angryC.anm")
PreLoad("winston_phoneme_I_angryC.anm")
PreLoad("winston_phoneme_LL_angryC.anm")
PreLoad("winston_phoneme_MM_angryC.anm")
PreLoad("winston_phoneme_NN_angryC.anm")
PreLoad("winston_phoneme_O_angryC.anm")
PreLoad("winston_phoneme_SH_angryC.anm")
PreLoad("winston_phoneme_TH_angryC.anm")
PreLoad("winston_phoneme_U_angryC.anm")
PreLoad("ui_notification.prop")
PreLoad("ui_notification_text.prop")
PreLoad("ui_notification_background.prop")
PreLoad("ui_notification_exclamation.prop")
PreLoad("ui_notification_question.prop")
PreLoad("ui_notification_saving.prop")
PreLoad("ui_notification.scene")
PreLoad("SceneShadowMapAlpha_QHi.t3fxb")
PreLoad("SceneVelocityAlpha_QHi.t3fxb")
PreLoad("SceneGlowAlphaTest_QHi.t3fxb")
PreLoad("ui_peek.prop")
PreLoad("ui_peek_arrow.prop")
PreLoad("ui_peek.scene")
PreLoad("ui_peek_arrow.d3dmesh")
PreLoad("ui_peek_arrow.d3dtx")
PreLoad("ui_notification_background.d3dmesh")
PreLoad("ui_notification_exclamation.d3dmesh")
PreLoad("ui_notification_question.d3dmesh")
PreLoad("ui_notification_saving.d3dmesh")
PreLoad("ui_notification_background.d3dtx")
PreLoad("ui_notification_exclamation.d3dtx")
PreLoad("ui_notification_question.d3dtx")
PreLoad("ui_notification_saving1.d3dtx")
PreLoad("cam_nav_clemAtRock_horizontal_adv_riverWoods.chore")
PreLoad("cam_nav_clemAtRock_vertical_adv_riverWoods.chore")
PreLoad("ui_peek_arrowOn.chore")
PreLoad("Peek.imap")
PreLoad("sk54_idle_winstonAngryB.chore")
PreLoad("ui_panicMeter.prop")
PreLoad("ui_panicMeter_vignette.prop")
PreLoad("ui_panicMeter_background.prop")
PreLoad("ui_dialog_timer.prop")
PreLoad("ui_dialog_timerLine.prop")
PreLoad("ui_panicMeter.scene")
PreLoad("ui_panicMeter_timerCombat.chore")
PreLoad("ui_panicMeter_vignetteRotateRight.chore")
PreLoad("ui_panicMeter_vignetteRotateLeft.chore")
PreLoad("ui_panicMeter_vignette.d3dmesh")
PreLoad("ui_panicMeter_background.d3dmesh")
PreLoad("ui_dialog_timer.d3dmesh")
PreLoad("ui_dialog_timerLine.d3dmesh")
PreLoad("ui_panicMeter_vignette.d3dtx")
PreLoad("ui_dialog_timer.d3dtx")
PreLoad("ui_dialog_timerLine.d3dtx")
PreLoad("ui_episode.dlog")
PreLoad("ui_notification_tutorialOn.chore")
PreLoad("ui_peek_arrowOff.chore")
PreLoad("ui_dot.prop")
PreLoad("ui_dot.d3dmesh")
PreLoad("ui_dot.d3dtx")
PreLoad("ui_icon_Walk.d3dtx")
PreLoad("ui_reticle_textShow.chore")
PreLoad("ui_reticle_defaultPrompt_keyboard.d3dtx")
PreLoad("ui_reticle_combatExpand.chore")
PreLoad("ui_reticle_defaultExpand.chore")
PreLoad("ui_reticle_cursorAcknowledgeIput.chore")
PreLoad("ui_reticle_actionExpandPress.chore")
PreLoad("ui_reticle_actionExpandPress.d3dtx")
PreLoad("ui_notification_tutorialOff.chore")
PreLoad("Action.imap")
PreLoad("ui_hud_prompt_keyboard_stroke.d3dtx")
PreLoad("ui_hud_prompt_stick.d3dmesh")
PreLoad("ui_hud_prompt_stick_left.d3dtx")
PreLoad("ui_hud_prompt_stick_stroke.d3dmesh")
PreLoad("ui_hud_prompt_stick_stroke.d3dtx")
PreLoad("ui_hud_prompt_keyboard_right.d3dtx")
PreLoad("ui_hud_prompt_stick_reveal.chore")
PreLoad("ui_hud_prompt_arrow_reveal.chore")
PreLoad("ui_hud_prompt_arrow.d3dtx")
PreLoad("ui_hud_prompt_arrow.d3dmesh")
PreLoad("ui_hud_prompt_button.d3dmesh")
PreLoad("ui_hud_prompt_button_glow.d3dmesh")
PreLoad("ui_hud_prompt_button_stroke.d3dmesh")
PreLoad("ui_hud_prompt_arrow_background.d3dmesh")
PreLoad("ui_mask.d3dmesh")
PreLoad("ui_hud_prompt_button_background.d3dmesh")
PreLoad("ui_hud_prompt_facebutton_down.d3dtx")
PreLoad("ui_hud_prompt_facebutton_down_glow.d3dtx")
PreLoad("ui_hud_prompt_button_stroke.d3dtx")
PreLoad("ui_hud_prompt_arrow_background.d3dtx")
PreLoad("ui_mask.d3dtx")
PreLoad("ui_hud_prompt_button_background.d3dtx")
PreLoad("ui_hud_prompt_stick_succeed.chore")
PreLoad("ui_hud_prompt_arrow_succeed.chore")
PreLoad("ui_hud_prompt_arrowPress.d3dtx")
PreLoad("ui_reticle_textHide.chore")
PreLoad("sk54_idle_zombieAverageStandA.anm")
PreLoad("zombieAverage200_face_default.anm")
PreLoad("Mesh_1SKN_BMP_CC_TINT_QHi.t3fxb")
PreLoad("SceneToonOutline2_1SKN_CC_TINT_QHi.t3fxb")
PreLoad("ui_hud_prompt_keyboard_left.d3dtx")
PreLoad("fs_wet_mud_1.wav")
PreLoad("fs_wet_mud_2.wav")
PreLoad("fs_wet_mud_3.wav")
PreLoad("fs_wet_mud_4.wav")
PreLoad("SceneGBuffer_1SKN_QHi.t3fxb")
PreLoad("SceneToonOutline2_GBuffer_1SKN_QHi.t3fxb")
PreLoad("SceneVelocity_1SKN_QHi.t3fxb")
PreLoad("SceneGlow_1SKN_QHi.t3fxb")
PreLoad("cam_nav_clemAtDeadfall_horizontal_adv_riverWoods.chore")
PreLoad("cam_nav_clemAtDeadfall_vertical_adv_riverWoods.chore")
PreLoad("ui_notification_saving.chore")
PreLoad("ui_notification_saving2.d3dtx")
PreLoad("ui_notification_saving3.d3dtx")
PreLoad("ui_notification_saving4.d3dtx")
PreLoad("ui_notification_saving5.d3dtx")
PreLoad("ui_notification_saving6.d3dtx")
PreLoad("ui_notification_saving7.d3dtx")
PreLoad("ui_notification_saving8.d3dtx")
PreLoad("sk56_idle_clementine200AngryB.chore")
PreLoad("sk56_clementine200AngryB.ptable")
PreLoad("clementine200_phoneme_AA_angryB.anm")
PreLoad("clementine200_phoneme_default_angryB.anm")
PreLoad("clementine200_phoneme_EE_angryB.anm")
PreLoad("clementine200_phoneme_FV_angryB.anm")
PreLoad("clementine200_phoneme_I_angryB.anm")
PreLoad("clementine200_phoneme_LL_angryB.anm")
PreLoad("clementine200_phoneme_MM_angryB.anm")
PreLoad("clementine200_phoneme_NN_angryB.anm")
PreLoad("clementine200_phoneme_O_angryB.anm")
PreLoad("clementine200_phoneme_SH_angryB.anm")
PreLoad("clementine200_phoneme_TH_angryB.anm")
PreLoad("clementine200_phoneme_U_angryB.anm")
PreLoad("ui_icon_hand.d3dtx")
PreLoad("sk56_idle_clementine200AngryC.chore")
PreLoad("sk56_clementine200AngryC.ptable")
PreLoad("clementine200_phoneme_AA_angryC.anm")
PreLoad("clementine200_phoneme_default_angryC.anm")
PreLoad("clementine200_phoneme_EE_angryC.anm")
PreLoad("clementine200_phoneme_FV_angryC.anm")
PreLoad("clementine200_phoneme_I_angryC.anm")
PreLoad("clementine200_phoneme_LL_angryC.anm")
PreLoad("clementine200_phoneme_MM_angryC.anm")
PreLoad("clementine200_phoneme_NN_angryC.anm")
PreLoad("clementine200_phoneme_O_angryC.anm")
PreLoad("clementine200_phoneme_SH_angryC.anm")
PreLoad("clementine200_phoneme_TH_angryC.anm")
PreLoad("clementine200_phoneme_U_angryC.anm")
PreLoad("fx_bloodSpurtRadEmitter_idleA.chore")
PreLoad("sk54_idle_winstonPainA.chore")
PreLoad("sk56_idle_clementine200ThinkingB.chore")
PreLoad("sk56_idle_clem200ThinkingB.anm")
PreLoad("sk56_clementine200ThinkingB.ptable")
PreLoad("clementine200_phoneme_AA_thinkingB.anm")
PreLoad("clementine200_phoneme_default_thinkingB.anm")
PreLoad("clementine200_phoneme_EE_thinkingB.anm")
PreLoad("clementine200_phoneme_FV_thinkingB.anm")
PreLoad("clementine200_phoneme_I_thinkingB.anm")
PreLoad("clementine200_phoneme_LL_thinkingB.anm")
PreLoad("clementine200_phoneme_MM_thinkingB.anm")
PreLoad("clementine200_phoneme_NN_thinkingB.anm")
PreLoad("clementine200_phoneme_O_thinkingB.anm")
PreLoad("clementine200_phoneme_SH_thinkingB.anm")
PreLoad("clementine200_phoneme_TH_thinkingB.anm")
PreLoad("clementine200_phoneme_U_thinkingB.anm")
PreLoad("sk54_petePainAX.ptable")
PreLoad("pete_phoneme_AA_painAX.anm")
PreLoad("pete_phoneme_default_painAX.anm")
PreLoad("pete_phoneme_EE_painAX.anm")
PreLoad("pete_phoneme_FV_painAX.anm")
PreLoad("pete_phoneme_I_painAX.anm")
PreLoad("pete_phoneme_LL_painAX.anm")
PreLoad("pete_phoneme_MM_painAX.anm")
PreLoad("pete_phoneme_NN_painAX.anm")
PreLoad("pete_phoneme_O_painAX.anm")
PreLoad("pete_phoneme_SH_painAX.anm")
PreLoad("pete_phoneme_TH_painAX.anm")
PreLoad("pete_phoneme_U_painAX.anm")
PreLoad("sk56_idle_clementine200SurprisedC.chore")
PreLoad("sk56_idle_clem200SurpriseC.anm")
PreLoad("sk56_clementine200SurpriseC.ptable")
PreLoad("clementine200_phoneme_AA_surpriseC.anm")
PreLoad("clementine200_phoneme_default_surpriseC.anm")
PreLoad("clementine200_phoneme_EE_surpriseC.anm")
PreLoad("clementine200_phoneme_FV_surpriseC.anm")
PreLoad("clementine200_phoneme_I_surpriseC.anm")
PreLoad("clementine200_phoneme_LL_surpriseC.anm")
PreLoad("clementine200_phoneme_MM_surpriseC.anm")
PreLoad("clementine200_phoneme_NN_surpriseC.anm")
PreLoad("clementine200_phoneme_O_surpriseC.anm")
PreLoad("clementine200_phoneme_SH_surpriseC.anm")
PreLoad("clementine200_phoneme_TH_surpriseC.anm")
PreLoad("clementine200_phoneme_U_surpriseC.anm")
PreLoad("sk56_idle_clementine200SurprisedCX.chore")
PreLoad("sk56_idle_clem200SurpriseCX.anm")
PreLoad("sk56_clementine200SurpriseCX.ptable")
PreLoad("clementine200_phoneme_AA_surpriseCX.anm")
PreLoad("clementine200_phoneme_default_surpriseCX.anm")
PreLoad("clementine200_phoneme_EE_surpriseCX.anm")
PreLoad("clementine200_phoneme_FV_surpriseCX.anm")
PreLoad("clementine200_phoneme_I_surpriseCX.anm")
PreLoad("clementine200_phoneme_LL_surpriseCX.anm")
PreLoad("clementine200_phoneme_MM_surpriseCX.anm")
PreLoad("clementine200_phoneme_NN_surpriseCX.anm")
PreLoad("clementine200_phoneme_O_surpriseCX.anm")
PreLoad("clementine200_phoneme_SH_surpriseCX.anm")
PreLoad("clementine200_phoneme_TH_surpriseCX.anm")
PreLoad("clementine200_phoneme_U_surpriseCX.anm")
PreLoad("sk56_idle_clementine200PainD.chore")
PreLoad("sk56_idle_clem200PainD.anm")
PreLoad("sk56_clementine200PainD.ptable")
PreLoad("clementine200_phoneme_AA_painD.anm")
PreLoad("clementine200_phoneme_default_painD.anm")
PreLoad("clementine200_phoneme_EE_painD.anm")
PreLoad("clementine200_phoneme_FV_painD.anm")
PreLoad("clementine200_phoneme_I_painD.anm")
PreLoad("clementine200_phoneme_LL_painD.anm")
PreLoad("clementine200_phoneme_MM_painD.anm")
PreLoad("clementine200_phoneme_NN_painD.anm")
PreLoad("clementine200_phoneme_O_painD.anm")
PreLoad("clementine200_phoneme_SH_painD.anm")
PreLoad("clementine200_phoneme_TH_painD.anm")
PreLoad("clementine200_phoneme_U_painD.anm")
PreLoad("Mesh_BMP_SCM_DTL_DBMP_CC_TINT_QHi.t3fxb")
PreLoad("cam_nav_clemBiteThumb_horizontal_adv_riverWoods.chore")
PreLoad("cam_nav_clemBiteThumb_vertical_adv_riverWoods.chore")
PreLoad("sk56_idle_clementine200PainC.chore")
PreLoad("sk54_idle_winstonHoldSpear.chore")
PreLoad("sk54_idle_winstonHoldSpear.anm")
PreLoad("ui_icon_Bite.d3dtx")
PreLoad("sk56_clementine200PainC.ptable")
PreLoad("clementine200_phoneme_AA_painC.anm")
PreLoad("clementine200_phoneme_default_painC.anm")
PreLoad("clementine200_phoneme_EE_painC.anm")
PreLoad("clementine200_phoneme_FV_painC.anm")
PreLoad("clementine200_phoneme_I_painC.anm")
PreLoad("clementine200_phoneme_LL_painC.anm")
PreLoad("clementine200_phoneme_MM_painC.anm")
PreLoad("clementine200_phoneme_NN_painC.anm")
PreLoad("clementine200_phoneme_O_painC.anm")
PreLoad("clementine200_phoneme_SH_painC.anm")
PreLoad("clementine200_phoneme_TH_painC.anm")
PreLoad("clementine200_phoneme_U_painC.anm")
PreLoad("sk56_idle_clementine200PainB.chore")
PreLoad("sk56_idle_clem200PainB.anm")
PreLoad("sk56_clementine200PainB.ptable")
PreLoad("clementine200_phoneme_AA_painB.anm")
PreLoad("clementine200_phoneme_default_painB.anm")
PreLoad("clementine200_phoneme_EE_painB.anm")
PreLoad("clementine200_phoneme_FV_painB.anm")
PreLoad("clementine200_phoneme_I_painB.anm")
PreLoad("clementine200_phoneme_LL_painB.anm")
PreLoad("clementine200_phoneme_MM_painB.anm")
PreLoad("clementine200_phoneme_NN_painB.anm")
PreLoad("clementine200_phoneme_O_painB.anm")
PreLoad("clementine200_phoneme_SH_painB.anm")
PreLoad("clementine200_phoneme_TH_painB.anm")
PreLoad("clementine200_phoneme_U_painB.anm")
PreLoad("bg_riverWoods_struggle_clemBitesWinstonThumb.chore")
PreLoad("sk56_idle_clementine200BitesWinstonThumb.chore")
PreLoad("sk54_winston_sk56_idle_clementine200BitesWinstonThumb.anm")
PreLoad("sk56_idle_clementine200BitesWinstonThumb.anm")
PreLoad("cam_cutscene_cameraNoiseSniper_add.anm")
PreLoad("struggle.chore")
PreLoad("struggle_left.chore")
PreLoad("ui_struggle.prop")
PreLoad("ui_struggle_square.prop")
PreLoad("ui_struggle_chevron.prop")
PreLoad("ui_struggle_facebuttonA.prop")
PreLoad("ui_struggle_swipe.prop")
PreLoad("ui_struggle_arrow.prop")
PreLoad("ui_struggle_actionArrow.prop")
PreLoad("ui_struggle_facebuttonA_shadow.prop")
PreLoad("ui_struggle_mashProgressFill.prop")
PreLoad("ui_struggle.scene")
PreLoad("Struggle.imap")
PreLoad("ui_struggle_mashShow.chore")
PreLoad("ui_struggle_facebuttonA.d3dtx")
PreLoad("ui_struggle_facebuttonA.d3dmesh")
PreLoad("ui_struggle_facebuttonQ_keyboard.d3dtx")
PreLoad("ui_struggle_facebuttonA_shadow.d3dmesh")
PreLoad("ui_struggle_facebuttonA_shadow.d3dtx")
PreLoad("ui_struggle_mashProgressFill_keyboard.chore")
PreLoad("ui_struggle_mashProgressMeter.d3dtx")
PreLoad("ui_struggle_mashProgressFill.d3dmesh")
PreLoad("ui_struggle_mashProgressFill.d3dmesh")
PreLoad("ui_struggle_square.d3dmesh")
PreLoad("ui_struggle_chevron.d3dmesh")
PreLoad("ui_struggle_actionArrow.d3dmesh")
PreLoad("ui_struggle_square.d3dtx")
PreLoad("ui_struggle_chevron.d3dtx")
PreLoad("ui_struggle_actionArrow.d3dtx")
PreLoad("ui_struggle_mash.chore")
PreLoad("sk56_idle_clementine200NormalA.chore")
PreLoad("sk54_idle_winstonNormalA.chore")
PreLoad("cam_nav_clemInLog_horizontal_adv_riverWoods.chore")
PreLoad("cam_nav_clemInLog_vertical_adv_riverWoods.chore")
PreLoad("ui_icon_Kick.d3dtx")
PreLoad("sk56_idle_clementine200PainAX.chore")
PreLoad("sk56_idle_clem200PainAX.anm")
PreLoad("sk54_move_winstonWalk.chore")
PreLoad("sk54_move_wd200GMWalkA.anm")
PreLoad("sk56_clementine200PainAX.ptable")
PreLoad("clementine200_phoneme_AA_painAX.anm")
PreLoad("clementine200_phoneme_default_painAX.anm")
PreLoad("clementine200_phoneme_FV_painAX.anm")
PreLoad("clementine200_phoneme_I_painAX.anm")
PreLoad("clementine200_phoneme_LL_painAX.anm")
PreLoad("clementine200_phoneme_MM_painAX.anm")
PreLoad("clementine200_phoneme_NN_painAX.anm")
PreLoad("clementine200_phoneme_O_painAX.anm")
PreLoad("clementine200_phoneme_SH_painAX.anm")
PreLoad("clementine200_phoneme_TH_painAX.anm")
PreLoad("clementine200_phoneme_U_painAX.anm")
PreLoad("cam_nav_secondDrag_horizontal_adv_riverWoods.chore")
PreLoad("cam_nav_secondDrag_vertical_adv_riverWoods.chore")
PreLoad("bg_riverWoods_struggle_winstonClemStruggleHoldTreeNearFail_1.chore")
PreLoad("bg_riverWoods_struggle_winstonClemStruggleHoldTree_1.chore")
PreLoad("bg_riverWoods_struggle_winstonClemStruggleHoldTreeNearSuccess_1.chore")
PreLoad("sk54_idle_winstonClemStrugglesHoldTreeNearFail.chore")
PreLoad("sk54_idle_winstonClemStrugglesHoldTreeNearFail.anm")
PreLoad("sk56_clementine200_sk54_idle_winstonClemStrugglesHoldTreeNearFail.anm")
PreLoad("clementine200_headGesture_lookUpRight_add.anm")
PreLoad("NV_Clem_Grunt_Exertion-01.wav")
PreLoad("Vox_David_attackRecovery_lp_3.wav")
PreLoad("fs_wet_mud_13.wav")
PreLoad("fs_wet_mud_14.wav")
PreLoad("mus_loop_Action_19b.wav")
PreLoad("bg_riverWoods_struggle_clemPushWinstonChinStruggleRightNearFail_1.chore")
PreLoad("bg_riverWoods_struggle_clemPushWinstonChinStruggleRight_1.chore")
PreLoad("bg_riverWoods_struggle_clemPushWinstonChinStruggleRightNearSuccess_1.chore")
PreLoad("sk56_idle_clemPushWinstonChinStruggleRightNearFail.chore")
PreLoad("sk54_winston_sk56_idle_clemPushWinstonChinStruggleRightNearFail.anm")
PreLoad("sk54_winston_toAngryA.chore")
PreLoad("sk56_idle_clemPushWinstonChinStruggleRightNearFail.anm")
PreLoad("sk56_idle_clemPushWinstonChinStruggleRightNearSuccess.chore")
PreLoad("sk54_winston_sk56_idle_clemPushWinstonChinStruggleRightNearSuccess.anm")
PreLoad("sk54_winston_toSurpriseA.chore")
PreLoad("sk54_idle_peteSurprisedA.anm")
PreLoad("sk56_idle_clemPushWinstonChinStruggleRightNearSuccess.anm")
PreLoad("sk54_alvin_indifferentHeadSideToSide_add.anm")
PreLoad("bg_riverWoods_struggle_clemPushWinstonChinStruggleLeftNearFail_1.chore")
PreLoad("bg_riverWoods_struggle_clemPushWinstonChinStruggleLeft_1.chore")
PreLoad("bg_riverWoods_struggle_clemPushWinstonChinStruggleLeftNearSuccess_1.chore")
PreLoad("env_riverWoods_struggle_impaledZombie_2.chore")
PreLoad("sk55_lillyHandOnHip_heavyBreathing_add.anm")
PreLoad("sk54_idle_winstonSurprisedA.chore")
PreLoad("sk54_peteSurprisedA.ptable")
PreLoad("pete_phoneme_AA_surprisedA.anm")
PreLoad("pete_phoneme_default_surprisedA.anm")
PreLoad("pete_phoneme_EE_surprisedA.anm")
PreLoad("pete_phoneme_FV_surprisedA.anm")
PreLoad("pete_phoneme_I_surprisedA.anm")
PreLoad("pete_phoneme_LL_surprisedA.anm")
PreLoad("pete_phoneme_MM_surprisedA.anm")
PreLoad("pete_phoneme_NN_surprisedA.anm")
PreLoad("pete_phoneme_O_surprisedA.anm")
PreLoad("pete_phoneme_SH_surprisedA.anm")
PreLoad("pete_phoneme_TH_surprisedA.anm")
PreLoad("pete_phoneme_U_surprisedA.anm")
PreLoad("Mesh_1SKN_BMP_DTL_CC_TINT_SDTL_QHi.t3fxb")
PreLoad("bg_riverWoods_struggle_zombieYankNearFail_1.chore")
PreLoad("bg_riverWoods_struggle_zombieYank_1.chore")
PreLoad("bg_riverWoods_struggle_zombieYankNearSuccess_1.chore")
PreLoad("sk56_idle_clementine200StruggleZombieThruTree.chore")
PreLoad("Zombie2_sk56_idle_clementine200StruggleZombieThruTree.anm")
PreLoad("ZombieScavengerB_sk56_idle_clementine200StruggleZombieThruTree.anm")
PreLoad("sk56_idle_clementine200StruggleZombieThruTree.anm")
PreLoad("obj_trunksYRiverWoods_sk56_idle_clementine200StruggleZombieThruTree.anm")
PreLoad("sk56_idle_clementine200StruggleZombieThruTreeNearSuccess.chore")
PreLoad("ZombieScavengerB_sk56_idle_clementine200StruggleZombieThruTreeNearSuccess.anm")
PreLoad("sk56_idle_clementine200StruggleZombieThruTreeNearSuccess.anm")
PreLoad("obj_trunksYRiverWoods_sk56_idle_clementine200StruggleZombieThruTreeNearSuccess.anm")
PreLoad("vox_susan_attack_lee_grabs.wav")
PreLoad("cam_nav_clemDodgeZombieGround_horizontal_adv_riverWoods.chore")
PreLoad("cam_nav_clemDodgeZombieGround_vertical_adv_riverWoods.chore")
PreLoad("sk56_idle_clementine200Tense.chore")
PreLoad("Mesh_1SKN_BMP_TOON_CC_TINT_QHi.t3fxb")
PreLoad("ui_hud_prompt_keyboard_down.d3dtx")
PreLoad("cam_nav_clemDodgeTreeZombie_horizontal_adv_riverWoods.chore")
PreLoad("cam_nav_clemDodgeTreeZombie_vertical_adv_riverWoods.chore")
PreLoad("cam_nav_clemThrowRock_horizontal_adv_riverWoods.chore")
PreLoad("cam_nav_clemThrowRock_vertical_adv_riverWoods.chore")
PreLoad("NV_Clem_Yell_Falling_01.wav")
PreLoad("Mesh_1SKN_VCOL_CC_TINT_QHi.t3fxb")
PreLoad("FX_GaussianBlurX1_QHi.t3fxb")
PreLoad("FX_GaussianBlurX2_QHi.t3fxb")
PreLoad("FX_DepthOfField_QHi.t3fxb")
PreLoad("SceneShadowMap_1SKN_VCOL_QHi.t3fxb")
PreLoad("SceneGlowAlphaBlend_1SKN_QHi.t3fxb")
if (_ENV.Platform_NeedShaderPreload)() then
(_ENV.RenderPreloadShader)("SceneShadowMap_QLo.t3fxb", "0")
;
(_ENV.RenderPreloadShader)("SceneShadowMapAlpha_QLo.t3fxb", "0")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "78")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_CC_TINT_QLo.t3fxb", "71")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_DTL_CC_TINT_QLo.t3fxb", "71")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "327")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "326")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_CC_TINT_QLo.t3fxb", "326")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_CC_TINT_QLo.t3fxb", "327")
;
(_ENV.RenderPreloadShader)("FX_Null_QLo.t3fxb", "0")
;
(_ENV.RenderPreloadShader)("DirectionalLightShadow_QLo.t3fxb", "1024")
;
(_ENV.RenderPreloadShader)("SceneToonOutline2_CC_TINT_QLo.t3fxb", "0")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "7")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "3")
;
(_ENV.RenderPreloadShader)("Mesh_DTL_CC_TINT_SDTL_QLo.t3fxb", "3")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "259")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "135")
;
(_ENV.RenderPreloadShader)("Mesh_DTL_CC_TINT_QLo.t3fxb", "198")
;
(_ENV.RenderPreloadShader)("Mesh_DTL_CC_TINT_QLo.t3fxb", "196")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_CC_TINT_QLo.t3fxb", "199")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "199")
;
(_ENV.RenderPreloadShader)("Mesh_VCOL_CC_TINT_QLo.t3fxb", "135")
;
(_ENV.RenderPreloadShader)("SceneToonOutline2_CC_TINT_QLo.t3fxb", "64")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "67")
;
(_ENV.RenderPreloadShader)("Mesh_DTL_CC_TINT_SDTL_QLo.t3fxb", "67")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "323")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "14")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "263")
;
(_ENV.RenderPreloadShader)("Mesh_VCOL_CC_TINT_QLo.t3fxb", "78")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "70")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_CC_TINT_QLo.t3fxb", "327")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "195")
;
(_ENV.RenderPreloadShader)("Mesh_DTL_VCOL_CC_TINT_QLo.t3fxb", "199")
;
(_ENV.RenderPreloadShader)("Mesh_DTL_VCOL_CC_TINT_QLo.t3fxb", "196")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "142")
;
(_ENV.RenderPreloadShader)("Mesh_QLo.t3fxb", "134")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_CC_TINT_QLo.t3fxb", "7")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_DTL_VCOL_CC_TINT_QLo.t3fxb", "7")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "334")
;
(_ENV.RenderPreloadShader)("SceneShadowMapAlpha_1SKN_QLo.t3fxb", "0")
;
(_ENV.RenderPreloadShader)("SceneShadowMap_1SKN_QLo.t3fxb", "0")
;
(_ENV.RenderPreloadShader)("SceneToonOutline2_1SKN_CC_TINT_QLo.t3fxb", "64")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_CC_TINT_QLo.t3fxb", "67")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_CC_TINT_QLo.t3fxb", "323")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_DTL_CC_TINT_QLo.t3fxb", "199")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "198")
;
(_ENV.RenderPreloadShader)("Mesh_VCOL_CC_TINT_QLo.t3fxb", "67")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_CC_TINT_QLo.t3fxb", "3")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_CC_TINT_QLo.t3fxb", "259")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_DTL_VCOL_CC_TINT_QLo.t3fxb", "199")
;
(_ENV.RenderPreloadShader)("Mesh_VCOL_CC_TINT_QLo.t3fxb", "7")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_CC_TINT_QLo.t3fxb", "262")
;
(_ENV.RenderPreloadShader)("Mesh_VCOL_CC_TINT_QLo.t3fxb", "14")
;
(_ENV.RenderPreloadShader)("Mesh_VCOL_CC_TINT_QLo.t3fxb", "263")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_VCOL_CC_TINT_QLo.t3fxb", "7")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_CC_TINT_QLo.t3fxb", "263")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_DTL_VCOL_CC_TINT_QLo.t3fxb", "70")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_VCOL_CC_TINT_QLo.t3fxb", "70")
;
(_ENV.RenderPreloadShader)("Mesh_VCOL_CC_TINT_QLo.t3fxb", "70")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_CC_TINT_QLo.t3fxb", "6")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "262")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "258")
;
(_ENV.RenderPreloadShader)("Mesh_VCOL_CC_TINT_QLo.t3fxb", "326")
;
(_ENV.RenderPreloadShader)("Mesh_VCOL_CC_TINT_QLo.t3fxb", "322")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "2")
;
(_ENV.RenderPreloadShader)("Mesh_CC_TINT_QLo.t3fxb", "0")
;
(_ENV.RenderPreloadShader)("Mesh_DTL_CC_TINT_SDTL_QLo.t3fxb", "2")
;
(_ENV.RenderPreloadShader)("Mesh_LGT_VCOL_CC_TINT_QLo.t3fxb", "198")
;
(_ENV.RenderPreloadShader)("Mesh_VCOL_CC_TINT_QLo.t3fxb", "198")
;
(_ENV.RenderPreloadShader)("Mesh_DTL_CC_TINT_SDTL_QLo.t3fxb", "70")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_CC_TINT_QLo.t3fxb", "68")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_DTL_CC_TINT_SDTL_QLo.t3fxb", "70")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_TOON_CC_TINT_QLo.t3fxb", "70")
;
(_ENV.RenderPreloadShader)("SceneToonOutline2_1SKN_CC_TINT_QLo.t3fxb", "0")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_CC_TINT_QLo.t3fxb", "4")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_DTL_CC_TINT_SDTL_QLo.t3fxb", "6")
;
(_ENV.RenderPreloadShader)("Mesh_DTL_CC_TINT_SDTL_QLo.t3fxb", "6")
;
(_ENV.RenderPreloadShader)("Mesh_SCM_DTL_CC_TINT_QLo.t3fxb", "195")
;
(_ENV.RenderPreloadShader)("Mesh_SCM_DTL_VCOL_CC_TINT_QLo.t3fxb", "199")
;
(_ENV.RenderPreloadShader)("Mesh_1SKN_VCOL_CC_TINT_QLo.t3fxb", "199")
end
end
RiverWoods = function()
-- function num : 0_2 , upvalues : _ENV, kScene, kScript, PreloadAssets
Game_NewScene(kScene, kScript)
PreloadAssets()
if IsPlatformIOS() then
AgentHide("fx_rainSphereWDFar", true)
AgentSetProperty("cam_nav_secondDrag", "Pan Cam - Percentage Initial Horizontal", 0)
end
Navigate_Enable(false)
Game_StartScene(true)
end
RiverWoods_HideAllClemObjs = function()
-- function num : 0_3 , upvalues : _ENV, clemAttachedObjs
for key,value in pairs(clemAttachedObjs) do
AgentHide(value, true)
end
end
RiverWoods_MultiAgents_Init = function()
-- function num : 0_4 , upvalues : _ENV, multiAgents
local multiAgentKey, multiAgentValue = nil, nil
local actionTime = 0
for multiAgentKey,multiAgentValue in pairs(multiAgents) do
do
for key,value in pairs(multiAgentValue.agents) do
local agent = value
do
local MultiAgentsVisCheck = function(propKey, bVisible)
-- function num : 0_4_0 , upvalues : multiAgentValue, _ENV, multiAgents, multiAgentKey, agent
if bVisible then
if multiAgentValue.lastUpdateTime == GetTotalTime() then
return
end
for key,value in pairs((multiAgents[multiAgentKey]).agents) do
if value ~= agent then
AgentHide(value, true)
end
end
multiAgentValue.lastUpdateTime = GetTotalTime()
end
end
PropertyAddKeyCallback(AgentGetProperties(agent), "Runtime: Visible", MultiAgentsVisCheck)
end
end
end
end
end
RiverWoods_MultiAgents_Off = function()
-- function num : 0_5 , upvalues : _ENV, multiAgents
for multiAgentKey,multiAgentValue in pairs(multiAgents) do
for key,value in pairs(multiAgentValue.agents) do
PropertyClearKeyCallbacks(AgentGetProperties(value), "Runtime: Visible")
end
end
end
RiverWoods_ClemTreeStruggleWait = function()
-- function num : 0_6 , upvalues : _ENV, kClemTreeStruggleTime
local curTime = GetTotalTime()
local targetTime = curTime + kClemTreeStruggleTime
while GetTotalTime() < targetTime and not AgentGetProperty("struggle_tree", "Struggle - Complete") do
Yield()
end
end
RiverWoods_ClemInLog_WinstonAmbience = function(delay1, delay2)
-- function num : 0_7 , upvalues : _ENV
if not delay1 or type(delay1) ~= "number" then
delay1 = 0
end
Sleep(delay1)
if not LogicGet("1RiverWoods - Clem Hiding in Log") then
return
end
Dialog_Run(Game_GetSceneDialog(), "ambient_winstonAtLog", false)
if not delay2 or type(delay2) ~= "number" then
delay2 = 0
end
delay2 = delay2 - delay1
if delay2 < 0 then
delay2 = 0
end
Sleep(delay2)
if not LogicGet("1RiverWoods - Clem Hiding in Log") then
return
end
Dialog_Run(Game_GetSceneDialog(), "ambient_winstonAtLog", false)
end
RiverWoods_MakeAllObjsUnselectable = function()
-- function num : 0_8 , upvalues : _ENV, kScene
for key,value in pairs(SceneGetAgents(kScene)) do
if AgentHasProperty(value, "Game Selectable") then
AgentSetSelectable(value, false)
end
end
end
RiverWoods_PrintCurrentStartNode = function(bEnabled)
-- function num : 0_9 , upvalues : _ENV, StartNodeDebugPrint
if bEnabled then
Callback_DialogOnStartNodeBegin:Add(StartNodeDebugPrint)
else
Callback_DialogOnStartNodeBegin:Remove(StartNodeDebugPrint)
end
end
RiverWoods_RunBGdialog = function(dlgNode)
-- function num : 0_10 , upvalues : mBGdlgID, _ENV
if not dlgNode then
return
end
mBGdlgID = Game_RunSceneDialog(dlgNode, false)
print("Starting BG dialog! id is " .. tostring(mBGdlgID))
end
RiverWoods_KillBGdialog = function()
-- function num : 0_11 , upvalues : _ENV, mBGdlgID
if DlgIsRunning(mBGdlgID) then
print("Killing BG dialog!")
DlgStop(mBGdlgID)
end
end
RiverWoods_DoTreeStruggle = function()
-- function num : 0_12 , upvalues : _ENV
-- DECOMPILER ERROR at PC4: Confused about usage of register: R0 in 'UnsetPending'
((AgentFind("struggle_zombieYank")).mProps)["Button Mash - Rate of Increase"] = 4.5
Sleep(0.5)
local bAvoidDeath = false
local timeToFinish = GetTotalTime() + 1
while 1 do
while 1 do
if ((AgentFind("struggle_zombieYank")).mProps)["Chore Scrubber - Enabled"] then
Yield()
-- DECOMPILER ERROR at PC32: Confused about usage of register: R2 in 'UnsetPending'
if ((AgentFind("struggle_zombieYank")).mProps)["Button Mash - Current Percentage"] >= 0.8 then
((AgentFind("struggle_zombieYank")).mProps)["Button Mash - Current Percentage"] = 0.8
end
-- DECOMPILER ERROR at PC46: Confused about usage of register: R2 in 'UnsetPending'
if bAvoidDeath and ((AgentFind("struggle_zombieYank")).mProps)["Button Mash - Current Percentage"] < 0.1 then
((AgentFind("struggle_zombieYank")).mProps)["Button Mash - Current Percentage"] = 0.15
end
-- DECOMPILER ERROR at PC62: Confused about usage of register: R2 in 'UnsetPending'
if timeToFinish <= GetTotalTime() and ((AgentFind("struggle_zombieYank")).mProps)["Button Mash - Current Percentage"] > 0.15 then
((AgentFind("struggle_zombieYank")).mProps)["Button Mash - Rate of Increase"] = 0.3
bAvoidDeath = true
LogicSet("1RiverWoods - Tree Zombie Arm About to Rip Off", true)
-- DECOMPILER ERROR at PC68: LeaveBlock: unexpected jumping out IF_THEN_STMT
-- DECOMPILER ERROR at PC68: LeaveBlock: unexpected jumping out IF_STMT
-- DECOMPILER ERROR at PC68: LeaveBlock: unexpected jumping out IF_THEN_STMT
-- DECOMPILER ERROR at PC68: LeaveBlock: unexpected jumping out IF_STMT
end
end
end
if bAvoidDeath or not ((AgentFind("struggle_zombieYank")).mProps)["Struggle - Complete"] or ((AgentFind("struggle_zombieYank")).mProps)["Button Mash - Current Percentage"] == 0 then
Game_RunDialog("fail_treeZombie")
end
end
end
SceneOpen(kScene, kScript)
|
mosespa_conversationtemplate = ConvoTemplate:new {
initialScreen = "mosespa_initial",
templateType = "Lua",
luaClassHandler = "mosespa_racetrack_convo_handler",
screens = {}
}
mosespa_initial = ConvoScreen:new {
id = "mosespa_initial",
leftDialog = "@conversation/racing_mosespa:s_e0de16cc",
stopConversation = "false",
options = {
{"@conversation/racing_mosespa:s_dffdee4b","cs_jsPlumb_1_90"},
{"@conversation/racing_mosespa:s_1736e216","cs_jsPlumb_1_29"},
{"@conversation/racing_mosespa:s_838e4ffb","cs_jsPlumb_1_181"},
{"@conversation/racing_mosespa:s_2492930f","cs_jsPlumb_1_207"}
}
}
mosespa_conversationtemplate:addScreen(mosespa_initial);
cs_jsPlumb_1_29 = ConvoScreen:new {
id = "cs_jsPlumb_1_29",
leftDialog = "@conversation/racing_mosespa:s_cea50112",
stopConversation = "false",
options = {
{"@conversation/racing_mosespa:s_e460e3d3","cs_jsPlumb_1_233"},
{"@conversation/racing_mosespa:s_fbd55d9d",""}
}
}
mosespa_conversationtemplate:addScreen(cs_jsPlumb_1_29);
cs_jsPlumb_1_90 = ConvoScreen:new {
id = "cs_jsPlumb_1_90",
leftDialog = "@conversation/racing_mosespa:s_d24f3595",
stopConversation = "false",
options = {
{"@conversation/racing_mosespa:s_2528fad7","cs_jsPlumb_1_116"},
{"@conversation/racing_mosespa:s_262e8687","cs_jsPlumb_1_142"}
}
}
mosespa_conversationtemplate:addScreen(cs_jsPlumb_1_90);
cs_jsPlumb_1_116 = ConvoScreen:new {
id = "cs_jsPlumb_1_116",
leftDialog = "@conversation/racing_mosespa:s_b2acc217",
stopConversation = "true",
options = {
}
}
mosespa_conversationtemplate:addScreen(cs_jsPlumb_1_116);
cs_jsPlumb_1_142 = ConvoScreen:new {
id = "cs_jsPlumb_1_142",
leftDialog = "@conversation/racing_mosespa:s_c0918d6",
stopConversation = "true",
options = {
}
}
mosespa_conversationtemplate:addScreen(cs_jsPlumb_1_142);
cs_jsPlumb_1_181 = ConvoScreen:new {
id = "cs_jsPlumb_1_181",
leftDialog = "@conversation/racing_mosespa:s_abd9745d",
stopConversation = "true",
options = {
}
}
mosespa_conversationtemplate:addScreen(cs_jsPlumb_1_181);
cs_jsPlumb_1_207 = ConvoScreen:new {
id = "cs_jsPlumb_1_207",
leftDialog = "@conversation/racing_mosespa:s_abd9745d",
stopConversation = "true",
options = {
}
}
mosespa_conversationtemplate:addScreen(cs_jsPlumb_1_207);
cs_jsPlumb_1_233 = ConvoScreen:new {
id = "cs_jsPlumb_1_233",
leftDialog = "@conversation/racing_mosespa:s_4b4fb2b7",
stopConversation = "true",
options = {
}
}
mosespa_conversationtemplate:addScreen(cs_jsPlumb_1_233);
addConversationTemplate("mosespa_conversationtemplate", mosespa_conversationtemplate); |
local M = {}
function M.setup()
require("toggleterm").setup {
size = 20,
hide_numbers = true,
open_mapping = [[<C-\>]],
shade_filetypes = {},
shade_terminals = false,
shading_factor = 0.3,
start_in_insert = true,
persist_size = true,
direction = "horizontal",
}
end
return M
|
-- This file is subject to copyright - contact [email protected] for more information.
-- INSTALL: CINEMA
SS_Tab("Construction", "bricks")
SS_Heading("Tools")
local function CannotBuyTrash(self, ply)
if SERVER then return CannotMakeTrash(ply) end
end
SS_WeaponProduct({
class = "weapon_trash_paint",
name = 'Paint Tool',
description = "Paint a solid color onto props. Also changes the color of lights.",
model = 'models/props_junk/metal_paintcan001a.mdl',
price = 2000
})
SS_WeaponProduct({
class = "weapon_trash_tape",
price = 0,
name = 'Tape Tool',
description = "Use this to tape (freeze) and un-tape props.",
model = 'models/swamponions/ducktape.mdl'
})
SS_Product({
class = 'trash',
price = 0,
name = 'Trash',
description = "Spawn a random piece of junk for building stuff with",
model = 'models/props_junk/cardboard_box001b.mdl',
CannotBuy = CannotBuyTrash,
OnBuy = function(self, ply)
makeTrash(ply, trashlist[math.random(1, #trashlist)])
end
})
SS_Heading("Props")
SS_Product({
class = 'plate1',
price = 1000,
name = 'Small Plate',
description = "Easy but costs money",
model = 'models/props_phx/construct/metal_plate1.mdl',
CannotBuy = CannotBuyTrash,
OnBuy = function(self, ply)
makeTrash(ply, self.model)
end
})
SS_Product({
class = 'plate2',
price = 2000,
name = 'Medium Plate',
description = "Easy but costs money",
model = 'models/props_phx/construct/metal_plate1x2.mdl',
CannotBuy = CannotBuyTrash,
OnBuy = function(self, ply)
makeTrash(ply, self.model)
end
})
SS_Product({
class = 'plate3',
price = 5000,
name = 'Big Plate',
description = "Easy but costs money",
model = 'models/props_phx/construct/metal_plate2x2.mdl',
CannotBuy = CannotBuyTrash,
OnBuy = function(self, ply)
makeTrash(ply, self.model)
end
})
SS_Product({
class = 'plate4',
price = 2000,
name = 'Triangle',
description = "Easy but costs money",
model = 'models/props_phx/construct/metal_plate2x2_tri.mdl',
CannotBuy = CannotBuyTrash,
OnBuy = function(self, ply)
makeTrash(ply, self.model)
end
})
SS_Product({
class = 'trashfield',
price = 200,
name = 'Medium Protection Field',
description = "While taped, prevents other players from building in your space. Also makes blocks stronger in the mines.",
model = 'models/maxofs2d/hover_classic.mdl',
CannotBuy = CannotBuyTrash,
OnBuy = function(self, ply)
for k, v in pairs(ents.FindByClass("prop_trash_field")) do
if v:GetOwnerID() == ply:SteamID() then
v:Remove()
end
end
--Delay 1 tick
timer.Simple(0, function()
timer.Simple(0.001, function()
makeForcefield(ply, self.model)
end)
end)
end
})
SS_Product({
class = 'trashfieldlarge',
price = 3000,
name = 'Large Protection Field',
description = "While taped, prevents other players from building in your space. Also makes blocks stronger in the mines.",
model = 'models/dav0r/hoverball.mdl',
CannotBuy = CannotBuyTrash,
OnBuy = function(self, ply)
for k, v in pairs(ents.FindByClass("prop_trash_field")) do
if v:GetOwnerID() == ply:SteamID() then
v:Remove()
end
end
--Delay 1 tick
timer.Simple(0, function()
timer.Simple(0.001, function()
makeForcefield(ply, self.model)
end)
end)
end
})
SS_Product({
class = 'trashlight',
price = 1000,
name = 'Lights',
description = "Lights up while taped",
model = 'models/maxofs2d/light_tubular.mdl',
CannotBuy = CannotBuyTrash,
OnBuy = function(self, ply)
local nxt = {}
for k, v in pairs(trashlist) do
if PropTrashLightData[v] then
table.insert(nxt, v)
end
end
e = makeTrash(ply, nxt[math.random(1, #nxt)])
end
})
SS_Product({
class = 'trashseat',
price = 2000,
name = 'Chairs',
description = "Can be sat on",
model = 'models/props_c17/furniturechair001a.mdl',
CannotBuy = CannotBuyTrash,
OnBuy = function(self, ply)
local nxt = {}
for k, v in pairs(trashlist) do
if ChairOffsets[v] then
table.insert(nxt, v)
end
end
e = makeTrash(ply, nxt[math.random(1, #nxt)])
end
})
SS_Product({
class = 'trashtheater',
price = 8000,
name = 'Medium Theater Screen',
description = "Create your own private theater anywhere! You'll remain owner even if you walk away.",
model = 'models/props_phx/rt_screen.mdl',
CannotBuy = CannotBuyTrash,
OnBuy = function(self, ply)
for k, v in pairs(ents.FindByClass("prop_trash_theater")) do
if v:GetOwnerID() == ply:SteamID() then
v:Remove()
end
end
--Delay 1 tick
timer.Simple(0, function()
timer.Simple(0.001, function()
makeTrashTheater(ply, self.model)
end)
end)
end
})
SS_Product({
class = 'trashtheatertiny',
price = 4000,
name = "Tiny Theater Screen",
description = "Create your own private theater anywhere! You'll remain owner even if you walk away.",
model = "models/props_c17/tv_monitor01.mdl",
CannotBuy = CannotBuyTrash,
OnBuy = function(self, ply)
for k, v in pairs(ents.FindByClass("prop_trash_theater")) do
if v:GetOwnerID() == ply:SteamID() then
v:Remove()
end
end
--Delay 1 tick
timer.Simple(0, function()
timer.Simple(0.001, function()
makeTrashTheater(ply, self.model)
end)
end)
end
})
SS_Product({
class = 'trashtheaterbig',
price = 16000,
name = 'Large Theater Screen',
description = "Create your own private theater anywhere! You'll remain owner even if you walk away.",
model = "models/hunter/plates/plate1x2.mdl",
material = "tools/toolsblack",
CannotBuy = CannotBuyTrash,
OnBuy = function(self, ply)
for k, v in pairs(ents.FindByClass("prop_trash_theater")) do
if v:GetOwnerID() == ply:SteamID() then
v:Remove()
end
end
--Delay 1 tick
timer.Simple(0, function()
timer.Simple(0.001, function()
makeTrashTheater(ply, self.model)
end)
end)
end
})
-- TODO finish this, make env_projectedtexture when in the theater
-- SS_Product({
-- class = 'trashtheaterprojector',
-- price = 640,
-- name = 'Projector Theater',
-- description = "Create your own private theater anywhere! You'll remain owner even if you walk away.",
-- model = "models/dav0r/camera.mdl",
-- OnBuy = function(self, ply)
-- for k, v in pairs(ents.FindByClass("prop_trash_theater")) do
-- if v:GetOwnerID() == ply:SteamID() then
-- v:Remove()
-- end
-- end
-- --Delay 1 tick
-- timer.Simple(0, function()
-- timer.Simple(0.001, function()
-- if tryMakeTrash(ply) then
-- makeTrashTheater(ply, self.model)
-- else
-- ply:SS_GivePoints(self.price)
-- end
-- end)
-- end)
-- end
-- }) |
local function mangle(text)
return text:gsub('[\128-\255]', function(s)
local b = string.byte(s)
if b >= 128 and b <= 191 then
return '\194' .. s
else
return '\195' .. string.char(128 + b - 192)
end
end)
end
local pp = require 'pl.pretty'.write
local function zip(...)
local iters, consts, initials = {}, {}, {}
for i, iter_gen in ipairs({...}) do
local iter, const, var = table.unpack(iter_gen, 1, 3)
iters[i] = iter
consts[i] = const
initials[i] = var
end
local function next(consts, vars)
local reses, vars_res = {}, {}
for i, iter in ipairs(iters) do
local res = {iter(consts[i], vars[i])}
if res[1] == nil then
return
end
reses[i] = res
vars_res[i] = res[1]
end
return vars_res, table.unpack(reses, 1, #iters)
end
return next, consts, initials
end
local function test(before)
print '-- before:'
print(pp({string.byte(before, 1, #before)}))
local after = mangle(before)
print '-- after:'
print(pp({utf8.codepoint(after, 1, #after)}))
for _, b, a in zip({before:gmatch'.'}, {utf8.codes(after)}) do
if string.byte(b[1]) ~= a[2] then
print('expected: ' .. string.byte(b[1]) .. ', got: ' .. a[2])
end
end
end
for i = 128, 255 do
test(string.char(i))
end
|
--[[--
request.set_cache_time(
seconds -- duration in seconds
)
Sets the expiration timeout for static content.
--]]--
function request.set_cache_time(seconds)
request.configure(function()
request._cache_time = seconds
end)
end
|
local reset = function(self)
self._t0 = nil
self._t1 = nil
self._delta_t = nil
self._grep = false
end
local calculate_delta_t = function(self)
self._delta_t = (vci.me.Time - self._t0).Milliseconds * 0.001
end
local is_double_grip = function(self)
if not self:on_grip() then return false end
if self._t0 == nil or self._t1 == nil then return false end
self:calculate_delta_t()
if self._delta_t <= self._threshold then
self:reset()
return true
else
return false
end
end
local is_single_grip = function(self)
if not self:on_grip() then return false end
if self._t0 == nil then return false end
self:calculate_delta_t()
if self._delta_t > self._threshold then
self:reset()
return true
else
return false
end
end
local grip = function(self)
self._grep = true
if self._t0 == nil then self._t0 = vci.me.Time
elseif self._t0 ~= nil then self._t1 = vci.me.Time
end
end
local on_grip = function(self)
return self._grep
end
local set_threshold = function(self, num)
assert(type(num) == "number", "input is not number")
self._threshold = num
end
local functions = {
reset = reset,
is_single_grip = is_single_grip,
is_double_grip = is_double_grip,
set_threshold = set_threshold,
grip = grip,
on_grip = on_grip,
calculate_delta_t = calculate_delta_t,
}
local new = function(self)
local __member_params = {
_t0 = nil,
_t1 = nil,
_delta_t = nil,
_threshold = 0.5,
_grep = false
}
return setmetatable(__member_params, {__index = functions})
end
return {
new = new
} |
local t = Def.ActorFrame {
};
local PColor = {
P1 = "#00dcff",
P2 = "#ff00cf"
};
local xPosPlayer = {
P1 = -158,
P2 = -153
};
--lights
--ex wheel lights aren't necessary here and look weird
--score underlay
if GAMESTATE:GetCoinMode() == 'CoinMode_Home' and SCREENMAN:GetTopScreen() ~= "ScreenNetRoom" then
for _, pn in pairs(GAMESTATE:GetEnabledPlayers()) do
t[#t+1] = Def.ActorFrame {
LoadActor("frame ex")..{
OnCommand=cmd(queuecommand,"Set");
BeginCommand=function(self,param)
if not GAMESTATE:IsPlayerEnabled('PlayerNumber_P1') then
self:croptop(0.5)
elseif not GAMESTATE:IsPlayerEnabled('PlayerNumber_P2') then
self:cropbottom(0.5)
end
end;
CurrentSongChangedMessageCommand=cmd(playcommand,"Set");
CurrentCourseChangedMessageCommand=cmd(playcommand,"Set");
CurrentStepsP1ChangedMessageCommand=cmd(playcommand,"Set");
CurrentTrailP1ChangedMessageCommand=cmd(playcommand,"Set");
CurrentStepsP2ChangedMessageCommand=cmd(playcommand,"Set");
CurrentTrailP2ChangedMessageCommand=cmd(playcommand,"Set");
SetCommand= function(self)
local SongOrCourse, StepsOrTrail;
if GAMESTATE:IsCourseMode() then
SongOrCourse = GAMESTATE:GetCurrentCourse();
StepsOrTrail = GAMESTATE:GetCurrentTrail(pn);
else
SongOrCourse = GAMESTATE:GetCurrentSong();
StepsOrTrail = GAMESTATE:GetCurrentSteps(pn);
end;
if SongOrCourse and StepsOrTrail then
local st = StepsOrTrail:GetStepsType();
local diff = StepsOrTrail:GetDifficulty();
local courseType = GAMESTATE:IsCourseMode() and SongOrCourse:GetCourseType() or nil;
if PROFILEMAN:IsPersistentProfile(pn) then
--player
profile = PROFILEMAN:GetProfile(pn);
else
-- machine profile
profile = PROFILEMAN:GetMachineProfile();
end;
scorelist = profile:GetHighScoreList(SongOrCourse,StepsOrTrail);
assert(scorelist)
local scores = scorelist:GetHighScores();
if scores[1] then
topscore = scores[1]:GetScore()
else
topscore = 0;
end;
assert(topscore)
if topscore ~= 0 then
self:diffusealpha(1)
else
self:diffusealpha(0)
end
end;
end;
};
};
end;
end
--Scores
local yPosPlayer = {
P1 = -78,
P2 = 78
};
local xPosPlayerScore = {
P1 = 78,
P2 = -78
};
local ScoreHalign = {
P1 = 1,
P2 = 0
};
--Player Scores
for _, pn in pairs(GAMESTATE:GetEnabledPlayers()) do
t[#t+1] = Def.BitmapText{
Font="ScreenSelectMusic score",
CurrentSongChangedMessageCommand=cmd(playcommand,"Set");
CurrentCourseChangedMessageCommand=cmd(playcommand,"Set");
CurrentStepsP1ChangedMessageCommand=cmd(playcommand,"Set");
CurrentTrailP1ChangedMessageCommand=cmd(playcommand,"Set");
CurrentStepsP2ChangedMessageCommand=cmd(playcommand,"Set");
CurrentTrailP2ChangedMessageCommand=cmd(playcommand,"Set");
InitCommand=function(self)
local short = ToEnumShortString(pn)
self:x(xPosPlayerScore[short]):y(yPosPlayer[short]):halign(ScoreHalign[short])
:diffusealpha(0)
end;
OnCommand=cmd(queuecommand,"Set");
SetCommand= function(self)
local SongOrCourse, StepsOrTrail;
if GAMESTATE:IsCourseMode() then
SongOrCourse = GAMESTATE:GetCurrentCourse();
StepsOrTrail = GAMESTATE:GetCurrentTrail(pn);
else
SongOrCourse = GAMESTATE:GetCurrentSong();
StepsOrTrail = GAMESTATE:GetCurrentSteps(pn);
end;
if SongOrCourse and StepsOrTrail then
local st = StepsOrTrail:GetStepsType();
local diff = StepsOrTrail:GetDifficulty();
local courseType = GAMESTATE:IsCourseMode() and SongOrCourse:GetCourseType() or nil;
if PROFILEMAN:IsPersistentProfile(pn) then
--player
profile = PROFILEMAN:GetProfile(pn);
else
-- machine profile
profile = PROFILEMAN:GetMachineProfile();
end;
scorelist = profile:GetHighScoreList(SongOrCourse,StepsOrTrail);
assert(scorelist)
local scores = scorelist:GetHighScores();
if scores[1] then
topscore = scores[1]:GetScore()
else
topscore = 0;
end;
assert(topscore)
if topscore ~= 0 then
self:ClearAttributes():diffusealpha(1)
local attr = GetLeadingAttribute(topscore, 7, {0.5,0.5,0.5,1})
if attr then
self:AddAttribute(0, attr)
end
self:settext(string.format("%07d",tostring(math.floor(topscore))))
else
self:diffusealpha(0)
end
end;
end;
};
end;
return t;
|
-- Internal custom properties
local COMPONENT_ROOT = script:GetCustomProperty("ComponentRoot"):WaitForObject()
-- User exposed properties
local STAMINA_DURATION = COMPONENT_ROOT:GetCustomProperty("StaminaDuration")
local RECOVERY_COOLDOWN = COMPONENT_ROOT:GetCustomProperty("RecoveryCooldown")
local RECOVERY_SPEED = COMPONENT_ROOT:GetCustomProperty("RecoverySpeed")
local SHIFT_ABILITY = "ability_feet"
local CROUCH_ABILITY = "ability_extra_41";
local SLOW_WALK_ABILITY = "ability_extra_10";
local LOCAL_PLAYER = Game.GetLocalPlayer()
local currentStates = {
Crouched = false;
Running = false;
Slow = false;
}
local isSprinting, isCrouching, isSlowWalk, isAiming = false, false, false, false
local currentStamina = STAMINA_DURATION
local lastStaminaUsed = time()
local function InputBegan(playerObject, event)
if event == SHIFT_ABILITY then
isSprinting = true
elseif event == SLOW_WALK_ABILITY then
isSlowWalk = true;
end
end
local function InputEnded(playerObject, event)
if event == SHIFT_ABILITY then
isSprinting = false
elseif event == SLOW_WALK_ABILITY then
isSlowWalk = false
end
end
local function CanRun()
if currentStamina <= 0 then
return false
end
return true
end
function Tick(deltaTime)
isCrouching = LOCAL_PLAYER.isCrouching
local didChange = false
local newStates = {
Crouched = isCrouching;
Running = isSprinting;
Slow = isSlowWalk;
}
-- Check if the player can run
if newStates.Running then
if not CanRun() or isAiming then
isSprinting = false
newStates.Running = false
end
end
-- Update player stamina
if newStates.Running then
currentStamina = currentStamina - deltaTime
lastStaminaUsed = time()
else
if time() - lastStaminaUsed > RECOVERY_COOLDOWN then
if currentStamina >= STAMINA_DURATION then
currentStamina = STAMINA_DURATION
else
currentStamina = currentStamina + deltaTime * RECOVERY_SPEED
end
end
end
-- Set player current stamina percentage
LOCAL_PLAYER.clientUserData.stamina = currentStamina / STAMINA_DURATION
-- Checks change to send event
for state, oldValue in pairs(currentStates) do
if oldValue ~= newStates[state] then
didChange = true
break
end
end
currentStates = newStates
if didChange then
Events.BroadcastToServer("ChangeMovementType", currentStates)
Events.Broadcast("ChangeMovementType", currentStates)
end
end
local function UpdateAiming(player, aiming)
if player ~= LOCAL_PLAYER then return end
isAiming = aiming
end
local function Reset()
isSprinting, isCrouching, isSlowWalk, isAiming = false, false, false, false
currentStamina = STAMINA_DURATION
end
-- Initialize
LOCAL_PLAYER.bindingPressedEvent:Connect(InputBegan)
LOCAL_PLAYER.bindingReleasedEvent:Connect(InputEnded)
LOCAL_PLAYER.diedEvent:Connect(Reset)
Events.Connect("WeaponAiming", UpdateAiming) |
if string.compare_version(sys.xtversion(), "1.2-10") < 0 then
sys.alert("此示例内容仅支持 XXTouch v1.2-10 及以上版本")
return os.exit()
end
local defaultsKey = "com.yourcompany.A-Script-Bundle"
-- 获取 Button 组件 LaunchScript: 额外参数
local operation
local args = utils.launch_args()
if args ~= nil then
operation = args.envp['operation']
end
if operation == nil then
operation = 'demo'
end
if operation == 'demo' then
local tab = xui.read(defaultsKey)
sys.alert(json.encode(tab))
elseif operation == 'ntime' then
local ntstr
local nt = sys.net_time(5)
if nt == 0 then
sys.alert("获取网络时间失败")
return os.exit()
else
ntstr = os.date("%Y-%m-%d %H:%M:%S", nt)
end
xui.set(defaultsKey, "ntime", ntstr)
xui.reload({defaults = defaultsKey, {key = "ntime", value = ntstr}})
elseif operation == 'add-switch' then
local num = xui.get(defaultsKey, "ui-group-num") or 0
xui.set(defaultsKey, "ui-group-num", num + 1)
xui.reload()
elseif operation == 'rm-switch' then
local num = xui.get(defaultsKey, "ui-group-num") or 0
if num <= 0 then
sys.alert("已经不能减少了")
return os.exit()
end
xui.set(defaultsKey, "ui-group-num", num - 1)
xui.reload()
end
os.exit() |
fx_version 'adamant'
game 'gta5'
description 'Paradise Heists'
version '1.0.0'
-- server_scripts {
-- '@mysql-async/lib/MySQL.lua',
-- '@es_extended/locale.lua',
-- 'server/main.lua'
-- }
client_scripts {
'@es_extended/locale.lua',
'config.lua',
'client/client.lua',
'client/fleeca.lua',
'client/drilling.lua',
'client/hacking.lua',
'locales/cs.lua',
}
server_scripts {
'@es_extended/locale.lua',
'config.lua',
'server/server.lua',
'locales/cs.lua',
}
dependencies {
'es_extended',
} |
-- Decompiled using luadec 2.2 rev: for Lua 5.2 from https://github.com/viruscamp/luadec
-- Command line: A:\Steam\twd-definitive\scripteditor-10-31-20\definitive_lighting_improvements\WDC_pc_WalkingDead103_data\env_epilogue_temp.lua
-- params : ...
-- function num : 0 , upvalues : _ENV
require("Relighting.lua")
require("PropertyMenuTool.lua")
require("CustomSound.lua")
local kScript = "Epilogue"
local kScene = "adv_trainTileEpilogue"
ModifyScene = function(sceneObj)
local clemAgent = AgentFindInScene("Clementine", sceneObj)
local leeAgent = AgentFindInScene("Lee", sceneObj)
local sunColor = RGBColor(255, 180, 35, 255)
local ambientColor = RGBColor(72,178,255, 255)
local skyColor = RGBColor(24, 99, 205, 255)
--local fogColor = Desaturate_RGBColor(skyColor, 0.45)
skyColor = Desaturate_RGBColor(skyColor, 0.2)
ambientColor = Desaturate_RGBColor(ambientColor, 0.35)
sunColor = Desaturate_RGBColor(sunColor, 0.1)
sunColor = Multiplier_RGBColor(sunColor, 1.0)
Custom_AgentSetProperty("light_Directional", "EnvLight - Intensity", 8.0, sceneObj)
Custom_AgentSetProperty("light_Directional", "EnvLight - Intensity Specular", 1.0, sceneObj)
Custom_AgentSetProperty("light_Directional", "EnvLight - Enlighten Intensity", 5.0, sceneObj)
Custom_AgentSetProperty("light_Directional", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Amb", "EnvLight - Intensity", 0.025, sceneObj)
Custom_AgentSetProperty("light_Amb", "EnvLight - Intensity Specular", 1.0, sceneObj)
Custom_AgentSetProperty("light_Amb", "EnvLight - Color", ambientColor, sceneObj)
Custom_RemoveAgent("light_Amb_train", sceneObj)
--Custom_AgentSetProperty("light_Amb_train", "EnvLight - Intensity", 0.025, sceneObj)
--Custom_AgentSetProperty("light_Amb_train", "EnvLight - Intensity Specular", 1.0, sceneObj)
--Custom_AgentSetProperty("light_Amb_train", "EnvLight - Color", ambientColor, sceneObj)
Custom_AgentSetProperty("light_Amb_SKY", "EnvLight - Intensity", 0.5, sceneObj)
Custom_AgentSetProperty("light_Spot_ext", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Spot_ext06", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Spot_ext07", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Spot_ext13", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Spot_ext10", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Spot_ext17", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Spot_ext18", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Spot_ext02", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Spot_ext19", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Spot_ext20", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Spot_ext21", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Spot_ext22", "EnvLight - Color", sunColor, sceneObj)
Custom_AgentSetProperty("light_Spot_ext23", "EnvLight - Color", sunColor, sceneObj)
local spotlightIntensities = 1.0
Custom_AgentSetProperty("light_Spot_ext", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("light_Spot_ext06", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("light_Spot_ext07", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("light_Spot_ext13", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("light_Spot_ext10", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("light_Spot_ext17", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("light_Spot_ext18", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("light_Spot_ext02", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("light_Spot_ext19", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("light_Spot_ext20", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("light_Spot_ext21", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("light_Spot_ext22", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("light_Spot_ext23", "EnvLight - Intensity", spotlightIntensities, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX anti-aliasing", true, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Sharp Shadows Enabled", true, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "Generate NPR Lines", false, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "Screen Space Lines - Enabled", false, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Ambient Occlusion Enabled", true, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Tonemap Intensity", 1.0, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Tonemap White Point", 5.0, sceneObj)
--Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Tonemap Black Point", 0.001, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Tonemap Filmic Toe Intensity", 1.0, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Tonemap Filmic Shoulder Intensity", 1.5, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "HBAO Intensity", 2.5, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "HBAO Max Radius Percent", 0.75, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Bloom Threshold", -0.2, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Bloom Intensity", 0.5, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "Ambient Color", RGBColor(0, 0, 0, 0), sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "Shadow Color", RGBColor(0, 0, 0, 0), sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Vignette Tint Enabled", true, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Vignette Tint", RGBColor(0, 0, 0, 0), sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Vignette Falloff", 1.5, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Vignette Center", 0, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "FX Vignette Corners", 3.0, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "LightEnv Saturation", 1.5, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "LightEnv Reflection Intensity Shadow", 1.0, sceneObj)
Custom_AgentSetProperty("adv_trainTileEpilogue.scene", "Specular Multiplier Enabled", true, sceneObj)
--DevTools_AgentMenuTool_GetValidPropertyNames(sceneAgent)
--cine mode
SetPropertyOnAllCameras(sceneObj, "Field of View Scale", 1.4)
local sceneagent = AgentFindInScene("adv_trainTileEpilogue.scene", sceneObject)
local amount = 0.125
--Custom_AgentSetProperty("adv_drugstoreOffice.scene", "Viewport Scissor Left", amount, sceneObj)
--Custom_AgentSetProperty("adv_drugstoreOffice.scene", "Viewport Scissor Bottom", amount, sceneObj)
--Custom_AgentSetProperty("adv_drugstoreOffice.scene", "Frame Buffer Scale Override", true, sceneObj)
SetPropertyOnSpecificAgents(sceneObj, "ui_", "Render FX Color Enabled", false)
SetPropertyOnSpecificAgents(sceneObj, "ui_", "Render Depth Test", false)
SetPropertyOnSpecificAgents(sceneObj, "ui_", "Render Depth Write", false)
SetPropertyOnSpecificAgents(sceneObj, "ui_", "Render Color Write", false)
SetPropertyOnSpecificAgents(sceneObj, "ui_", "Render After Anti-Aliasing", true)
RemovingAllLightingRigs(sceneObj)
--ResourceSetEnable("ProjectSeason4")
ResourceSetEnable("WalkingDead403")
local clem400_prop = "sk63_clementineFlashback.prop"
local clem400_skl = "sk56_clementine.skl"
local clem400 = AgentCreate("sk63_clementineFlashback", clem400_prop, Vector(0,0,0), Vector(0,0,0), sceneObj, false, false)
local clem400_props = AgentGetRuntimeProperties(clem400)
local clem_props = AgentGetRuntimeProperties(clemAgent)
Custom_AgentSetProperty("sk63_clementineFlashback", "Mesh sk63_clementineFlashback_bodyLower - Visible", true, sceneObj)
Custom_AgentSetProperty("sk63_clementineFlashback", "Mesh sk63_clementineFlashback_bodyUpper - Visible", true, sceneObj)
Custom_AgentSetProperty("sk63_clementineFlashback", "Mesh sk63_clementineFlashback_eyesMouth - Visible", true, sceneObj)
Custom_AgentSetProperty("sk63_clementineFlashback", "Mesh sk63_clementineFlashback_hair - Visible", true, sceneObj)
Custom_AgentSetProperty("sk63_clementineFlashback", "Mesh sk63_clementineFlashback_hands - Visible", true, sceneObj)
Custom_AgentSetProperty("sk63_clementineFlashback", "Mesh sk63_clementineFlashback_head - Visible", true, sceneObj)
local clemMeshFrom400 = PropertyGet(clem400_props, "D3D Mesh")
local clemMeshListFrom400 = PropertyGet(clem400_props, "D3D Mesh List")
local clemSklFrom400 = PropertyGet(clem400_props, "Skeleton File")
local clemSklBodyFrom400 = PropertyGet(clem400_props, "Skeleton Body")
local clemSklFaceFrom400 = PropertyGet(clem400_props, "Skeleton Face")
Custom_AgentSetProperty("Clementine", "Mesh sk56_clementine - Visible", false, sceneObj)
Custom_AgentSetProperty("Clementine", "D3D Mesh List", clemMeshListFrom400, sceneObj)
Custom_AgentSetProperty("Clementine", "D3D Mesh", clemMeshFrom400, sceneObj)
Custom_AgentSetProperty("Clementine", "Skeleton File", clemSklFrom400, sceneObj)
Custom_AgentSetProperty("Clementine", "Skeleton Body", clemSklBodyFrom400, sceneObj)
Custom_AgentSetProperty("Clementine", "Skeleton Face", clemSklFaceFrom400, sceneObj)
Custom_AgentSetProperty("Clementine", "Render Share Skeleton With Agent", PropertyGet(clem400_props, "Render Share Skeleton With Agent"), sceneObj)
Custom_AgentSetProperty("Clementine", "Eye Look-At Position", PropertyGet(clem400_props, "Eye Look-At Position"), sceneObj)
--Custom_AgentSetProperty("Clementine", "Eye Look-At Child Properties", PropertyGet(clem400_props, "Eye Look-At Child Properties"), sceneObj)
--Custom_AgentSetProperty("Clementine", "Eye Look-At Properties", PropertyGet(clem400_props, "Eye Look-At Properties"), sceneObj)
--Custom_AgentSetProperty("Clementine", "Look-at Buffer Angle", PropertyGet(clem400_props, "Look-at Buffer Angle"), sceneObj)
--Custom_AgentSetProperty("Clementine", "Look-at Min Buffer Angle", PropertyGet(clem400_props, "Look-at Min Buffer Angle"), sceneObj)
--Custom_AgentSetProperty("Clementine", "Style Idle", PropertyGet(clem400_props, "Style Idle"), sceneObj)
--Custom_AgentSetProperty("Clementine", "Style Guide", PropertyGet(clem400_props, "Style Guide"), sceneObj)
--Custom_AgentSetProperty("Clementine", "Style Guide2", PropertyGet(clem400_props, "Style Guide2"), sceneObj)
--Custom_AgentSetProperty("Clementine", "Style Idle2", PropertyGet(clem400_props, "Style Idle2"), sceneObj)
Custom_AgentSetProperty("Clementine", "Look - Chore Head", PropertyGet(clem400_props, "Look - Chore Head"), sceneObj)
Custom_AgentSetProperty("Clementine", "Look - Chore Eyes", PropertyGet(clem400_props, "Look - Chore Eyes"), sceneObj)
Custom_AgentSetProperty("Clementine", "Look - Contribution Fade Speed", PropertyGet(clem400_props, "Look - Contribution Fade Speed"), sceneObj)
Custom_AgentSetProperty("Clementine", "Look - FOV Degrees", PropertyGet(clem400_props, "Look - FOV Degrees"), sceneObj)
Custom_AgentSetProperty("Clementine", "Eye Look-At Properties", PropertyGet(clem400_props, "Eye Look-At Properties"), sceneObj)
Custom_AgentSetProperty("Clementine", "Eye Look-At Properties", PropertyGet(clem400_props, "Eye Look-At Properties"), sceneObj)
Custom_AgentSetProperty("Clementine", "Look-at Buffer Angle", PropertyGet(clem400_props, "Look-at Buffer Angle"), sceneObj)
Custom_AgentSetProperty("Clementine", "Look-at Min Buffer Angle", PropertyGet(clem400_props, "Look-at Min Buffer Angle"), sceneObj)
Custom_AgentSetProperty("Clementine", "Render Global Scale", 1.05, sceneObj)
AgentHide(clem400, true)
--lee
local lee400_prop = "sk61_lee.prop"
local lee400 = AgentCreate("sk61_lee", lee400_prop, Vector(0,0,0), Vector(0,0,0), sceneObj, false, false)
local lee400_props = AgentGetRuntimeProperties(lee400)
local lee_props = AgentGetRuntimeProperties(leeAgent)
Custom_AgentSetProperty("Lee", "Mesh sk54_lee_armL - Visible", false, sceneObj)
Custom_AgentSetProperty("Lee", "Mesh sk54_lee_armR - Visible", false, sceneObj)
Custom_AgentSetProperty("Lee", "Mesh sk54_lee_body - Visible", true, sceneObj)
Custom_AgentSetProperty("Lee", "Mesh sk54_lee_bodyStomachGutted - Visible", false, sceneObj)
Custom_AgentSetProperty("Lee", "Mesh sk54_lee_head - Visible", false, sceneObj)
Custom_AgentSetProperty("Lee", "Mesh sk54_lee_legs - Visible", false, sceneObj)
Custom_AgentSetProperty("Lee", "Mesh sk54_leeJacket_armL - Visible", false, sceneObj)
Custom_AgentSetProperty("Lee", "Mesh sk54_leeJacket_armR - Visible", false, sceneObj)
Custom_AgentSetProperty("Lee", "Mesh sk54_leeJacket_body - Visible", false, sceneObj)
Custom_AgentSetProperty("Lee", "Mesh sk54_leeJacket_head - Visible", false, sceneObj)
Custom_AgentSetProperty("Lee", "Mesh sk54_leeJacket_legs - Visible", false, sceneObj)
Custom_AgentSetProperty("Lee", "D3D Mesh List", PropertyGet(lee400_props, "D3D Mesh List"), sceneObj)
Custom_AgentSetProperty("Lee", "D3D Mesh", PropertyGet(lee400_props, "D3D Mesh"), sceneObj)
Custom_AgentSetProperty("Lee", "Skeleton File", PropertyGet(lee400_props, "Skeleton File"), sceneObj)
Custom_AgentSetProperty("Lee", "Skeleton Body", PropertyGet(lee400_props, "Skeleton Body"), sceneObj)
Custom_AgentSetProperty("Lee", "Skeleton Face", PropertyGet(lee400_props, "Skeleton Face"), sceneObj)
Custom_AgentSetProperty("Lee", "Render Share Skeleton With Agent", PropertyGet(lee400_props, "Render Share Skeleton With Agent"), sceneObj)
--Custom_AgentSetProperty("Lee", "Eye Look-At Position", PropertyGet(lee400_props, "Eye Look-At Position"), sceneObj)
Custom_AgentSetProperty("Lee", "Eye Look-At Child Properties", PropertyGet(lee400_props, "Eye Look-At Child Properties"), sceneObj)
Custom_AgentSetProperty("Lee", "Eye Look-At Properties", PropertyGet(lee400_props, "Eye Look-At Properties"), sceneObj)
--Custom_AgentSetProperty("Lee", "Style Idle", PropertyGet(lee400_props, "Style Idle"), sceneObj)
--Custom_AgentSetProperty("Lee", "Style Guide", PropertyGet(lee400_props, "Style Guide"), sceneObj)
--Custom_AgentSetProperty("Lee", "Style Guide2", PropertyGet(lee400_props, "Style Guide2"), sceneObj)
--Custom_AgentSetProperty("Lee", "Style Idle2", PropertyGet(lee400_props, "Style Idle2"), sceneObj)
--Custom_AgentSetProperty("Lee", "Look - Enabled", PropertyGet(lee400_props, "Look - Enabled"), sceneObj)
Custom_AgentSetProperty("Lee", "Look - Chore Head", PropertyGet(lee400_props, "Look - Chore Head"), sceneObj)
Custom_AgentSetProperty("Lee", "Look - Chore Eyes", PropertyGet(lee400_props, "Look - Chore Eyes"), sceneObj)
Custom_AgentSetProperty("Lee", "Look - Contribution Fade Speed", PropertyGet(lee400_props, "Look - Contribution Fade Speed"), sceneObj)
Custom_AgentSetProperty("Lee", "Look - FOV Degrees", PropertyGet(lee400_props, "Look - FOV Degrees"), sceneObj)
Custom_AgentSetProperty("Lee", "Eye Look-At Properties", PropertyGet(lee400_props, "Eye Look-At Properties"), sceneObj)
Custom_AgentSetProperty("Lee", "Eye Look-At Properties", PropertyGet(lee400_props, "Eye Look-At Properties"), sceneObj)
Custom_AgentSetProperty("Lee", "Look-at Buffer Angle", PropertyGet(lee400_props, "Look-at Buffer Angle"), sceneObj)
Custom_AgentSetProperty("Lee", "Look-at Min Buffer Angle", PropertyGet(lee400_props, "Look-at Min Buffer Angle"), sceneObj)
--Custom_AgentSetProperty("Lee", "Render Global Scale", 0.95, sceneObj)
--SetPreference("Animated Lookats Active", true)
AgentHide(lee400, true)
end
Epilogue = function()
-- function num : 0_0 , upvalues : _ENV
ModifyScene(kScene)
--PrintSceneListToTXT(kScene, "env_trainEpilogue103.txt")
Mode(mode_Main)
if SaveLoad_IsFromLoad() then
return
end
Episode_SetFightTextures(false)
if AllowIntroCutscenes() then
if Platform_IsWiiU() then
print("Dialog Preloading start1: Epilogue")
DlgPreload("env_trainEpilogue.dlog", "cs_enter", 0, 15, 0, false)
end
Dialog_Play("cs_enter")
end
end
SceneOpen(kScene, kScript)
|
local HooI
return function(lib)
HooI = lib
local TooltipComponent = HooI.component.create("TooltipComponent")
function TooltipComponent:initialize(...)
HooI.initComponent(self, {
{name = "widget", varType = "Entity"},
}, ...)
self.init = false
end
return TooltipComponent
end
|
-- _.isBoolean.lua
--
-- Checks if value is classified as a boolean primitive.
-- @usage _.print(_.isBoolean(false))
-- --> true
-- _.print(_.isBoolean('x'))
-- --> false
--
-- @param value the value to check
-- @return Returns true if value is correctly classified, else false.
_.isBoolean = function(value)
return type(value) == 'boolean'
end
|
-- Стример местности
--<[ Модуль Terrain ]>
Terrain = {
init = function()
end;
}
addEventHandler( "onClientResourceStart", resourceRoot, Terrain.init ) |
function Rodotuk.main()
end
function Rodotuk.LaunchDamageSound(_ARG_0_)
end
|
-- contrib/btc_all.lua
-- Copyright (C) 2017 0x5b <[email protected]>
-- Copyright (C) 2017 Joerg Thalheim <[email protected]>
-- Copyright (C) 2019 Nguyễn Gia Phong <[email protected]>
--
-- This file is part of Vicious.
--
-- Vicious is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as
-- published by the Free Software Foundation, either version 2 of the
-- License, or (at your option) any later version.
--
-- Vicious is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Vicious. If not, see <https://www.gnu.org/licenses/>.
-- {{{ Grab environment
local pcall = pcall
local helpers = require("vicious.helpers")
local spawn = require("vicious.spawn")
local success, json = pcall(require, "cjson")
if not success then
json = require("json")
end
local string = {
sub = string.sub,
upper = string.upper,
}
-- }}}
-- Btc: provides current bitcoin price
-- vicious.widgets.btc
local btc_all = {}
-- {{ Bitcoin widget type
function btc_all.async(format, warg, callback)
-- Default values
if not warg then warg = "usd" end
local btc = { ["{price}"] = "N/A" }
local currency_code = string.upper(warg)
local url = "https://api.coindesk.com/v1/bpi/currentprice/" .. currency_code .. ".json"
local cmd = "curl "..helpers.shellquote(url)
-- {{ Checking response
local function parse(response)
-- If 'response' is not json, 'json.decode' will return Error
local status, data = pcall(function() return json.decode(response) end)
if not status or not data then
return btc
end
btc["{price}"] = string.sub(data["bpi"][currency_code]["rate"], 0, -3)
return btc
end
-- }}
spawn.easy_async(cmd, function(stdout) callback(parse(stdout)) end)
end
-- }}}
return helpers.setasyncall(btc_all)
|
local Roact = require(script.Parent.Packages.Roact)
return {
name = script.Parent.Name,
summary = "The one (and only) storybook for flipbook",
storyRoots = {
script.Parent.Components,
},
roact = Roact,
}
|
--
-- Utility functions for KaitaiStruct
--
local utils = {}
local function array_compare(arr, fn, subscript_fn)
if #arr == 0 then
return nil
end
local ret = subscript_fn(arr, 1)
for i = 2, #arr do
local el = subscript_fn(arr, i)
if fn(el, ret) then
ret = el
end
end
return ret
end
local function array_subscript(arr, i)
return arr[i]
end
local function bytes_subscript(str, i)
return string.byte(str, i)
end
function utils.array_min(arr)
return array_compare(arr, function(x, y) return x < y end, array_subscript)
end
function utils.array_max(arr)
return array_compare(arr, function(x, y) return x > y end, array_subscript)
end
function utils.byte_array_min(str)
return array_compare(str, function(x, y) return x < y end, bytes_subscript)
end
function utils.byte_array_max(str)
return array_compare(str, function(x, y) return x > y end, bytes_subscript)
end
-- http://lua-users.org/wiki/TernaryOperator (section Boxing/unboxing, using functions)
local False = {}
local Nil = {}
function utils.box_wrap(o)
return o == nil and Nil or o == false and False or o
end
function utils.box_unwrap(o)
if o == Nil then return nil
elseif o == False then return false
else return o end
end
return utils
|
local loaded = pcall(require, 'openssl')
if not loaded then return end
local _common_tls = require('tls/common')
local net = require('net')
local DEFAULT_CIPHERS = _common_tls.DEFAULT_CIPHERS
local extend = function(...)
local args = {...}
local obj = args[1]
for i = 2, #args do for k, v in pairs(args[i]) do obj[k] = v end end
return obj
end
local Server = net.Server:extend()
function Server:init(options, connectionListener)
options = options or {}
options.server = true
options.secureContext = options.secureContext or
_common_tls.createCredentials(options)
net.Server.init(self, options, function(raw_socket)
local socket
socket = _common_tls.TLSSocket:new(raw_socket, options)
socket:on('secureConnection', function()
connectionListener(socket)
end)
socket:on('error', function(err) connectionListener(socket, err) end)
self.socket = socket
if self.sni_hosts then socket:sni(self.sni_hosts) end
end)
end
function Server:sni(hosts) self.sni_hosts = hosts end
local DEFAULT_OPTIONS = {
ciphers = DEFAULT_CIPHERS,
rejectUnauthorized = true
-- TODO checkServerIdentity
}
local function connect(options, callback)
local hostname, port, sock, colon
callback = callback or function() end
options = extend({}, DEFAULT_OPTIONS, options or {})
options.server = false
port = options.port
hostname = options.host or options.hostname
colon = hostname:find(':')
if colon then hostname = hostname:sub(1, colon - 1) end
sock = _common_tls.TLSSocket:new(nil, options)
sock:connect(port, hostname, callback)
return sock
end
local function createServer(options, secureCallback)
local server = Server:new()
server:init(options, secureCallback)
return server
end
return {
DEFAULT_SECUREPROTOCOL = _common_tls.DEFAULT_SECUREPROTOCOL,
isLibreSSL = _common_tls.isLibreSSL,
isTLSv1_3 = _common_tls.isTLSv1_3,
TLSSocket = _common_tls.TLSSocket,
createCredentials = _common_tls.createCredentials,
connect = connect,
createServer = createServer
}
|
-----------------------------------
-- Area: Navukgo Execution Chamber
-- BCNM: TOAU-22 Shield of Diplomacy
-----------------------------------
require("scripts/globals/battlefield")
require("scripts/globals/missions")
local ID = require("scripts/zones/Navukgo_Execution_Chamber/IDs")
----------------------------------------
function onBattlefieldTick(battlefield, tick)
tpz.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldInitialise(battlefield)
local karababa = battlefield:insertEntity(2157, true, true)
karababa:setSpawn(360.937, -116.5, 376.937, 0)
karababa:spawn()
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == tpz.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
local arg8 = (player:hasCompletedMission(TOAU, tpz.mission.id.toau.SHIELD_OF_DIPLOMACY)) and 1 or 0
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), arg8)
elseif leavecode == tpz.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 and player:getCurrentMission(TOAU) == tpz.mission.id.toau.SHIELD_OF_DIPLOMACY then
player:completeMission(TOAU, tpz.mission.id.toau.SHIELD_OF_DIPLOMACY)
player:addMission(TOAU, tpz.mission.id.toau.SOCIAL_GRACES)
player:setCharVar("AhtUrganStatus", 0)
end
end
|
--[[
Addon: Lib
For: G-Core
By: SlownLS ( www.g-core.fr )
]]
local PANEL = {}
function PANEL:Init()
self.tblCheckBoxs = {}
self:SetVisible(false)
self:SetSize(0,0)
self.intCheckBoxSelected = 0
end
function PANEL:Select(id)
if !self.tblCheckBoxs[id] then return end
if !IsValid(self.tblCheckBoxs[id]) then return end
for k,v in pairs(self.tblCheckBoxs or {}) do
if !IsValid(v) then continue end
v:SetChecked(false)
if v.intCheckId == id then
v:SetChecked(true)
self.intCheckBoxSelected = id
end
end
return self
end
function PANEL:GetValueRadio()
local intSelected = self.intCheckBoxSelected
if !self.tblCheckBoxs[intSelected] then return "" end
if !IsValid(self.tblCheckBoxs[intSelected]) then return "" end
return self.tblCheckBoxs[intSelected].valRadio or ""
end
hook.Add("GCore:Lib:CanCreateVgui","GCore:Lib:DRadio",function()
vgui.Register("GCore:DRadio",PANEL,"DPanel")
end) |
--[[ Shattrath City -- Aldor Vindicator.lua
This script was written and is protected
by the GPL v2. This script was released
by BlackHer0 of the BLUA Scripting
Project. Please give proper accredidations
when re-releasing or sharing this script
with others in the emulation community.
~~End of License Agreement
-- BlackHer0, Oktober, 28th, 2008. ]]
function Vindicator_OnCombat(Unit, Event)
Unit:RegisterEvent("Vindicator_Banish", 7000, 0)
end
function Vindicator_Banish(Unit, Event)
Unit:FullCastSpellOnTarget(36642, Unit:GetMainTank())
end
function Vindicator_OnLeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function Vindicator_OnDied(Unit, Event)
Unit:RemoveEvents()
end
function Vindicator_OnKilledTarget(Unit, Event)
end
RegisterUnitEvent(18549, 1, "Vindicator_OnCombat")
RegisterUnitEvent(18549, 2, "Vindicator_OnLeaveCombat")
RegisterUnitEvent(18549, 3, "Vindicator_OnKilledTarget")
RegisterUnitEvent(18549, 4, "Vindicator_OnDied") |
-- ----------------------------------------------------------------------------
--
-- Mainframe
--
-- ----------------------------------------------------------------------------
local wx = require("wx") -- uses wxWidgets for Lua
local Timers = require("lib.ticktimer") -- timers
local trace = require("lib.trace") -- shortcut for tracing
local palette = require("lib.wxX11Palette") -- declarations for colors
local _frmt = string.format
local _sub = string.sub
local _gmatch = string.gmatch
local _min = math.min
local _max = math.max
local _abs = math.abs
-- ----------------------------------------------------------------------------
--
local m_thisApp = nil
-- ----------------------------------------------------------------------------
--
local m_logger = trace.new("debug")
-- ----------------------------------------------------------------------------
-- colors combinations
--
local m_tDefColours =
{
tSchemeDark =
{
cColBk0 = palette.WhiteSmoke,
cColFo0 = palette.DeepPink,
cColBk1 = palette.Gray20,
cColFo1 = palette.WhiteSmoke,
cColBk2 = palette.Gray10,
cColFo2 = palette.WhiteSmoke,
cColBk3 = palette.Gray20,
cColFo3 = palette.NavajoWhite1,
cFail = palette.VioletRed1,
cSucc = palette.SeaGreen3,
cLines = palette.Gray10,
CLblBk = palette.DarkSlateBlue,
CLblFo = palette.Honeydew2,
cHighlt = palette.DarkSlateGray2,
},
tSchemeContrast =
{
cColBk0 = palette.PaleGreen2,
cColFo0 = palette.RoyalBlue4,
cColBk1 = palette.LightBlue2,
cColFo1 = palette.Black,
cColBk2 = palette.LightBlue3,
cColFo2 = palette.Black,
cColBk3 = palette.SteelBlue4,
cColFo3 = palette.LightCyan1,
cFail = palette.MediumPurple2,
cSucc = palette.Yellow1,
cLines = palette.SteelBlue4,
CLblBk = palette.Gray20,
CLblFo = palette.LightSalmon3,
cHighlt = palette.MediumOrchid,
},
tSchemeIvory =
{
cColBk0 = palette.Orange,
cColFo0 = palette.White,
cColBk1 = palette.Ivory3,
cColFo1 = palette.Gray10,
cColBk2 = palette.Ivory2,
cColFo2 = palette.Gray10,
cColBk3 = palette.Ivory1,
cColFo3 = palette.Firebrick,
cFail = palette.Violet,
cSucc = palette.SkyBlue1,
cLines = palette.Gray50,
CLblBk = palette.Ivory4,
CLblFo = palette.Gray20,
cHighlt = palette.NavajoWhite3,
},
tSchemeMatte =
{
cColBk0 = palette.SlateGray2,
cColFo0 = palette.Firebrick,
cColBk1 = palette.MediumPurple1,
cColFo1 = palette.Black,
cColBk2 = palette.MediumPurple2,
cColFo2 = palette.Black,
cColBk3 = palette.WhiteSmoke,
cColFo3 = palette.Black,
cFail = palette.PaleVioletRed1,
cSucc = palette.MediumAquamarine,
cLines = palette.LightYellow3,
CLblBk = palette.Gray75,
CLblFo = palette.Gray25,
cHighlt = palette.Salmon1,
},
}
-- ----------------------------------------------------------------------------
-- grid's labels anf font
--
local m_sGdLbls =
{
"E.", "#1", "#2", "Organization"
}
-- ----------------------------------------------------------------------------
-- default dialog size and position
--
local m_tDefWinProp =
{
window_xy = {20, 20}, -- top, left
window_wh = {750, 265}, -- width, height
grid_ruler = {75, 200, 200, 500}, -- size of each column
use_font = {12, "Calibri"}, -- font for grid and tab
filter = "",
}
-- ----------------------------------------------------------------------------
--
local TaskOptions =
{
iTaskInterval = 65, -- timer interval
iBatchLimit = 9, -- max servers per taks
iSchedInterval = 5, -- scheduler timeout in secs
}
-- ----------------------------------------------------------------------------
-- contains various handlers and values
--
local m_Mainframe =
{
hWindow = nil, -- window handle
hNotebook = nil, -- notebook handle
hEditFind = nil,
hStatusBar = nil, -- statusbar handle
hGridDNSList = nil, -- grid
tColors = m_tDefColours.tSchemeIvory, -- colours for the grid
tWinProps = m_tDefWinProp, -- window layout settings
tStatus = {0, 0, 0, 0}, -- total, enabled, completed, failed
hTickTimer = nil, -- (Win) timer associated with window
bReentryLock = false, -- avoid re-entrant calling
tScheduler = Timers.new("Scheduler"), -- ticktimer for scheduler
iSearchStart = 1, -- current start for search
}
-- ----------------------------------------------------------------------------
-- create a filename just for the machine running on
--
local function SettingsName()
return "window@" .. wx.wxGetHostName() .. ".ini"
end
-- ----------------------------------------------------------------------------
-- read dialogs' settings from settings file
--
local function ReadSettings()
-- m_logger:line("ReadSettings")
local sFilename = SettingsName()
local fd = io.open(sFilename, "r")
if not fd then return end
fd:close()
local tSettings = dofile(sFilename)
if tSettings then m_Mainframe.tWinProps = tSettings end
end
-- ----------------------------------------------------------------------------
-- save a table to the settings file
--
local function SaveSettings()
-- m_logger:line("SaveSettings")
local fd = io.open(SettingsName(), "w")
if not fd then return end
fd:write("local window_ini =\n{\n")
local tWinProps = m_Mainframe.tWinProps
local sLine
sLine = _frmt("\twindow_xy\t= {%d, %d},\n", tWinProps.window_xy[1], tWinProps.window_xy[2])
fd:write(sLine)
sLine = _frmt("\twindow_wh\t= {%d, %d},\n", tWinProps.window_wh[1], tWinProps.window_wh[2])
fd:write(sLine)
sLine = _frmt("\tgrid_ruler\t= {%d, %d, %d, %d},\n",
tWinProps.grid_ruler[1], tWinProps.grid_ruler[2],
tWinProps.grid_ruler[3], tWinProps.grid_ruler[4])
fd:write(sLine)
sLine = _frmt("\tuse_font\t= {%d, \"%s\"},\n", tWinProps.use_font[1], tWinProps.use_font[2])
fd:write(sLine)
sLine = _frmt("\tfilter\t\t= \"%s\",\n", tWinProps.filter)
fd:write(sLine)
fd:write("}\n\nreturn window_ini\n")
io.close(fd)
end
-- ----------------------------------------------------------------------------
-- Generate a unique new wxWindowID
--
local ID_IDCOUNTER = wx.wxID_HIGHEST + 1
local NewMenuID = function()
ID_IDCOUNTER = ID_IDCOUNTER + 1
return ID_IDCOUNTER
end
-- ----------------------------------------------------------------------------
-- Simple interface to pop up a message
--
local function DlgMessage(message)
wx.wxMessageBox(message, m_thisApp.sAppName,
wx.wxOK + wx.wxICON_INFORMATION, m_Mainframe.hWindow)
end
-- ----------------------------------------------------------------------------
--
local function OnAbout()
DlgMessage(_frmt( "%s [%s] Rel. date [%s]\n %s, %s, %s",
m_thisApp.sAppName, m_thisApp.sAppVersion, m_thisApp.sRelDate,
_VERSION, wxlua.wxLUA_VERSION_STRING, wx.wxVERSION_STRING))
end
-- ----------------------------------------------------------------------------
--
local function SetStatusText(inText)
local hBar = m_Mainframe.hStatusBar
hBar:SetStatusText(inText, 1)
m_logger:line(inText)
end
-- ----------------------------------------------------------------------------
--
local m_SymbInd = 0
local m_tSymbols =
{
" |", " /", " -", " \\"
}
local function UpdateProgress()
local hBar = m_Mainframe.hStatusBar
m_SymbInd = m_SymbInd + 1
if #m_tSymbols < m_SymbInd then m_SymbInd = 1 end
hBar:SetStatusText(m_tSymbols[m_SymbInd], 0)
end
-- ----------------------------------------------------------------------------
--
local function UpdateStatus(inStatusTable)
local hBar = m_Mainframe.hStatusBar
local tStatus = m_Mainframe.tStatus
local bRefresh = false
-- check if refresh
--
for i=1, #tStatus do
if tStatus[i] ~= inStatusTable[i] then
bRefresh = true
break
end
end
if not bRefresh then return end
-- save values and update screen
-- total, enabled, completed, failed
--
for i=1, #tStatus do
tStatus[i] = inStatusTable[i]
hBar:SetStatusText(" " .. tostring(tStatus[i]), i + 1)
end
end
-- ----------------------------------------------------------------------------
--
local function BacktaskRunning()
-- m_logger:line("BacktaskRunning")
return nil ~= m_Mainframe.hTickTimer
end
-- ----------------------------------------------------------------------------
-- enable or disable the Windows timer object of the window
--
local function EnableBacktask(inEnable)
-- m_logger:line("EnableBacktask")
local hTick = m_Mainframe.hTickTimer
if inEnable then
if not hTick then
-- assign a timeout for the scheduler
--
m_Mainframe.tScheduler:setup(TaskOptions.iSchedInterval, true)
-- start a repeating Windows' timer
--
hTick = wx.wxTimer(m_Mainframe.hWindow, wx.wxID_ANY)
hTick:Start(TaskOptions.iTaskInterval, false)
SetStatusText("Backtask started")
end
else
if hTick then
m_Mainframe.tScheduler:enable(false)
hTick:Stop()
hTick = nil
SetStatusText("Backtask stopped")
end
end
-- store handle
--
m_Mainframe.hTickTimer = hTick
end
-- ----------------------------------------------------------------------------
-- read the settings file
--
local function ResetDescBkClr()
-- m_logger:line("ResetDescBkClr")
local hGrid = m_Mainframe.hGridDNSList
local iCount = hGrid:GetNumberRows()
local tDefault = m_Mainframe.tColors.cColBk3
if 0 == iCount then return end
for i=1, iCount do
hGrid:SetCellBackgroundColour(i - 1, 3, tDefault)
end
hGrid:ForceRefresh()
end
-- ----------------------------------------------------------------------------
-- read the settings file
--
local function ShowServers()
-- m_logger:line("ShowServers")
-- remove all rows
--
local hGrid = m_Mainframe.hGridDNSList
if 0 < hGrid:GetNumberRows() then
hGrid:DeleteRows(0, hGrid:GetNumberRows())
end
-- --------------------------------
-- fill the servers' grid
--
local tDNS = m_thisApp.tServers -- here we are sure the table is not empty
hGrid:AppendRows(#tDNS, false) -- create empty rows
local tCurrent
for iRow=0, #tDNS - 1 do
tCurrent = tDNS[iRow + 1]
hGrid:SetCellValue(iRow, 0, tostring(tCurrent.iEnabled)) -- active state
hGrid:SetCellValue(iRow, 1, tCurrent.tAddresses[1].sAddress) -- ip address
hGrid:SetCellValue(iRow, 2, tCurrent.tAddresses[2].sAddress) -- ip address
hGrid:SetCellValue(iRow, 3, tCurrent.sReference) -- url or name
end
UpdateStatus({#tDNS, 0, 0, 0})
end
-- ----------------------------------------------------------------------------
-- update the display
--
local function UpdateDisplay()
-- m_logger:line("UpdateDisplay")
local tDNS = m_thisApp.tServers -- here we are sure the table is not empty
local hGrid = m_Mainframe.hGridDNSList
local tColors = m_Mainframe.tColors
local tStatus = {#tDNS, 0, 0, 0} -- total, enabled, completed, failed
for i, tCurrent in next, tDNS do
if 1 == tCurrent.iEnabled then tStatus[2] = tStatus[2] + 1 end
if tCurrent:HasCompletedAll() then
for y=1, 2 do
if tCurrent:IsResponseOK(y) then
hGrid:SetCellBackgroundColour(i - 1, y, tColors.cSucc)
tStatus[3] = tStatus[3] + 1
else
-- extra check to avoid colouring a cell without address
--
if tCurrent:IsValid(y) then
hGrid:SetCellBackgroundColour(i - 1, y, tColors.cFail)
tStatus[4] = tStatus[4] + 1
end
end
end
end
end
UpdateStatus(tStatus)
end
-- ----------------------------------------------------------------------------
-- save the settings file
--
local function OnScramble()
-- m_logger:line("OnScramble")
m_thisApp.Scramble()
ShowServers()
UpdateDisplay()
-- text not found, wrap search
--
m_Mainframe.iSearchStart = 1
end
-- ----------------------------------------------------------------------------
-- save the settings file
--
local function OnSaveServers()
-- m_logger:line("OnSaveServers")
local ret = m_thisApp.SaveDNSFile()
if 0 == ret then DlgMessage("Failed to save DNS servers' list") return end
end
-- ----------------------------------------------------------------------------
-- read the servers' file
--
local function OnImportServers()
-- m_logger:line("OnImportServers")
-- read the settings file and create the clients
--
local ret = m_thisApp.ImportDNSFile()
if 0 == ret then DlgMessage("Failed to read DNS servers' list\nor the list is empty") return end
ShowServers()
UpdateDisplay()
end
-- ----------------------------------------------------------------------------
--
local function OnFilterByRef(event)
-- m_logger:line("OnSearchText")
local sText = m_Mainframe.hEditFind:GetValue()
if 0 == #sText then return end
if m_thisApp.FilterByRef(sText) then
ShowServers()
UpdateDisplay()
-- restart the search from the top
--
m_Mainframe.iSearchStart = 1
end
end
-- ----------------------------------------------------------------------------
--
local function OnSearchText(event)
-- m_logger:line("OnSearchText")
-- don't process further if not pressed the command key
--
if wx.WXK_RETURN ~= event:GetKeyCode() then
event:Skip()
return
end
local sText = m_Mainframe.hEditFind:GetValue()
local hGrid = m_Mainframe.hGridDNSList
local iStart = m_Mainframe.iSearchStart
local bkColor = m_Mainframe.tColors.cHighlt
-- at start cancel the old findings
--
if 1 == iStart then ResetDescBkClr() end
-- get the row containing the text
-- might start from 0 if first search
-- otherwise go ahead
--
local iMinIdx = nil
local tTokens = { }
-- collect all tokens
--
for sToken in _gmatch(sText, "[^;]*") do
if sToken and 0 < #sToken then tTokens[#tTokens + 1] = sToken end
end
-- parse the list for each token
-- and find the lowest index
--
for i, sToken in next, tTokens do
local iIndex = m_thisApp.IndexFromText(iStart, sToken)
if 0 < iIndex then
if not iMinIdx or iMinIdx > iIndex then
iMinIdx = iIndex
end
end
end
-- check the row
--
if iMinIdx then
hGrid:SetCellBackgroundColour(iMinIdx - 1, 3, bkColor)
-- if not hGrid:IsVisible(iMinIdx - 1, 3) then
hGrid:MakeCellVisible(iMinIdx - 1, 3)
-- end
hGrid:ForceRefresh()
-- advance for next search
--
m_Mainframe.iSearchStart = iMinIdx + 1
return
end
-- text not found, wrap search
--
m_Mainframe.iSearchStart = 1
DlgMessage("End of file.")
end
-- ----------------------------------------------------------------------------
-- set the enable flag for all DNS servers or a specific row
-- here the inRow ca have 2 values:
-- -1 means all rows
-- a zero based index (wxWidgets is zero based)
--
local function SetEnable(inRow, inEnabled)
-- m_logger:line("SetEnable")
local tServers = m_thisApp.tServers
if not next(tServers) then return end
local tRowsList = { }
if -1 == inRow then
-- all rows
--
for i=1, #tServers do tRowsList[i] = i end
else
-- selected row only
--
tRowsList[1] = inRow + 1
end
-- give a list of rows and get back a list of rows
--
tRowsList = m_thisApp.EnableServers(tRowsList, inEnabled)
local grid = m_Mainframe.hGridDNSList
for i=1, #tRowsList do
grid:SetCellValue(tRowsList[i] - 1, 0, tostring(inEnabled))
end
end
-- ----------------------------------------------------------------------------
-- toggle the enable/disable flag for the selected rows
--
local function OnToggleSelected()
-- m_logger:line("OnToggleSelected")
local grid = m_Mainframe.hGridDNSList
local tSelected = grid:GetSelectedRows():ToLuaTable()
local iValue
for i=1, #tSelected do
iValue = grid:GetCellValue(tSelected[i], 0)
SetEnable(tSelected[i], _abs(iValue - 1))
end
UpdateDisplay()
end
-- ----------------------------------------------------------------------------
-- toggle the enable/disable flag for the selected rows
--
local function OnToggleAll()
-- m_logger:line("OnToggleAll")
m_thisApp.ToggleAll()
ShowServers()
UpdateDisplay()
end
-- ----------------------------------------------------------------------------
-- call for the enable/disable all
--
local function OnEnableAll(inValue)
-- m_logger:line("OnEnableAll")
SetEnable(-1, inValue)
ShowServers()
UpdateDisplay()
end
-- ----------------------------------------------------------------------------
-- fuzzy enable servers
--
local function OnFuzzyEnable()
-- m_logger:line("OnFuzzyEnable")
m_thisApp.FuzzyEnable()
ShowServers()
UpdateDisplay()
end
-- ----------------------------------------------------------------------------
-- delete selected rows
--
local function OnDeleteSelected()
-- m_logger:line("OnDeleteSelected")
local grid = m_Mainframe.hGridDNSList
local tSelected = grid:GetSelectedRows():ToLuaTable()
if not next(tSelected) then DlgMessage("Select rows to delete") return end
-- from base 0 to base 1
--
for i=1, #tSelected do tSelected[i] = tSelected[i] + 1 end
-- remove
--
m_thisApp.DeleteServers(tSelected)
-- refresh view
--
ShowServers()
UpdateDisplay()
end
-- ----------------------------------------------------------------------------
-- reset the DNS client to the start
--
local function OnResetCompleted()
-- m_logger:line("OnResetCompleted")
local tServers = m_thisApp.tServers
local grid = m_Mainframe.hGridDNSList
local tColors = m_Mainframe.tColors
-- set each server to unchecked
--
for _, server in next, tServers do server:Restart() end
for i=1, #tServers do
grid:SetCellBackgroundColour(i - 1, 1, tColors.cColBk1)
grid:SetCellBackgroundColour(i - 1, 2, tColors.cColBk2)
end
UpdateDisplay()
grid:ForceRefresh() -- seldom there's no colour changing
end
-- ----------------------------------------------------------------------------
--
local function OnRandomHosts()
-- m_logger:line("OnRandomHosts")
m_thisApp.SetRandomHosts()
end
-- ----------------------------------------------------------------------------
-- reset the DNS client to the start
--
local function OnPurgeServers(inWhich)
-- m_logger:line("OnPurgeServers")
if m_thisApp.PurgeServers(inWhich) then
ShowServers()
UpdateDisplay()
end
end
-- ----------------------------------------------------------------------------
-- reset the DNS client to the start
--
local function OnPurgeInvalid(inWhich)
-- m_logger:line("OnPurgeInvalid")
if m_thisApp.PurgeInvalid() then
ShowServers()
UpdateDisplay()
end
end
-- ----------------------------------------------------------------------------
-- reset the DNS client to the start
--
local function OnPurgeFailing()
-- m_logger:line("OnPurgeFailing")
if m_thisApp.BasicFilter() then
ShowServers()
UpdateDisplay()
end
end
-- ----------------------------------------------------------------------------
-- tick timer backtask
--
local function OnScheduler()
-- m_logger:line("OnScheduler")
local tScheduler = m_Mainframe.tScheduler
if not tScheduler:hasFired() then return false end
cleanup = function()
-- correspond to menus:
OnPurgeServers(Purge.verified) -- purge responding
OnPurgeFailing() -- filter failing
OnRandomHosts() -- assign random hosts
OnResetCompleted() -- reset completed
end
-- perform a cleanup
--
cleanup()
local iTotal = m_Mainframe.tStatus[1]
local iEnabled = m_Mainframe.tStatus[2]
if 0 == iTotal then
OnImportServers()
cleanup()
end
if 35 > iEnabled then
OnPurgeInvalid()
iTotal = m_Mainframe.tStatus[1]
iEnabled = m_Mainframe.tStatus[2]
if iTotal ~= iEnabled then
if 15 > (iTotal - iEnabled) then
OnEnableAll(1)
else
OnFuzzyEnable()
end
end
end
tScheduler:reset()
return true
end
-- ----------------------------------------------------------------------------
-- windows timer backtask
-- uses a simple boolean to avoid re-entry calls
--
local function OnWindowsTimer()
-- check if it is still running
--
if m_Mainframe.bReentryLock then return end
m_Mainframe.bReentryLock = true
-- m_logger:line("OnWindowsTimer")
-- run the batch and get the count of touched items
--
local iBatch, iLast = m_thisApp.RunBatch(TaskOptions.iBatchLimit)
if 0 < iBatch and 0 < iLast then
UpdateDisplay()
local hGrid = m_Mainframe.hGridDNSList
if not hGrid:IsVisible(iLast - 1, 0) then
hGrid:MakeCellVisible(iLast - 1, 0)
end
hGrid:ForceRefresh() -- seldom there's no colour changing
m_Mainframe.tScheduler:reset() -- restart the timer
else
-- idling
--
OnScheduler()
end
UpdateProgress()
m_Mainframe.bReentryLock = false
end
-- ----------------------------------------------------------------------------
-- a cell was modified
--
local function OnCellChanged(event)
-- m_logger:line("OnCellChanged")
local hGrid = m_Mainframe.hGridDNSList
local iRow = event:GetRow()
local iCol = event:GetCol()
local aValue = hGrid:GetCellValue(iRow, iCol)
local tRow = m_thisApp.tServers[iRow + 1]
-- treat the enable disable
--
if 0 == iCol then
local iValue = tonumber(aValue) or 0
iValue = _min(1, _max(0, iValue))
tRow.iEnabled = iValue
hGrid:SetCellValue(iRow, iCol, tostring(iValue))
elseif 3 == iCol then
tRow.sReference = aValue
else
-- check for a valid ip4 address
--
local tAddress = tRow.tAddresses[iCol]
if not tAddress:ChangeAddress(aValue) then
tAddress:ChangeAddress("")
hGrid:SetCellValue(iRow, iCol, "")
end
end
end
-- ----------------------------------------------------------------------------
-- window size changed
--
local function OnLabelSelected(event)
-- m_logger:line("OnLabelSelected")
local iRow = event:GetRow()
local iCol = event:GetCol()
-- the Enabled column is excluded
--
if -1 == iRow and 0 < iCol and 4 > iCol then
m_thisApp.Sort(iCol + 1) -- grid index starts from 0
ShowServers()
UpdateDisplay()
else
-- chain default processing
--
event:Skip()
end
end
-- ----------------------------------------------------------------------------
-- window size changed
--
local function OnSize()
-- m_logger:line("OnSize")
if not m_Mainframe.hWindow then return end
local grid = m_Mainframe.hGridDNSList
local hEdit = m_Mainframe.hEditFind
local iHeight= hEdit:GetSize():GetHeight()
local iWidth = grid:GetColSize(3)
local iLeft = grid:GetRowLabelSize() + grid:GetColSize(0) + grid:GetColSize(1) + grid:GetColSize(2)
-- align the find text window to the company\s description
--
if 0 < iWidth then
hEdit:SetSize(iWidth, iHeight)
hEdit:Move(iLeft + 4, 2)
end
-- space available for the notebook
--
local size = m_Mainframe.hWindow:GetClientSize()
m_Mainframe.hNotebook:SetSize(size)
-- grids on notebook
--
local sizeBar = m_Mainframe.hStatusBar:GetSize()
size = m_Mainframe.hNotebook:GetClientSize()
size:SetWidth(size:GetWidth() - 6)
size:SetHeight(size:GetHeight() - sizeBar:GetHeight())
m_Mainframe.hGridDNSList:SetSize(size)
end
-- ----------------------------------------------------------------------------
-- called when closing the window
--
local function OnCloseMainframe()
-- m_logger:line("OnCloseMainframe")
if not m_Mainframe.hWindow then return end
-- stop the backtask timer
--
EnableBacktask(false)
wx.wxGetApp():Disconnect(wx.wxEVT_TIMER)
-- need to convert from size to pos
--
local pos = m_Mainframe.hWindow:GetPosition()
local size = m_Mainframe.hWindow:GetSize()
local tColWidths = { }
local grid = m_Mainframe.hGridDNSList
for i=1, 4 do
tColWidths[i] = grid:GetColSize(i - 1)
end
-- filter text
--
local sFilterText = m_Mainframe.hEditFind:GetValue()
-- update the current settings
--
local tWinProps = { }
tWinProps.window_xy = {pos:GetX(), pos:GetY()}
tWinProps.window_wh = {size:GetWidth(), size:GetHeight()}
tWinProps.grid_ruler= tColWidths
tWinProps.use_font = m_Mainframe.tWinProps.use_font -- just copy over
tWinProps.filter = sFilterText
m_Mainframe.tWinProps = tWinProps -- switch structures
SaveSettings() -- write to file
m_Mainframe.hWindow.Destroy(m_Mainframe.hWindow)
m_Mainframe.hWindow = nil
end
-- ----------------------------------------------------------------------------
-- apply styles to the grid's elements
--
local function SetGridStyles(inGrid)
-- m_logger:line("SetGridStyles")
local tWinProps = m_Mainframe.tWinProps
local tRulers = tWinProps.grid_ruler
local tColors = m_Mainframe.tColors
local iFontSize = tWinProps.use_font[1]
local sFontname = tWinProps.use_font[2]
local fntCell = wx.wxFont( iFontSize, wx.wxFONTFAMILY_MODERN, wx.wxFONTSTYLE_NORMAL,
wx.wxFONTWEIGHT_LIGHT, false, sFontname, wx.wxFONTENCODING_SYSTEM)
local fntCellBold = wx.wxFont( iFontSize - 1, wx.wxFONTFAMILY_MODERN, wx.wxFONTSTYLE_NORMAL,
wx.wxFONTWEIGHT_BOLD, false, sFontname, wx.wxFONTENCODING_SYSTEM)
local fntLbl = wx.wxFont( iFontSize - 2, wx.wxFONTFAMILY_MODERN, wx.wxFONTSTYLE_SLANT,
wx.wxFONTWEIGHT_LIGHT, false, sFontname, wx.wxFONTENCODING_SYSTEM)
local tAttrs = { }
tAttrs[1] = wx.wxGridCellAttr(tColors.cColFo0, tColors.cColBk0, fntCellBold, wx.wxALIGN_CENTRE, wx.wxALIGN_CENTRE)
tAttrs[2] = wx.wxGridCellAttr(tColors.cColFo1, tColors.cColBk1, fntCell, wx.wxALIGN_CENTRE, wx.wxALIGN_CENTRE)
tAttrs[3] = wx.wxGridCellAttr(tColors.cColFo2, tColors.cColBk2, fntCell, wx.wxALIGN_CENTRE, wx.wxALIGN_CENTRE)
tAttrs[4] = wx.wxGridCellAttr(tColors.cColFo3, tColors.cColBk3, fntCell, wx.wxALIGN_CENTRE, wx.wxALIGN_CENTRE)
inGrid:CreateGrid(50, #tRulers) -- some rows ad libitum
inGrid:DisableDragRowSize()
inGrid:DisableDragCell()
inGrid:SetSelectionMode(1) -- wx.wxGridSelectRows = 1
-- headers and rows
--
inGrid:SetLabelBackgroundColour(tColors.CLblBk)
inGrid:SetLabelTextColour(tColors.CLblFo)
inGrid:SetGridLineColour(tColors.cLines)
inGrid:SetLabelFont(fntLbl)
-- properties for columns
--
for i=1, #tRulers do
inGrid:SetColSize(i - 1, tRulers[i]) -- size
inGrid:SetColAttr(i - 1, tAttrs[i]) -- style
inGrid:SetColLabelValue(i - 1, m_sGdLbls[i]) -- labels
end
end
-- ----------------------------------------------------------------------------
-- load functions from the module functions.lua
-- re-create the menu entries
--
local rcMnuLoadFxs = NewMenuID()
local function OnLoadFunctions()
-- m_logger:line("OnLoadFunctions")
-- find the menu "Functions"
--
local menuBar = m_Mainframe.hWindow:GetMenuBar()
local menuLoad, menuFxs = menuBar:FindItem(rcMnuLoadFxs)
if not menuFxs then DlgMessage("Internal error!") return end
-- remove the menus except the very first
--
local iCount = menuFxs:GetMenuItemCount()
for i=1, iCount - 1 do
menuFxs:Remove(menuFxs:FindItemByPosition(1))
end
-- compile and import functions
--
local functions = dofile("user.lua")
-- create the menu entries
--
for i, item in next, functions do
local id = NewMenuID()
-- protected function to execute
--
MenuItemCmd = function()
-- interpreted code at run time
-- locals are out of scope here at run time
-- use full names to select objects
--
local bRet = pcall(item[1])
if not bRet then DlgMessage(item[2] .. " failed!") end
return bRet
end
if 0 < #item[2] then
menuFxs:Append(id, _frmt("%s\tCtrl-%d", item[2], i), item[3])
m_Mainframe.hWindow:Connect(id, wx.wxEVT_COMMAND_MENU_SELECTED, MenuItemCmd)
else
menuFxs:AppendSeparator()
end
end
end
-- ----------------------------------------------------------------------------
-- show the main window and runs the main loop
--
local function ShowMainWindow()
-- m_logger:line("ShowMainWindow")
if not m_Mainframe.hWindow then return end
m_Mainframe.hWindow:Show(true)
OnLoadFunctions()
OnImportServers()
-- run the main loop
--
wx.wxGetApp():MainLoop()
end
-- ----------------------------------------------------------------------------
--
local function CloseMainWindow()
-- m_logger:line("CloseMainWindow")
if m_Mainframe.hWindow then OnCloseMainframe() end
end
-- ----------------------------------------------------------------------------
-- called to create the main window
--
local function CreateMainWindow()
-- trace:line("CreateMainWindow")
m_thisApp = _G.m_ThisApp
-- read deafult positions for the dialogs
--
ReadSettings()
-- unique IDs for the menu
--
local rcMnuImportFile = NewMenuID()
local rcMnuSaveFile = NewMenuID()
local rcMnuScramble = NewMenuID()
local rcMnuFilterText = NewMenuID()
local rcMnuDisableAll = NewMenuID()
local rcMnuEnableAll = NewMenuID()
local rcMnuEnableFuz = NewMenuID()
local rcMnuToggleSel = NewMenuID()
local rcMnuToggleAll = NewMenuID()
local rcMnuPurge_VALID = NewMenuID()
local rcMnuPurge_OK = NewMenuID()
local rcMnuPurge_KO = NewMenuID()
local rcMnuPurge_DEL = NewMenuID()
local rcMnuPurge_FAIL = NewMenuID()
local rcMnuToggleBkTsk = NewMenuID()
local rcMnuResetCmpltd = NewMenuID()
local rcMnuRandomHosts = NewMenuID()
-- ------------------------------------------------------------------------
-- create a window
--
local tWinProps = m_Mainframe.tWinProps
local pos = tWinProps.window_xy
local size = tWinProps.window_wh
local iFontSize = tWinProps.use_font[1]
local sFontname = tWinProps.use_font[2]
local sTitle = m_thisApp.sAppName .. " [" .. m_thisApp.sAppVersion .. "]"
local frame = wx.wxFrame(wx.NULL, wx.wxID_ANY, sTitle,
wx.wxPoint(pos[1], pos[2]), wx.wxSize(size[1], size[2]))
frame:SetMinSize(wx.wxSize(300, 200))
-- ------------------------------------------------------------------------
-- create the menus
--
local mnuFile = wx.wxMenu("", wx.wxMENU_TEAROFF)
mnuFile:Append(rcMnuImportFile, "Import Servers\tCtrl-I", "Read the settings file")
mnuFile:Append(rcMnuSaveFile, "Save Servers\tCtrl-S", "Write the settings file")
mnuFile:AppendSeparator()
mnuFile:Append(rcMnuScramble, "Scramble list", "Scramble the current list")
mnuFile:Append(rcMnuFilterText, "Filter list", "Filter servers by text")
mnuFile:AppendSeparator()
mnuFile:Append(wx.wxID_EXIT, "E&xit\tAlt-X", "Quit the program")
local mnuEdit = wx.wxMenu("", wx.wxMENU_TEAROFF)
mnuEdit:Append(rcMnuDisableAll, "Disable all rows\tCtrl-D", "Each DNS entry will be disabled")
mnuEdit:Append(rcMnuEnableAll, "Enable all rows\tCtrl-E", "Each DNS entry will be anabled")
mnuEdit:Append(rcMnuEnableFuz, "Fuzzy enable\tCtrl-Q", "Enable servers at random")
mnuEdit:Append(rcMnuToggleSel, "Toggle selected rows\tCtrl-T", "Toggle enable/disable for selection")
mnuEdit:Append(rcMnuToggleAll, "Invert all\tCtrl-A", "Toggle enable/disable for all rows")
local mnuFilt = wx.wxMenu("", wx.wxMENU_TEAROFF)
mnuFilt:Append(rcMnuPurge_VALID,"Purge invalid\tCtrl-W", "Remove servers without address")
mnuFilt:Append(rcMnuPurge_OK, "Purge failed\tCtrl-X", "Remove not responding servers")
mnuFilt:Append(rcMnuPurge_KO, "Purge responding\tCtrl-Y", "Remove responding servers")
mnuFilt:AppendSeparator()
mnuFilt:Append(rcMnuPurge_DEL, "Delete selected\tCtrl-Z", "Build a new list without selected")
mnuFilt:AppendSeparator()
mnuFilt:Append(rcMnuPurge_FAIL, "Filter failing\tCtrl-Z", "Remove addresses in failing list")
local mnuCmds = wx.wxMenu("", wx.wxMENU_TEAROFF)
mnuCmds:Append(rcMnuToggleBkTsk,"Toggle backtask\tCtrl-B", "Start/Stop the backtask")
mnuCmds:Append(rcMnuResetCmpltd,"Reset completed\tCtrl-R", "Reset the completed flag")
mnuCmds:Append(rcMnuRandomHosts,"Assign random hosts\tCtrl-H", "Assign a new question to each server")
local mnuFunc = wx.wxMenu("", wx.wxMENU_TEAROFF)
mnuFunc:Append(rcMnuLoadFxs, "Reload functions\tCtrl-L", "Load functions.lua, create menu entries")
local mnuHelp = wx.wxMenu("", wx.wxMENU_TEAROFF)
mnuHelp:Append(wx.wxID_ABOUT, "&About", "About the application")
-- create the menu bar and associate sub-menus
--
local mnuBar = wx.wxMenuBar()
mnuBar:Append(mnuFile, "&File")
mnuBar:Append(mnuEdit, "&Enable")
mnuBar:Append(mnuFilt, "&Delete")
mnuBar:Append(mnuCmds, "&Commands")
mnuBar:Append(mnuFunc, "&Functions")
mnuBar:Append(mnuHelp, "&Help")
frame:SetMenuBar(mnuBar)
-- ------------------------------------------------------------------------
-- create the bottom status bar
-- (wxSB_SUNKEN 0x0003)
--
local stsBar = frame:CreateStatusBar(6, 0)
stsBar:SetFont(wx.wxFont(iFontSize - 2, wx.wxFONTFAMILY_DEFAULT, wx.wxFONTSTYLE_NORMAL, wx.wxFONTWEIGHT_NORMAL))
stsBar:SetStatusWidths({20, -1, 75, 50, 50, 50})
stsBar:SetStatusStyles({wx.wxSB_FLAT, 3, wx.wxSB_FLAT, wx.wxSB_FLAT, wx.wxSB_FLAT, wx.wxSB_FLAT})
stsBar:SetStatusText(m_thisApp.sAppName, 1)
frame:SetStatusBarPane(1) -- this is reserved for the menu
-- ------------------------------------------------------------------------
-- standard event handlers
--
frame:Connect(wx.wxEVT_CLOSE_WINDOW, CloseMainWindow)
frame:Connect(wx.wxEVT_SIZE, OnSize)
frame:Connect(wx.wxEVT_TIMER, OnWindowsTimer)
-- menu event handlers
--
frame:Connect(rcMnuImportFile, wx.wxEVT_COMMAND_MENU_SELECTED, OnImportServers)
frame:Connect(rcMnuSaveFile, wx.wxEVT_COMMAND_MENU_SELECTED, OnSaveServers)
frame:Connect(rcMnuScramble, wx.wxEVT_COMMAND_MENU_SELECTED, OnScramble)
frame:Connect(rcMnuFilterText, wx.wxEVT_COMMAND_MENU_SELECTED, OnFilterByRef)
frame:Connect(rcMnuDisableAll, wx.wxEVT_COMMAND_MENU_SELECTED, function() OnEnableAll(0) end)
frame:Connect(rcMnuEnableAll, wx.wxEVT_COMMAND_MENU_SELECTED, function() OnEnableAll(1) end)
frame:Connect(rcMnuEnableFuz, wx.wxEVT_COMMAND_MENU_SELECTED, OnFuzzyEnable)
frame:Connect(rcMnuToggleSel, wx.wxEVT_COMMAND_MENU_SELECTED, OnToggleSelected)
frame:Connect(rcMnuToggleAll, wx.wxEVT_COMMAND_MENU_SELECTED, OnToggleAll)
frame:Connect(rcMnuPurge_VALID, wx.wxEVT_COMMAND_MENU_SELECTED, OnPurgeInvalid)
frame:Connect(rcMnuPurge_OK, wx.wxEVT_COMMAND_MENU_SELECTED, function() OnPurgeServers(Purge.failed) end)
frame:Connect(rcMnuPurge_KO, wx.wxEVT_COMMAND_MENU_SELECTED, function() OnPurgeServers(Purge.verified) end)
frame:Connect(rcMnuPurge_DEL, wx.wxEVT_COMMAND_MENU_SELECTED, OnDeleteSelected)
frame:Connect(rcMnuPurge_FAIL, wx.wxEVT_COMMAND_MENU_SELECTED, OnPurgeFailing)
frame:Connect(rcMnuLoadFxs, wx.wxEVT_COMMAND_MENU_SELECTED, OnLoadFunctions)
frame:Connect(rcMnuToggleBkTsk, wx.wxEVT_COMMAND_MENU_SELECTED, function() EnableBacktask(not BacktaskRunning()) end)
frame:Connect(rcMnuResetCmpltd, wx.wxEVT_COMMAND_MENU_SELECTED, OnResetCompleted)
frame:Connect(rcMnuRandomHosts, wx.wxEVT_COMMAND_MENU_SELECTED, OnRandomHosts)
frame:Connect(wx.wxID_EXIT, wx.wxEVT_COMMAND_MENU_SELECTED, CloseMainWindow)
frame:Connect(wx.wxID_ABOUT, wx.wxEVT_COMMAND_MENU_SELECTED, OnAbout)
-- ------------------------------------------------------------------------
-- create a notebook style pane and apply styles
--
local notebook = wx.wxNotebook(frame, wx.wxID_ANY)
local fntNote = wx.wxFont( iFontSize, wx.wxFONTFAMILY_MODERN, wx.wxFONTSTYLE_NORMAL,
wx.wxFONTWEIGHT_BOLD, false, sFontname, wx.wxFONTENCODING_SYSTEM)
notebook:SetBackgroundColour(palette.Gray20)
notebook:SetFont(fntNote)
local newGrid = wx.wxGrid(notebook, wx.wxID_ANY, wx.wxDefaultPosition, notebook:GetSize())
notebook:AddPage(newGrid, "Servers List", true, 0)
SetGridStyles(newGrid)
frame:Connect(wx.wxEVT_GRID_CELL_CHANGED, OnCellChanged) -- validate input from user
frame:Connect(wx.wxEVT_GRID_LABEL_LEFT_CLICK, OnLabelSelected) -- apply sort
-- ------------------------------------------------------------------------
-- control for finding text
--
local fntFind = wx.wxFont( iFontSize, wx.wxFONTFAMILY_MODERN, wx.wxFONTSTYLE_NORMAL,
wx.wxFONTWEIGHT_BOLD, false, sFontname, wx.wxFONTENCODING_SYSTEM)
local iEdWidth = 500 -- width of the edit control
local iEdHeight = notebook:GetCharHeight() + 6
local editFind = wx.wxTextCtrl( notebook, wx.wxID_ANY, "", wx.wxDefaultPosition,
wx.wxSize(iEdWidth, iEdHeight), wx.wxTE_PROCESS_ENTER)
editFind:SetFont(wx.wxFont(fntFind))
editFind:Connect(wx.wxEVT_CHAR, OnSearchText)
-- assign the last text used in text box
--
editFind:WriteText(tWinProps.filter or "")
-- assign an icon
--
local icon = wx.wxIcon("lib/icons/pDNS.ico", wx.wxBITMAP_TYPE_ICO)
frame:SetIcon(icon)
-- store for later
--
m_Mainframe.hWindow = frame
m_Mainframe.hStatusBar = stsBar
m_Mainframe.hNotebook = notebook
m_Mainframe.hGridDNSList= newGrid
m_Mainframe.hEditFind = editFind
end
-- ----------------------------------------------------------------------------
-- associate functions
--
local function SetupPublic()
m_Mainframe.CreateMainWindow = CreateMainWindow
m_Mainframe.ShowMainWindow = ShowMainWindow
m_Mainframe.CloseMainWindow = CloseMainWindow
m_Mainframe.ShowServers = ShowServers
m_Mainframe.UpdateDisplay = UpdateDisplay
end
-- ----------------------------------------------------------------------------
--
SetupPublic()
return m_Mainframe
-- ----------------------------------------------------------------------------
-- ---------------------------------------------------------------------------- |
return {
corgant = {
acceleration = 0,
brakerate = 0,
buildcostenergy = 377452,
buildcostmetal = 17151,
builder = true,
buildinggrounddecaldecayspeed = 0.01,
buildinggrounddecalsizex = 10,
buildinggrounddecalsizey = 10,
buildinggrounddecaltype = "corgant_aoplane.dds",
buildpic = "corgant.dds",
buildtime = 250000,
canmove = true,
canpatrol = true,
canstop = 1,
category = "LEVEL2 ALL SURFACE",
collisionvolumeoffsets = "0 -5 8",
collisionvolumescales = "150 43 150",
collisionvolumetype = "CylY",
corpse = "dead",
description = "Produces Heavy T3 Units",
energystorage = 500,
energyuse = 0,
explodeas = "LARGE_BUILDINGEX",
firestandorders = 1,
footprintx = 9,
footprintz = 9,
icontype = "building",
idleautoheal = 5,
idletime = 1800,
losemitheight = 41,
mass = 18155,
maxdamage = 16055,
maxslope = 18,
maxvelocity = 0,
maxwaterdepth = 0,
metalstorage = 800,
mobilestandorders = 1,
name = "Experimental Gantry",
noautofire = false,
objectname = "CORGANT",
radardistance = 50,
radaremitheight = 41,
seismicsignature = 0,
selfdestructas = "LARGE_BUILDING",
shownanospray = false,
sightdistance = 273,
standingfireorder = 2,
standingmoveorder = 1,
turninplaceanglelimit = 140,
turninplacespeedlimit = 0,
turnrate = 0,
unitname = "corgant",
usebuildinggrounddecal = true,
usepiececollisionvolumes = true,
usepieceselectionvolumes = true,
workertime = 800,
yardmap = "oooooooooooooooooo occccccco occccccco occccccco occccccco occccccco occccccco occccccco",
buildoptions = {
[1] = "corpinchy",
[2] = "corshiva",
[3] = "corkarg",
[4] = "cortroman",
[5] = "corraven",
[6] = "coreak",
[7] = "corhowie",
--[8] = "macross",
[9] = "corkrog",
[10] = "corgorg",
},
customparams = {
buildpic = "corgant.dds",
faction = "CORE",
providetech = "T3 Factory",
},
featuredefs = {
dead = {
blocking = true,
collisionvolumeoffsets = "0 -21 0",
collisionvolumescales = "114 74 129",
collisionvolumetype = "CylZ",
damage = 9570,
description = "Experimental Gantry Wreckage",
energy = 0,
featuredead = "heap",
footprintx = 9,
footprintz = 9,
metal = 13599,
object = "CORGANT_DEAD",
reclaimable = true,
customparams = {
fromunit = 1,
},
},
heap = {
blocking = false,
damage = 11962,
description = "Experimental Gantry Debris",
energy = 0,
footprintx = 9,
footprintz = 9,
metal = 7253,
object = "7X7B",
reclaimable = true,
customparams = {
fromunit = 1,
},
},
},
nanocolor = {
[1] = 0.34,
[2] = 0.69,
[3] = 0.69,
},
sfxtypes = {
explosiongenerators = {
[1] = "custom:GantWhiteLight",
[2] = "custom:YellowLight",
[3] = "custom:WhiteLight",
},
pieceexplosiongenerators = {
[1] = "piecetrail0",
[2] = "piecetrail1",
[3] = "piecetrail2",
[4] = "piecetrail3",
[5] = "piecetrail4",
[6] = "piecetrail6",
},
},
sounds = {
activate = "gantok2",
build = "gantok2",
canceldestruct = "cancel2",
deactivate = "gantok2",
repair = "lathelrg",
underattack = "warning1",
unitcomplete = "gantok1",
working = "build",
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
select = {
[1] = "gantsel1",
},
},
},
}
|
local playsession = {
{"mewmew", {32297}},
{"Pandarnash", {35055}},
{"_Mash_", {34872}},
{"Akhrem", {34730}},
{"Revar", {34691}},
{"cogito123", {34443}},
{"loutanifi", {23078}},
{"BallisticGamer04", {2419}},
{"dpoba", {31720}},
{"lyman", {30804}},
{"Nukesman", {4121}},
{"Zory", {29966}},
{"Timfee", {29741}},
{"co2coffee", {6065}},
{"Whouser", {24213}},
{"cchpucky", {23900}},
{"Krezal", {19803}},
{"TheNetworkDoctor", {19320}},
{"GreySintax", {8330}},
{"xubos", {18747}},
{"RaGeProD", {1411}},
{"Higgel", {16263}},
{"bandis", {16047}},
{"shakaman", {3448}},
{"michaelsweetman", {10362}},
{"safriq", {6814}},
{"grilledham", {1503}}
}
return playsession |
-- Copyright (C) 2011 - 2013 David Reid. See included LICENCE file.
function GTGUI.Element:SceneEditorPropertiesPanel(sceneEditor)
self:EditorPanel();
self.Body.MessageContainer = GTGUI.Server.CreateElement(self.Body, "scene-editor-properties-panel-body-message");
self.Body.PanelsContainer = GTGUI.Server.CreateElement(self.Body, "scene-editor-properties-panel-panels-container");
self.Body.DetailsPanel = GTGUI.Server.CreateElement(self.Body.PanelsContainer, "panel-groupbox");
self.Body.DetailsPanel:SceneEditorDetailsPanel(self, sceneEditor);
self.Body.TransformPanel = GTGUI.Server.CreateElement(self.Body.PanelsContainer, "panel-groupbox");
self.Body.TransformPanel:SceneEditorTransformPanel(self, sceneEditor);
self.CurrentSceneNode = nil; -- The scene node whose details are currently being shown on this panel.
self.SceneEditor = sceneEditor;
-- This will create the panels for every registered component. We always want the editor metadata to be last.
self.ComponentPanels = {};
for key,value in pairs(GTEngine.Components) do
if value ~= GTEngine.Components.EditorMetadata and value ~= GTEngine.Components.Prefab then
local panel = Editor.SceneEditor.CreateComponentPanel(self, value);
if panel then
self.ComponentPanels[value] = panel;
-- We need to attach an event handler to each component panel for when it is closed. When closing a component panel, that component
-- will be removed from the scene node. Note that closing a panel is not the same as collapsing it.
panel:OnClose(function()
self.CurrentSceneNode:RemoveComponent(value);
self:UpdateComponentPanels();
self:OnSceneNodeChanged();
end);
end
end
end
self.ComponentPanels[GTEngine.Components.EditorMetadata] = Editor.SceneEditor.CreateComponentPanel(self, GTEngine.Components.EditorMetadata);
---------------------------------------------------
-- New Component Drop-Down Box.
self.NewComponentDropDownBox = GTGUI.Server.CreateElement(self.Body.PanelsContainer, "picking-dropdown-box");
self.NewComponentDropDownBox:PickingDropDownBox("New Component");
self.NewComponentDropDownBox:SetStyle("margin", "4px 8px");
self.NewComponentDropDownBox:AppendItem("Camera"):OnPressed(function()
local component = self.CurrentSceneNode:AddComponent(GTEngine.Components.Camera);
if component ~= nil then
component:Set3DProjection(90.0, 16.0 / 9.0, 0.1, 1000.0);
end
self:UpdateComponentPanels();
self:OnSceneNodeChanged();
end)
self.NewComponentDropDownBox:AppendItem("Model"):OnPressed(function()
local component = self.CurrentSceneNode:AddComponent(GTEngine.Components.Model);
if component ~= nil then
component:SetModel("engine/models/default.dae");
end
self:UpdateComponentPanels();
self:OnSceneNodeChanged();
end)
self.NewComponentDropDownBox:AppendItem("Point Light"):OnPressed(function()
self.CurrentSceneNode:AddComponent(GTEngine.Components.PointLight);
self:UpdateComponentPanels();
self:OnSceneNodeChanged();
end)
self.NewComponentDropDownBox:AppendItem("Spot Light"):OnPressed(function()
self.CurrentSceneNode:AddComponent(GTEngine.Components.SpotLight);
self:UpdateComponentPanels();
self:OnSceneNodeChanged();
end)
self.NewComponentDropDownBox:AppendItem("Directional Light"):OnPressed(function()
self.CurrentSceneNode:AddComponent(GTEngine.Components.DirectionalLight);
self:UpdateComponentPanels();
self:OnSceneNodeChanged();
end)
self.NewComponentDropDownBox:AppendItem("Ambient Light"):OnPressed(function()
local component = self.CurrentSceneNode:AddComponent(GTEngine.Components.AmbientLight);
if component ~= nil then
component:SetColour(0.25, 0.25, 0.25);
end
self:UpdateComponentPanels();
self:OnSceneNodeChanged();
end)
self.NewComponentDropDownBox:AppendItem("Dynamics (Collision and Physics)"):OnPressed(function()
self.CurrentSceneNode:AddComponent(GTEngine.Components.Dynamics);
self:UpdateComponentPanels();
self:OnSceneNodeChanged();
end)
self.NewComponentDropDownBox:AppendItem("Proximity"):OnPressed(function()
self.CurrentSceneNode:AddComponent(GTEngine.Components.Proximity);
self:UpdateComponentPanels();
self:OnSceneNodeChanged();
end)
self.NewComponentDropDownBox:AppendItem("Particle System"):OnPressed(function()
self.CurrentSceneNode:AddComponent(GTEngine.Components.ParticleSystem);
self:UpdateComponentPanels();
self:OnSceneNodeChanged();
end)
self.NewComponentDropDownBox:AppendItem("Script"):OnPressed(function()
self.CurrentSceneNode:AddComponent(GTEngine.Components.Script);
self:UpdateComponentPanels();
self:OnSceneNodeChanged();
end)
-- Clears the panels and shows a message.
function self:HidePanels(message)
self.Body.PanelsContainer:Hide();
self.Body.MessageContainer:Show();
self.Body.MessageContainer:SetText(message);
end
-- Shows the panels, but does not update them.
--
-- This will also update the details of the panels.
function self:ShowPanels()
self.Body.MessageContainer:Hide();
self.Body.PanelsContainer:Show();
end
-- Updates the details panel.
function self:UpdateDetailsPanel()
if self.CurrentSceneNode ~= nil then
self.Body.DetailsPanel:Update(self.CurrentSceneNode);
end
end
-- Updates the transform panel to show the transformation of the current node.
function self:UpdateTransformPanel()
if self.CurrentSceneNode ~= nil then
self.Body.TransformPanel:Update(self.CurrentSceneNode);
end
end
-- Updates the component panels.
function self:UpdateComponentPanels()
-- We need to determine which panels need to be shown and which need to be hidden. We'll hide and then show.
local componentIDs = {};
if self.CurrentSceneNode ~= nil then
componentIDs = self.CurrentSceneNode:GetAttachedComponentIDs();
end
-- We need to hide every panel that is not contained in componentIDs.
for componentID,componentPanel in pairs(self.ComponentPanels) do
if GT.table.indexof(componentIDs, componentID) == nil then
componentPanel:Hide();
end
end
-- Now we need to show and update every panel that is contained in componentIDs.
for i,componentID in ipairs(componentIDs) do
local panel = self.ComponentPanels[componentID];
if panel then
panel:Show();
panel:Update(self.CurrentSceneNode);
end
end
end
-- Updates the properties in the script panel.
function self:UpdateScriptProperties()
local scriptPanel = self.ComponentPanels[GTEngine.Components.Script];
if scriptPanel ~= nil then
scriptPanel:UpdateVariables();
end
end
-- Hides every component panel.
function self:HideAllComponentPanels()
for key,value in pairs(self.ComponentPanels) do
value:Hide();
end
end
-- Shows the relevant component panels for the current node.
function self:ShowComponentPanels()
if self.CurrentSceneNode ~= nil then
local componentIDs = self.CurrentSceneNode:GetAttachedComponentIDs();
for i,value in ipairs(componentIDs) do
local panel = self.ComponentPanels[value];
if panel then
panel:Show();
panel:Update(self.CurrentSceneNode);
end
end
end
end
-- Updates the panel to show the details of the given scene node.\
--
-- This does not actually show the panels.
function self:Update(node)
self.CurrentSceneNode = node;
if self.CurrentSceneNode ~= nil then
self:UpdateDetailsPanel();
self:UpdateTransformPanel();
self:UpdateComponentPanels();
end
end
function self:OnSceneNodeChanged(arg1)
self.Callbacks:BindOrCall("OnSceneNodeChanged", arg1);
end
return self;
end
function GTGUI.Element:SceneEditorSceneDetailsPropertiesPanel(sceneEditor)
self:PanelGroupBox("Details");
self.NameTextBox = GTGUI.Server.CreateElement(self.Body, "labelled-textbox");
self.NameTextBox:LabelledTextBox("Name", "");
self.NameTextBox:OnTextChanged(function()
sceneEditor:SetSceneName(self.NameTextBox:GetText());
end);
function self:Refresh()
self.NameTextBox:SetText(sceneEditor:GetSceneName());
end
return self;
end
function GTGUI.Element:SceneEditorSceneRenderingPropertiesPanel(sceneEditor)
self:PanelGroupBox("Rendering");
-- Clear Background
self.ClearBackgroundCheckBox = GTGUI.Server.CreateElement(self.Body, "checkbox");
self.ClearBackgroundCheckBox:CheckBox("Clear Background");
self.ClearBackgroundCheckBox:Check();
self.ClearBackgroundColour = GTGUI.Server.CreateElement(self.Body, "vector3-input");
self.ClearBackgroundColour:Vector3Input();
self.ClearBackgroundColour:SetValue(0.5);
self.ClearBackgroundColour:SetStyle("margin-top", "2px");
self.ClearBackgroundCheckBox:OnChecked(function()
self.ClearBackgroundColour:Enable();
sceneEditor:EnableSceneBackgroundClearing(self.ClearBackgroundColour:GetValue());
end);
self.ClearBackgroundCheckBox:OnUnchecked(function()
self.ClearBackgroundColour:Disable();
sceneEditor:DisableSceneBackgroundClearing();
end);
self.ClearBackgroundColour:OnValueChanged(function()
sceneEditor:EnableSceneBackgroundClearing(self.ClearBackgroundColour:GetValue());
end);
-- HDR
self.EnableHDRCheckBox = GTGUI.Server.CreateElement(self.Body, "checkbox");
self.EnableHDRCheckBox:CheckBox("Enable HDR");
self.EnableHDRCheckBox:Uncheck();
self.EnableHDRCheckBox:SetStyle("margin-top", "8px");
self.EnableHDRCheckBox:OnChecked(function()
sceneEditor:EnableSceneHDR();
end);
self.EnableHDRCheckBox:OnUnchecked(function()
sceneEditor:DisableSceneHDR();
end);
-- Bloom
self.EnableBloomCheckBox = GTGUI.Server.CreateElement(self.Body, "checkbox");
self.EnableBloomCheckBox:CheckBox("Enable Bloom");
self.EnableBloomCheckBox:Uncheck();
self.EnableBloomCheckBox:SetStyle("margin-top", "8px");
self.EnableBloomCheckBox:OnChecked(function()
sceneEditor:EnableSceneBloom();
end);
self.EnableBloomCheckBox:OnUnchecked(function()
sceneEditor:DisableSceneBloom();
end);
function self:Refresh()
if sceneEditor:IsSceneBackgroundClearingEnabled() then
self.ClearBackgroundCheckBox:Check(true); -- 'true' means to block posting the event.
self.ClearBackgroundColour:Enable();
else
self.ClearBackgroundCheckBox:Uncheck(false); -- 'true' means to block posting the event.
self.ClearBackgroundColour:Disable();
end
self.ClearBackgroundColour:SetValue(sceneEditor:GetSceneBackgroundClearColour());
if sceneEditor:IsSceneHDREnabled() then
self.EnableHDRCheckBox:Check(true); -- 'true' means to block posting the event.
else
self.EnableHDRCheckBox:Uncheck(true); -- 'true' means to block posting the event.
end
if sceneEditor:IsSceneBloomEnabled() then
self.EnableBloomCheckBox:Check(true); -- 'true' means to block posting the event.
else
self.EnableBloomCheckBox:Uncheck(true); -- 'true' means to block posting the event.
end
end
return self;
end
function GTGUI.Element:SceneEditorSceneNavigationPropertiesPanel(sceneEditor)
self:PanelGroupBox("Navigation");
self.ShowInViewport = GTGUI.Server.CreateElement(self.Body, "checkbox");
self.ShowInViewport:CheckBox("Show in Viewport");
self.ShowInViewport:SetStyle("margin-bottom", "4px");
self.WalkableHeight = GTGUI.Server.CreateElement(self.Body, "labelled-number-input");
self.WalkableHeight:LabelledNumberInput("Walkable Height");
self.WalkableRadius = GTGUI.Server.CreateElement(self.Body, "labelled-number-input");
self.WalkableRadius:LabelledNumberInput("Walkable Radius");
self.WalkableSlopeAngle = GTGUI.Server.CreateElement(self.Body, "labelled-number-input");
self.WalkableSlopeAngle:LabelledNumberInput("Walkable Slope Angle");
self.WalkableClimbHeight = GTGUI.Server.CreateElement(self.Body, "labelled-number-input");
self.WalkableClimbHeight:LabelledNumberInput("Walkable Climb Height");
self.BuildButtonContainer = GTGUI.Server.CreateElement(self.Body, "");
self.BuildButtonContainer:SetStyle("horizontal-align", "center");
self.BuildButton = GTGUI.Server.CreateElement(self.BuildButtonContainer, "button");
self.BuildButton:Button("Build");
self.BuildButton:SetStyle("margin-top", "8px");
self.BuildButton:SetStyle("padding", "32px 4px");
self.BuildButton:OnPressed(function()
sceneEditor:BuildNavigationMesh(0);
-- If the "Show in Viewport" checkbox is checked, we want to show it after building. It looks strange, but hiding before showing will ensure
-- that the visualization is refreshed and up-to-date.
if self.ShowInViewport:IsChecked() then
sceneEditor:HideNavigationMesh(0);
sceneEditor:ShowNavigationMesh(0);
end
end)
self.ShowInViewport:OnChecked(function()
sceneEditor:ShowNavigationMesh(0); -- '0' is the navigation mesh index. Always 0 for now, but will change later on when we add support for multiple navigation meshes.
end)
self.ShowInViewport:OnUnchecked(function()
sceneEditor:HideNavigationMesh(0); -- '0' has the same meaning as above.
end)
self.WalkableHeight:OnValueChanged(function()
sceneEditor:SetSceneWalkableHeight(self.WalkableHeight:GetValue());
sceneEditor:SetSceneWalkableRadius(self.WalkableRadius:GetValue());
sceneEditor:SetSceneWalkableSlopeAngle(self.WalkableSlopeAngle:GetValue());
sceneEditor:SetSceneWalkableClimbHeight(self.WalkableClimbHeight:GetValue());
end);
function self:Refresh()
self.WalkableHeight:SetValue(sceneEditor:GetSceneWalkableHeight());
self.WalkableRadius:SetValue(sceneEditor:GetSceneWalkableRadius());
self.WalkableSlopeAngle:SetValue(sceneEditor:GetSceneWalkableSlopeAngle());
self.WalkableClimbHeight:SetValue(sceneEditor:GetSceneWalkableClimbHeight());
end
return self;
end
function GTGUI.Element:SceneEditorScenePropertiesPanel(sceneEditor)
self:EditorPanel();
self.SceneEditor = sceneEditor;
self.PanelsContainer = GTGUI.Server.CreateElement(self.Body);
self.DetailsPanel = GTGUI.Server.CreateElement(self.PanelsContainer, "panel-groupbox");
self.DetailsPanel:SceneEditorSceneDetailsPropertiesPanel(sceneEditor);
self.RenderingPanel = GTGUI.Server.CreateElement(self.PanelsContainer, "panel-groupbox");
self.RenderingPanel:SceneEditorSceneRenderingPropertiesPanel(sceneEditor);
self.NavigationPanel = GTGUI.Server.CreateElement(self.PanelsContainer, "panel-groupbox");
self.NavigationPanel:SceneEditorSceneNavigationPropertiesPanel(sceneEditor);
function self:Refresh()
self.DetailsPanel:Refresh();
self.RenderingPanel:Refresh();
self.NavigationPanel:Refresh();
end
return self;
end
function GTGUI.Element:SceneEditorPanel(sceneEditor)
self.TabBar = GTGUI.Server.CreateElement(self, "scene-editor-panel-tabbar");
self.Body = GTGUI.Server.CreateElement(self, "scene-editor-panel-body");
self.PropertiesPanel = GTGUI.Server.CreateElement(self.Body, "scene-editor-properties-panel");
self.HierarchyPanel = GTGUI.Server.CreateElement(self.Body, "scene-editor-hierarchy-panel");
self.ScenePropertiesPanel = GTGUI.Server.CreateElement(self.Body, "scene-editor-properties-panel");
self.SceneEditor = sceneEditor;
self.TabBar:TabBar();
self.TabBar.ActiveTabBorderColor = "#222";
self.TabBar.HoveredTabBorderColor = "#222";
self.TabBar.ActiveTabBackgroundColor = "#363636";
self.ScenePropertiesTab = self.TabBar:AddTab("Scene Properties");
self.HierarchyTab = self.TabBar:AddTab("Hierarchy");
self.PropertiesTab = self.TabBar:AddTab("Properties");
self.TabBar:OnTabActivated(function(data)
if data.tab == self.PropertiesTab then
self.PropertiesPanel:Show();
elseif data.tab == self.HierarchyTab then
self.HierarchyPanel:Show();
elseif data.tab == self.ScenePropertiesTab then
self.ScenePropertiesPanel:Show();
end
end);
self.TabBar:OnTabDeactivated(function(data)
if data.tab == self.PropertiesTab then
self.PropertiesPanel:Hide();
elseif data.tab == self.HierarchyTab then
self.HierarchyPanel:Hide();
elseif data.tab == self.ScenePropertiesTab then
self.ScenePropertiesPanel:Hide();
end
end);
self.TabBar:ActivateTab(self.PropertiesTab);
self:OnDrop(function(data)
if self.PropertiesPanel:IsVisible() then
-- If we drop a script file onto the properties panel we want to add a script component if it doesn't already have one
-- and add the given script to it.
if data.droppedElement.isAsset and GTEngine.IsScriptFile(data.droppedElement.path) then
if self.PropertiesPanel.CurrentSceneNode ~= nil then
local scriptComponent = self.PropertiesPanel.CurrentSceneNode:GetComponent(GTEngine.Components.Script);
if scriptComponent == nil then
scriptComponent = self.PropertiesPanel.CurrentSceneNode:AddComponent(GTEngine.Components.Script);
end
self.PropertiesPanel:UpdateComponentPanels();
self.PropertiesPanel.ComponentPanels[GTEngine.Components.Script]:AddScript(data.droppedElement.path);
end
end
end
end);
self.PropertiesPanel:SceneEditorPropertiesPanel(sceneEditor);
self.HierarchyPanel:SceneEditorHierarchyPanel(sceneEditor);
self.ScenePropertiesPanel:SceneEditorScenePropertiesPanel(sceneEditor);
-- Properties Panel Events.
self.PropertiesPanel:OnSceneNodeChanged(function()
self.SceneEditor:CommitStateStackFrame()
end);
end
|
-----------------------------------
-- Area: Bastok Markets
-- NPC: Malene
-- Type: Quest NPC
-- !pos -173 -5 64 235
-----------------------------------
require("scripts/globals/npc_util")
require("scripts/globals/quests")
require("scripts/globals/titles")
function onTrade(player, npc, trade)
if (player:getQuestStatus(BASTOK, tpz.quest.id.bastok.THE_COLD_LIGHT_OF_DAY) >= QUEST_AVAILABLE and npcUtil.tradeHas(trade, 550)) then
player:startEvent(104)
end
end
function onTrigger(player, npc)
if (player:getQuestStatus(BASTOK, tpz.quest.id.bastok.WISH_UPON_A_STAR) == QUEST_ACCEPTED and player:getCharVar("WishUponAStar_Status") == 1) then -- Quest: Wish Upon a Star
player:startEvent(330)
else -- Quest: The Cold Light of Day
player:startEvent(102)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
-- THE COLD LIGHT OF DAY
if (csid == 102) then
if (player:getQuestStatus(BASTOK, tpz.quest.id.bastok.THE_COLD_LIGHT_OF_DAY) == QUEST_AVAILABLE) then
player:addQuest(BASTOK, tpz.quest.id.bastok.THE_COLD_LIGHT_OF_DAY)
end
elseif (csid == 104) then
local fame = player:hasCompletedQuest(BASTOK, tpz.quest.id.bastok.THE_COLD_LIGHT_OF_DAY) and 8 or 50
if (npcUtil.completeQuest(player, BASTOK, tpz.quest.id.bastok.THE_COLD_LIGHT_OF_DAY, {title=tpz.title.CRAB_CRUSHER, gil=500, fame=fame})) then
player:confirmTrade()
end
-- WISH UPON A STAR
elseif (csid == 330) then
player:setCharVar("WishUponAStar_Status", 2)
end
end
|
--[=[
Intended for classes that extend BaseObject only
@class PromiseRemoteEventMixin
]=]
local require = require(script.Parent.loader).load(script)
local promiseChild = require("promiseChild")
local PromiseRemoteEventMixin = {}
--[=[
Adds the remote function mixin to a class
```lua
local BaseObject = require("BaseObject")
local Bird = setmetatable({}, BaseObject)
Bird.ClassName = "Bird"
Bird.__index = Bird
require("PromiseRemoteEventMixin"):Add(Bird, "BirdRemoteEvent")
function Bird.new(inst)
local self = setmetatable(BaseObject.new(inst), Bird)
self:PromiseRemoteEvent():Then(function(remoteEvent)
self._maid:GiveTask(remoteEvent.OnClientEvent:Connect(function(...)
self:_handleRemoteEvent(...)
end)
end)
return self
end
```
@param class { _maid: Maid }
@param remoteEventName string
]=]
function PromiseRemoteEventMixin:Add(class, remoteEventName)
assert(type(class) == "table", "Bad class")
assert(type(remoteEventName) == "string", "Bad remoteEventName")
assert(not class.PromiseRemoteEventMixin, "Class already has PromiseRemoteEventMixin defined")
assert(not class._remoteEventName, "Class already has _remoteEventName defined")
class.PromiseRemoteEvent = self.PromiseRemoteEvent
class._remoteEventName = remoteEventName
end
--[=[
Returns a promise that returns a remote event
@return Promise<RemoteEvent>
]=]
function PromiseRemoteEventMixin:PromiseRemoteEvent()
return self._maid:GivePromise(promiseChild(self._obj, self._remoteEventName))
end
return PromiseRemoteEventMixin |
--- An ordered, linear, last in first out @{Collection} of items.
-- Stacks have a distinct ordering of their elements and can be added to at the
-- back and removed from in the back. The combination of these ensures that
-- the last elements added are the first ones out of the Stack.
--
-- The Stack interface provides a base set of operations for interacting
-- with any abstract Stack type. Abstract data types may provide addtional
-- specific operations based on the particular implemented type. Concrete
-- implementations, such as @{ArrayStack|ArrayStacks}, ultimately determine
-- the properties of the concrete Stack such as time and space complexity for
-- any operations.
--
-- The Stack interface provides certain optional methods in addition to those in
-- @{Collection}. Some Stacks, such as immutable or type-restricted data types,
-- may not be able to provide full functionality for these methods. All Stacks
-- are guaranteed to provide a required set of behaviors without exception and,
-- unless otherwise noted, a method is required. All Stacks should attempt
-- to provide optional functionality, if they're able, regardless.
--
-- **Implements:** @{Collection}, @{Enumerable}
--
-- @classmod Stack
local module = script.Parent
local Collection = require(module:WaitForChild("Collection"))
local ErrorOverride = "Abstract method %s must be overridden in first concrete subclass. Called directly from Stack."
local Stack = Collection.new()
Stack.__index = Stack
--- Creates a new Stack interface instance.
-- This should only be used when implementing a new Stack.
--
-- @return the new Stack interface
-- @static
-- @access private
function Stack.new()
local self = setmetatable({}, Stack)
return self
end
--- Creates an enumerator for the Stack.
-- The enumerator can be used directly in a generic for loop similar to pairs
-- or ipairs.
--
-- @return the enumerator generator
-- @return the invariant state
-- @return the control variable state
-- @from @{Enumerable}
function Stack:Enumerator()
error(string.format(ErrorOverride, "Enumerator"))
end
--- Determines whether the Stack contains an item.
--
-- @param item the item to locate in the Stack
-- @return true if the item is in the Stack, false otherwise
-- @from @{Collection}
function Stack:Contains()
error(string.format(ErrorOverride, "Contains"))
end
--- Determines whether the Stack contains all of the provided items.
-- Checks for items provided in another @{Collection} in an arbitrary,
-- deterministic order. The order is the same as the order of enumeration.
--
-- @param items the @{Collection} of items to locate in this Stack
-- @return true if all items are in the Stack, false otherwise
-- @from @{Collection}
function Stack:ContainsAll()
error(string.format(ErrorOverride, "ContainsAll"))
end
--- Determines whether the Stack contains any of the provided items.
-- Checks for items provided in another @{Collection} in an arbitrary,
-- deterministic order. The order is the same as the order of enumeration.
--
-- @param items the @{Collection} of items to locate in this Stack
-- @return true if any items are in the Stack, false otherwise
-- @from @{Collection}
function Stack:ContainsAny()
error(string.format(ErrorOverride, "ContainsAny"))
end
--- Gets the number of items in the Stack.
--
-- @return the number of items
-- @from @{Collection}
function Stack:Count()
error(string.format(ErrorOverride, "Count"))
end
--- Determines whether the Stack has no elements.
--
-- @return true if the Stack empty, false otherwise
-- @from @{Collection}
function Stack:Empty()
error(string.format(ErrorOverride, "Empty"))
end
--- Creates a new array indexed table of this Stack.
-- The order of the array is the same as the order of the Stack. The first
-- element of the Stack will get index 1 and so on.
--
-- @return the array indexed table
-- @see ToTable
-- @from @{Collection}
function Stack:ToArray()
error(string.format(ErrorOverride, "ToArray"))
end
--- Creates a new table of this Stack.
-- Stacks, being ordered and linear, need no indices that are not array indices,
-- so this provides a table with all the same array indices as @{ToArray}.
--
-- @return the table
-- @see ToArray
-- @from @{Collection}
function Stack:ToTable()
error(string.format(ErrorOverride, "ToTable"))
end
--- Adds an item to the Stack.
--
-- This method is optional. All Stack implementations should attempt to
-- implement this method, but some may be unable to do so or may need to
-- impose additional conditions to do so.
--
-- This method should always be overridden regardless of implementation. If
-- unimplemented, it should return an error specific to the optional
-- functionality that can't be provided by this Stack.
--
-- @param item the item to add
-- @return true if the Stack changed as a result, false otherwise
-- @from @{Collection}
function Stack:Add()
error(string.format(ErrorOverride, "Add"))
end
--- Adds all provided items to the Stack.
-- Adds items provided in another @{Collection} in an arbitrary, deterministic
-- order. The order is the same as the order of enumeration.
--
-- This method is optional. All Stack implementations should attempt to
-- implement this method, but some may be unable to do so or may need to
-- impose additional conditions to do so.
--
-- This method should always be overridden regardless of implementation. If
-- unimplemented, it should return an error specific to the optional
-- functionality that can't be provided by this Stack.
--
-- @param items the @{Collection} of items to add to this Stack
-- @return true if the Stack changed as a result, false otherwise
-- @from @{Collection}
function Stack:AddAll()
error(string.format(ErrorOverride, "AddAll"))
end
--- Removes everything from the Stack.
--
-- This method is optional. All Stack implementations should attempt to
-- implement this method, but some may be unable to do so or may need to
-- impose additional conditions to do so.
--
-- This method should always be overridden regardless of implementation. If
-- unimplemented, it should return an error specific to the optional
-- functionality that can't be provided by this Stack.
--
-- @from @{Collection}
function Stack:Clear()
error(string.format(ErrorOverride, "Clear"))
end
--- Removes the specified item from the Stack.
-- Removes only a single item. If there are multiple of the same item, it
-- removes only the first encountered.
--
-- When an item is removed any others are shifted to fill the gap left at
-- the index of removal.
--
-- This method is optional. All Stack implementations should attempt to
-- implement this method, but some may be unable to do so or may need to
-- impose additional conditions to do so.
--
-- This method should always be overridden regardless of implementation. If
-- unimplemented, it should return an error specific to the optional
-- functionality that can't be provided by this Stack.
--
-- @param item the item to remove from the Stack
-- @return true if the Stack changed as a result, false otherwise
-- @from @{Collection}
function Stack:Remove()
error(string.format(ErrorOverride, "Remove"))
end
--- Removes all provided items from the Stack.
-- Removes each instance of a provided item only once for each time provided.
-- If there are multiple of the same item in this Queue, it removes only
-- the first encountered for each provided.
--
-- This method is optional. All Stack implementations should attempt to
-- implement this method, but some may be unable to do so or may need to
-- impose additional conditions to do so.
--
-- This method should always be overridden regardless of implementation. If
-- unimplemented, it should return an error specific to the optional
-- functionality that can't be provided by this Stack.
--
-- @param items the @{Collection} of items to remove from this Stack
-- @return true if the Stack changed as a result, false otherwise
-- @from @{Collection}
function Stack:RemoveAll()
error(string.format(ErrorOverride, "RemoveAll"))
end
--- Removes all items except those provided from the Stack.
-- Retains only the items contained in the specified @{Collection}. If there are
-- duplicates they are all kept.
--
-- This method is optional. All Stack implementations should attempt to
-- implement this method, but some may be unable to do so or may need to
-- impose additional conditions to do so.
--
-- This method should always be overridden regardless of implementation. If
-- unimplemented, it should return an error specific to the optional
-- functionality that can't be provided by this Stack.
--
-- @param items the @{Collection} of items to retain in this Stack
-- @return true if the Stack changed as a result, false otherwise
-- @from @{Collection}
function Stack:RetainAll()
error(string.format(ErrorOverride, "RetainAll"))
end
--- Gets the item at the end of the Stack.
--
-- @return the last item in the Stack
-- @raise if the Stack is empty
function Stack:Last()
error(string.format(ErrorOverride, "Last"))
end
--- Adds an item to the end of the Stack.
--
-- This method is optional. All Stack implementations should attempt to
-- implement this method, but some may be unable to do so or may need to
-- impose additional conditions to do so.
--
-- This method should always be overridden regardless of implementation. If
-- unimplemented, it should return an error specific to the optional
-- functionality that can't be provided by this Stack.
--
-- @param item the item to add
-- @return true if the Stack changed as a result, false otherwise
function Stack:Push()
error(string.format(ErrorOverride, "Push"))
end
--- Gets an item from the end and removes that item from the Stack.
-- Shifts other elements to fill the gap left.
--
-- This method is optional. All Stack implementations should attempt to
-- implement this method, but some may be unable to do so or may need to
-- impose additional conditions to do so.
--
-- This method should always be overridden regardless of implementation. If
-- unimplemented, it should return an error specific to the optional
-- functionality that can't be provided by this Stack.
--
-- @return the item in the Stack
-- @raise if the Stack is empty
function Stack:Pop()
error(string.format(ErrorOverride, "Pop"))
end
return Stack
|
Clockwork.config:Add("context_menu_always", false, true);
|
local vehicleLogs = {}
function loadHandlingLog ( )
local data = getElementData ( root, "hedit:vehicleLogs" )
if data then
vehicleLogs = data
end
return true
end
function unloadHandlingLog ( )
setElementData ( root, "hedit:vehicleLogs", vehicleLogs, false )
return true
end
function addLogEntry ( vehicle, player, textPointer, arguments, oldValue, level )
if not isValidVehicle ( vehicle ) then
return false
end
if not isValidPlayer ( player ) then
return false
end
if type ( textPointer ) ~= "string" then
return false
end
if arguments and type ( arguments ) ~= "table" then
return false
end
if type ( level ) ~= "number" or level < 1 or level > 3 then
level = 3
end
if not vehicleLogs[vehicle] then
vehicleLogs[vehicle] = {}
end
if #vehicleLogs[vehicle] == 25 then
table.remove ( vehicleLogs[vehicle], 1 )
end
local realtime = getRealTime ( )
local addingEntry = {
responsiblePlayer = getPlayerName ( player ),
timeStamp = {
hour = realtime.hour,
minute = realtime.minute,
second = realtime.second
},
textPointer = textPointer,
arguments = arguments,
oldValue = oldValue,
level = level
}
table.insert ( vehicleLogs[vehicle], addingEntry )
local occupants = getVehicleOccupants ( vehicle )
for seat=0,getVehicleMaxPassengers ( vehicle ) do
local occupant = occupants[seat]
if isValidPlayer ( occupant ) then
triggerClientEvent ( occupant, "addToLogGUI", occupant, addingEntry )
end
end
return true
end
addEvent ( "addToLog", true )
addEventHandler ( "addToLog", root, addLogEntry )
function uploadMiniLog ( vehicle, amountToSend )
if not isValidVehicle ( vehicle ) then
return false
end
local fullLog = vehicleLogs[vehicle]
local toSend = {}
if type ( fullLog ) == "table" then
local size = #fullLog
for i=(amountToSend-1),0,-1 do
table.insert ( toSend, fullLog[size-i] )
end
end
triggerClientEvent ( client, "receiveMiniLog", client, toSend )
return true
end
addEvent ( "requestMiniLog", true )
addEventHandler ( "requestMiniLog", root, uploadMiniLog )
function uploadFullLog ( vehicle )
if not isValidVehicle ( vehicle ) then
return false
end
triggerClientEvent ( client, "receiveFullLog", client, getElementData(root,"hedit:vehicleLogs")[vehicle] )
return true
end
addEvent ( "requestFullLog", true )
addEventHandler ( "requestFullLog", root, uploadFullLog )
-- Destroy log information when vehicle is destroyed
local function cleanupVehicleLog()
if source.type == "vehicle" then
vehicleLogs[source] = nil
end
end
addEventHandler("onElementDestroy", root, cleanupVehicleLog)
|
_=loadfile and loadfile("TQAE.lua"){
user="admin",
pwd="admin",
host="192.168.1.57",
temp = "temp/",
}
--[[
Test WebSocket QA to control Samsung Q7 TV
Power off works...
--]]
--%%name="SamsungTV"
--%%type="com.fibaro.philipsTV"
--%%quickVars={ IP = "192.168.1.175", name = "HC3" }
--%%u1={button="Power", text="Power", onReleased="power"}
--%%u2={button="Mute", text="Mute", onReleased="mute"}
local self,connect,handleDataReceived,handleError,handleDisconnected,handleConnected
local function setSelf(qa) self = qa end
local function base64encode(data)
__assert_type(data,"string" )
local bC='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
return ((data:gsub('.', function(x)
local r,b='',x:byte() for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
return r;
end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
if (#x < 6) then return '' end
local c=0
for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
return bC:sub(c+1,c+1)
end)..({ '', '==', '=' })[#data%3+1])
end
function QuickApp:sendCmd(key)
self:trace("Send key:",key)
if self.sock:isOpen() then
local data = {
method = "ms.remote.control",
params = { Cmd = "Click", DataOfCmd = key, Option=false, TypeOfRemote="SendRemoteKey"}
}
local ok,err = self.sock:send(json.encode(data).."\n")
if not ok then self:warning("Send error:",err) end
else
self:warning("Socket closed")
end
end
function QuickApp:mute() self:sendCmd("KEY_MUTE") end
function QuickApp:power() self:sendCmd("KEY_POWER") end
function handleConnected()
self:debug("Connected")
end
function handleDisconnected()
self:debug("Disconnected")
self:debug("Trying to reconnect...")
connect()
end
function handleError(error)
self:error("Error:",error)
end
function handleDataReceived(resp)
local data = json.decode(resp)
self:debug("Event:",data.event)
self:debug("Data:",data.data)
if data.event == "ms.channel.connect" then
if data.data.token then
self.token = data.data.token
self:debug("token:",self.token)
self:setVariable("token",self.token)
local base = self.url:match("(.-)&token=") or self.url
self.url=self.url.."&token="..self.token
end
end
end
function connect()
self.sock = net.WebSocketClientTls()
self.sock:addEventListener("connected", handleConnected)
self.sock:addEventListener("disconnected", handleDisconnected)
self.sock:addEventListener("error", handleError)
self.sock:addEventListener("dataReceived", handleDataReceived)
self.sock:connect(self.url)
end
function QuickApp:onInit()
setSelf(self)
self.ip = self:getVariable("IP")
self.tvname = self:getVariable("name")
self.token = self:getVariable("token") or ""
self.url = "wss://%s:8002/api/v2/channels/samsung.remote.control?name="..base64encode(self.tvname)
if self.token and self.token ~= "" then
self.url = self.url.."&token="..self.token
end
self.url=self.url:format(self.ip)
self:debug("URL:",self.url)
connect()
end |
-- 20120302 mvh Created
-- 20141102 mvh Used studyUID as passed to support CC without relational queries
function getmodality()
local a,b,s;
if CGI('source')=='(local)' then
s = servercommand('get_param:MyACRNema')
else
s = CGI('source')
end
b=newdicomobject();
b.PatientID = CGI('patientidmatch');
b.SeriesInstanceUID = CGI('seriesUID');
b.StudyInstanceUID = CGI('studyUID');
b.Modality = '';
a=dicomquery(s, 'SERIES', b);
return a[0].Modality
end
function queryimages()
local images,imaget,b,s;
if CGI('source')=='(local)' then
s = servercommand('get_param:MyACRNema')
else
s = CGI('source')
end
b=newdicomobject();
b.PatientID = CGI('patientidmatch')
b.StudyInstanceUID = CGI('studyUID');
b.SeriesInstanceUID= CGI('seriesUID');
b.SOPInstanceUID = '';
images=dicomquery(s, 'IMAGE', b);
imaget={}
for k=0,#images-1 do
imaget[k+1]={}
imaget[k+1].SOPInstanceUID=images[k].SOPInstanceUID
end
table.sort(imaget, function(a,b) return a.SOPInstanceUID<b.SOPInstanceUID end)
return imaget
end
HTML('Content-type: text/html\n\n');
local modality = getmodality()
local size = 256
local header = CGI('header')
if modality=='RTSTRUCT' or modality=='RTPLAN' then size = 0 end
print([[
<HEAD><TITLE> ]]..header..[[ </TITLE></HEAD>
<BODY BGCOLOR='F3F3F3'>
<H3> ]]..header..[[ </H3>
<SCRIPT language=JavaScript>
function load()
{
]])
if CGI('source')=='(local)' then
bridge=[[]]
else
bridge=[[&bridge=]]..CGI('source')
end
if string.sub(modality, 1, 2)~='RT' then
print([[
document.images[0].src = ']]..script_name..[[?requestType=WADO&contentType=image/gif'+
']]..bridge..[[' +
'&studyUID=]]..CGI('studyUID')..[[' +
'&seriesUID=]]..CGI('seriesUID')..[[' +
'&objectUID=' + document.forms[0].slice.value;
]])
end
if string.sub(modality, 1, 2)=='RT' then
print([[
document.getElementById("myframe").src = ']]..script_name..[[?requestType=WADO&contentType=text/plain'+
]]..bridge..[[ +
'&studyUID=]]..CGI('studyUID')..[[' +
'&seriesUID=]]..CGI('seriesUID')..[[' +
'&objectUID=' + document.forms[0].slice.value;
]])
end
print([[
}
function PopupCenter(pageURL, title,w,h)
{ var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}
function nextslice()
{ if (document.forms[0].slice.selectedIndex == document.forms[0].slice.length-1) document.forms[0].slice.selectedIndex = 0; else document.forms[0].slice.selectedIndex = document.forms[0].slice.selectedIndex + 1; load()
}
</SCRIPT>
<IMG SRC=loading.jpg BORDER=0 HEIGHT=]].. size ..[[>
]])
if string.sub(modality, 1, 2)=='RT' then
print([[
<iframe id="myframe" BORDER=0 HEIGHT=256>
<p>Your browser does not support iframes.</p>
</iframe>
]])
end
print([[
<H3>]].. modality ..[[</H3>
<FORM>
Slice:
<select name=slice onchange=load()>
]]
)
local i, images;
images = queryimages();
for i=1, #images do
print('<option value='..images[i].SOPInstanceUID..'>'..i..'</option>')
end
print([[
</select>
<INPUT TYPE=BUTTON VALUE='>' onclick=nextslice() >
</FORM>
]])
print([[<a href=# onclick="javascript:PopupCenter(']]..script_name..[[?requestType=WADO]]..bridge..[[&contentType=text/plain&studyUID=]]..CGI('studyUID')..[[&seriesUID=]]..CGI('seriesUID')..[[&objectUID=' + document.forms[0].slice.value + '&dum=.txt', 'hoi', 500, 500)">[original header]</a>
]])
print([[<a href=# onclick="javascript:PopupCenter(']]..script_name..[[?requestType=WADO]]..bridge..[[&contentType=text/plain&anonymize=yes&studyUID=]]..CGI('studyUID')..[[&seriesUID=]]..CGI('seriesUID')..[[&objectUID=' + document.forms[0].slice.value + '&dum=.txt', 'hoi', 500, 500)">[anonymized header]</a>
]])
print([[
<SCRIPT language=JavaScript>
document.onload=document.forms[0].slice.selectedIndex= document.forms[0].slice.length/2;load()
</SCRIPT>
</BODY>
]])
|
return function()
return {
onBeforeRender = function(_, _)
return true
end,
onRender = function(_, worldPart, viewportPart, highlight)
viewportPart.CFrame = worldPart.CFrame
viewportPart.Color = highlight.color
end,
onAdded = function(_, viewportPart, highlight)
local function clearTextures(instance)
if instance:IsA("MeshPart") then
instance.TextureID = ""
elseif instance:IsA("UnionOperation") then
instance.UsePartColor = true
elseif instance:IsA("SpecialMesh") then
instance.TextureId = ""
end
end
local function colorObject(instance)
if instance:IsA("BasePart") then
instance.Color = highlight.color
end
end
for _, object in pairs(viewportPart:GetDescendants()) do
clearTextures(object)
colorObject(object)
end
clearTextures(viewportPart)
colorObject(viewportPart)
end,
}
end |
-- See LICENSE for terms
local mod_SpaceCount
local EnableMarker
-- fired when settings are changed/init
local function ModOptions()
mod_SpaceCount = CurrentModOptions:GetProperty("SpaceCount")
-- no sense in updating unless it's a cold wave
if g_ColdWave then
local objs = UICity.labels.LandscapeConstructionSite or ""
for i = 1, #objs do
EnableMarker(objs[i])
end
end
end
-- load default/saved settings
OnMsg.ModsReloaded = ModOptions
-- fired when option is changed
function OnMsg.ApplyModOptions(id)
if id ~= CurrentModId then
return
end
ModOptions()
end
local DoneObject = DoneObject
local type = type
local function DisableMarker(obj)
if obj.ChoGGi_ColdLines then
local lines = obj.ChoGGi_ColdLines
for i = 1, #lines do
DoneObject(lines[i])
end
obj.ChoGGi_ColdLines = nil
return
end
end
local cls_obj
EnableMarker = function(obj)
if type(obj.drone_dests_cache) ~= "table" then
return
end
-- might as well be on the safe side
if obj.ChoGGi_ColdLines then
DisableMarker(obj)
end
obj.ChoGGi_ColdLines = {}
local lines = obj.ChoGGi_ColdLines
local c = 0
local drone_dests_cache = obj.drone_dests_cache
if not obj.drone_dests_cache[1]:z() then
for i = 1, #drone_dests_cache do
drone_dests_cache[i] = drone_dests_cache[i]:SetTerrainZ()
end
end
if not cls_obj then
cls_obj = WayPointBig
end
for i = 1, #drone_dests_cache do
if i == 1 or i % mod_SpaceCount == 0 then
local mark = cls_obj:new()
mark:SetPos(drone_dests_cache[i])
c = c + 1
lines[c] = mark
end
end
end
GlobalVar("g_ChoGGi_ColdWaveLandscapeConstructionSite", false)
function OnMsg.ClassesPostprocess()
-- add remove lines depending on coldwaves
local ChoOrig_BuildingUpdate = LandscapeConstructionSite.BuildingUpdate
function LandscapeConstructionSite:BuildingUpdate(...)
local is_coldwave = g_ColdWave
local flags_enabled = g_ChoGGi_ColdWaveLandscapeConstructionSite
if is_coldwave and not (flags_enabled and self.ChoGGi_ColdLines) then
EnableMarker(self)
g_ChoGGi_ColdWaveLandscapeConstructionSite = true
elseif not is_coldwave and flags_enabled and self.ChoGGi_ColdLines then
DisableMarker(self)
g_ChoGGi_ColdWaveLandscapeConstructionSite = false
end
return ChoOrig_BuildingUpdate(self, ...)
end
local ChoOrig_Done = LandscapeConstructionSite.Done
function LandscapeConstructionSite:Done(...)
DisableMarker(self)
return ChoOrig_Done(self, ...)
end
end
-- make sure there's no markers left around
function OnMsg.SaveGame()
if g_ColdWave then
return
end
local markers = MapGet("map", "WayPointBig")
for i = 1, #markers do
DoneObject(markers[i])
end
end
|
if (SERVER) then
AddCSLuaFile( "shared.lua" );
end
if (CLIENT) then
--[[ Basic SWEP Information to display to the client. ]]--
SWEP.PrintName = "Scout"
SWEP.Author = "Zig"
SWEP.Purpose = "A firearm used to harm beings."
SWEP.Instructions = "Press LMB to fire and R to reload."
SWEP.Contact = "Cloudsixteen.com"
SWEP.CSMuzzleFlashes = true; -- Use Counter-Strike muzzle flashes?
end;
--[[ Set whether the SWEP is spawnable (by users or by admins). --]]
SWEP.Spawnable = true;
SWEP.AdminSpawnable = true;
--[[ Misc. SWEP Content --]]
SWEP.HoldType = "ar2"
SWEP.Base = "bs_sniper_base"
SWEP.Category = "Backsword"
SWEP.ViewModelFOV = 70
SWEP.ViewModelFlip = false; -- Some view models are incorrectly flipped.
SWEP.UseHands = true;
SWEP.ViewModel = "models/weapons/cstrike/c_snip_scout.mdl"
SWEP.WorldModel = "models/weapons/w_snip_scout.mdl"
SWEP.DrawAmmo = true; -- Draw our own ammo display?
SWEP.DrawCrosshair = false; -- Draw the crosshair, or draw our own?
--[[ These really aren't important. Keep them at false, and the weight at five. --]]
SWEP.Weight = 5
SWEP.AutoSwitchTo = false;
SWEP.AutoSwitchFrom = false;
--[[ Set the SWEP's primary fire information. --]]
SWEP.Primary.DefaultClip = 8;
SWEP.Primary.ClipSize = 8;
SWEP.Primary.Automatic = false;
SWEP.Primary.NumShots = 1;
SWEP.Primary.Damage = 22;
SWEP.Primary.Recoil = 0.50;
SWEP.Primary.Sound = Sound("weapons/hunting_rifle/gunfire/hunting_rifle_fire_1.wav")
SWEP.ReloadHolster = 0.1
SWEP.Primary.Delay = 1.3; -- Make sure we keep this at 1.3 so the bolt animation can play! (If it's a bolt action rifle, of course.)
SWEP.Primary.Ammo = "ar2";
SWEP.Primary.Cone = 0.0001;
--[[ Basic Scope Options. ]]--
SWEP.UseScope = true -- Use a scope instead of iron sights.
SWEP.ScopeScale = 0.55 -- The scale of the scope's reticle in relation to the player's screen size.
SWEP.ScopeZoom = 6 -- How much is the zoom on the scope?
SWEP.IronsightTime = 0.35 -- How long does it take to zoom in?
SWEP.BoltAction = true
--Only Select one... Only one.
SWEP.Scope1 = true
SWEP.Scope2 = false
SWEP.Scope3 = false
SWEP.Scope4 = false
SWEP.Scope5 = false
SWEP.Scope6 = false
--[[ Set the SWEP's secondary fire information. --]]
SWEP.Secondary.ClipSize = 1
SWEP.Secondary.DefaultClip = 100
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "smg2"
--[[ Define the bullet information for later use. --]]
SWEP.BulletTracerFreq = 1; -- Show a tracer every x bullets.
SWEP.BulletTracerName = nil -- Use a custom effect for the tracer.
SWEP.BulletForce = 5;
--[[ Set up the accuracy for the weapon. --]]
SWEP.CrouchCone = 0.001 -- Accuracy when we're crouching
SWEP.CrouchWalkCone = 0.009 -- Accuracy when we're crouching and walking
SWEP.WalkCone = 0.025 -- Accuracy when we're walking
SWEP.AirCone = 0.1 -- Accuracy when we're in air
SWEP.StandCone = 0.015 -- Accuracy when we're standing still |
-- 导入第三方包和系统包
local lunajson = require 'lunajson'
local io = require 'io'
local os = require 'os'
-- 全局变量
-- 默认配置文件位置,请直接修改config_file_ostype()
local config_file = ''
local autosave_dir_os = ''
local ostype = ''
local conf_content = {}
local running = false
-- 工程结构
local project_template = {
-- 硬编码部分:工程版本,无API获取
version = 120,
time = {
meter = {},
tempo = {}
},
library = {},
tracks = {},
-- 硬编码部分:渲染设置,无API获取
renderConfig = {
destination = './',
filename = '未命名',
numChannels = 1,
aspirationFormat = 'noAspiration',
bitDepth = 16,
sampleRate = 44100,
exportMixDown = true
}
}
-- 生成下一个自动保存的文件名
function filename_generate()
-- 当前项目名
local project_name = SV:getProject():getFileName()
-- 分离出文件名
if ostype == 'Windows' then
project_name = string.match(project_name, '.*\\(.*)')
else
project_name = string.match(project_name, '.*/(.*)')
end
-- 如果文件名为空
if project_name == nil then
project_name = 'Unnamed'
end
-- 当前时间
local current_time = os.date('%y%m%d_%H%M%S')
-- 合成文件名
local next_filename = project_name .. '-' .. current_time .. '.svp'
return next_filename
end
-- 判断系统
function config_file_ostype()
ostype = SV:getHostInfo().osType
if ostype == 'Windows' then
-- Windows系统下的配置文件位置
config_file = os.getenv('USERPROFILE') .. '\\Documents\\Dreamtonics\\Synthesizer V Studio\\scripts\\autosave.cfg'
autosave_dir_os = os.getenv('USERPROFILE') .. '\\Documents\\Dreamtonics\\Synthesizer V Studio\\autosave'
elseif ostype == 'Linux' then
-- Linux系统下的配置文件位置
config_file = os.getenv('PWD') .. '/scripts/autosave.cfg'
autosave_dir_os = os.getenv('PWD') .. '/autosave'
else
-- Mac系统下的配置文件位置
config_file = os.getenv('HOME') .. 'Library/Application Support/Dreamtonics/Synthesizer V Studio/scripts/autosave.cfg'
autosave_dir_os = os.getenv('HOME') .. 'Library/Application Support/Dreamtonics/Synthesizer V Studio/autosave'
end
end
-- 读取配置文件
function readConfig()
-- 读取文件内容
local conf_file_ptr = io.open(config_file, 'a+')
conf_file_ptr:seek('set')
local conf_content_str = conf_file_ptr:read('*a')
-- 如果文件内容为空
if conf_content_str == "" then
writeDefaultConfig(conf_file_ptr)
conf_file_ptr:seek('set')
conf_content_str = conf_file_ptr:read('*a')
end
-- JSON解码
conf_content = lunajson.decode(conf_content_str)
conf_file_ptr:close()
end
-- 配置文件不存在,写入默认配置
function writeDefaultConfig(conf_file_ptr)
-- 默认配置
local default_conf = {
-- 自动保存时间间隔
interval = 5,
-- 自动保存的文件位置
autosave_dir = autosave_dir_os
}
-- JSON编码
local default_conf_json = lunajson.encode(default_conf)
conf_file_ptr:write(default_conf_json)
end
-- 修改配置文件
function writeConfig()
-- 清空文件内容
local conf_file_ptr = io.open(config_file, 'w')
-- 直接覆盖JSON
conf_file_ptr:write(lunajson.encode(conf_content))
-- 关闭文件
conf_file_ptr:close()
end
-- 曲速标记
function project_tempo()
-- 项目 - 时间轴 - 获取所有曲速标记
local tempo_mark = SV:getProject():getTimeAxis():getAllTempoMarks()
-- 删掉不需要的成员
for key, _ in pairs(tempo_mark)
do
tempo_mark[key]['positionSeconds'] = nil
end
return tempo_mark
end
-- 拍号标记
function project_measure()
-- 项目 - 时间轴 - 获取所有拍号标记
local measure_mark = SV:getProject():getTimeAxis():getAllMeasureMarks()
-- 格式修改
for key, _ in pairs(measure_mark)
do
measure_mark[key]['positionBlick'] = nil
measure_mark[key]['index'] = measure_mark[key]['position']
measure_mark[key]['position'] = nil
end
return measure_mark
end
-- 参数点
function note_params(notegroup)
-- 模板
local param_array = {}
-- 参数类型
local param_type = {
'pitchDelta',
'vibratoEnv',
'loudness',
'tension',
'breathiness',
'voicing',
'gender'
}
-- 对每一种参数类型都执行
for _, val in pairs(param_type)
do
-- 获取参数对应的Automation
local automate_data = notegroup:getParameter(val)
-- 单一参数的模板
param_array[val] = {
-- 插值类型
mode = automate_data:getInterpolationMethod(),
-- 点数组
points = {}
}
param_array[val]['points'][0] = 0
-- 获得所有点的二维数组
local all_points = automate_data:getAllPoints()
-- 二维数组转一维数组
for _, vec in pairs(all_points)
do
table.insert(param_array[val]['points'], vec[1])
table.insert(param_array[val]['points'], vec[2])
param_array[val]['points'][0] = param_array[val]['points'][0] + 2
end
end
return param_array
end
-- 音符轨道公共属性
function note_attribute(attribute_obj)
-- 音符属性模板
local attribute_array = {}
-- 属性列表
local attribute_type = {
'tF0Left',
'tF0Right',
'dF0Left',
'dF0Right',
'tF0VbrStart',
'tF0VbrLeft',
'tF0VbrRight',
'dF0Vbr',
'fF0Vbr',
}
-- 判断各属性值是否进行了修改
for _, param in pairs(attribute_type)
do
if attribute_obj[param] ~= nil then
attribute_array[param] = attribute_obj[param]
end
end
return attribute_array
end
-- 音符信息
function note_info(notegroup)
-- 单个音符组的音符信息模板
local note_info_array = {
-- 音符组名
name = notegroup:getName(),
-- 音符组UUID
uuid = notegroup:getUUID(),
-- 音符组的各参数信息
parameters = note_params(notegroup)
}
-- 音符数组
local note_array = {}
-- 共有几个音符?
local note_num = notegroup:getNumNotes()
note_array[0] = 0
-- 对每一个音符执行
for j=1, note_num
do
-- 获取到音符对象
local current_note = notegroup:getNote(j)
note_array[0] = note_array[0] + 1
-- 单个音符的模板
note_array[j] = {
-- 开始时间
onset = current_note:getOnset(),
-- 持续时间
duration = current_note:getDuration(),
-- 歌词
lyrics = current_note:getLyrics(),
-- 音素
phonemes = current_note:getPhonemes(),
-- 所在音高
pitch = current_note:getPitch(),
-- 音符属性
attributes = {}
}
-- 音符属性
local attribute_obj = current_note:getAttributes()
note_array[j]['attributes'] = note_attribute(attribute_obj)
-- 特有的音符属性
local special_attribute = {
'tF0Offset',
'pF0Vbr',
'tNoteOffset',
'exprGroup'
}
for _, param in pairs(special_attribute)
do
if attribute_obj[param] ~= nil then
note_array[j]['attributes'][param] = attribute_obj[param]
end
end
-- array类型的属性
if next(attribute_obj.dur) ~= nil then
note_array[j]['attributes']['dur'] = attribute_obj['dur']
end
if next(attribute_obj.alt) ~= nil then
note_array[j]['attributes']['alt'] = attribute_obj['alt']
end
end
note_info_array['notes'] = note_array
return note_info_array
end
-- 音符组引用
function notegroup_ref(current_ref)
-- 音符组引用模板
local ref_obj = {
groupID = current_ref:getTarget():getUUID(),
blickOffset = current_ref:getTimeOffset(),
pitchOffset = current_ref:getPitchOffset(),
isInstrumental = current_ref:isInstrumental(),
-- 硬编码部分,伴奏文件名和位置,无API
audio = {
filename = '',
duration = 0.0
},
-- 硬编码部分,声库设置,无API
database = {
name = '',
language = '',
languageOverride = '',
phonesetOverride = '',
backendType = ''
},
-- 硬编码部分,词典设置,无API
dictionary = '',
-- 音符属性
voice = {}
}
local attribute_obj = current_ref:getVoice()
-- 公有属性
ref_obj['voice'] = note_attribute(attribute_obj)
-- 特有属性
local special_attribute = {
'paramLoudness',
'paramTension',
'paramBreathiness',
'paramGender'
}
for _, param in pairs(special_attribute)
do
if attribute_obj[param] ~= nil then
ref_obj['voice'][param] = attribute_obj[param]
end
end
return ref_obj
end
-- 轨道
function project_track()
-- 轨道数组
local track_array = {}
-- 工程里共有几个轨道?
local track_num = SV:getProject():getNumTracks()
-- 对每条轨道都执行
for i=1, track_num
do
-- 获取轨道对象
local current_track = SV:getProject():getTrack(i)
-- 单个轨道的模板
track_array[i] = {
-- 轨道名称
name = current_track:getName(),
-- 显示颜色
dispColor = current_track:getDisplayColor(),
-- 显示顺序
dispOrder = current_track:getDisplayOrder(),
-- 有没有启用渲染
renderEnabled = current_track:isBounced(),
-- 硬编码部分,混音器设置,无API
mixer = {
gainDecibel = 0.0,
pan = 0.0,
mute = false,
solo = false,
display = true
}
}
-- 轨道里不在任何音符组里的内容
local current_ref = current_track:getGroupReference(1)
-- 这些音符所在的main音符组
track_array[i]['mainGroup'] = note_info(current_ref:getTarget())
-- main音符组的引用
track_array[i]['mainRef'] = notegroup_ref(current_ref)
-- 总音符组数,去掉main
local track_group_num = current_track:getNumGroups() - 1
-- 初始化数组
track_array[i]['groups'] = {}
track_array[i]['groups'][0] = 0
-- 把每一个组都加入
for j=1, track_group_num
do
track_array[i]['groups'][0] = track_array[i]['groups'][0] + 1
track_array[i]['groups'][j] = notegroup_ref(current_track:getGroupReference(j + 1))
end
end
return track_array
end
-- 库
function project_library()
-- 库数组模板
local library_array = {}
library_array[0] = 0
-- 找到库里的轨道数
local notegroup_num = SV:getProject():getNumNoteGroupsInLibrary()
-- 对库里的每个轨道执行
for i=1, notegroup_num
do
library_array[0] = library_array[0] + 1
-- 得到对应的音符组
local current_group = SV:getProject():getNoteGroup(i)
-- 获得该音符组的信息
library_array[i] = note_info(current_group)
end
return library_array
end
-- 持续执行函数
function autosave_main()
-- 创建工程文件
local filename = filename_generate()
local full_path = autosave_dir_os .. '/' .. filename
local file_ptr = io.open(full_path, 'w')
-- 组装工程文件
local current_project = project_template
-- 曲速
current_project['time']['tempo'] = project_tempo()
-- 拍号
current_project['time']['meter'] = project_measure()
-- 库
current_project['library'] = project_library()
-- 轨道
current_project['tracks'] = project_track()
-- 写文件
file_ptr:write(lunajson.encode(current_project))
file_ptr:write('\0')
file_ptr:close()
-- 预定下一次运行
SV:setTimeout(conf_content['interval'] * 60 * 1000, autosave_main)
end
-- 插件描述
function getClientInfo()
return {
name = SV:T('AutoSave Preview'),
author = 'ObjectNotFound <[email protected]>',
versionNumber = 1,
minEditorVersion = 65540
}
end
-- 本地化
function getTranslations(langCode)
if langCode == 'zh-cn' then
return {
{'AutoSave Preview', '自动保存 测试版'},
{'AutoSave Plugin Settings', '自动保存插件设置'},
{'File save interval (minutes)', '保存时间间隔(分钟)'},
{'File save location', '自动保存文件位置'},
{'Filename demo (display only)', '自动保存文件名示例(修改无效)'}
}
end
end
function main()
-- 加载
config_file_ostype()
readConfig()
-- 设置窗口
local form = {
title = SV:T('AutoSave Plugin Settings'),
message = 'ObjectNotFound <[email protected]>',
buttons = 'OkCancel',
widgets = {
{
name = 'interval',
type = 'Slider',
label = SV:T('File save interval (minutes)'),
format = '%0.1f',
minValue = 1,
maxValue = 60,
interval = 0.5,
default = conf_content['interval']
},
{
name = 'autosave_dir',
type = 'TextArea',
label = SV:T('File save location'),
default = conf_content['autosave_dir']
},
{
name = 'filename_demo',
type = 'TextArea',
label = SV:T('Filename demo (display only)'),
default = filename_generate()
}
}
}
-- 拿返回值
local settings = SV:showCustomDialog(form)
local triggerWriteConfig = false
-- 确认才进行比较
if settings.status == true then
-- 需要修改配置文件吗?
if conf_content['interval'] ~= settings.answers.interval then
conf_content['interval'] = settings.answers.interval
triggerWriteConfig = true
end
if conf_content['autosave_dir'] ~= settings.answers.autosave_dir then
conf_content['autosave_dir'] = settings.answers.autosave_dir
triggerWriteConfig = true
end
end
-- 如果配置文件被修改,则重写配置文件
if triggerWriteConfig == true then
writeConfig()
end
if running == false then
autosave_main()
running = true
end
end |
return function()
local Reducer = require(script.Parent.InspectAndBuyReducer)
it("has the expected fields, and only the expected fields", function()
local state = Reducer(nil, {})
local expectedKeys = {
view = true,
playerId = true,
playerName = true,
assets = true,
bundles = true,
equippedAssets = true,
detailsInformation = true,
tryingOnInfo = true,
favorites = true,
locale = true,
visible = true,
itemBeingPurchased = true,
gamepadEnabled = true,
isLoaded = true,
FetchingStatus = true,
storeId = true,
}
for key in pairs(expectedKeys) do
assert(state[key] ~= nil, string.format("Expected field %q", key))
end
for key in pairs(state) do
assert(expectedKeys[key] ~= nil, string.format("Did not expect field %q", key))
end
end)
end
|
PointGenerator = {}
setmetatable(PointGenerator, {__index = HiveBaseModule})
PointGenerator.new = function (varname)
local this = HiveBaseModule.new(varname)
this.gen = PrimitiveGenerator()
setmetatable(this, {__index=PointGenerator})
return this
end
function PointGenerator:Do()
self:UpdateValue()
--[[
self.value.vertices = {}
for i = 1, 10 do
table.insert(self.value.vertices, 100 * math.sin(i))
table.insert(self.value.vertices, 100 * math.cos(i))
table.insert(self.value.vertices, 3 * math.cos(i) * math.sin(i))
end
]]
local v = self.value
self.point = self.gen:PointList(v.vertices, #v.vertices / 3, v.radius);
return (self.point ~= nil)
end
function PointGenerator:PointData()
return self.point
end
|
-----------------------------------------------------------------
-- lua-capnproto compiler
-- @copyright 2013-2016 Jiale Zhi ([email protected])
-----------------------------------------------------------------
local cjson = require("cjson")
local encode = cjson.encode
local util = require "capnp.util"
local insert = table.insert
local concat = table.concat
local format = string.format
local lower = string.lower
local gsub = string.gsub
local sub = string.sub
local debug = false
local NOT_UNION = 65535
local _M = {}
local missing_enums = {}
local config = {
default_naming_func = util.lower_underscore_naming,
default_enum_naming_func = util.upper_underscore_naming,
}
function _M.set_debug(_debug)
debug = _debug
end
function dbg(...)
if not debug then
return
end
print(...)
end
function dbgf(...)
if not debug then
return
end
print(format(...))
end
function get_schema_text(file)
local f = io.open(file)
if not f then
return nil, "Can't open file: " .. tostring(file)
end
local s = f:read("*a")
f:close()
s = string.gsub(s, "%(", "{")
s = string.gsub(s, "%)", "}")
s = string.gsub(s, "%[", "{")
s = string.gsub(s, "%]", "}")
s = string.gsub(s, "%<", "\"")
s = string.gsub(s, "%>", "\"")
s = string.gsub(s, "id = (%d+)", "id = \"%1\"")
s = string.gsub(s, "typeId = (%d+)", "typeId = \"%1\"")
s = string.gsub(s, "void", "\"void\"")
return "return " .. s
end
function comp_header(res, nodes)
dbg("compile_headers")
insert(res, format([[
-- Generated by lua-capnproto %s on %s
-- https://github.com/cloudflare/lua-capnproto.git
]], config.version, os.date()))
insert(res, format([[
local ffi = require "ffi"
local capnp = require "capnp"
local bit = require "bit"
local ceil = math.ceil
local write_struct_field= capnp.write_struct_field
local read_struct_field = capnp.read_struct_field
local read_text = capnp.read_text
local write_text = capnp.write_text
local get_enum_val = capnp.get_enum_val
local get_enum_name = capnp.get_enum_name
local get_data_off = capnp.get_data_off
local write_listp_buf = capnp.write_listp_buf
local write_structp_buf = capnp.write_structp_buf
local write_structp = capnp.write_structp
local read_struct_buf = capnp.read_struct_buf
local read_listp_struct = capnp.read_listp_struct
local read_list_data = capnp.read_list_data
local write_list = capnp.write_list
local write_list_data = capnp.write_list_data
local ffi_new = ffi.new
local ffi_string = ffi.string
local ffi_cast = ffi.cast
local ffi_copy = ffi.copy
local ffi_fill = ffi.fill
local ffi_typeof = ffi.typeof
local band, bor, bxor = bit.band, bit.bor, bit.bxor
local pint8 = ffi_typeof("int8_t *")
local pint16 = ffi_typeof("int16_t *")
local pint32 = ffi_typeof("int32_t *")
local pint64 = ffi_typeof("int64_t *")
local puint8 = ffi_typeof("uint8_t *")
local puint16 = ffi_typeof("uint16_t *")
local puint32 = ffi_typeof("uint32_t *")
local puint64 = ffi_typeof("uint64_t *")
local pbool = ffi_typeof("uint8_t *")
local pfloat32 = ffi_typeof("float *")
local pfloat64 = ffi_typeof("double *")
local ok, new_tab = pcall(require, "table.new")
if not ok then
new_tab = function (narr, nrec) return {} end
end
local round8 = function(size)
return ceil(size / 8) * 8
end
local str_buf
local default_segment_size = 4096
local function get_str_buf(size)
if size > default_segment_size then
return ffi_new("char[?]", size)
end
if not str_buf then
str_buf = ffi_new("char[?]", default_segment_size)
end
return str_buf
end
-- Estimated from #nodes, not accurate
local _M = new_tab(0, %d)
]], #nodes))
end
function get_name(display_name)
local n = string.find(display_name, ":")
return string.sub(display_name, n + 1)
end
--- @see http://kentonv.github.io/_Mroto/encoding.html#lists
local list_size_map = {
[0] = 0,
[1] = 0.125,
[2] = 1,
[3] = 2,
[4] = 4,
[5] = 8,
[6] = 8,
-- 7 = ?,
}
local size_map = {
void = 0,
bool = 1,
int8 = 8,
int16 = 16,
int32 = 32,
int64 = 64,
uint8 = 8,
uint16 = 16,
uint32 = 32,
uint64 = 64,
float32 = 32,
float64 = 64,
text = "2", -- list(uint8)
data = "2",
list = 2, -- size: list item size id, not actual size
struct = 8, -- struct pointer
enum = 16,
object = 8, -- FIXME object is a pointer ?
anyPointer = 8, -- FIXME object is a pointer ?
group = 0, -- TODO
}
local check_type = {
struct = 'type(value) == "table"',
group = 'type(value) == "table"',
enum = 'type(value) == "string" or type(value) == "number"',
list = 'type(value) == "table"',
text = 'type(value) == "string"',
data = 'type(value) == "string"',
}
function get_size(type_name)
local size = size_map[type_name]
if not size then
error("Unknown type_name:" .. type_name)
end
return size
end
function _set_field_default(nodes, field, slot)
local default
if slot.defaultValue
and field.type_name ~= "object"
and field.type_name ~= "anyPointer"
then
for k, v in pairs(slot.defaultValue) do
if field.type_name == "bool" then
field.print_default_value = v and 1 or 0
field.default_value = field.print_default_value
elseif field.type_name == "text" or field.type_name == "data" then
field.print_default_value = '"' .. v .. '"'
field.default_value = field.print_default_value
elseif field.type_name == "struct" or field.type_name == "list"
or field.type_name == "object"
or field.type_name == "anyPointer"
then
field.print_default_value = '"' .. v .. '"'
elseif field.type_name == "void" then
field.print_default_value = "\"Void\""
field.default_value = field.print_default_value
elseif field.type_name == "enum" then
local enum = assert(nodes[slot["type"].enum.typeId].enum)
field.print_default_value = '"' .. enum.enumerants[v + 1].name
.. '"'
field.default_value = v
else
field.print_default_value = v
field.default_value = field.print_default_value
end
break
end
dbgf("[%s] %s.print_default_value=%s", field.type_name, field.name,
field.print_default_value)
end
if not field.default_value then
field.default_value = "Nil"
end
if not field.print_default_value then
field.print_default_value = "Nil"
end
end
function _get_type(type_field)
local type_name
for k, v in pairs(type_field) do
type_name = k
break
end
return type_name
end
function _set_field_type(field, slot, nodes)
local type_name
if field.group then
field.type_name = "group"
field.type_display_name = get_name(
nodes[field.group.typeId].displayName)
else
for k, v in pairs(slot["type"]) do
type_name = k
if type_name == "struct" then
field.type_display_name = get_name(nodes[v.typeId].displayName)
elseif type_name == "enum" then
field.enum_id = v.typeId
field.type_display_name = get_name(nodes[v.typeId].displayName)
elseif type_name == "list" then
local list_type
for k, v in pairs(field.slot["type"].list.elementType) do
list_type = k
if list_type == "struct" then
field.type_display_name = get_name(
nodes[v.typeId].displayName)
end
break
end
field.element_type = list_type
else
-- default = v
end
field.type_name = type_name
--field.default = default
break
end
end
dbgf("field %s.type_name = %s", field.name, field.type_name)
assert(field.type_name)
end
function comp_field(res, nodes, field)
dbg("comp_field")
local slot = field.slot
if not slot then
slot = {}
field.slot = slot
end
if not slot.offset then
slot.offset = 0
end
field.name = config.default_naming_func(field.name)
_set_field_type(field, slot, nodes)
_set_field_default(nodes, field, slot)
-- print("default:", field.name, field.default_value)
if not field.type_name then
field.type_name = "void"
field.size = 0
else
field.size = get_size(field.type_name)
end
end
local function process_list_type(list_type, nodes)
-- first one is not element type, so remove it
--table.remove(list_type, 1)
if list_type[#list_type - 1] == "struct" then
local id = list_type[#list_type]
local struct_name = get_name(nodes[id].displayName)
for i=1, #list_type - 1 do
list_type[i] = '"' .. list_type[i] .. '"'
end
list_type[#list_type] = "_M." .. struct_name
else
for i, v in ipairs(list_type) do
list_type[i] = '"' .. v .. '"'
end
end
end
function comp_parse_struct_data(res, nodes, struct, fields, size, name)
insert(res, format([[
parse_struct_data = function(p32, data_word_count, pointer_count, header,
tab)
local s = tab
]], size))
if struct.discriminantCount and struct.discriminantCount > 0 then
insert(res, format([[
local dscrm = _M.%s.which(p32, %d)]], name, struct.discriminantOffset))
end
for i, field in ipairs(fields) do
if field.discriminantValue and field.discriminantValue ~= NOT_UNION then
insert(res, format([[
-- union
if dscrm == %d then
]],field.discriminantValue))
end
if field.group then
insert(res, format([[
-- group
if not s["%s"] then
s["%s"] = new_tab(0, 4)
end
_M.%s["%s"].parse_struct_data(p32, _M.%s.dataWordCount,
_M.%s.pointerCount, header, s["%s"])
]], field.name, field.name, name, field.name, name, name, field.name))
elseif field.type_name == "enum" then
insert(res, format([[
-- enum
local val = read_struct_field(p32, "uint16", %d, %d)
s["%s"] = get_enum_name(val, %d, _M.%sStr)
]], field.size, field.slot.offset, field.name, field.default_value,
field.type_display_name))
elseif field.type_name == "list" then
local off = field.slot.offset
local list_type = util.get_field_type(field)
table.remove(list_type, 1)
process_list_type(list_type, nodes)
local types = concat(list_type, ", ")
insert(res, format([[
-- list
local off, size, num = read_listp_struct(p32, header, _M.%s, %d)
if off and num then
-- dataWordCount + offset + pointerSize + off
s["%s"] = read_list_data(p32 + (%d + %d + 1 + off) * 2, header,
num, %s)
else
s["%s"] = nil
end
]], name, off, field.name, struct.dataWordCount, off, types, field.name))
elseif field.type_name == "struct" then
local off = field.slot.offset
insert(res, format([[
-- struct
local p = p32 + (%d + %d) * 2 -- p32, dataWordCount, offset
local off, dw, pw = read_struct_buf(p, header)
if off and dw and pw then
if not s["%s"] then
s["%s"] = new_tab(0, 2)
end
_M.%s.parse_struct_data(p + 2 + off * 2, dw, pw, header, s["%s"])
else
s["%s"] = nil
end
]], struct.dataWordCount, off, field.name, field.name, field.type_display_name,
field.name, field.name))
elseif field.type_name == "text" then
local off = field.slot.offset
insert(res, format([[
-- text
local off, size, num = read_listp_struct(p32, header, _M.%s, %d)
if off and num then
-- dataWordCount + offset + pointerSize + off
local p8 = ffi_cast(pint8, p32 + (%d + %d + 1 + off) * 2)
s["%s"] = ffi_string(p8, num - 1)
else
s["%s"] = nil
end
]], name, off, struct.dataWordCount, off, field.name, field.name))
elseif field.type_name == "data" then
local off = field.slot.offset
insert(res, format([[
-- data
local off, size, num = read_listp_struct(p32, header, _M.%s, %d)
if off and num then
-- dataWordCount + offset + pointerSize + off
local p8 = ffi_cast(pint8, p32 + (%d + %d + 1 + off) * 2)
s["%s"] = ffi_string(p8, num)
else
s["%s"] = nil
end
]], name, off, struct.dataWordCount, off, field.name, field.name))
elseif field.type_name == "anyPointer" then
-- TODO support anyPointer
elseif field.type_name == "void" then
insert(res, format([[
s["%s"] = "Void"]], field.name))
else
local default = field.default_value and field.default_value or "nil"
insert(res, format([[
s["%s"] = read_struct_field(p32, "%s", %d, %d, %s)
]], field.name, field.type_name, field.size, field.slot.offset, default))
end
if field.discriminantValue and field.discriminantValue ~= NOT_UNION then
insert(res, format([[
else
s["%s"] = nil
end
]],field.name))
end
end
insert(res, [[
return s
end,
]])
end
function comp_parse(res, name)
insert(res, format([[
parse = function(bin, tab)
if #bin < 16 then
return nil, "message too short"
end
local header = new_tab(0, 4)
local p32 = ffi_cast(puint32, bin)
header.base = p32
local nsegs = p32[0] + 1
header.seg_sizes = {}
for i=1, nsegs do
header.seg_sizes[i] = p32[i]
end
local pos = round8(4 + nsegs * 4)
header.header_size = pos / 8
p32 = p32 + pos / 4
if not tab then
tab = new_tab(0, 8)
end
local off, dw, pw = read_struct_buf(p32, header)
if off and dw and pw then
return _M.%s.parse_struct_data(p32 + 2 + off * 2, dw, pw,
header, tab)
else
return nil
end
end,
]], name))
end
function comp_serialize(res, name)
insert(res, format([[
serialize = function(data, p8, size)
if not p8 then
size = _M.%s.calc_size(data)
p8 = get_str_buf(size)
end
ffi_fill(p8, size)
local p32 = ffi_cast(puint32, p8)
-- Because needed size has been calculated, only 1 segment is needed
p32[0] = 0
p32[1] = (size - 8) / 8
-- skip header
write_structp(p32 + 2, _M.%s, 0)
-- skip header & struct pointer
_M.%s.flat_serialize(data, p32 + 4)
return ffi_string(p8, size)
end,
]], name, name, name))
end
function comp_flat_serialize(res, nodes, struct, fields, size, name)
dbgf("comp_flat_serialize")
insert(res, format([[
flat_serialize = function(data, p32, pos)
pos = pos and pos or %d -- struct size in bytes
local start = pos
local dscrm]], size))
insert(res, [[
local value]])
for i, field in ipairs(fields) do
insert(res, format([=[
value = data["%s"]]=], field.name))
--print("comp_field", field.name)
-- union
if field.discriminantValue and field.discriminantValue ~= NOT_UNION then
dbgf("field %s: union", field.name)
insert(res, format([[
if value then
dscrm = %d
end
]], field.discriminantValue))
end
if field.group then
dbgf("field %s: group", field.name)
-- group size is the same as the struct, so we can use "size" to
-- represent group size
insert(res, format([[
if ]] .. check_type["group"] .. [[ then
-- groups are just namespaces, field offsets are set within parent
-- structs
pos = pos + _M.%s.%s.flat_serialize(value, p32, pos) - %d
end
]], name, field.name, size))
elseif field.type_name == "enum" then
dbgf("field %s: enum", field.name)
insert(res, format([[
if ]] .. check_type["enum"] .. [[ then
local val = get_enum_val(value, %d, _M.%s, "%s.%s")
write_struct_field(p32, val, "uint16", %d, %d)
end]], field.default_value, field.type_display_name, name,
field.name, field.size, field.slot.offset))
elseif field.type_name == "list" then
dbgf("field %s: list", field.name)
local off = field.slot.offset
local list_type = util.get_field_type(field)
-- nested list
if #list_type > 1 then
-- composite
if list_type[#list_type -1] == "struct" then
field.size = 7
else
-- pointer
field.size = 6
end
end
process_list_type(list_type, nodes)
local types = concat(list_type, ", ")
insert(res, format([[
if ]] .. check_type["list"] .. [[ then
local data_off = get_data_off(_M.%s, %d, pos)
pos = pos + write_list(p32 + _M.%s.dataWordCount * 2 + %d * 2,
value, (data_off + 1) * 8, %s)
end]], name, off, name, off, types))
elseif field.type_name == "struct" then
dbgf("field %s: struct", field.name)
local off = field.slot.offset
insert(res, format([[
if ]] .. check_type["struct"] .. [[ then
local data_off = get_data_off(_M.%s, %d, pos)
write_structp_buf(p32, _M.%s, _M.%s, %d, data_off)
local size = _M.%s.flat_serialize(value, p32 + pos / 4)
pos = pos + size
end]], name, off, name, field.type_display_name,
off, field.type_display_name))
elseif field.type_name == "text" then
dbgf("field %s: text", field.name)
local off = field.slot.offset
insert(res, format([[
if ]] .. check_type["text"] .. [[ then
local data_off = get_data_off(_M.%s, %d, pos)
local len = #value + 1
write_listp_buf(p32, _M.%s, %d, %d, len, data_off)
ffi_copy(p32 + pos / 4, value)
pos = pos + round8(len)
end]], name, off, name, off, 2))
elseif field.type_name == "data" then
dbgf("field %s: data", field.name)
local off = field.slot.offset
insert(res, format([[
if ]] .. check_type["data"] .. [[ then
local data_off = get_data_off(_M.%s, %d, pos)
local len = #value
write_listp_buf(p32, _M.%s, %d, %d, len, data_off)
-- prevent copying trailing '\0'
ffi_copy(p32 + pos / 4, value, len)
pos = pos + round8(len)
end]], name, off, name, off, 2))
else
dbgf("field %s: %s", field.name, field.type_name)
local default = field.default_value and field.default_value or "nil"
local cdata_condition = ""
if field.type_name == "uint64" or field.type_name == "int64" then
cdata_condition = 'or data_type == "cdata"'
end
if field.type_name ~= "void" then
insert(res, format([[
local data_type = type(value)
if (data_type == "number"
or data_type == "boolean" %s) then
write_struct_field(p32, value, "%s", %d, %d, %s)
end]], cdata_condition, field.type_name, field.size,
field.slot.offset, default))
end
end
end
if struct.discriminantCount and struct.discriminantCount ~= 0 then
insert(res, format([[
if dscrm then
--buf, discriminantOffset, discriminantValue
_M.%s.which(p32, %d, dscrm)
end
]], name, struct.discriminantOffset))
end
insert(res, format([[
return pos - start + %d
end,
]], size))
end
-- insert a list with indent level
function insertlt(res, level, data_table)
for i, v in ipairs(data_table) do
insertl(res, level, v)
end
end
-- insert with indent level
function insertl(res, level, data)
for i=1, level * 4 do
insert(res, " ")
end
insert(res, data)
end
function _M.comp_calc_list_size(res, field, nodes, name, level, elm_type, ...)
if not elm_type then
return
end
insertl(res, level, format("if data[\"%s\"] and " ..
"type(data[\"%s\"]) == \"table\" then\n", name, name))
if elm_type == "object" or elm_type == "anyPointer"
or elm_type == "group" then
error("List of object/anyPointer/group type is not supported yet.")
end
if elm_type ~= "struct" and elm_type ~= "list" and elm_type ~= "data"
and elm_type ~= "text" then
-- elm_type is a plain type.
local elm_size = get_size(elm_type) / 8
insertlt(res, level + 1, {
"-- num * acutal size\n",
format("size = size + round8(#data[\"%s\"] * %d)\n",
name, elm_size)
})
else
-- struct tag
if elm_type == "struct" then
insertl(res, level + 1, format("size = size + 8\n", name))
end
local new_name = "[\"" .. name .. "\"]" .. "[i" .. level .. "]"
-- calculate body size
insertl(res, level + 1, format("local num%d = #data[\"%s\"]\n",
level, name))
insertl(res, level + 1, format("for %s=1, num%d do\n",
"i" .. level, level))
if elm_type == "list" then
insertl(res, level + 2, format("size = size + 8\n", name))
_M.comp_calc_list_size(res, field, nodes, new_name, level + 2, ...)
elseif elm_type == "text" then
insertl(res, level + 2, format("size = size + 8\n", name))
insertlt(res, level + 2, {
" -- num * acutal size\n",
format("size = size + round8(#data%s * 1 + 1)\n", new_name)
})
elseif elm_type == "data" then
insertl(res, level + 2, format("size = size + 8\n", name))
insertlt(res, level + 2, {
" -- num * acutal size\n",
format("size = size + round8(#data%s * 1)\n", new_name)
})
elseif elm_type == "struct" then
local id = ...
local struct_name = get_name(nodes[id].displayName)
insertl(res, level + 2, format(
"size = size + _M.%s.calc_size_struct(data%s)\n",
struct_name, new_name))
end
insertl(res, level + 1, "end\n")
end
insertl(res, level, "end")
end
function comp_calc_size(res, fields, size, name, nodes, is_group)
dbgf("comp_calc_size")
if is_group then
size = 0
end
insert(res, format([[
calc_size_struct = function(data)
local size = %d]], size))
insert(res, [[
local value]])
for i, field in ipairs(fields) do
dbgf("field %s is %s", field.name, field.type_name)
if field.type_name == "list" then
local list_type = util.get_field_type(field)
insert(res, "\n")
-- list_type[1] must be "list" and should be skipped because is
-- is not element type
insert(res, " -- list\n")
_M.comp_calc_list_size(res, field, nodes, field.name, 2,
select(2, unpack(list_type)))
elseif field.type_name == "struct" or field.type_name == "group" then
insert(res, format([[
-- struct
value = data["%s"]
if ]] .. check_type["struct"] .. [[ then
size = size + _M.%s.calc_size_struct(value)
end]], field.name, field.type_display_name))
elseif field.type_name == "text" then
insert(res, format([[
-- text
value = data["%s"]
if ]] .. check_type["text"] .. [[ then
-- size 1, including trailing NULL
size = size + round8(#value + 1)
end]], field.name))
elseif field.type_name == "data" then
insert(res, format([[
-- data
value = data["%s"]
if ]] .. check_type["data"] .. [[ then
size = size + round8(#value)
end]], field.name))
end
end
insert(res, format([[
return size
end,
calc_size = function(data)
local size = 16 -- header + root struct pointer
return size + _M.%s.calc_size_struct(data)
end,
]], name))
end
function comp_which(res)
insert(res, [[
which = function(buf, offset, n)
if n then
-- set value
write_struct_field(buf, n, "uint16", 16, offset)
else
-- get value
return read_struct_field(buf, "uint16", 16, offset)
end
end,
]])
end
function comp_fields(res, nodes, node, struct)
insert(res, [[
fields = {
]])
for i, field in ipairs(struct.fields) do
comp_field(res, nodes, field)
if field.group then
if not node.nestedNodes then
node.nestedNodes = {}
end
insert(node.nestedNodes,
{ name = field.name, id = field.group.typeId })
end
insert(res, format([[
{ name = "%s", default = %s, ["type"] = "%s" },
]], field.name, field.print_default_value, field.type_name))
end
dbg("struct:", name)
insert(res, format([[
},
]]))
end
function comp_struct(res, nodes, node, struct, name)
if not struct.dataWordCount then
struct.dataWordCount = 0
end
if not struct.pointerCount then
struct.pointerCount = 0
end
insert(res, " dataWordCount = ")
insert(res, struct.dataWordCount)
insert(res, ",\n")
insert(res, " pointerCount = ")
insert(res, struct.pointerCount)
insert(res, ",\n")
if struct.discriminantCount then
insert(res, " discriminantCount = ")
insert(res, struct.discriminantCount)
insert(res, ",\n")
end
if struct.discriminantOffset then
insert(res, " discriminantOffset = ")
insert(res, struct.discriminantOffset)
insert(res, ",\n")
end
if struct.isGroup then
insert(res, " isGroup = true,\n")
end
insert(res, " field_count = ")
insert(res, #struct.fields)
insert(res, ",\n")
struct.size = struct.dataWordCount * 8 + struct.pointerCount * 8
if struct.fields then
comp_fields(res, nodes, node, struct)
--if not struct.isGroup then
--end
comp_calc_size(res, struct.fields, struct.size,
struct.type_name, nodes, struct.isGroup)
comp_flat_serialize(res, nodes, struct, struct.fields, struct.size,
struct.type_name)
if not struct.isGroup then
comp_serialize(res, struct.type_name)
end
if struct.discriminantCount and struct.discriminantCount > 0 then
comp_which(res)
end
comp_parse_struct_data(res, nodes, struct, struct.fields,
struct.size, struct.type_name)
if not struct.isGroup then
comp_parse(res, struct.type_name)
end
end
end
function comp_enum(res, nodes, enum, name, enum_naming_func)
if not enum_naming_func then
enum_naming_func = config.default_enum_naming_func
end
-- string to enum
insert(res, format([[
_M.%s = {
]], name))
for i, v in ipairs(enum.enumerants) do
-- inherent parent naming function
v.naming_func = enum_naming_func
if not v.codeOrder then
v.codeOrder = 0
end
if v.annotations then
local anno_res = {}
dbgf("%s annotations: %s", name, cjson.encode(v.annotations))
process_annotations(v.annotations, nodes)
for i, anno in ipairs(v.annotations) do
if anno.name == "naming" then
v.naming_func = get_naming_func(anno.value)
dbgf("Naming function: %s", anno.value)
if not v.naming_func then
error("Unknown naming annotation: " .. anno.value)
end
elseif anno.name == "literal" then
dbgf("enumerant literal: %s", anno.value)
v.literal = anno.value
end
end
end
-- literal has higher priority
if v.literal then
insert(res, format(" [\"%s\"] = %s,\n",
v.literal, v.codeOrder))
else
insert(res, format(" [\"%s\"] = %s,\n",
v.naming_func(v.name), v.codeOrder))
end
end
insert(res, "\n}\n")
-- enum to string
insert(res, format([[
_M.%sStr = {
]], name))
for i, v in ipairs(enum.enumerants) do
if not v.codeOrder then
v.codeOrder = 0
end
if v.literal then
insert(res, format(" [%s] = \"%s\",\n",
v.codeOrder, v.literal))
else
insert(res, format(" [%s] = \"%s\",\n",
v.codeOrder, v.naming_func(v.name)))
end
end
insert(res, "\n}\n")
end
_M.naming_funcs = {
upper_dash = util.upper_dash_naming,
lower_underscore = util.lower_underscore_naming,
upper_underscore = util.upper_underscore_naming,
camel = util.camel_naming,
lower_space = util.lower_space_naming,
}
function process_annotations(annos, nodes)
dbg("process_annotations:" .. encode(annos))
for i, anno in ipairs(annos) do
local id = anno.id
anno.name = get_name(nodes[id].displayName)
anno.value_saved = anno.value
assert(type(anno.value_saved) == "table", 'expected "table" but got "'
.. type(anno.value_saved) .. "\": " .. tostring(anno.value_saved))
for k, v in pairs(anno.value_saved) do
anno["type"] = k
anno["value"] = v
break
end
anno.value_saved = nil
end
end
function get_naming_func(name)
local func = _M.naming_funcs[name]
if not func then
error("unknown naming: " .. tostring(name))
end
return func
end
function comp_node(res, nodes, node, name)
dbgf("comp_node: %s, %s", name, node.id)
if not node then
print("Ignore node: ", name)
return
end
if node.annotation then
-- do not need to generation any code for annotations
return
end
node.name = name
node.type_name = get_name(node.displayName)
local s = node.struct
if s then
insert(res, format([[
_M.%s = {
]], name))
s.type_name = node.type_name
insert(res, format([[
id = "%s",
displayName = "%s",
]], node.id, node.displayName))
comp_struct(res, nodes, node, s, name)
insert(res, "\n}\n")
end
local e = node.enum
if e then
local anno_res = {}
if node.annotations then
process_annotations(node.annotations, nodes)
end
local naming_func
if node.annotations then
for i, anno in ipairs(node.annotations) do
if anno.name == "naming" then
naming_func = get_naming_func(anno.value)
end
break
end
end
comp_enum(res, nodes, e, name, naming_func)
end
if node.const then
dbgf("compile const: %s", name)
local const = node.const
local const_type = _get_type(const["type"])
if const_type == "text" or const_type == "data" or const_type == "void"
or const_type == "list" or const_type == "struct"
or const_type == "enum" or const_type == "group"
or const_type == "anyPointer"
then
insert(res, format([[
_M.%s = "%s"
]], name, const.value[const_type]))
else
insert(res, format([[
_M.%s = %s
]], name, const.value[const_type]))
end
end
if node.nestedNodes then
for i, child in ipairs(node.nestedNodes) do
comp_node(res, nodes, nodes[child.id], name .. "." .. child.name)
end
end
end
function comp_body(res, schema)
dbg("comp_body")
local nodes = schema.nodes
for i, v in ipairs(nodes) do
nodes[v.id] = v
end
local files = schema.requestedFiles
for i, file in ipairs(files) do
comp_file(res, nodes, file)
local imports = file.imports
for i, import in ipairs(imports) do
--import node are compiled later by comp_file
--comp_import(res, nodes, import)
check_import(files, import)
end
end
for k, v in pairs(missing_enums) do
insert(res, k .. ".enum_schema = _M." ..
get_name(nodes[v].displayName .. "\n"))
end
insert(res, "\nreturn _M\n")
end
function check_import(files, import)
local id = import.id
local name = import.name
for i, file in ipairs(files) do
if file.id == id then
return true
end
end
error('imported file "' .. name .. '" is missing, compile it together with'
.. 'other Cap\'n Proto files')
end
function comp_import(res, nodes, import)
local id = import.id
dbgf("comp_import: %s", id)
local import_node = nodes[id]
for i, node in ipairs(import_node.nestedNodes) do
comp_node(res, nodes, nodes[node.id], node.name)
end
end
function comp_file(res, nodes, file)
dbg("comp_file")
local id = file.id
local file_node = nodes[id]
for i, node in ipairs(file_node.nestedNodes) do
comp_node(res, nodes, nodes[node.id], node.name)
end
end
function comp_dg_node(res, nodes, node)
if not node.struct then
return
end
local name = gsub(lower(node.name), "%.", "_")
insert(res, format([[
function gen_%s()
if rand.random_nil() then
return nil
end
]], name))
if node.nestedNodes then
for i, child in ipairs(node.nestedNodes) do
comp_dg_node(res, nodes, nodes[child.id])
end
end
insert(res, format(" local %s = {}\n", name))
for i, field in ipairs(node.struct.fields) do
if field.group then
-- TODO group stuffs
elseif field.type_name == "struct" then
insert(res, format(" %s.%s = gen_%s()\n", name,
field.name,
gsub(lower(field.type_display_name), "%.", "_")))
elseif field.type_name == "enum" then
elseif field.type_name == "list" then
local list_type = field.element_type
insert(res, format([[
%s["%s"] = rand.%s(rand.uint8(), rand.%s)]], name,
field.name, field.type_name, list_type))
else
insert(res, format(' %s["%s"] = rand.%s()\n', name,
field.name, field.type_name))
end
end
insert(res, format([[
return %s
end
]], name))
end
function _M.compile_data_generator(schema)
local res = {}
insert(res, [[
local rand = require("random")
local cjson = require("cjson")
local pairs = pairs
local ok, new_tab = pcall(require, "table.new")
if not ok then
new_tab = function (narr, nrec) return {} end
end
module(...)
]])
local files = schema.requestedFiles
local nodes = schema.nodes
for i, file in ipairs(files) do
local file_node = nodes[file.id]
for i, node in ipairs(file_node.nestedNodes) do
comp_dg_node(res, nodes, nodes[node.id])
end
end
return table.concat(res)
end
function _M.compile(schema)
local res = {}
comp_header(res, schema.nodes)
comp_body(res, schema)
return table.concat(res)
end
function _M.init(user_conf)
dbg("set config init")
for k, v in pairs(user_conf) do
--if not config[k] then
-- print(format("Unknown user config: %s, ignored.", k))
--end
config[k] = v
dbg("set config " .. k)
end
end
return _M
|
-- - - - - - - - - - - - - - - - - - - - -
-- first, reset the global SL table to default values
-- this is defined in: ./Scripts/SL_Init.lua
InitializeSimplyLove()
--GAMESTATE:UpdateDiscordMenu("Title Menu: Simply "..ThemePrefs.Get("VisualStyle"))
if ThemePrefs.Get("VisualStyle") == "SRPG6" then
SL.SRPG6:MaybeRandomizeColor()
end
-- -----------------------------------------------------------------------
-- preliminary Lua setup is done
-- now define actors to be passed back to the SM engine
ThemePrefs.Set("isGoodReads",false)
local af = Def.ActorFrame{}
af.InitCommand=function(self) self:Center() end
-- IsSpooky() will be true during October if EasterEggs are enabled
-- this is the content found in ./Graphics/_VisualStyles/Spooky/ExtraSpooky
-- it needs to be layered appropriately, some assets behind, some in front
-- Spooky.lua includes a quad that fades the screen to black and the glowing pumpkin that remains
-- SpookyButFadeOut.lua includes cobwebs in the upper-right and upper-left
if IsSpooky() then
af[#af+1] = LoadActor("./Spooky.lua")
end
-- -----------------------------------------------------------------------
-- af2 contains things that should fade out during the OffCommand
local af2 = Def.ActorFrame{}
af2.OffCommand=function(self) self:smooth(0.65):diffusealpha(0) end
af2.Name="SLInfo"
-- the big blocky Wendy text that says SIMPLY LOVE (or SIMPLY THONK, or SIMPLY DUCKS, etc.)
-- and the arrows graphic that appears between the two words
af2[#af2+1] = LoadActor("./Logo.lua")
-- 3 lines of text:
-- theme_name theme_version
-- stepmania_version
-- num_songs in num_groups, num_courses
af2[#af2+1] = LoadActor("./UserContentText.lua")
-- "The chills, I have them down my spine."
if IsSpooky() then
af2[#af2+1] = LoadActor("./SpookyButFadeOut.lua")
end
-- the best way to spread holiday cheer is singing loud for all to hear
if HolidayCheer() then
af2[#af2+1] = Def.Sprite{
Texture=THEME:GetPathB("ScreenTitleMenu", "underlay/hat.png"),
InitCommand=function(self) self:zoom(0.225):xy( 130, -self:GetHeight()/2 ):rotationz(15):queuecommand("Drop") end,
DropCommand=function(self) self:decelerate(1.333):y(-110) end,
}
end
-- ensure that af2 is added as a child of af
af[#af+1] = af2
-- -----------------------------------------------------------------------
return af
|
--[[
The Vapour registry, as its name implies is used to register 'vapour'-ized recipes.
The vapour in question is treated as a normal fluid, so register it there first.
Note currently vapour > fluid is a 1:1 mapping, both back and forth, this may change in the future, if I feel so inclined.
]]
local VapourRegistry = foundation.com.Class:extends("VapourRegistry")
local ic = VapourRegistry.instance_class
function ic:initialize()
ic._super.initialize(self)
self.m_fluid_name_to_recipe = {}
self.m_vapour_name_to_recipe = {}
end
function ic:register_vapour(fluid_name, vapour_name, data)
local recipe = {
vapour_name = vapour_name,
fluid_name = fluid_name,
data = data or {}
}
self.m_fluid_name_to_recipe[fluid_name] = recipe
self.m_vapour_name_to_recipe[vapour_name] = recipe
return self
end
function ic:find_recipe_for_fluid(fluid_name)
return self.m_fluid_name_to_recipe[fluid_name]
end
yatm_refinery.VapourRegistry = VapourRegistry
|
--!NEEDS:luac_loader.lua
local debug=false
local codeName={
"MOVE",
"LOADK",
"LOADBOOL",
"LOADNIL",
"GETUPVAL",
"GETGLOBAL",
"GETTABLE",
"SETGLOBAL",
"SETUPVAL",
"SETTABLE",
"NEWTABLE",
"SELF",
"ADD",
"SUB",
"MUL",
"DIV",
"MOD",
"POW",
"BOR",
"BAND",
"OP_BXOR",
"BLSHFT",
"BRSHFT",
"BNOT",
"INTDIV",
"UNM",
"NOT",
"LEN",
"CONCAT",
"JMP",
"EQ",
"LT",
"LE",
"TEST",
"TESTSET",
"CALL",
"TAILCALL",
"RETURN",
"FORLOOP",
"FORPREP",
"TFORLOOP",
"SETLIST",
"CLOSE",
"CLOSURE",
"VARARG",
"MAX",
"MIN",
"DEG",
"RAD",
"ADD_EQ",
"SUB_EQ",
"MUL_EQ",
"DIV_EQ",
"MOD_EQ",
"POW_EQ",
}
--UNSUPPORTED: GETUPVAL,SETUPVAL,NEWTABLE,SETTABLE,SELF
local function mprint(...)
if debug then print(...) end
end
local function KStr(k)
if type(k)=="table" then
if k[1]=="double" then
return k[2]
end
end
return tostring(k)
end
local function RKStr(f,i)
if (i&0x100)>0 then
return KStr(f.k[i&0xFF+1])
else
return "$"..i
end
end
local function numvalue(n)
n=tostring(n)
if (n:find("%.")) then return n end
return n..".0"
end
local function KVal(f,i)
local k=f.k[i+1]
assert((type(k)=="table")and(k[1]=="double"),"Only numbers are allowed")
return { type="val",value=numvalue(k[2]),vtype="hF1" }
end
local function KRVal(f,i)
if (i&0x100)>0 then
local k=f.k[i&0xFF+1]
assert((type(k)=="table")and(k[1]=="double"),"Only numbers are allowed")
return { type="val",value=numvalue(k[2]),vtype="hF1" }
else
return f._l[i]
end
end
local function outcode(f,s)
--print("C:",s)
f._c=f._c..s
end
local function mapGlobal(f,sym)
assert(f._g[sym],"Unknown global "..sym)
return f._g[sym]
end
local ivar=1
local ccvar=1
local function ensureLocalVar(f,v,r)
--print("LOCAL:"..v)
if (f._l[v] and f._l[v].type=="var" and f._l[v].vtype==r) then return end
local vname="_GID_Local_"..ivar
ivar+=1
assert(f._t[r],"Unknown type '"..r.."'")
f._hc=f._hc..f._t[r].." "..vname..";\n"
if (f._l[v] and f._l[v].type=="val" and f._l[v].vtype==r) then
outcode(f,vname.."="..f._l[v].value..";\n")
end
f._l[v]={type="var",value=vname,vtype=r}
end
function gen_GETUPVAL(is,f,a,b,c,bc)
assert(false,"Upvalues aren't supported")
end
function gen_SETUPVAL(is,f,a,b,c,bc)
assert(false,"Upvalues aren't supported")
end
function gen_GETGLOBAL(is,f,a,b,c,bc)
mprint("$"..a.."=_G["..KStr(f.k[bc+1]).."]")
f._l[a]=mapGlobal(f,KStr(f.k[bc+1]))
end
local function genfunc(f,fg)
if fg.type=="func" and fg.funcnum and f.p[fg.funcnum] then
fg._fcode=f.p[fg.funcnum]
if f._handlers.SUBFUNC then
f._handlers.SUBFUNC(f,fg)
end
end
end
function gen_SETGLOBAL(is,f,a,b,c,bc)
mprint("_G["..KStr(f.k[bc+1]).."]=$"..a)
if f._l[a].type=="func" then
local glf=mapGlobal(f,KStr(f.k[bc+1]))
assert(glf.type=="func",glf.value.." must be a function")
assert(f._l[a].funcnum,glf.value.." must be a local function")
glf.funcnum=f._l[a].funcnum
genfunc(f,glf)
else
outcode(f,mapGlobal(f,KStr(f.k[bc+1])).value.."="..f._l[a].value..";\n")
end
end
local function checkSwizzling(var,sw)
assert(#sw>0 and #sw<=4,"Swizzling pattern size issue:"..sw)
local vecType=var.vtype:sub(1,2)
local vecSize=tonumber(var.vtype:sub(3))
assert(vecSize,"Only vectors can be swizzled: "..var.vtype.."["..sw.."]")
assert((vecType=="lF" or vecType=="hF" or vecType=="mF") and (vecSize>1) and (vecSize<=4),"Only vectors of float are supported when swizzling: "..var.vtype.."["..sw.."]")
local comps="xyrgst"
if vecSize>2 then comps=comps.."zbp" end
if vecSize>3 then comps=comps.."waq" end
assert(sw==sw:match("["..comps.."]+"),"Invalid swizzling pattern: "..sw)
return vecType..(#sw)
end
function gen_GETTABLE(is,f,a,b,c,bc)
local idx=RKStr(f,c)
mprint("$"..a.."=$"..b.."["..idx.."]")
local bv,newType
if (c&0x100)>0 then
newType=checkSwizzling(f._l[b],idx)
--UGLY, this only handle swizzling, shader specific, and don't do any checks
bv=f._l[b].value.."."..idx
else
-- Assume integer lookup
bv=f._l[b].value.."["..f._l[c].value.."]"
newType=f._l[b].vtype
end
ensureLocalVar(f,a,newType)
outcode(f,f._l[a].value.."="..bv..";\n")
--f._l[a]={type=f._l[b].type,value=f._l[b].value.."."..idx,vtype=newType}
--outcode(f,mapGlobal(f,KStr(f.k[bc+1])).value.."="..f._l[a].value..";\n")
end
function gen_SETTABLE(is,f,a,b,c,bc)
local idx=RKStr(f,b)
mprint("$"..a.."["..idx.."]".."=$"..c)
local bv,newType
assert(f._l[a].type=="var","Cannot set value of ("..f._l[a].value.."), a '"..f._l[a].type.."'")
if (b&0x100)>0 then
--UGLY, this only handle swizzling, shader specific, and don't do any checks
newType=checkSwizzling(f._l[a],idx)
--assert(f._l[a].vtype==newType,"Cannot set value of ("..f._l[a].value.."), type mismatch '"..f._l[a].vtype.."'!='"..newType.."'")
outcode(f,f._l[a].value.."."..idx.."="..KRVal(f,c).value..";\n")
else
--Assume integer index
outcode(f,f._l[a].value.."["..f._l[b].value.."]="..KRVal(f,c).value..";\n")
end
end
function gen_FORPREP(is,f,a,b,c,bc,sbc)
mprint("for ($"..a..",PC:"..sbc..")")
ensureLocalVar(f,a,f._l[a].vtype)
ensureLocalVar(f,a+3,f._l[a].vtype)
outcode(f,("for (%s=%s;%s<=%s;%s+=%s,%s=%s) {"):format(f._l[a+3].value,f._l[a].value,f._l[a].value,f._l[a+1].value,f._l[a].value,f._l[a+2].value,f._l[a+3].value,f._l[a].value))
end
function gen_FORLOOP(is,f,a,b,c,bc,sbc)
mprint("forloop ($"..a..",PC:"..sbc..")")
outcode(f,"}\n")
end
function gen_MOVE(is,f,a,b)
assert(f._l[b],"Local "..b.." not yet initialized")
mprint("$"..a.."=$"..b)
if f._l[b].type=="func" then
f._l[a]=f._l[b]
else
ensureLocalVar(f,a,f._l[b].vtype)
outcode(f,f._l[a].value.."="..f._l[b].value..";\n")
end
end
function gen_opun(is,f,a,b,op,rtype)
mprint("$"..a.."="..op..RKStr(f,b))
local vb=KRVal(f,b)
local terms=f._handlers.GENOPUN and f._handlers.GENOPUN(op,vb.value)
if not terms then
terms=op.."("..vb.value..")"
end
rtype=rtype or f._ot[op..vb.vtype] or vb.vtype
ensureLocalVar(f,a,rtype)
outcode(f,f._l[a].value.."="..terms..";\n")
end
function gen_UNM(is,f,a,b)
gen_opun(is,f,a,b,"-")
end
function gen_op(is,f,a,b,c,op,rtype)
mprint("$"..a.."="..RKStr(f,b)..op..RKStr(f,c))
local vb=KRVal(f,b)
local vc=KRVal(f,c)
local terms=f._handlers.GENOP and f._handlers.GENOP(op,vb,vc)
if not terms then
if op=="^^" then
terms="pow("..vb.value..","..vc.value..")"
else
terms="("..vb.value..op..vc.value..")"
end
end
rtype=rtype or f._ot[vb.vtype..op..vc.vtype] or vb.vtype
ensureLocalVar(f,a,rtype)
outcode(f,f._l[a].value.."="..terms..";\n")
end
function gen_MUL(is,f,a,b,c)
gen_op(is,f,a,b,c,"*")
end
function gen_DIV(is,f,a,b,c)
gen_op(is,f,a,b,c,"/")
end
function gen_ADD(is,f,a,b,c)
gen_op(is,f,a,b,c,"+")
end
function gen_SUB(is,f,a,b,c)
gen_op(is,f,a,b,c,"-")
end
function gen_MOD(is,f,a,b,c)
gen_op(is,f,a,b,c,"%")
end
function gen_POW(is,f,a,b,c)
gen_op(is,f,a,b,c,"^^")
end
function gen_opeq(is,f,a,b,op,rtype)
mprint("$"..a..op..RKStr(f,b))
local vb=KRVal(f,b)
rtype=rtype or f._ot[f._l[a].vtype..op..vb.vtype] or f._l[a].vtype
ensureLocalVar(f,a,rtype)
local terms=f._handlers.GENOPEQ and f._handlers.GENOPEQ(op,f._l[a],vb)
if not terms then
if op=="^^=" then
terms=f._l[a].value.."=pow("..f._l[a].value..","..vb.value..")"
else
terms=f._l[a].value..op..vb.value
end
end
outcode(f,terms..";\n")
end
function gen_ADD_EQ(is,f,a,b,c)
gen_opeq(is,f,a,b,"+=")
end
function gen_SUB_EQ(is,f,a,b,c)
gen_opeq(is,f,a,b,"-=")
end
function gen_MUL_EQ(is,f,a,b,c)
gen_opeq(is,f,a,b,"*=")
end
function gen_DIV_EQ(is,f,a,b,c)
gen_opeq(is,f,a,b,"/=")
end
function gen_MOD_EQ(is,f,a,b,c)
gen_opeq(is,f,a,b,"%=")
end
function gen_POW_EQ(is,f,a,b,c)
gen_opeq(is,f,a,b,"^^=")
end
local function endblock(c,f)
outcode(f,"}\n")
end
local function elseblock(c,f)
outcode(f,"} else {\n")
end
local function crossJump(f,lcs,lce)
for lc=lcs,lce do
local jis=f.code[lc]
local jcode=(jis&0x3F)()
local joff
if jcode==29 then --JMP
joff=((jis>>14)&0x3FFFF)()-131071
if joff==0 then joff=nil end
elseif jcode==2 then --LOADBOOL
local c=((jis>>14)&0x1FF)()
if c>0 then joff=1 end
end
if joff and (lc+joff)>lce then return true end
end
return false
end
local function insBreak(f,lc,brk)
f._breaks[lc]=f._breaks[lc] or {}
table.insert(f._breaks[lc],1,brk)
end
local function popBreak(f,lc)
table.remove(f._breaks[lc],1)
end
local function cond_end(f,lc,lcs)
local jis=f.code[lc-1]
local jcode=(jis&0x3F)()
local joff
if jcode==29 then --JMP
joff=((jis>>14)&0x3FFFF)()-131071
if joff==0 then joff=nil end
elseif jcode==2 then --LOADBOOL
local c=((jis>>14)&0x1FF)()
if c>0 then joff=1 end
end
local cb=endblock
f._breaks[lc]=f._breaks[lc] or {}
local condvar=false
if joff then
local jtst=(f.code[lc-2]&0x3F)()
local lce=lc-2
if jtst>=30 and jtst<=33 then lce+=1 end
--print("IF-BLK:",lcs,lce,"ELSE-BLK:",lc,lc+joff-1)
local cji,cje=crossJump(f,lcs,lce),crossJump(f,lc,lc+joff-1)
--print("IFC:",cji,"ELSE",cje)
assert(cje==false,"Complex else block found, not supported. Avoid complex conditions and 'else' clauses")
condVar=cji
if cji then
local vname="_GID_Cond_"..ccvar
ccvar+=1
f._hc=f._hc.."bool "..vname..";\n"
outcode(f,vname.."=true;\n")
insBreak(f,lcs,{ callback=function(c,f) outcode(f,vname.."=false;\n") end })
insBreak(f,lc,{ callback=function(c,f) outcode(f,"}\nif ("..vname..") {\n") end })
insBreak(f,lc+joff,{ callback=endblock })
f._elsetgt[lc]=vname
cb=nil
else
f._jignore[lc-1]=true
if f._elsetgt[lc] then
cb=function(c,f) outcode(f,"} else "..f._elsetgt[lc].."=true;\n") end
else
cb=elseblock
f._jignore[lc-1]=true
insBreak(f,lc+joff,{ callback=endblock })
end
end
end
if cb then
insBreak(f,lc,{ callback=cb })
end
return condVar
end
function gen_compop(is,f,a,b,c,op,lc)
mprint("$"..a.."(comp)"..RKStr(f,b)..op..RKStr(f,c))
local jis=f.code[lc+1]
assert((jis&0x3F)()==29,"JMP expected after a conditional")
local joff=((jis>>14)&0x3FFFF)()-131071
mprint("JMP off:",joff,lc+2+joff)
f._lc=f._lc+1
local vb=KRVal(f,b)
local vc=KRVal(f,c)
local cj=cond_end(f,lc+2+joff,lc+2)
local terms="("..vb.value..op..vc.value..")"
local abool="false" if (a>0) then abool="true" end
outcode(f,"if (("..terms..")!="..abool..") ")
if f._elsetgt[lc+2] then
outcode(f,f._elsetgt[lc+2].."=true;\n")
popBreak(f,lc+2+joff)
else
outcode(f,"{\n")
end
end
function gen_EQ(is,f,a,b,c,bc,sbc,lc)
gen_compop(is,f,a,b,c,"==",lc)
end
function gen_LT(is,f,a,b,c,bc,sbc,lc)
gen_compop(is,f,a,b,c,"<",lc)
end
function gen_LE(is,f,a,b,c,bc,sbc,lc)
gen_compop(is,f,a,b,c,"<=",lc)
end
function gen_TEST(is,f,a,b,c,bc,sbc,lc)
mprint("$(test)"..RKStr(f,a)..","..c)
local jis=f.code[lc+1]
assert((jis&0x3F)()==29,"JMP expected after a conditional")
local joff=((jis>>14)&0x3FFFF)()-131071
mprint("JMP off:",joff,lc+2+joff)
f._lc=f._lc+1
local vb=KRVal(f,a)
local abool="false" if (c>0) then abool="true" end
if vb.type=="cvar" and vb.vtype=="BOOL" then
if vb.value==abool then
f._lc=lc+2+joff
else
outcode(f,"{\n")
f._breaks[lc+2+joff]=f._breaks[lc+2+joff] or {}
table.insert(f._breaks[lc+2+joff],{ callback=endblock })
end
else
local cj=cond_end(f,lc+2+joff,lc+2)
local terms="("..vb.value..")"
outcode(f,"if (("..terms..")!="..abool..") ")
if f._elsetgt[lc+2] then
outcode(f,f._elsetgt[lc+2].."=true;\n")
popBreak(f,lc+2+joff)
else
outcode(f,"{\n")
end
end
end
function gen_LOADK(is,f,a,b,c,bc)
mprint("$"..a.."="..KStr(f.k[bc+1]))
local v=KVal(f,bc)
--f._l[a]={type="val",value=v.value, vtype="hF1"}
ensureLocalVar(f,a,"hF1")
outcode(f,f._l[a].value.."="..v.value..";\n")
end
function gen_LOADBOOL(is,f,a,b,c,bc)
local v="true"
if (b==0) then v="false" end
mprint("$"..a.."="..v)
ensureLocalVar(f,a,"BOOL")
outcode(f,f._l[a].value.."="..v..";\n")
end
function gen_CLOSURE(is,f,a,b,c,bc)
assert(f.p[bc+1],"No such local function ("..bc..")")
mprint("$"..a.."=function("..bc..")")
f._l[a]={type="func",funcnum=bc+1}
end
function gen_JMP(is,f,a,b,c,bc,sbc,lc)
if f._jignore[lc] then return end
assert(false,"Standalone JMP aren't supported")
--Generate if context
-- outcode(f,"if ("..f._l[a].value..") {\n")
f._breaks[lc+1+sbc]=f._breaks[lc+1+sbc] or {}
table.insert(f._breaks[lc+1+sbc],{ callback=endblock })
--TODO: handle subpart
end
function gen_CALL(is,f,a,b,c)
assert((c-1)<=1,"Multiple returns aren't allowed ("..(c-1)..")")
--assert(c>0,"Indeterminate return count aren't allowed. Avoid directly passing the result of a function as the last arg of another.")
if c<=0 then c=2 end --Indeterminate return count, typically a tail call: assume one return since we don't support anything else
local fname=f._l[a].value or ("local("..f._l[a].funcnum..")")
assert(f._l[a].type=="func",fname.." isn't a function")
if b==0 then b=(f._l[a].acount or -1)+1 end
assert(b>0,"Indeterminate arg count aren't allowed on '"..fname.."'. Avoid directly passing the result of a function as the last arg of another.")
mprint("$"..a.."=$"..a.."(#"..b..")")
local fn=fname
local fne=f._l[a].evaluate
local fnr=f._l[a].rtype
local fnca=f._l[a].callarg
if c==2 then -- Return
assert(fnr,"Function '"..fn.."' return type not specified")
if tonumber(fnr) then
fnr=f._l[a+fnr].vtype
end
ensureLocalVar(f,a,fnr)
outcode(f,f._l[a].value.."=")
end
if fne then
--INLINE
local args={}
for p=1,b-1 do
args[p]=f._l[a+p]
end
outcode(f,fne(f,f._l[a],unpack(args))..";\n")
else
outcode(f,fn.."(")
for p=1,b-1 do
outcode(f,f._l[a+p].value)
if p<(b-1) then outcode(f,",") end
end
if fnca and #fnca>0 then
if b>1 then outcode(f,",") end
outcode(f,fnca)
end
outcode(f,");\n")
end
end
function gen_RETURN(is,f,a,b)
assert(b<=2,"Multiple returns aren't allowed")
mprint("return $"..a.." (#"..(b-1)..")")
if (f._handlers.RETURN) then
local gcode=nil
if (b<2) then
gcode=f._handlers.RETURN()
else
gcode=f._handlers.RETURN(f._l[a].value)
end
if gcode then
outcode(f,gcode)
return
end
end
if (b<2) then
outcode(f,"return;\n")
else
outcode(f,"return "..f._l[a].value..";\n");
end
end
function gen_TAILCALL(is,f,a,b,c)
gen_CALL(is,f,a,b,c)
gen_RETURN(is,f,a,2,0)
end
local pcount=0
local tcount=0
local function processFunction(f)
assert(f.nups==0,"Upvalues not supported")
if f.nups==0 then --candidate for C
pcount+=1
--print("FCT",f.source)
local lc=1
f._breaks={}
while lc<=f.codeSize do
if f._breaks[lc] then
for _,c in ipairs(f._breaks[lc])
do c:callback(f,lc)
end
end
local is=f.code[lc]
local a=((is>>6)&0xFF)()
local c=((is>>14)&0x1FF)()
local b=((is>>23)&0x1FF)()
local bc=((is>>14)&0x3FFFF)()
local op=(is&0x3F)()
local cn=codeName[op+1]
mprint(lc,cn,op,a,b,c,bc,bc-131071)
lc+=1
f._lc=lc
assert(_G["gen_"..cn],cn.." instruction isn't supported")
_G["gen_"..cn](is,f,a,b,c,bc,bc-131071,lc-1) --Add sbc with bias
lc=f._lc
end
end
tcount+=1
end
function codegen_l(f,argsmap,globalmap,typemap,optypemap,ophandlers)
pcount=0
tcount=0
if type(f)=="function" then
f=luacLoad(string.dump(f))
end
f._c=""
f._hc=""
f._g=globalmap or {}
f._l={}
f._t=typemap
f._ot=optypemap
f._handlers=ophandlers or {}
f._jignore={}
f._elsetgt={}
for k,v in ipairs(argsmap or {}) do f._l[k-1]=v end
processFunction(f)
--print("ProcessedCount",pcount,tcount)
--print("CODE:\n",f._hc..f._c)
return f._hc..f._c
end |
--[[
table
]]
local string_format = string.format
local pairs = pairs
local ok, table_new = pcall(require, "table.new")
if not ok or type(table_new) ~= "function" then
function table:new()
return {}
end
end
local _copy
_copy = function(t, lookup)
if type(t) ~= "table" then
return t
elseif lookup[t] then
return lookup[t]
end
local n = {}
lookup[t] = n
for key, value in pairs(t) do
n[_copy(key, lookup)] = _copy(value, lookup)
end
return n
end
function table.copy(t)
local lookup = {}
return _copy(t, lookup)
end
function table.keys(hashtable)
local keys = {}
for k, v in pairs(hashtable) do
keys[#keys + 1] = k
end
return keys
end
function table.values(hashtable)
local values = {}
for k, v in pairs(hashtable) do
values[#values + 1] = v
end
return values
end
function table.merge(dest, src)
for k, v in pairs(src) do
dest[k] = v
end
end
function table.map(t, fn)
local n = {}
for k, v in pairs(t) do
n[k] = fn(v, k)
end
return n
end
function table.walk(t, fn)
for k,v in pairs(t) do
fn(v, k)
end
end
function table.filter(t, fn)
local n = {}
for k, v in pairs(t) do
if fn(v, k) then
n[k] = v
end
end
return n
end
function table.length(t)
local count = 0
for _, __ in pairs(t) do
count = count + 1
end
return count
end
function table.readonly(t, name)
name = name or "table"
setmetatable(t, {
__newindex = function()
error(string_format("<%s:%s> is readonly table", name, tostring(t)))
end,
__index = function(_, key)
error(string_format("<%s:%s> not found key: %s", name, tostring(t), key))
end
})
return t
end
|
-------------------------------------------------
-- Volume Widget for Awesome Window Manager
-- Shows the current volume level
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/volume-widget
-- @author Pavel Makhov
-- @copyright 2018 Pavel Makhov
-------------------------------------------------
local wibox = require("wibox")
local watch = require("awful.widget.watch")
local spawn = require("awful.spawn")
local naughty = require("naughty")
local gfs = require("gears.filesystem")
local dpi = require('beautiful').xresources.apply_dpi
local PATH_TO_ICONS = "/usr/share/icons/Arc/status/symbolic/"
local volume_widget = {}
local function worker(args)
local args = args or {}
local volume_audio_controller = args.volume_audio_controller or 'pulse'
local display_notification = args.notification or 'false'
local position = args.notification_position or "top_right"
local device_arg = ''
if volume_audio_controller == 'pulse' then
device_arg = '-D pulse'
end
local GET_VOLUME_CMD = 'amixer ' .. device_arg .. ' sget Master'
local INC_VOLUME_CMD = 'amixer ' .. device_arg .. ' sset Master 5%+'
local DEC_VOLUME_CMD = 'amixer ' .. device_arg .. ' sset Master 5%-'
local TOG_VOLUME_CMD = 'amixer ' .. device_arg .. ' sset Master toggle'
if not gfs.dir_readable(PATH_TO_ICONS) then
naughty.notify{
title = "Volume Widget",
text = "Folder with icons doesn't exist: " .. PATH_TO_ICONS,
preset = naughty.config.presets.critical
}
end
volume_widget = wibox.widget {
{
id = "icon",
image = PATH_TO_ICONS .. "audio-volume-muted-symbolic.svg",
resize = false,
widget = wibox.widget.imagebox,
},
layout = wibox.container.margin(_, _, _, 3),
set_image = function(self, path)
self.icon.image = path
end
}
local notification = {}
local volume_icon_name="audio-volume-high-symbolic"
local function get_notification_text(txt)
local mute = string.match(txt, "%[(o%a%a?)%]")
local volume = string.match(txt, "(%d?%d?%d)%%")
volume = tonumber(string.format("% 3d", volume))
if mute == "off" then
return volume.."% <span color=\"red\"><b>Mute</b></span>"
else
return volume .."%"
end
end
local function show_volume(val)
spawn.easy_async(GET_VOLUME_CMD,
function(stdout, _, _, _)
naughty.destroy(notification)
notification = naughty.notify{
text = get_notification_text(stdout),
icon=PATH_TO_ICONS .. val .. ".svg",
icon_size = dpi(16),
title = "Volume",
position = position,
timeout = 0, hover_timeout = 0.5,
width = 200,
}
end
)
end
local update_graphic = function(widget, stdout, _, _, _)
local mute = string.match(stdout, "%[(o%D%D?)%]")
local volume = string.match(stdout, "(%d?%d?%d)%%")
volume = tonumber(string.format("% 3d", volume))
if mute == "off" then volume_icon_name="audio-volume-muted-symbolic_red"
elseif (volume >= 0 and volume < 25) then volume_icon_name="audio-volume-muted-symbolic"
elseif (volume < 50) then volume_icon_name="audio-volume-low-symbolic"
elseif (volume < 75) then volume_icon_name="audio-volume-medium-symbolic"
elseif (volume <= 100) then volume_icon_name="audio-volume-high-symbolic"
end
widget.image = PATH_TO_ICONS .. volume_icon_name .. ".svg"
if display_notification then
notification.iconbox.image = PATH_TO_ICONS .. volume_icon_name .. ".svg"
naughty.replace_text(notification, "Volume", get_notification_text(stdout))
end
end
--[[ allows control volume level by:
- clicking on the widget to mute/unmute
- scrolling when cursor is over the widget
]]
volume_widget:connect_signal("button::press", function(_,_,_,button)
if (button == 4) then spawn(INC_VOLUME_CMD, false)
elseif (button == 5) then spawn(DEC_VOLUME_CMD, false)
elseif (button == 1) then spawn(TOG_VOLUME_CMD, false)
end
spawn.easy_async(GET_VOLUME_CMD, function(stdout, stderr, exitreason, exitcode)
update_graphic(volume_widget, stdout, stderr, exitreason, exitcode)
end)
end)
if display_notification then
volume_widget:connect_signal("mouse::enter", function() show_volume(volume_icon_name) end)
volume_widget:connect_signal("mouse::leave", function() naughty.destroy(notification) end)
end
watch(GET_VOLUME_CMD, 1, update_graphic, volume_widget)
return volume_widget
end
return setmetatable(volume_widget, { __call = function(_, ...) return worker(...) end })
|
--[[
Reference renderer intended for use in tests as well as for documenting the
minimum required interface for a Roact renderer.
]]
local NoopRenderer = {}
function NoopRenderer.isHostObject(target)
-- Attempting to use NoopRenderer to target a Roblox instance is almost
-- certainly a mistake.
return target == nil
end
function NoopRenderer.mountHostNode(reconciler, node)
end
function NoopRenderer.unmountHostNode(reconciler, node)
end
function NoopRenderer.updateHostNode(reconciler, node, newElement)
return node
end
return NoopRenderer |
--[[
The MIT License (MIT)
Copyright (c) 2015 ediiknorand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
-- Dependencies
require "AI\\USER_AI\\actor"
-- Constants
local GID_BASE = 110000000
local GID_SHIFT = 0
local RENEWAL = true
local CONST = dofile("./AI/USER_AI/lib/const.lua")
local V_MOTION = 3
local V_TARGET = 5
local V_CLASS = 7
local V_MERCLASS = 12
-- Utility
local function copytable_shallow(t,mt)
local result = {}
for i,v in pairs(t) do
result[i] = v
end
if mt then
return setmetatable(result, mt)
end
return result
end
-- Player Class
local motion2class = {
[CONST.MOTION_VULCAN] = CONST.CLOWN,
[CONST.MOTION_SPIRAL] = CONST.LORD_KNIGHT,
[CONST.MOTION_COUNTER] = CONST.KNIGHT,
[CONST.MOTION_DANCE] = CONST.DANCER,
[CONST.MOTION_PERFORM] = CONST.BARD,
[CONST.MOTION_SHARPSHOOT] = CONST.SNIPER,
[CONST.MOTION_JUMP_UP] = CONST.TAEKWON_KID,
[CONST.MOTION_JUMP_FALL] = CONST.TAEKWON_KID,
[CONST.MOTION_PWHIRL] = CONST.TAEKWON_KID,
[CONST.MOTION_PAXE] = CONST.TAEKWON_KID,
[CONST.MOTION_PCOUNTER] = CONST.TAEKWON_KID,
[CONST.MOTION_TUMBLE] = CONST.TAEKWON_KID,
[CONST.MOTION_COUNTERK] = CONST.TAEKWON_KID,
[CONST.MOTION_FLYK] = CONST.TAEKWON_KID,
[CONST.MOTION_BIGTOSS] = CONST.CREATOR,
[CONST.MOTION_WHIRLK] = CONST.TAEKWON_KID,
[CONST.MOTION_AXEK] = CONST.TAEKWON_KID,
[CONST.MOTION_ROUNDK] = CONST.TAEKWON_KID,
[CONST.MOTION_COMFORT] = CONST.TAEKWON_MASTER,
[CONST.MOTION_HEAT] = CONST.TAEKWON_MASTER,
[CONST.MOTION_NINJAGROUND] = CONST.NINJA,
[CONST.MOTION_NINJAHAND] = CONST.NINJA,
[CONST.MOTION_NINJACAST] = CONST.NINJA,
[CONST.MOTION_GUNTWIN] = CONST.GUNSLINGER,
[CONST.MOTION_GUNFLIP] = CONST.GUNSLINGER,
[CONST.MOTION_GUNSHOW] = CONST.GUNSLINGER,
[CONST.MOTION_GUNCAST] = CONST.GUNSLINGER,
[CONST.MOTION_FULLBLAST] = CONST.GUNSLINGER,
}
local motion2classf = {
[CONST.MOTION_SOULLINK] = function(gid)
local target_gid = GetV(V_TARGET, gid)
local tmotion = GetV(V_MOTION, target_gid)
if tmotion == CONST.MOTION_DAMAGE then
return CONST.TAEKWON_KID
end
return CONST.SOUL_LINKER
end,
}
local motion_confirm = {
[CONST.MOTION_SPIRAL] = not RENEWAL,
[CONST.MOTION_SHARPSHOOT] = not RENEWAL,
[CONST.MOTION_BIGTOSS] = not RENEWAL,
[CONST.MOTION_COMFORT] = true,
[CONST.MOTION_HEAT] = true,
[CONST.MOTION_NINJAGROUND] = not RENEWAL,
[CONST.MOTION_NINJAHAND] = not RENEWAL,
[CONST.MOTION_NINJACAST] = not RENEWAL,
[CONST.MOTION_GUNTWIN] = not RENEWAL,
[CONST.MOTION_GUNFLIP] = not RENEWAL,
[CONST.MOTION_GUNCAST] = not RENEWAL,
[CONST.MOTION_FULLBLAST] = not RENEWAL,
}
local function getClassPlayer(gid)
local motion = GetV(V_MOTION, gid)
if motion2class[motion] then
return motion2class[motion],motion_confirm[motion]
end
return nil
end
-- getClassMob
-- work-in-progress
-- General getClass
local function getClass(gid) -- Avoiding circular dependencies is a good practice
local class = GetV(V_CLASS, gid)
local confirm
if class then
return class
end
if gid < GID_BASE then
class,confirm = getClassPlayer(gid)
return class,confirm
end
return
end
-- Actor metatable
local actor_index_f = actor_metatable.__index
merclass_actor_metatable = copytable_shallow(actor_metatable)
merclass_actor_metatable.__index = function(actor,key)
if not actor.gid then
return nil
end
if key == 'class' then
local class,confirm = getClass(actor.gid)
if class and confirm then
rawset(actor,'class',class)
return class
end
end
return actor_index_f(actor, key)
end
-- Merclass API
local MERCLASS = {}
MERCLASS.getActor = function(gid)
local actor = getActor(gid)
return setmetatable(actor, merclass_actor_metatable)
end
MERCLASS.getActors = function(foreach)
local actors = getActors(foreach)
for _,actor in pairs(actors) do
setmetatable(actor, merclass_actor_metatable)
end
return actors
end
MERCLASS.shift = function(n)
if type(n) == 'number' then
GID_SHIFT = n
end
end
MERCLASS.ROversion = function(version)
if version == 'pre-renewal' then
RENEWAL = false
elseif version == 'renewal' then
RENEWAL = true
end
end
return MERCLASS
|
Script.ReloadScript("SCRIPTS/Entities/actor/BasicActor.lua");
Script.ReloadScript("SCRIPTS/Entities/AI/Shared/BasicAI.lua");
Flyer_x =
{
AnimationGraph = "",
AIType = AIOBJECT_2D_FLY,
PropertiesInstance =
{
aibehavior_behaviour = "FlyerIdle",
},
Properties =
{
esBehaviorSelectionTree = "Flyer",
fileModel = "Objects/Characters/Dragon/Dragon.cdf",
Damage =
{
health = 1,
},
},
gameParams =
{
stance =
{
{
stanceId = STANCE_STAND,
normalSpeed = 10,
maxSpeed = 20,
heightCollider = 0,
heightPivot = -1,
size = { x = 3, y = 3, z = 3 },
viewOffset = { x = 0, y = 0, z = 0 },
name = "fly",
},
},
},
AIMovementAbility =
{
b3DMove = 1,
optimalFlightHeight = 15,
minFlightHeight = 10,
maxFlightHeight = 30,
pathType = AIPATH_HELI,
},
}
function Flyer_x:OnResetCustom()
self.AI.bUpdate = false;
end
|
Technology = {name = nil, cost_production = 0, cost_gold = 0, icon = nil}
function Technology:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end |
slot2 = "FishingJoyBuffSpeed"
slot5 = "entity.FishingJoyBuffBase"
FishingJoyBuffSpeed = class(slot1, FishingJoyRequireLua(slot4))
FishingJoyBuffSpeed.ctor = function (slot0)
slot3 = slot0
FishingJoyBuffSpeed.super.ctor(slot2)
slot4 = FISHINGJOY_BUFF_TYPE.CHANGESPEED
slot0.setBuffType(slot2, slot0)
end
FishingJoyBuffSpeed.getBuffParam = function (slot0)
return slot0.buffParam
end
return FishingJoyBuffSpeed
|
-- FUNCTIONAL
require 'Q/UTILS/lua/strict'
local Q = require 'Q'
local Scalar = require 'libsclr' ;
local tests = {}
tests.t1 = function()
local x = Q.mk_col({1, 0, 1, 0, 1, 0, 1}, "B1")
local y = Q.mk_col({1, 2, 3, 4, 5, 6, 7}, "I4")
local z = Q.mk_col({-1, -2, -3, -4, -5, -6, -7}, "I4")
local exp_w = Q.mk_col({1, -2, 3, -4, 5, -6, 7}, "I4")
local w = Q.ifxthenyelsez(x, y, z)
-- w:eval()
-- local opt_args = { opfile = "" }
-- Q.print_csv({w, exp_w, y, z}, opt_args)
local n = Q.sum(Q.vveq(w, exp_w))
local m = n:eval():to_num()
assert(m == 7)
print("Test t1 succeeded")
end
--==========================
tests.t2 = function()
local x = Q.mk_col({1, 0, 1, 0, 1, 0, 1}, "B1")
local y = Q.mk_col({1, 2, 3, 4, 5, 6, 7}, "I4")
local z = Scalar.new("10", "I4")
local w = Q.ifxthenyelsez(x, y, z)
local n = Q.sum(Q.vseq(w, Scalar.new(10, w:fldtype())))
-- w:eval()
-- local opt_args = { opfile = "" }
-- Q.print_csv({w, exp_w, y}, opt_args)
local m = n:eval():to_num()
assert(m == 3)
print("Test t2 succeeded")
end
--===========================
tests.t3 = function()
local x = Q.mk_col({1, 0, 1, 0, 1, 0, 1}, "B1")
local y = Scalar.new("100", "I4")
local z = Q.mk_col({-1, -2, -3, -4, -5, -6, -7}, "I4")
local w = Q.ifxthenyelsez(x, y, z)
local n = Q.sum(Q.vseq(w, Scalar.new(100, w:fldtype())))
local m = n:eval():to_num()
assert(m == 4)
-- w:eval()
-- local opt_args = { opfile = "" }
-- Q.print_csv({w, z}, opt_args)
print("Test t3 succeeded")
end
--===========================
tests.t4 = function()
local x = Q.mk_col({1, 0, 1, 0, 1, 0, 1}, "B1")
local y = Scalar.new("100", "I4")
local z = Scalar.new("-100", "I4")
local w = Q.ifxthenyelsez(x, y, z)
local n = Q.sum(Q.vseq(w, Scalar.new(100, w:fldtype())))
local m = n:eval():to_num()
-- w:eval()
-- local opt_args = { opfile = "" }
-- Q.print_csv({w, x}, opt_args)
assert(m == 4)
print("Test t4 succeeded")
end
return tests
|
local index = {}
function index:enter(from)
Signal.register("pressed-a", function(...) self:pressed_a(...) end)
Signal.register("pressed-b", function(...) self:pressed_b(...) end)
Signal.register("pressed-x", function(...) self:pressed_x(...) end)
Signal.register("pressed-y", function(...) self:pressed_y(...) end)
Signal.register("pressed-back", function(...) self:pressed_back(...) end)
Signal.register("pressed-guide", function(...) self:pressed_guide(...) end)
Signal.register("pressed-start", function(...) self:pressed_start(...) end)
Signal.register("pressed-leftstick", function(...) self:pressed_leftstick(...) end)
Signal.register("pressed-rightstick", function(...) self:pressed_rightstick(...) end)
Signal.register("pressed-leftshoulder", function(...) self:pressed_leftshoulder(...) end)
Signal.register("pressed-rightshoulder", function(...) self:pressed_rightshoulder(...) end)
Signal.register("pressed-dpup", function(...) self:pressed_dpup(...) end)
Signal.register("pressed-dpdown", function(...) self:pressed_dpdown(...) end)
Signal.register("pressed-dpleft", function(...) self:pressed_dpleft(...) end)
Signal.register("pressed-dpright", function(...) self:pressed_dpright(...) end)
Signal.register("released-a", function(...) self:released_a(...) end)
Signal.register("released-b", function(...) self:released_b(...) end)
Signal.register("released-x", function(...) self:released_x(...) end)
Signal.register("released-y", function(...) self:released_y(...) end)
Signal.register("released-back", function(...) self:released_back(...) end)
Signal.register("released-guide", function(...) self:released_guide(...) end)
Signal.register("released-start", function(...) self:released_start(...) end)
Signal.register("released-leftstick", function(...) self:released_leftstick(...) end)
Signal.register("released-rightstick", function(...) self:released_rightstick(...) end)
Signal.register("released-leftshoulder", function(...) self:released_leftshoulder(...) end)
Signal.register("released-rightshoulder", function(...) self:released_rightshoulder(...) end)
Signal.register("released-dpup", function(...) self:released_dpup(...) end)
Signal.register("released-dpdown", function(...) self:released_dpdown(...) end)
Signal.register("released-dpleft", function(...) self:released_dpleft(...) end)
Signal.register("released-dpright", function(...) self:released_dpright(...) end)
Signal.register("moved-axisleft", function(...) self:moved_axisleft(...) end)
Signal.register("moved-axisright", function(...) self:moved_axisright(...) end)
Signal.register("moved-triggerleft", function(...) self:moved_triggerleft(...) end)
Signal.register("moved-triggerright", function(...) self:moved_triggerright(...) end)
end
function index:leave()
Signal.clear_pattern("pressed%-.*")
Signal.clear_pattern("released%-.*")
Signal.clear_pattern("moved%-.*")
end
function index:pressed_a(joystick)
end
function index:pressed_b(joystick)
end
function index:pressed_x(joystick)
end
function index:pressed_y(joystick)
end
function index:pressed_back(joystick)
end
function index:pressed_guide(joystick)
end
function index:pressed_start(joystick)
end
function index:pressed_leftstick(joystick)
end
function index:pressed_rightstick(joystick)
end
function index:pressed_leftshoulder(joystick)
end
function index:pressed_rightshoulder(joystick)
end
function index:pressed_dpup(joystick)
end
function index:pressed_dpdown(joystick)
end
function index:pressed_dpleft(joystick)
end
function index:pressed_dpright(joystick)
end
function index:released_a(joystick)
end
function index:released_b(joystick)
end
function index:released_x(joystick)
end
function index:released_y(joystick)
end
function index:released_back(joystick)
end
function index:released_guide(joystick)
end
function index:released_start(joystick)
end
function index:released_leftstick(joystick)
end
function index:released_rightstick(joystick)
end
function index:released_leftshoulder(joystick)
end
function index:released_rightshoulder(joystick)
end
function index:released_dpup(joystick)
end
function index:released_dpdown(joystick)
end
function index:released_dpleft(joystick)
end
function index:released_dpright(joystick)
end
function index:moved_axisleft(joystick, x, y)
end
function index:moved_axisright(joystick, x, y)
end
function index:moved_triggerleft(joystick, direction)
end
function index:moved_triggerright(joystick, direction)
end
return index
|
local handler = call ( getResourceFromName ( "rp_mysql" ), "getDbHandler")
addEventHandler ( "onResourceStart", resourceRoot, function() outputDebugString("[startup] Załadowano system obiektów") end )
-- Branch: KYLO
-- Zmiana działania obiektów, są trzymane po stronie serwera i wysyłane klientowi w ramach streamera
objects = {}
-- dodawanie obiektów do bazy
function addObject(model, x, y, z, world, interior)
local object = createObject ( model, x, y, z )
if not object then return false end
local query = dbQuery(handler, "INSERT INTO lsrp_objects (object_model, object_posx, object_posy, object_posz, object_rotx, object_roty, object_rotz, object_world, object_interior, object_group, object_gaterotx, object_gateroty, object_gaterotz, object_owner) VALUES ("..model..", "..x..", "..y..", "..z..", 0.0, 0.0, 0.0, "..world..", "..interior..", '', 0.0, 0.0, 0.0, 0)")
local _, _, insert_id = dbPoll(query, -1)
setElementData(object, "object.uid", insert_id)
setElementDimension(object, world)
setElementDimension(object, world)
setElementInterior(object, interior)
if query then dbFree(query) end
return insert_id
end
-- usuwanie obiektu z bazy
function removeObject(object)
local object_uid = getElementData(object, "object.uid")
local query = dbQuery(handler, "DELETE FROM lsrp_objects WHERE object_uid = "..object_uid)
if query then dbFree(query) end
destroyElement(object)
return true
end
addEvent("RemoveObject", true)
addEventHandler("RemoveObject", getRootElement(), removeObject)
-- wczytywanie wszystkich obiektów na starcie
function LoadObjects()
local debug = exports.lsrp:getDebugStatus( )
local query = nil
if debug == true then
outputDebugString("[debug] Wczytuje tylko obiekty z VW 0.")
query = dbQuery(handler, "SELECT * FROM lsrp_objects WHERE object_world = 0")
else
query = dbQuery(handler, "SELECT * FROM lsrp_objects")
end
local load = 0
--local query = dbQuery(handler, "SELECT * FROM lsrp_objects")
local result = dbPoll(query, -1)
local ile = 0 -- usuwanie błędnych obiektów
if result then
for k = 0, table.getn(result) do
if result[k] then
objects[load] = {}
objects[load]["uid"] = tonumber(result[k]["object_uid"])
objects[load]["vw"] = tonumber(result[k]["object_world"])
objects[load]["model"] = tonumber(result[k]["object_model"])
objects[load]["posx"] = tonumber(result[k]["object_posx"])
objects[load]["posy"] = tonumber(result[k]["object_posy"])
objects[load]["posz"] = tonumber(result[k]["object_posz"])
objects[load]["rotx"] = tonumber(result[k]["object_rotx"])
objects[load]["roty"] = tonumber(result[k]["object_roty"])
objects[load]["rotz"] = tonumber(result[k]["object_rotz"])
--local created = createObject ( tonumber(result[k]["object_model"]), tonumber(result[k]["object_posx"]), tonumber(result[k]["object_posy"]), tonumber(result[k]["object_posz"]), tonumber(result[k]["object_rotx"]), tonumber(result[k]["object_roty"]), tonumber(result[k]["object_rotz"]) )
-- usuwanie błędnych obiektów
--[[if not created then
local destroy_q = dbQuery(handler, "DELETE FROM lsrp_objects WHERE object_uid = "..tonumber(result[k]["object_uid"]))
if destroy_q then dbFree(destroy_q) end
ile = ile + 1
end]]--
if created then
setElementData(created, "object.uid", tonumber(result[k]["object_uid"]))
setElementDimension(created, result[k]["object_world"])
addObjectTextureInfo(created) -- zadziałczy?
end
load = load + 1
end
end
end
outputDebugString("[load] Usunieto "..ile.." obiektów!")
outputDebugString("[load] Wczytano "..table.getn(objects).." obiektów!")
if query then dbFree(query) end
end
addEventHandler ( "onResourceStart", resourceRoot, LoadObjects )
-- zapis obiektu i sync (jakiś błąd jest podczas pierwszej edycji obiektu (?))
function SaveObject(object_uid, x, y, z, rx, ry, rz)
local object = getObjectByUID(object_uid)
setElementPosition(object, x, y, z)
setElementRotation(object, rx, ry, rz)
local query = dbQuery(handler, "UPDATE lsrp_objects SET object_posx = "..x..", object_posy = "..y..", object_posz = "..z..", object_rotx = "..rx..", object_roty = "..ry..", object_rotz = "..rz.." WHERE object_uid = "..object_uid)
dbFree(query)
end
addEvent("SaveObject", true)
addEventHandler ( "SaveObject", getRootElement(), SaveObject )
function getObjectByUID(uid)
local objects = getElementsByType ( "object" )
for i, object in ipairs(objects) do
if tonumber(getElementData(object, "object.uid")) == uid then
return object
end
end
return false
end |
local unformat = {}
local mattata = require('mattata')
local utf8 = require('lua-utf8')
function unformat:init(configuration)
unformat.arguments = 'unformat'
unformat.commands = mattata.commands(self.info.username, configuration.commandPrefix):c('unformat').table
unformat.help = configuration.commandPrefix .. 'unformat - Returns the raw Markdown formatting of the replied-to message. Special characters are not supported.'
end
function unformat.markdown(entity, str)
local sub = str:sub(entity.offset + 1, entity.offset + entity.length)
if entity.type == 'italic' then
return '_' .. sub .. '_'
elseif entity.type == 'bold' then
return '*' .. sub .. '*'
elseif entity.type =='text_link' then
return '[' .. sub .. '](' .. entity.url ..')'
elseif entity.type == 'pre' then
return '```' .. sub .. '```'
elseif entity.type == 'code' then
return '`' .. sub .. '`'
end
end
function unformat:onMessage(message, configuration)
if not message.reply_to_message then
mattata.sendMessage(message.chat.id, unformat.help, nil, true, false, message.message_id)
return
end
local output = ''
local str = message.reply_to_message.text
if str:len() > utf8.len(str) then
mattata.sendMessage(message.chat.id, unformat.help, nil, true, false, message.message_id)
return
end
if message.reply_to_message.entities then
local char = 0
for k, v in pairs(message.reply_to_message.entities) do
if v.offset ~= char then
output = output .. str:sub(char + 1, v.offset)
char = v.offset
end
output = output .. unformat.markdown(v, str)
char = char + v.length
end
else
output = message.reply_to_message.text
end
mattata.sendMessage(message.chat.id, output, nil, true, false, message.message_id)
end
return unformat |
local Spell = { }
Spell.LearnTime = 180
Spell.Description = [[
Knocks down your opponent.
Useful in duels.
]]
Spell.Category = HpwRewrite.CategoryNames.Fight
Spell.FlyEffect = "hpw_sectumsemp_main"
Spell.ImpactEffect = "hpw_white_impact"
Spell.ApplyDelay = 0.5
Spell.ForceAnim = { ACT_VM_PRIMARYATTACK_1, ACT_VM_PRIMARYATTACK_2 }
Spell.SpriteColor = Color(255, 255, 255)
Spell.NodeOffset = Vector(-960, -317, 0)
function Spell:OnSpellSpawned(wand, spell)
sound.Play("ambient/wind/wind_snippet2.wav", spell:GetPos(), 75, 255)
wand:PlayCastSound()
end
function Spell:OnFire(wand)
return true
end
function Spell:AfterCollide(spell, data)
local ent = HpwRewrite:ThrowEntity(data.HitEntity, spell:GetFlyDirection(), nil, 0.7, self.Owner)
if IsValid(ent) then
sound.Play("npc/zombie/claw_strike" .. math.random(1, 3) .. ".wav", ent:GetPos(), 70, math.random(90, 110))
local phys = ent:GetPhysicsObject()
if phys:IsValid() then
phys:AddAngleVelocity(Vector(0, 30000, 0))
end
end
end
HpwRewrite:AddSpell("Rictusempra", Spell) |
local nvim = require("nvim")
local fs = require("arshlib.fs")
local colour = require("arshlib.colour")
local quick = require("arshlib.quick")
local lsp = require("arshlib.lsp")
local listish = require("listish")
local reloader = require("plenary.reload")
local fzf = require("fzf-lua")
local fzfcore = require("fzf-lua.core")
local fzfutils = require("fzf-lua.utils")
local fzfconfig = require("fzf-lua.config")
local fzfactions = require("fzf-lua.actions")
local fzfbuiltin = require("fzf-lua.previewer.builtin")
local M = {}
---Launches a ripgrep search with a fzf search interface.
---@param term? string if empty, the search will only happen on the content.
---@param no_ignore? boolean disables the ignore rules.
---@param filenames? boolean let the search on filenames too.
function M.ripgrep_search(term, no_ignore, filenames) --{{{
term = vim.fn.shellescape(term)
local nth = ""
local with_nth = ""
local delimiter = ""
if term then
with_nth = "--with-nth 1.."
if filenames then
nth = "--nth 1,4.."
else
nth = "--nth 4.."
end
delimiter = "--delimiter :"
end
no_ignore = no_ignore and "" or "--no-ignore"
local rg_cmd = table.concat({
"rg",
"--line-number",
"--column",
"--no-heading",
"--color=always",
"--smart-case",
"--hidden",
'-g "!.git/" ',
no_ignore,
"--",
term,
}, " ")
local args = {
options = table.concat({
'--prompt="Search in files> "',
"--preview-window nohidden",
delimiter,
with_nth,
nth,
}, " "),
}
local preview = vim.fn["fzf#vim#with_preview"](args)
vim.fn["fzf#vim#grep"](rg_cmd, 1, preview)
end --}}}
---Launches an incremental search with ripgrep and fzf.
---@param term? string if empty, the search will only happen on the content.
---@param no_ignore? string disables the ignore rules.
function M.ripgrep_search_incremental(term, no_ignore) --{{{
term = vim.fn.shellescape(term)
local query = ""
local nth = ""
local with_nth = ""
local delimiter = ""
if term then
query = "--query " .. term
with_nth = "--nth 2.."
nth = "--nth 1,4.."
delimiter = "--delimiter :"
end
no_ignore = no_ignore and "" or "--no-ignore"
local rg_cmd = table.concat({
"rg",
"--line-number",
"--column",
"--no-heading",
"--color=always",
"--smart-case",
"--hidden",
'-g "!.git/" ',
no_ignore,
"-- %s || true",
}, " ")
local initial = string.format(rg_cmd, term)
local reload_cmd = string.format(rg_cmd, "{q}")
local args = {
options = table.concat({
'--prompt="1. Ripgrep> "',
'--header="<Alt-Enter>:Reload on current query"',
"--header-lines=1",
"--preview-window nohidden",
query,
"--bind",
string.format("'change:reload:%s'", reload_cmd),
'--bind "alt-enter:unbind(change,alt-enter)+change-prompt(2. FZF> )+enable-search+clear-query"',
"--tiebreak=index",
delimiter,
with_nth,
nth,
}, " "),
}
local preview = vim.fn["fzf#vim#with_preview"](args)
vim.fn["fzf#vim#grep"](initial, 1, preview)
end --}}}
function M.delete_buffers_native() --{{{
local list = vim.fn.getbufinfo({ buflisted = 1 })
local buf_list = {
table.concat({ "", "", "", "Buffer", "", "Filename", "" }, "\t"),
}
local cur_buf = vim.fn.bufnr("")
local alt_buf = vim.fn.bufnr("#")
for _, v in pairs(list) do
local name = vim.fn.fnamemodify(v.name, ":~:.")
-- the bufnr can't go to the first item otherwise it breaks the preview
-- line
local t = {
string.format("%s:%d", v.name, v.lnum),
v.lnum,
tostring(v.bufnr),
string.format("[%s]", colour.ansi_color(colour.colours.red, v.bufnr)),
"",
name,
"",
}
local signs = ""
if v.bufnr == cur_buf then
signs = signs .. colour.ansi_color(colour.colours.red, "%")
end
if v.bufnr == alt_buf then
signs = signs .. "#"
end
t[5] = signs
if v.changed > 0 then
t[7] = "[+]"
end
table.insert(buf_list, table.concat(t, "\t"))
end
local wrapped = vim.fn["fzf#wrap"]({
source = buf_list,
options = table.concat({
'--prompt "Delete Buffers > "',
"--multi",
"--exit-0",
"--ansi",
"--delimiter '\t'",
"--with-nth=4..",
"--nth=3",
"--bind 'ctrl-a:select-all+accept'",
"--preview-window +{3}+3/2,nohidden",
"--tiebreak=index",
"--header-lines=1",
}, " "),
placeholder = "{1}",
})
local preview = vim.fn["fzf#vim#with_preview"](wrapped)
preview["sink*"] = function(names)
for _, name in pairs({ unpack(names, 2) }) do
local num = tonumber(name:match("^[^\t]+\t[^\t]+\t([^\t]+)\t"))
pcall(vim.api.nvim_buf_delete, num, {})
end
end
vim.fn["fzf#run"](preview)
end --}}}
---Shows all opened buffers and let you search and delete them.
function M.delete_buffers() --{{{
fzf.buffers({
prompt = "Delete Buffers > ",
ignore_current_buffer = false,
sort_lastused = false,
fzf_opts = {
["--header"] = "'" .. table.concat({ "Buffer", "", "Filename", "" }, "\t") .. "'",
},
actions = {
["default"] = function(selected)
for _, name in pairs(selected) do
local num = name:match("^%[([^%]]+)%]")
pcall(vim.api.nvim_buf_delete, tonumber(num), {})
end
end,
},
})
end --}}}
---Searches in the lines of current buffer. It provides an incremental search
-- that would switch to fzf filtering on <Alt-Enter>.
---@param actions table the actions for the sink.
---@param header? string the header to explain the actions.
function M.lines_grep(actions, header) --{{{
header = header and '--header="' .. header .. '"' or ""
local options = table.concat({
'--prompt="Current Buffer> "',
header,
"--layout reverse-list",
'--delimiter="\t"',
"--with-nth=3..",
"--preview-window nohidden",
}, " ")
local filename = vim.fn.fnameescape(vim.fn.expand("%"))
local rg_cmd = {
"rg",
".",
"--line-number",
"--no-heading",
"--color=never",
"--smart-case",
filename,
}
local got = vim.fn.systemlist(rg_cmd)
local source = {}
for _, line in pairs(got) do
local num, content = line:match("^(%d+):(.+)$")
if not num then
return
end
table.insert(source, string.format("%s:%d\t%d\t%s", filename, num, num, content))
end
local wrapped = vim.fn["fzf#wrap"]({
source = source,
options = options,
placeholder = "{1}",
})
local preview = vim.fn["fzf#vim#with_preview"](wrapped)
preview["sink*"] = function(names)
if #names == 0 then
return
end
local action = names[1]
if #action > 0 then
local fn = actions[action]
_t(names)
:when(fn)
:slice(2)
:map(function(v)
local name, line, content = v:match("^([^:]+):([^\t]+)\t([^\t]+)\t(.+)")
return {
filename = vim.fn.fnameescape(name),
lnum = tonumber(line),
col = 1,
text = content,
}
end)
:exec(fn)
end
if #names == 2 then
local num = names[2]:match("^[^:]+:(%d+)\t")
quick.normal("n", string.format("%dgg", num))
end
end
vim.fn["fzf#run"](preview)
end --}}}
---Launches a fzf search for reloading config files.
function M.reload_config() --{{{
local loc = vim.env["MYVIMRC"]
local base_dir = require("plenary.path"):new(loc):parents()[1]
local got = vim.fn.systemlist({ "fd", ".", "-e", "lua", "-t", "f", "-L", base_dir })
local source = {}
for _, name in ipairs(got) do
table.insert(source, ("%s\t%s"):format(name, vim.fn.fnamemodify(name, ":~:.")))
end
local wrapped = vim.fn["fzf#wrap"]({
source = source,
options = table.concat({
'--prompt="Open Config> "',
'--header="<C-a>:Reload all"',
'--delimiter="\t"',
"--with-nth=2..",
"--nth=1",
"--multi",
"--bind ctrl-a:select-all+accept",
"--preview-window +{3}+3/2,nohidden",
"--tiebreak=index",
}, " "),
placeholder = "{1}",
})
local preview = vim.fn["fzf#vim#with_preview"](wrapped)
preview["sink*"] = function(list)
local names = _t(list):slice(2):map(function(v)
return v:match("^[^\t]*")
end)
names
:filter(function(name)
name = name:match("^[^\t]*")
local mod, ok = fs.file_module(name)
return ok, mod.module
end)
:map(function(mod)
reloader.reload_module(mod, false)
require(mod)
return mod
end)
:exec(function(mod)
local msg = table.concat(mod, "\n")
vim.notify(msg, vim.lsp.log_levels.INFO, {
title = "Reloaded",
timeout = 1000,
})
end)
end
vim.fn["fzf#run"](preview)
end --}}}
---Open one of your neovim config files.
function M.open_config() --{{{
local path = vim.fn.stdpath("config")
local got = vim.fn.systemlist({ "fd", ".", "-t", "f", "-F", path })
local source = {}
for _, name in ipairs(got) do
table.insert(source, ("%s\t%s"):format(name, vim.fn.fnamemodify(name, ":~:.")))
end
local wrapped = vim.fn["fzf#wrap"]({
source = source,
options = table.concat({
'--prompt="Open Config> "',
"+m",
"--with-nth=2..",
"--nth=1",
'--delimiter="\t"',
"--preview-window +{3}+3/2,nohidden",
"--tiebreak=index",
}, " "),
placeholder = "{1}",
})
local preview = vim.fn["fzf#vim#with_preview"](wrapped)
preview["sink*"] = function() end
preview["sink"] = function(filename)
filename = filename:match("^[^\t]*")
if filename ~= "" then
nvim.ex.edit(filename)
end
end
vim.fn["fzf#run"](preview)
end --}}}
---Show marks with preview.
function M.marks() --{{{
local home = vim.fn["fzf#shellescape"](vim.fn.expand("%"))
local preview = vim.fn["fzf#vim#with_preview"]({
placeholder = table.concat({
'$([ -r $(echo {4} | sed "s#^~#$HOME#") ]',
"&& echo {4}",
"|| echo ",
home,
"):{2}",
}, " "),
options = "--preview-window +{2}-/2",
})
vim.fn["fzf#vim#marks"](preview, 0)
end --}}}
---Show marks for deletion using fzf's native ui.
function M.delete_marks_native() --{{{
local mark_list = _t({
("666\tmark\t%5s\t%3s\t%s"):format("line", "col", "file/text"),
})
local bufnr = vim.fn.bufnr()
local bufname = vim.fn.bufname(bufnr)
_t(vim.fn.getmarklist(bufnr))
:map(function(v)
v.file = bufname
return v
end)
:merge(vim.fn.getmarklist())
:filter(function(v)
return string.match(string.lower(v.mark), "[a-z]")
end)
:map(function(v)
mark_list:insert(
("%s:%d\t%s\t%5d\t%3d\t%s"):format(
vim.fn.fnamemodify(v.file, ":~:."),
v.pos[2],
string.sub(v.mark, 2, 2),
v.pos[2],
v.pos[3],
v.file
)
)
end)
local wrapped = vim.fn["fzf#wrap"]({ --{{{
source = mark_list,
options = table.concat({
'--prompt="Delete Mark> "',
'--header="<C-a>:Delete all"',
"--header-lines=1",
'--delimiter="\t"',
"--with-nth=2..",
"--nth=3",
"--multi",
"--exit-0",
"--bind ctrl-a:select-all+accept",
"--preview-window +{3}+3/2,nohidden",
"--tiebreak=index",
}, " "),
placeholder = "{1}",
}) --}}}
local preview = vim.fn["fzf#vim#with_preview"](wrapped)
preview["sink*"] = function(names)
_t(names):slice(2):map(function(name)
local mark = string.match(name, "^[^\t]+\t(%a)")
nvim.ex.delmarks(mark)
end)
end
vim.fn["fzf#run"](preview)
end --}}}
---Show marks for deletion.
function M.delete_marks() --{{{
local opts = {
fzf_opts = {
["--multi"] = "",
["--exit-0"] = "",
["--bind"] = "ctrl-a:select-all+accept",
},
}
opts = fzfconfig.normalize_opts(opts, fzfconfig.globals.nvim.marks)
if not opts then
return
end
local marks = vim.fn.execute("marks")
marks = vim.split(marks, "\n")
local entries = {}
for i = #marks, 3, -1 do
if string.match(string.lower(marks[i]), "^%s+[a-z]") then
local mark, line, col, text = marks[i]:match("(.)%s+(%d+)%s+(%d+)%s+(.*)")
table.insert(
entries,
string.format(
"%-15s %-15s %-15s %s",
fzfutils.ansi_codes.yellow(mark),
fzfutils.ansi_codes.blue(line),
fzfutils.ansi_codes.green(col),
text
)
)
end
end
table.sort(entries, function(a, b)
return a < b
end)
fzfcore.fzf_wrap(opts, entries, function(selected)
for _, name in ipairs(selected) do
local mark = string.match(name, "^(%a)")
nvim.ex.delmarks(mark)
end
end)()
end -- }}}
---Two phase search in git commits. The initial search is with git and the
-- secondary is with fzf.
function M.git_grep(term) --{{{
local format = "format:"
.. table.concat({
"%H",
"%C(yellow)%h%C(reset)",
"%C(bold green)(%ar)%C(reset)",
"%s",
"%C(green)<%an>%C(reset)",
"%C(blue)%d%C(reset)",
}, "\t")
local query = [[git --no-pager log -G '%s' --color=always --format='%s']]
local source = vim.fn.systemlist(string.format(query, term.args, format))
local reload_cmd = string.format(query, "{q}", format)
local wrapped = vim.fn["fzf#wrap"]({ --{{{
source = source,
options = table.concat({
'--prompt="Search in tree> "',
"+m",
'--delimiter="\t"',
"--phony",
"--with-nth=2..",
"--nth=3..",
"--tiebreak=index",
"--preview-window +{3}+3/2,~1,nohidden",
"--exit-0",
"--bind",
string.format('"change:reload:%s"', reload_cmd),
"--ansi",
"--bind",
'"alt-enter:unbind(change,alt-enter)+change-prompt(2. FZF> )+enable-search+clear-query"',
"--preview",
'"',
[[echo {} | grep -o '[a-f0-9]\{7\}' | head -1 |]],
"xargs -I % sh -c 'git show --color=always %'",
'"',
}, " "),
placeholder = "{1}",
})
--}}}
wrapped["sink*"] = function(list)
for _, sha in pairs(list) do
sha = sha:match("^[^\t]*")
if sha ~= "" then
local toplevel = vim.fn.system("git rev-parse --show-toplevel")
toplevel = string.gsub(toplevel, "\n", "")
local str = string.format([[fugitive://%s/.git//%s]], toplevel, sha)
nvim.ex.edit(str)
end
end
end
vim.fn["fzf#run"](wrapped)
end --}}}
---Browse the git tree.
function M.git_tree() --{{{
local format = "format:"
.. table.concat({
"%H",
"%C(yellow)%h%C(reset)",
"%C(bold green)(%ar)%C(reset)",
"%s",
"%C(green)<%an>%C(reset)",
"%C(blue)%d%C(reset)",
}, "\t")
local query = [[git --no-pager log --all --color=always --format='%s']]
local source = vim.fn.systemlist(string.format(query, format))
local wrapped = vim.fn["fzf#wrap"]({ --{{{
source = source,
options = table.concat({
'--prompt="Search in tree> "',
"+m",
'--delimiter="\t"',
"--with-nth=2..",
"--nth=3..",
"--tiebreak=index",
"--preview-window +{3}+3/2,~1,nohidden",
"--exit-0",
"--ansi",
"--preview",
'"',
[[echo {} | grep -o '[a-f0-9]\{7\}' | head -1 |]],
"xargs -I % sh -c 'git show --color=always %'",
'"',
}, " "),
placeholder = "{1}",
})
--}}}
wrapped["sink*"] = function(list)
local sha = list[2]:match("^[^\t]*")
if sha ~= "" then
local toplevel = vim.fn.system("git rev-parse --show-toplevel")
toplevel = string.gsub(toplevel, "\n", "")
local str = string.format([[fugitive://%s/.git//%s]], toplevel, sha)
nvim.ex.edit(str)
end
end
vim.fn["fzf#run"](wrapped)
end --}}}
---Checkout a branch.
function M.checkout_branch() --{{{
local current = vim.fn.system("git symbolic-ref --short HEAD")
current = current:gsub("\n", "")
local current_escaped = current:gsub("/", "\\/")
local cmd = table.concat({
"git",
"branch",
"-r",
"--no-color |",
"sed",
"-r",
"-e 's/^[^/]*\\///'",
"-e '/^",
current_escaped,
"$/d' -e '/^HEAD/d' | sort -u",
}, " ")
local opts = {
sink = function(branch)
vim.fn.system("git checkout " .. branch)
end,
options = { "--no-multi", "--header=Currently on: " .. current },
}
vim.fn["fzf#vim#grep"](cmd, 0, opts)
end --}}}
---Search for all todo/fixme/etc.
---@param extra_terms table any extra terms.
function M.open_todo(extra_terms) --{{{
local terms = vim.tbl_extend("force", {
"fixme",
"todo",
}, extra_terms)
terms = table.concat(terms, "|")
local cmd = table.concat({
"rg",
"--line-number",
"--column",
"--no-heading",
"--color=always",
"--smart-case",
"--hidden",
'-g "!.git/"',
"--",
'"fixme|todo"',
'"' .. terms .. '"',
}, " ")
vim.fn["fzf#vim#grep"](cmd, 1, vim.fn["fzf#vim#with_preview"]())
end --}}}
---Find and add files to the args list using fzf.vim native interface.
function M.add_args_native() --{{{
local seen = _t({})
_t(vim.fn.argv()):map(function(v)
seen[v] = true
end)
local files = _t({})
_t(vim.fn.systemlist({ "fd", ".", "-t", "f" }))
:map(function(v)
return v:gsub("^./", "")
end)
:filter(function(v)
return not seen[v]
end)
:map(function(v)
table.insert(files, v)
end)
if #files == 0 then
local msg = "Already added everything from current folder"
vim.notify(msg, vim.lsp.log_levels.WARN, { title = "Adding Args" })
return
end
local wrapped = vim.fn["fzf#wrap"]({
source = files,
options = "--multi --bind ctrl-a:select-all+accept",
})
wrapped["sink*"] = function(lines)
nvim.ex.arga(lines)
end
vim.fn["fzf#run"](wrapped)
end --}}}
---Find and add files to the args list.
function M.add_args() --{{{
fzf.files({
prompt = "Choose Files> ",
-- fzf_opts = {
-- ["--header"] = "'" .. table.concat({ "Buffer", "", "Filename", "" }, "\t") .. "'",
-- },
fd_opts = "--color=never --type f --hidden --follow --exclude .git",
actions = {
["default"] = function(selected)
nvim.ex.arga(selected)
end,
},
})
end --}}}
---Find and add files to the args list.
function M.delete_args() --{{{
fzf.args({
prompt = "Choose Files> ",
fzf_opts = {
["--exit-0"] = "",
},
actions = {
["default"] = function(selected)
nvim.ex.argd(selected)
end,
},
})
end --}}}
---Choose and remove files from the args list.
function M.delete_args_native() --{{{
local wrapped = vim.fn["fzf#wrap"]({
source = vim.fn.argv(),
options = "--multi --bind ctrl-a:select-all+accept",
})
wrapped["sink*"] = function(lines)
nvim.ex.argd(lines)
end
vim.fn["fzf#run"](wrapped)
end --}}}
---Populate the quickfix/local lists search results. Use it as an action.
---@param items string[]|table[]
function M.insert_into_list(items, is_local) --{{{
local values = {}
for _, item in pairs(items) do
if type(item) == "string" then
item = {
filename = item,
lnum = 1,
col = 1,
text = "Added with fzf selection",
}
end
local bufnr = vim.fn.bufnr(item.filename)
if bufnr > 0 then
local line = vim.api.nvim_buf_get_lines(bufnr, item.lnum - 1, item.lnum, false)[1]
if line ~= "" then
item.text = line
end
end
table.insert(values, item)
end
listish.insert_list(values, is_local)
end --}}}
---Shows a fzf search for going to definition. If LSP is not attached, it uses
--the BTags functionality. Use it as an action.
---@param lines string[]
function M.goto_def(lines) --{{{
local file = lines[1]
vim.api.nvim_command(("e %s"):format(file))
if lsp.is_lsp_attached() and lsp.has_lsp_capability("documentSymbolProvider") then
local ok = pcall(vim.lsp.buf.document_symbol)
if ok then
return
end
end
nvim.ex.BTags()
end --}}}
function M.autocmds_native() --{{{
local autocmds = vim.api.nvim_get_autocmds({})
local source = {}
for _, item in pairs(autocmds) do
local buf = item.buflocal and colour.ansi_color(colour.colours.red, "BUF") or ""
local once = item.once and colour.ansi_color(colour.colours.yellow, "ONCE") or ""
local line = table.concat({
colour.ansi_color(colour.colours.blue, item.event),
buf .. once,
colour.ansi_color(colour.colours.green, item.pattern),
item.command,
}, "\t")
table.insert(source, line)
end
local wrapped = vim.fn["fzf#wrap"]({
source = source,
options = table.concat({
'--prompt "Search Term > "',
"--header 'Event\tBuffer/Once\tPattern\tCommand'",
"+m",
"--exit-0",
"--ansi",
"--delimiter '\t'",
"--no-preview",
"--tiebreak=index",
}, " "),
placeholder = "{1}",
})
wrapped["sink*"] = function() end
vim.fn["fzf#run"](wrapped)
end --}}}
local autocmd_previewer = { _values = {} } --{{{
autocmd_previewer.base = fzfbuiltin.base
function autocmd_previewer:new(o, opts, fzf_win) --{{{
self = setmetatable(autocmd_previewer.base(o, opts, fzf_win), {
__index = vim.tbl_deep_extend("keep", self, autocmd_previewer.base),
})
local list = vim.api.nvim_get_autocmds({})
for _, item in ipairs(list) do
local row = {
event = item.event,
is_buf = item.buflocal,
is_once = item.once,
pattern = item.pattern,
command = item.command,
desc = item.desc,
}
table.insert(autocmd_previewer._values, row)
end
return self
end --}}}
function autocmd_previewer:parse_entry(entry_str) --{{{
local idx = tonumber(entry_str:match("^(%d+)"))
return autocmd_previewer._values[idx]
end --}}}
function autocmd_previewer:populate_preview_buf(entry_str) --{{{
local entry = self:parse_entry(entry_str)
self.preview_bufloaded = true
local e = {
event = entry.raw_event,
buflocal = entry.is_buf,
once = entry.is_once,
pattern = entry.raw_pattern,
command = entry.command,
desc = entry.desc,
}
local lines = vim.split(vim.inspect(e), "\n")
vim.api.nvim_buf_set_lines(self.preview_bufnr, 0, -1, false, lines)
local filetype = "lua"
vim.api.nvim_buf_set_option(self.preview_bufnr, "filetype", filetype)
self.win:update_scrollbar()
end --}}}
--}}}
function M.autocmds() --{{{
local red = fzfutils.ansi_codes.red
local yellow = fzfutils.ansi_codes.yellow
local blue = fzfutils.ansi_codes.blue
local green = fzfutils.ansi_codes.green
local grey = fzfutils.ansi_codes.grey
local fn = function(fzf_cb) --{{{
for i, entry in ipairs(autocmd_previewer._values) do
local buf = entry.is_buf and red("BUF") or grey(" ")
local once = entry.is_once and yellow("ONCE") or grey(" ")
local desc = entry.desc or entry.command
local e = {
i,
buf,
once,
blue(entry.event),
green(entry.pattern),
desc,
}
fzf_cb(table.concat(e, "\t"))
end
fzf_cb(nil)
end
local actions = {
["default"] = function() end,
} --}}}
coroutine.wrap(function()
local selected = require("fzf-lua").fzf({
prompt = "Autocmds❯ ",
previewer = autocmd_previewer,
actions = actions,
fzf_opts = {
["--with-nth"] = "2..",
},
}, fn)
require("fzf-lua").actions.act(actions, selected, {})
end)()
end --}}}
function M.jumps(opts) --{{{
opts = fzfconfig.normalize_opts(opts, fzfconfig.globals.nvim.jumps)
if not opts then
return
end
local jumps = vim.fn.execute(opts.cmd)
jumps = vim.split(jumps, "\n")
local entries = {}
for i = #jumps - 1, 3, -1 do
local jump, line, col, text = jumps[i]:match("(%d+)%s+(%d+)%s+(%d+)%s+(.*)")
table.insert(
entries,
string.format(
"%-15s %-15s %-15s %s",
fzfutils.ansi_codes.yellow(jump),
fzfutils.ansi_codes.blue(line),
fzfutils.ansi_codes.green(col),
text
)
)
end
opts.fzf_opts["--no-multi"] = ""
fzfcore.fzf_wrap(opts, entries, function(selected)
if not selected then
return
end
fzfactions.act(opts.actions, selected, opts)
end)()
end --}}}
---Shows a fzf search for going to a line number.
---@param lines string[]
local function goto_line(lines) --{{{
local file = lines[1]
vim.api.nvim_command(("e %s"):format(file))
quick.normal("n", ":")
end --}}}
---Shows a fzf search for line content.
---@param lines string[]
local function search_file(lines) --{{{
local file = lines[1]
vim.api.nvim_command(("e +BLines %s"):format(file))
end --}}}
---Set selected lines in the quickfix list with fzf search.
---@param items string[]|table[]
local function set_qf_list(items) --{{{
M.insert_into_list(items, false)
nvim.ex.copen()
end --}}}
---Set selected lines in the local list with fzf search.
---@param items string[]|table[]
local function set_loclist(items) --{{{
M.insert_into_list(items, true)
nvim.ex.lopen()
end --}}}
M.fzf_actions = { --{{{
["ctrl-t"] = "tab split",
["ctrl-s"] = "split",
["ctrl-v"] = "vsplit",
["alt-q"] = set_qf_list,
["alt-w"] = set_loclist,
["alt-@"] = M.goto_def,
["alt-:"] = goto_line,
["alt-/"] = search_file,
} --}}}
vim.g.fzf_action = M.fzf_actions
return M
-- vim: fdm=marker fdl=0
|
vim.g.moonflyCursorColor = 1
vim.g.moonflyItalics = 1
vim.g.moonflyNormalFloat = 1 -- visit repo for more settings
vim.g.moonflyTerminalColors = 1
vim.g.moonflyTransparent = 1
vim.g.moonflyUndercurls = 0
vim.g.moonflyVertSplits = 1
|
-- @Author: Ritesh Pradhan
-- @Date: 2016-04-13 23:28:21
-- @Last Modified by: Ritesh Pradhan
-- @Last Modified time: 2016-04-21 14:48:28
-- This collectible is used for long term bonus items during game play; power up levels and get more health, ammo and fuel
-- coin
-- medal
local physics = require("physics")
local hemeGlobals = require('libs.globals')
local utils = require('libs.utils')
local sounds = require('libs.sounds')
local collisionFilters = require( 'libs.collisionFilters')
local _M = {tag='collectible', type='default', w=50, h=50, x=1330, y=hemeGlobals.yLevel[1], xVel=-10, yVel=0, value=1}
function _M:newCollectible(params)
local o = params or {}
setmetatable(o, self);
self.__index = self;
return o
end
function _M:spawn()
self.shape = display.newImageRect('images/collectible/' .. self.type .. '.png', self.w, self.h)
self.shape.x, self.shape.y = self.x, self.y
physics.addBody(self.shape, 'kinematic', {density = 2, friction = 0.5, bounce = 0.5, filter =collisionFilters.collectible})
self.shape.isSensor = true
self.shape.type = self.type
self.shape.tag = self.tag
self.shape.value = self.value
self.shape.ref = self
--kinematic body move with velocity --
self.shape:setLinearVelocity( self.xVel, self.yVel )
self.shape:addEventListener("collision", self)
-- self.shape:addEventListener("tap", self)
end
function _M:move()
-- print("In move here :", self.y, hemeGlobals.yLevel[1])
if (self.y == hemeGlobals.yLevel[1]) then
self:moveUp()
else
self:moveDown()
end
end
function _M:moveDown()
self.x = self.x - 20
local time = math.random(1000,3000)
transition.to(self.shape, {time=time, y=self.y+100, x=self.x-20, onComplete=function() self:moveUp() end})
end
function _M:moveUp()
self.x = self.x - 20
local time = math.random(1000,3000)
transition.to(self.shape, {time=time, y=self.y-100, x=self.x-20, onComplete=function() self:moveDown() end})
end
function _M:collision(event)
if event.phase == "ended" then
-- print("Collision of collectible")
self:destroy()
end
end
-- function _M:tap(event)
-- print("Tapped of collectible")
-- print (event.target)
-- end
function _M:destroy()
-- print("Destroying collectible")
if (self ~= nil and self.shape ~= nil) then
transition.to(self, {time=1, alpha=0})
timer.performWithDelay( 1, function() physics.removeBody( self.shape ); self.shape:removeSelf( ); self = nil end , 1 )
-- sounds.play('refill_destroy')
end
end
return _M |
ITEM.name = "Аккумулятор"
ITEM.desc = "Источник электричества для автономного питания. Рабочее напряжение: 1.5V. Продолжительность работы: 300 секунд. \n\nХАРАКТЕРИСТИКИ: \n-электроника \n-используется для: работы фонарика"
ITEM.price = 1040
ITEM.permit = "Разное"
ITEM.weight = 0.17
ITEM.model = "models/kek1ch/battery.mdl"
ITEM.width = 1
ITEM.height = 1
ITEM.iconCam = {
pos = Vector(52.070404052734, 43.692253112793, 32.759872436523),
ang = Angle(25, 220, 0),
fov = 2.6
}
--[[ITEM.functions.Use = {
onRun = function(item)
local character = item.player:getChar()
character:setData("flashlightzarad", 300)
end
}]]
|
format_version = "1.0"
local Axes = { r=180,g=180,b=180 }
local Rect = { r=80,g=80,b=80,a = 64 }
local Graph = { r=0,g=255,b=0 }
function clip(value)
return math.max(0,math.min(1,value))
end
function drawVolume(property_values,display_info,dirty_rect)
local volume=clip(property_values[1])
local w = display_info.width
local h = display_info.height
local width = w*volume
jbox_display.draw_rect({left= 0, top= 0, right= width, bottom= h-1},Graph)
end
-- extend this to a stereo version, then I can have two, one for input, the other for output
--
--jbox.custom_display {
-- graphics={node="volume"},
-- display_width_pixels=300,
-- display_height_pixels=40,
-- values = { "/custom_properties/volume" },
-- draw_function = "drawVolume"
-- },
--
-- volume = {
-- offset = {700,54},
-- { path = "Display_200_50_1frames", frames = 1 }
-- }, |
--[[
Planetfall: Catmull-Rom Cutscene Camera Track System
by Olivier 'LuaPineapple' Hamel
I'll be nice and release a stand alone version for you guys.
BUT I EXECPT A GODS AWFUL AMOUNT OF COOKIES!
If I don't I'll get annoyed and when I get annoyed I become irritable and when I become irritable people DIE! [/quote_dr_evil]
--]]
--[[
5:52 PM - Firgof Umbra: I worry about your sense of perception sometimes.
5:52 PM - LuaPineapple: I AM GOD!
5:52 PM - LuaPineapple: WORSHIP ME!
5:52 PM - Firgof Umbra: ...
5:53 PM - LuaPineapple: INSECT!
--]]
local function AddLua(filename)
local tmp = string.Explode("/", string.lower(filename))
local parts = string.Explode("_", tmp[#tmp])
if SERVER then
if (parts[1] == "sh") or (parts[1] == "shared.lua") then
include(filename)
return AddCSLuaFile(filename)
elseif parts[1] == "cl" then
return AddCSLuaFile(filename)
elseif (parts[1] == "sv") or (parts[1] == "init.lua") then
return include(filename)
end
ErrorNoHalt("Unknown file: ",filename,"\n")
PrintTable(tmp)
PrintTable(parts)
Error("Unable to determine if shared, serverside, or clientside.\n")
elseif CLIENT then
if (parts[1] == "sh") or (parts[1] == "cl") or (parts[1] == "shared.lua") then
return include(filename)
elseif (parts[1] == "sv") or (parts[1] == "init.lua") then //others, just to keep the system happy
return
end
ErrorNoHalt("Unknown file: ",filename,"\n")
PrintTable(tmp)
PrintTable(parts)
Error("Unable to determine if shared, serverside, or clientside.\n")
else
return Error("Apparently we're God as we're not the client or the server.\n")
end
end
if SERVER then AddCSLuaFile("sh_CatmullRomCams.lua") end
CatmullRomCams = CatmullRomCams or {}
CatmullRomCams.AddLua = AddLua
CatmullRomCams.FilePath = "CatmullRomCameraTracks/"
CatmullRomCams.SV = CatmullRomCams.SV or {}
CatmullRomCams.SH = CatmullRomCams.SH or {}
CatmullRomCams.CL = CatmullRomCams.CL or {}
CatmullRomCams.SToolMethods = {}
function CatmullRomCams.SH.UnitsToMeters(dist)
return (dist * 0.0254)
end
function CatmullRomCams.SH.MetersToUnits(dist)
return (dist * 39.3700787)
end
function CatmullRomCams.SToolMethods.ValidTrace(trace)
return (trace and trace.Entity and trace.Entity.GetClass and trace.Entity.IsValid and trace.Entity:IsValid() and (trace.Entity:GetClass() == "sent_catmullrom_camera"))
end
CatmullRomCams.Tracks = CatmullRomCams.Tracks or {}
local files = file.Find("CatmullRomCams/*.lua", "LUA")
for _, v in pairs(files) do
AddLua("CatmullRomCams/" .. v)
end
local files_stools = file.Find("CatmullRomCams/STools/*.lua", "LUA")
for _, v in pairs(files_stools) do
AddLua("CatmullRomCams/STools/" .. v)
end
---FREEZEBUG: You forgot client tool data.
local files_stools_client = file.Find("weapons/gmod_tool/stools/*.lua", "LUA")
for _, v in pairs(files_stools_client) do
AddCSLuaFile("weapons/gmod_tool/stools/" .. v)
end
--[[
CatmullRomCams = CatmullRomCams or {}
CatmullRomCams.AddLua = AddLua
CatmullRomCams.FilePath = "CatmullRomCameraTracks/"
local function AddLua(filename)
local tmp = string.Explode("/", string.lower(filename))
local parts = string.Explode("_", tmp[#tmp])
if SERVER then
if (parts[1] == "sh") or (parts[1] == "shared.lua") then
include(filename)
return AddCSLuaFile(filename)
elseif parts[1] == "cl" then
return AddCSLuaFile(filename)
elseif (parts[1] == "sv") or (parts[1] == "init.lua") then
return include(filename)
end
ErrorNoHalt("Unknown file: ",filename,"\n")
PrintTable(tmp)
PrintTable(parts)
Error("Unable to determine if shared, serverside, or clientside.\n")
elseif CLIENT then
if (parts[1] == "sh") or (parts[1] == "cl") or (parts[1] == "shared.lua") then
return include(filename)
elseif (parts[1] == "sv") or (parts[1] == "init.lua") then //others, just to keep the system happy
return
end
ErrorNoHalt("Unknown file: ",filename,"\n")
PrintTable(tmp)
PrintTable(parts)
Error("Unable to determine if shared, serverside, or clientside.\n")
else
return Error("Apparently we're God as we're not the client or the server.\n")
end
end
--[[
if SERVER then AddCSLuaFile("sh_CatmullRomCams.lua") end
CatmullRomCams = CatmullRomCams or {}
CatmullRomCams.AddLua = AddLua
CatmullRomCams.FilePath = "CatmullRomCameraTracks/"
CatmullRomCams.SV = CatmullRomCams.SV or {}
CatmullRomCams.SH = CatmullRomCams.SH or {}
CatmullRomCams.CL = CatmullRomCams.CL or {}
CatmullRomCams.SToolMethods = {}
function CatmullRomCams.SH.UnitsToMeters(dist)
return (dist * 0.0254)
end
function CatmullRomCams.SH.MetersToUnits(dist)
return (dist * 39.3700787)
end
function CatmullRomCams.SToolMethods.ValidTrace(trace)
return (trace and trace.Entity and trace.Entity.GetClass and trace.Entity.IsValid and trace.Entity:IsValid() and (trace.Entity:GetClass() == "sent_catmullrom_camera"))
end
CatmullRomCams.Tracks = CatmullRomCams.Tracks or {}
if SERVER then
AddCSLuaFile("CatmullRomCams/Stools/sh_duration_editor.lua")
AddCSLuaFile("CatmullRomCams/Stools/sh_hitchcock_effect.lua")
AddCSLuaFile("CatmullRomCams/Stools/sh_layout.lua")
AddCSLuaFile("CatmullRomCams/Stools/sh_linker.lua")
AddCSLuaFile("CatmullRomCams/Stools/sh_map_io_editor.lua")
AddCSLuaFile("CatmullRomCams/Stools/sh_numpad_trigger.lua")
AddCSLuaFile("CatmullRomCams/Stools/sh_smart_look.lua")
AddCSLuaFile("CatmullRomCams/cl_calcview_hook.lua")
AddCSLuaFile("CatmullRomCams/cl_edit_lock_display.lua")
AddCSLuaFile("CatmullRomCams/cl_tab.lua")
AddCSLuaFile("CatmullRomCams/cl_language_defs.lua")
AddCSLuaFile("CatmullRomCams/sh_catmullrom_spline_controller.lua")
AddCSLuaFile("CatmullRomCams/sh_cleanup.lua")
AddCSLuaFile("CatmullRomCams/sh_gc_booster.lua")
AddCSLuaFile("CatmullRomCams/sh_general_hooks.lua")
AddCSLuaFile("CatmullRomCams/sh_Quaternions.lua")
AddCSLuaFile("CatmullRomCams/sh_save_load.lua")
include("CatmullRomCams/sv_icon_resource.lua")
include("CatmullRomCams/sv_adv_dup_paste.lua")
include("CatmullRomCams/sv_saverestore.lua")
end
include("CatmullRomCams/sh_catmullrom_spline_controller.lua")
include("CatmullRomCams/sh_cleanup.lua")
include("CatmullRomCams/sh_gc_booster.lua")
include("CatmullRomCams/sh_general_hooks.lua")
include("CatmullRomCams/sh_Quaternions.lua")
include("CatmullRomCams/sh_save_load.lua")
include("CatmullRomCams/Stools/sh_duration_editor.lua") --
include("CatmullRomCams/Stools/sh_hitchcock_effect.lua") --
include("CatmullRomCams/Stools/sh_layout.lua") --
include("CatmullRomCams/Stools/sh_linker.lua") --
include("CatmullRomCams/Stools/sh_map_io_editor.lua") --
include("CatmullRomCams/Stools/sh_numpad_trigger.lua") --
include("CatmullRomCams/Stools/sh_smart_look.lua") --
if CLIENT then
include("CatmullRomCams/cl_language_defs.lua")
include("CatmullRomCams/cl_calcview_hook.lua")
include("CatmullRomCams/cl_edit_lock_display.lua")
include("CatmullRomCams/cl_tab.lua")
end
]]--
|
#!/usr/bin/env luajit
require 'ext'
local env = setmetatable({}, {__index=_G})
if setfenv then setfenv(1, env) else _ENV = env end
require 'symmath'.setup{env=env, implicitVars=true, fixVariableNames=true, MathJax={title='Gravitation 16.1 - expression'}}
local deta_eq_0 = eta'_ab,c':eq(0)
local ddelta_eq_0 = delta'_ab,c':eq(0)
printbr'metric:'
local g_def = g'_ab':eq(eta'_ab' - 2 * Phi * delta'_ab')
printbr(g_def)
printbr()
printbr'metric inverse:'
-- gU = -1/(1+2 Phi), 1 / (1 - 2 Phi)
-- = ( -1+2Phi, 1+2Phi )/(1-4Phi^2)
local gU_def = g'^ab':eq( frac(1, 1 - 4 * Phi^2) * (eta'^ab' + 2 * Phi * delta'^ab'))
printbr(gU_def)
local g_gU_ident = g'^ac' * g'_cb'
printbr(g_gU_ident)
g_gU_ident = g_gU_ident:subst(g_def:reindex{ab='cb'}, gU_def:reindex{ab='ac'}):simplify()
printbr(g_gU_ident)
g_gU_ident = g_gU_ident
:replace(eta'^ac' * eta'_cb', delta'^a_b')
-- none of these are being replace ...
:replace(-2 * eta'^ac' * Phi * delta'_cb', 0)
:replace(2 * Phi * delta'^ac' * eta'_cb', 0)
:replace(-4 * Phi^2 * delta'^ac' * delta'_cb', -4 * Phi^2 * delta'^a_b')
:simplify()
printbr(g_gU_ident)
-- and then this should turn out to be delta^a_b * (1 - 4 Phi^2) / (1 - 4 Phi^2)
printbr()
printbr'metric derivative:'
local dg_def = g_def'_,c'()
printbr(dg_def)
dg_def = dg_def:subst(deta_eq_0, ddelta_eq_0)()
printbr(dg_def)
printbr'connections:'
local ConnL_def = Gamma'_abc':eq(frac(1,2) * (g'_ab,c' + g'_ac,b' - g'_bc,a'))
printbr(ConnL_def)
ConnL_def = ConnL_def:subst(dg_def, dg_def:reindex{abc='acb'}, dg_def:reindex{abc='bca'})()
printbr(ConnL_def)
local Conn_def = Gamma'^a_bc':eq(g'^ad' * Gamma'_dbc')
printbr(Conn_def)
Conn_def = Conn_def:subst(gU_def:reindex{ab='ad'}, ConnL_def:reindex{abc='dbc'})()
printbr(Conn_def)
local function isTensorRef(x) return require 'symmath.tensor.Ref':isa(x) end
printbr('let ', Phi:eq(0), ', but keep ', Phi'_,a', 'to find:')
Conn_def = Conn_def:replace(Phi, 0, isTensorRef)()
printbr(Conn_def)
printbr()
local du_def = u'^a_;b':eq(u'^a_,b' + Gamma'^a_cb' * u'^c')
printbr(du_def)
du_def = du_def:subst(Conn_def:reindex{abc='acb'})
:simplify()
printbr(du_def)
local duit_def = du_def:reindex{ab='it'}
printbr(duit_def)
local duij_def = du_def:reindex{ab='ij'}
printbr(duij_def)
printbr()
-- TODO let Phi,t = 0 as well, but that means splitting Conn into time and space
printbr'stress-energy:'
local T_def = T'^ab':eq( (rho + P) * u'^a' * u'^b' + P * g'^ab')
printbr(T_def)
printbr'divergence-free...'
local dT_def = T_def'_;b'()
printbr(dT_def)
printbr'substitute...'
dT_def = dT_def
:replace(g'^ab_;b', 0)
:replace(g'^ab', eta'^ab')
:replace(P'_;b', P'_,b')
:replace(rho'_;b', rho'_,b')
:simplify()
printbr(dT_def)
printbr'separate b index into t and j:'
dT_def = dT_def:lhs():eq( dT_def:rhs():reindex{b='t'} + dT_def:rhs():reindex{b='j'} )
printbr(dT_def)
printbr'look at t component of a:'
local dTt_def = dT_def:reindex{a='t'}
printbr(dTt_def)
printbr'substitute...'
dTt_def = dTt_def
:replace(u'^t', 1)
:replace(u'^t_;t', 0)
:replace(u'^t_;j', 0)
:subst(du_def:reindex{ab='jj'})
:replace(eta'^tt', -1)
:replace(eta'^tj', 0)
:simplify()
printbr(dTt_def)
printbr()
printbr'look at i component of a:'
local dTi_def = dT_def:reindex{a='i'}
printbr(dTi_def)
printbr'substitute...'
dTi_def = dTi_def
:replace(u'^t', 1)
:replace(eta'^ti', 0)
:replace(eta'^it', 0)
:replace(eta'^tj', 0)
:simplify()
printbr(dTi_def)
|
local tasks = require("utils.tasks")
local utils = require("utils")
local mapStruct = require("structs.map")
local sideStruct = {}
local decoderBlacklist = {
Filler = true,
Style = true,
levels = true
}
local encoderBlacklist = {
map = true,
_type = true
}
local function tableify(data, t)
t = t or {}
local name = data.__name
local children = data.__children or {}
t[name] = {}
for k, v in pairs(data) do
if k:sub(1, 1) ~= "_" then
t[name][k] = v
end
end
for i, child in ipairs(children) do
tableify(child, t[name])
end
return t
end
local function binfileify(name, data)
local res = {
__name = name,
__children = {}
}
for k, v in pairs(data) do
if type(v) == "table" then
table.insert(res.__children, binfileify(k, v))
else
res[k] = v
end
end
if #res.__children == 0 then
res.__children = nil
end
return res
end
function sideStruct.decode(data)
local side = {
_type = "side"
}
for i, v in ipairs(data.__children or {}) do
local name = v.__name
if not decoderBlacklist[name] then
tableify(v, side)
end
end
side.map = mapStruct.decode(data)
tasks.update(side)
return side
end
function sideStruct.decodeTaskable(data, tasksTarget)
local sideTask = tasks.newTask(
function(task)
local side = {}
local mapTask = tasks.newTask(-> mapStruct.decode(data), nil, tasksTarget)
task:waitFor(mapTask)
side.map = mapTask.result
for i, v in ipairs(data.__children or {}) do
local name = v.__name
if not decoderBlacklist[name] then
tableify(v, side)
end
end
tasks.update(side)
end,
nil,
tasksTarget
)
tasks.waitFor(sideTask)
tasks.update(sideTask.result)
end
function sideStruct.encode(side)
local res = mapStruct.encode(side.map)
for k, v in pairs(side) do
if not encoderBlacklist[k] then
table.insert(res.__children, binfileify(k, v))
end
end
return res
end
function sideStruct.encodeTaskable(side, tasksTarget)
local sideTask = tasks.newTask(
function(task)
local mapTask = tasks.newTask(-> mapStruct.encode(side.map), nil, tasksTarget)
tasks.waitFor(mapTask)
local res = mapTask.result
for k, v in pairs(side) do
if not encoderBlacklist[k] then
table.insert(res.__children, binfileify(k, v))
end
end
tasks.update(res)
end,
nil,
tasksTarget
)
tasks.waitFor(sideTask)
tasks.update(sideTask.result)
end
return sideStruct |
local FixedNumber = {}
local function checkInt(x)
local _, dec = math.modf(x)
assert(dec == 0)
end
local function toInt(x)
local t = math.modf(x)
return t
end
FixedNumber.FRACTIONAL_BITS = 24
FixedNumber.FRACTIONAL_BASE = 1 << FixedNumber.FRACTIONAL_BITS
FixedNumber.FRACTIONAL_MASK = (1 << FixedNumber.FRACTIONAL_BITS) - 1
FixedNumber.FRACTIONAL_HALF = (1 << (FixedNumber.FRACTIONAL_BITS - 1))
FixedNumber.FromRaw = function(val)
checkInt(val)
local t = {
val = val,
}
setmetatable(t, FixedNumber)
return t
end
FixedNumber.FromDouble = function(val)
return FixedNumber.FromRaw(toInt((val or 0) * FixedNumber.FRACTIONAL_BASE))
end
FixedNumber.FromFraction = function(numerator, denominator)
checkInt(numerator)
checkInt(denominator)
if numerator >= 0 then
if denominator > 0 then
return FixedNumber.FromRaw(((numerator << (FixedNumber.FRACTIONAL_BITS + 1)) // denominator + 1) >> 1)
elseif denominator < 0 then
return FixedNumber.FromRaw(-(((numerator << (FixedNumber.FRACTIONAL_BITS + 1)) // -denominator + 1) >> 1))
end
else
if denominator > 0 then
return FixedNumber.FromRaw(-(((-numerator << (FixedNumber.FRACTIONAL_BITS + 1)) // denominator + 1) >> 1))
elseif denominator < 0 then
return FixedNumber.FromRaw(((-numerator << (FixedNumber.FRACTIONAL_BITS + 1)) // (-denominator) + 1) >> 1)
end
end
end
FixedNumber.Clone = function(a)
return FixedNumber.FromRaw(a.val)
end
FixedNumber.Copy = function(a, b)
a.val = b.val
end
FixedNumber.Get = function(a)
return a.val
end
FixedNumber.ToInt = function(a)
if a.val >= 0 then
return a.val >> FixedNumber.FRACTIONAL_BITS
else
return -(-a.val >> FixedNumber.FRACTIONAL_BITS)
end
end
FixedNumber.ToDouble = function(a)
return a.val / FixedNumber.FRACTIONAL_BASE
end
FixedNumber.ToFloor = function(a)
if a.val >= 0 then
return a.val >> FixedNumber.FRACTIONAL_BITS
else
return -((-a.val + FixedNumber.FRACTIONAL_MASK) >> FixedNumber.FRACTIONAL_BITS)
end
end
FixedNumber.ToCeil = function(a)
if a.val >= 0 then
return (a.val + FixedNumber.FRACTIONAL_MASK) >> FixedNumber.FRACTIONAL_BITS
else
return -(-a.val >> FixedNumber.FRACTIONAL_BITS)
end
end
FixedNumber.ToRound = function(a)
if a.val >= 0 then
return (a.val + FixedNumber.FRACTIONAL_HALF) >> FixedNumber.FRACTIONAL_BITS
else
return -((-a.val + FixedNumber.FRACTIONAL_HALF) >> FixedNumber.FRACTIONAL_BITS)
end
end
FixedNumber.__index = FixedNumber
FixedNumber.__tostring = function(a)
return tostring(a:ToDouble())
end
FixedNumber.__add = function(a, b)
return FixedNumber.FromRaw(a.val + b.val)
end
FixedNumber.__sub = function(a, b)
return FixedNumber.FromRaw(a.val - b.val)
end
FixedNumber.__mul = function(a, b)
local x = math.abs(a.val)
local y = math.abs(b.val)
local x1 = x >> FixedNumber.FRACTIONAL_BITS;
local x2 = x & FixedNumber.FRACTIONAL_MASK;
local y1 = y >> FixedNumber.FRACTIONAL_BITS;
local y2 = y & FixedNumber.FRACTIONAL_MASK;
if (a.val < 0 and b.val > 0) or (a.val > 0 and b.val < 0) then
return FixedNumber.FromRaw(-(((x1 * y1) << FixedNumber.FRACTIONAL_BITS) + x1 * y2 + x2 * y1 + ((x2 * y2 + FixedNumber.FRACTIONAL_HALF) >> FixedNumber.FRACTIONAL_BITS)))
else
return FixedNumber.FromRaw(((x1 * y1) << FixedNumber.FRACTIONAL_BITS) + x1 * y2 + x2 * y1 + ((x2 * y2 + FixedNumber.FRACTIONAL_HALF) >> FixedNumber.FRACTIONAL_BITS))
end
end
FixedNumber.__div = function(a, b)
local dividend = math.abs(a.val)
local divisor = math.abs(b.val)
local result = 0
for i = 0, FixedNumber.FRACTIONAL_BITS do
local t = dividend // divisor
if t > 0 then
result = result + (t << (FixedNumber.FRACTIONAL_BITS + 1 - i))
dividend = dividend % divisor
end
dividend = dividend << 1
end
if (a.val < 0 and b.val > 0) or (a.val > 0 and b.val < 0) then
return FixedNumber.FromRaw(-((result + 1) >> 1))
else
return FixedNumber.FromRaw((result + 1) >> 1)
end
end
FixedNumber.__unm = function(a)
return FixedNumber.FromRaw(-a.val)
end
FixedNumber.__eq = function(a, b)
return a.val == b.val
end
FixedNumber.__lt = function(a, b)
return a.val < b.val
end
FixedNumber.__le = function(a, b)
return a.val <= b.val
end
FixedNumber.EPS = FixedNumber.FromRaw(1)
FixedNumber.MIN = FixedNumber.FromRaw(-2^53)
FixedNumber.MAX = FixedNumber.FromRaw(2^53)
FixedNumber.NEG_ONE = FixedNumber.FromRaw(-FixedNumber.FRACTIONAL_BASE)
FixedNumber.NEG_TWO = FixedNumber.FromRaw(-2 * FixedNumber.FRACTIONAL_BASE)
FixedNumber.ZERO = FixedNumber.FromRaw(0)
FixedNumber.HALF = FixedNumber.FromRaw(FixedNumber.FRACTIONAL_HALF)
FixedNumber.ONE = FixedNumber.FromRaw(FixedNumber.FRACTIONAL_BASE)
FixedNumber.TWO = FixedNumber.FromRaw(2 * FixedNumber.FRACTIONAL_BASE)
FixedNumber.FOUR = FixedNumber.FromRaw(4 * FixedNumber.FRACTIONAL_BASE)
FixedNumber.NUM90 = FixedNumber.FromRaw(90 * FixedNumber.FRACTIONAL_BASE)
FixedNumber.NUM180 = FixedNumber.FromRaw(180 * FixedNumber.FRACTIONAL_BASE)
FixedNumber.NUM270 = FixedNumber.FromRaw(270 * FixedNumber.FRACTIONAL_BASE)
FixedNumber.NUM360 = FixedNumber.FromRaw(360 * FixedNumber.FRACTIONAL_BASE)
FixedNumber.NUM255 = FixedNumber.FromRaw(255 * FixedNumber.FRACTIONAL_BASE)
FixedNumber.DOT1 = FixedNumber.FromRaw(FixedConsts.DOT1)
FixedNumber.DOT01 = FixedNumber.FromRaw(FixedConsts.DOT01)
FixedNumber.DOT001 = FixedNumber.FromRaw(FixedConsts.DOT001)
FixedNumber.DOT0001 = FixedNumber.FromRaw(FixedConsts.DOT0001)
FixedNumber.DOT00001 = FixedNumber.FromRaw(FixedConsts.DOT00001)
FixedNumber.DOT000001 = FixedNumber.FromRaw(FixedConsts.DOT000001)
return FixedNumber |
--[[ create zip archive sample ]]
assert(Zip.compress(package.__dir .. "/iosample", package.__dir .. "/iosample.zip"))
print "✅ OK: Zip.compress: iosample/ => iosample.zip"
--[[ read zip archive sample ]]
local zip = Zip.Archiver.new(package.__dir .. "/iosample.zip", "r")
assert(zip:getState() ~= Object.State.FAILED)
assert(zip:toFirstFile())
print "✅ OK: Zip.Archiver:open-getCurrentFileInformation"
repeat
local info = zip:getCurrentFileInformation(true)
printf("\t%s: %s\n", info.fileName, info.uncompressedData:toString())
until not zip:toNextFile()
zip:close()
assert(IO.removeDirectory(package.__dir .. "/iosample"))
assert(IO.removeFile(package.__dir .. "/iosample.zip"))
assert(not Path.isDirectory(package.__dir .. "/iosample"))
assert(not Path.isFile(package.__dir .. "/iosample.zip"))
print "✅ OK: Aula.IO.removeDirectory, Aula.IO.removeFile"
|
return {
["end"] = "test passed?",
["notnull"] = true,
["test"] = "A test for null values"
}
|
return {
name = 'stanley',
--[[ Config file handling ]]
config_schema = {'name','description','version','author','autoload','require'},
config_file_name = 'package.yaml',
config = {},
-- Load configuration and build queue
initialize = function(self)
if File.exists(self.config_file_name) then
-- Parse configuration file 'package.yaml'
self.config = YAML.parse(
File.get_lines(self.config_file_name)
)
self.autoload_template = self.autoload_template:gsub('__NAME__', self.name)
-- Build queue according to configuration
self.autoload = {}
self.packages = {}
self:buildQueue(self.config)
end
end,
-- Dump self.config to package.yaml
save = function(self)
local file = File.open(self.config_file_name, 'w')
file:write(YAML.dump(self.config, self.config_schema))
File.close(file)
io.write('\nCurrent configuration has been saved to \'package.yaml\' file.\n')
end,
-- Required list manipulation
hasRequired = function(self, repo)
if self.config.require then
local package = {
name = repo,
source = CLI:getOption('source')
}
for index, required in ipairs(self.config.require) do
local source = required.source or CLI:getDefault('source')
if package.name == required.name and package.source == source then
return true, index
end
end
end
return false, nil
end,
requirePackages = function(self, ...)
local repos = { ... }
if not self.config.require then
self.config.require = {}
end
local changed = false
local source = CLI:getOption('source')
for _,repo in ipairs(repos) do
local package_text = 'Package "' .. source .. repo .. '" '
if not self:hasRequired(repo) then
local package = { name = repo }
if source ~= CLI:getDefault('source') then
package.source = source
end
table.insert(self.config.require, package)
changed = true
io.write(package_text .. 'added to required list.\n')
else
io.write(package_text .. 'is already required. Skip.\n')
end
end
if changed then
self:save()
end
end,
removePackages = function(self, ...)
if not self.config.require then return end
local repos = { ... }
local changed = false
local source = CLI:getOption('source')
for _,repo in ipairs(repos) do
local package_text = 'Package "' .. source .. repo .. '" '
local has, index = self:hasRequired(repo)
if has then
table.remove(self.config.require, index)
changed = true
io.write(package_text .. 'has been removed from list.\n')
else
io.write(package_text .. 'not found. Skip.\n')
end
end
if changed then
self:save()
end
end,
initializePackage = function(self)
io.write('\nInitializing "' .. self.config_file_name .. '" file...\n\n')
io.write('Please provide information for the package:\n')
self.config.name = CLI:input('Name:', self.config.name)
self.config.description = CLI:input('Description:', self.config.description)
self.config.version = CLI:input('Version:', self.config.version or '0.1')
local answer = false
answer = CLI:confirm('Do you want to add author information?', false)
if answer == true then
if CLI:confirm('Overwrite previous information?', false) == true then
self.config.author = {}
else
self.config.author = self.config.author or {}
end
while answer == true do
local author = {}
while author.name == nil do
author.name = CLI:input('Author name:')
end
while author.email == nil do
author.email = CLI:input('Author email:')
end
table.insert(self.config.author, author)
answer = CLI:confirm('Add another?', false)
end
end
answer = CLI:confirm('Do you want to add autoload information?', false)
if answer == true then
if CLI:confirm('Overwrite previous information?', false) == true then
self.config.autoload = {}
else
self.config.autoload = self.config.autoload or {}
end
while answer == true do
local autoload = {}
autoload.type = CLI:choice('Autoload type:', {'file', 'global'})
if autoload.type == 'global' then
while autoload.name == nil do
autoload.name = CLI:input('Autoload global:')
end
end
autoload.path = CLI:input('Autoload path:', 'init.lua')
autoload.relative = CLI:input('Is this path relative to current package?', true)
table.insert(self.config.autoload, autoload)
answer = CLI:confirm('Add another?', false)
end
end
answer = CLI:confirm('Do you want to add some packages to require list?', false)
if answer == true then
if CLI:confirm('Overwrite previous information?', false) == true then
self.config.require = {}
else
self.config.require = self.config.require or {}
end
while answer == true do
local package = {}
while package.name == nil do
package.name = CLI:input('Package name:')
end
package.source = CLI:input('Package source:', CLI:getOption('source'))
if package.source == CLI:getOption('source') then
package.source = nil
end
table.insert(self.config.require, package)
answer = CLI:confirm('Add another?', false)
end
end
self:save()
end,
updatePackages = function(self)
os.execute('mkdir -p ./lib') -- ensure lib directory exists
local git = os.capture('which git')
io.write('\nUpdating packages from sources...\n')
for _,queued in ipairs(self.packages) do
if queued.source ~= 'local' then
local source = queued.source or self.config.default_source or CLI:getOption('source')
source = source .. queued.name
io.write('\nDownloading from: ' .. source .. '\n')
io.flush()
local target = './lib/' .. (queued.target or queued.name)
if not File.exists(target .. '/') then
os.execute(git .. ' clone ' .. source .. ' ' .. target)
else
os.execute('cd ' .. target .. ' && ' .. git .. ' pull')
end
local config_file = target .. '/' .. self.config_file_name
if File.exists(config_file) then
self:buildQueue( YAML.parse( File.get_lines(config_file) ) )
end
os.execute('sleep 2')
end
end
io.write('\nDone.\n')
end,
--[[ Config file handling ]]
--[[ Queue handling ]]
--[[ Loaded packages structure:
{
name = 'test/package',
target = 'test/package2/gitea',
source = 'https://gitea.org/'
},
{
name = 'test/ssh_package',
source = 'ssh://[email protected]:'
},
{
name = 'test/package2',
source = 'local'
}
--]]
packages = {},
hasQueued = function(self, package)
if type(package) == 'string' then
local name = package
package = {
name = name,
source = CLI:getOption('source')
}
end
for index, queued in ipairs(self.packages) do
local source = queued.source or CLI:getOption('source')
if package.name == queued.name and package.source == source then
return true, index
end
end
return false, nil
end,
queuePackage = function(self, package)
if self:hasQueued(package) then return end
debug(4, 'Required package', package)
if package.name then
local package_config_path = 'lib/' .. package.name .. '/' .. self.config_file_name
debug(5, 'Required package config path', package_config_path)
local package_config = File.get_lines(package_config_path)
if package_config then
package_config = YAML.parse(package_config)
self:buildQueue(package_config)
end
-- Set package as processed
table.insert(self.packages, package)
end
end,
buildQueue = function(self, config)
debug(4, 'Build queue from config', config)
if config.require then
for _,required in ipairs(config.require) do
self:queuePackage(required)
end
end
if config.autoload then
for _,item in ipairs(config.autoload) do
self:addToAutoload(item, config)
end
elseif File.exists('./lib/' .. config.name .. '/init.lua') then
self:addToAutoload({
type = 'file',
path = 'init.lua'
}, config)
end
debug(5, 'Processed packages', self.packages)
debug(5, 'Processed autoload', self.autoload)
end,
--[[ Queue handling ]]
--[[ Autoload structure:
{
type = 'file',
path = 'init.lua',
relative = true
},
{
type = 'global',
path = 'test.lua'
name = 'test',
}
--]]
autoload = {},
autoload_template = "package.path = package.path .. ';./?/init.lua;~/.__NAME__/libs/?.lua;~/.__NAME__/libs/?/init.lua'\npackage.path = package.path .. ';' .. package.path:gsub('%.lua', '.luac')\ntable.insert(package.loaders, 2, function(modulename)\n\tlocal errmsg, modulepath = '', modulename:gsub('%.', '/'):gsub('`/', '.')\n\tfor path in package.path:gmatch('([^;]+)') do\n\t\tlocal filename = path:gsub('%?', modulepath)\n\t\tlocal file = io.open(filename, 'rb')\n\t\tif file then return assert(loadstring(assert(file:read('*a')), filename)) end\n\t\terrmsg = errmsg..'\\n\\tno file \\''..filename..'\\''\n\tend return errmsg\nend)\n",
_compareAndValidateItems = function(item1, item2)
if item1.type ~= item2.type and item1.path ~= item2.path then
return false
end
if item1.relative == item2.relative then
if item1.type == 'global' then
return item1.name ~= nil and item2.name ~= nil and item1.name == item2.name
end
return true
end
return false
end,
hasInAutoload = function(self, item)
for _,queued in ipairs(self.autoload) do
if self._compareAndValidateItems(item, queued) then
return true
end
end
return false
end,
addToAutoload = function(self, item, package)
local path = item.path:gsub('%.luac?$', '')
if package.name ~= self.config.name then
if item.relative ~= false then
path = package.name .. '/' .. path
end
path = 'lib/' .. path
end
item.path = path:gsub('%.', '`.'):gsub('/', '.')
if self:hasInAutoload(item) then return end
debug(5, 'Adding to autoload', item)
table.insert(self.autoload, item)
end,
generateAutoloadFile = function(self)
os.execute('mkdir -p ./lib') -- ensure lib directory exists
local file = File.open('lib/autoload.lua', 'w')
file:write('-- This file was generated by ' .. self.name:sub(1,1):upper() .. self.name:sub(2) .. ' :)\n')
file:write(self.autoload_template .. '\n')
local local_path = 'lib.' .. self.config.name:gsub('%.', '`.'):gsub('/', '.') .. '.'
for _,queued in ipairs(self.autoload) do
debug(2, 'Queued item', queued)
if queued.path then
local line = 'require\''
if queued.type == 'global' then
line = queued.name .. ' = ' .. line
end
line = line .. queued.path:gsub(local_path:gsub('%.', '%%.'), '') .. '\''
debug(1, 'Autoload line', line)
file:write(line .. '\n')
end
end
File.close(file)
io.write('\nYou can now use generated file with:\nrequire\'lib.autoload\'\n')
end,
} |
comp = {"najduži", "najkraći"}
year = {"trećina", "četvrtina", "petina", "šestina", "sedmina", "osmina"}
msg_day = " dana"
msg_week = {" nedelja", " nedelje"}
msg_month = {" meseci", " meseca"}
msg_year = " godine"
|
local response = require "resty.kafka.response"
local request = require "resty.kafka.request"
local bxor = bit.bxor
local to_int32 = response.to_int32
local pid = ngx.worker.pid
local _M = {}
local mt = { __index = _M }
local MECHANISM_PLAINTEXT = "PLAIN"
local MECHANISM_SCRAMSHA256 = "SCRAM-SHA-256"
local SEP = string.char(0)
local function normalize_username(username)
-- TODO:
-- * add SASLprep from external C lib
-- * also use SASLprep for passwords
username = username:gsub("=2C", ",");
username = username:gsub("=3D", "=");
return username
end
local function gen_nonce()
-- the nonces must be normalized with the SASLprep algorithm
-- see: https://datatracker.ietf.org/doc/html/rfc3454#section-7
local openssl_rand = require("resty.openssl.rand")
-- '18' is the number set by postgres on the server side
-- todo: does thsi change anything for us? Don't think so
local rand_bytes, err = openssl_rand.bytes(18)
if not (rand_bytes) then
return nil, "failed to generate random bytes: " .. tostring(err)
end
return ngx.encode_base64(rand_bytes)
end
local c_nonce = gen_nonce()
local function _encode_plaintext(user, pwd)
return (SEP..user)..(SEP..pwd)
end
local function _encode(mechanism, user, pwd, tokenauth)
if mechanism == MECHANISM_PLAINTEXT then
return _encode_plaintext(user, pwd)
elseif mechanism== MECHANISM_SCRAMSHA256 then
-- constructing the client-first-message
user = normalize_username(user)
return "n,,n="..user..",r="..c_nonce..",tokenauth=" .. tokenauth
else
return ""
end
end
-- TODO: Duplicate function in broker.lua
local function _sock_send_receive(sock, request)
local bytes, err = sock:send(request:package())
if not bytes then
return nil, err, true
end
-- Reading a 4 byte `message_size`
local len, err = sock:receive(4)
if not len then
if err == "timeout" then
sock:close()
return nil, err
end
return nil, err, true
end
local data, err = sock:receive(to_int32(len))
if not data then
if err == "timeout" then
sock:close()
return nil, err, true
end
end
return response:new(data, request.api_version), nil, true
end
local function _sasl_handshake_decode(resp)
-- TODO: contains mechanisms supported by the local server
-- read this like I did with the supported api versions thing
local err_code = resp:int16()
local mechanisms = resp:string()
if err_code ~= 0 then
return err_code, mechanisms
end
return 0, nil
end
local function _sasl_auth_decode(resp)
local err_code = resp:int16()
local error_msg = resp:nullable_string()
local auth_bytes = resp:bytes()
if err_code ~= 0 then
return nil, error_msg
end
return 0, nil, auth_bytes
end
local function be_tls_get_certificate_hash(sock)
local signature
local pem
local ssl = require("resty.openssl.ssl").from_socket(sock)
-- in case we don't have SSL enabled
if not ssl then
return ""
end
local server_cert = ssl:get_peer_certificate()
pem = server_cert:to_PEM()
signature = server_cert:get_signature_name()
signature = signature:lower()
if signature:match("md5") or signature:match("sha1") then
signature = "sha256"
end
local openssl_x509 = require("resty.openssl.x509").new(pem, "PEM")
local openssl_x509_digest, err = openssl_x509:digest(signature, "s")
if not (openssl_x509_digest) then
return nil, tostring(err)
end
return openssl_x509_digest
end
local function hmac(key, str)
-- HMAC(key, str): Apply the HMAC keyed hash algorithm (defined in
-- [RFC2104]) using the octet string represented by "key" as the key
-- and the octet string "str" as the input string. The size of the
-- result is the hash result size for the hash function in use. For
-- example, it is 20 octets for SHA-1 (see [RFC3174]).
local openssl_hmac = require "resty.openssl.hmac"
local hmac, err = openssl_hmac.new(key, "sha256")
if not (hmac) then
return nil, tostring(err)
end
hmac:update(str)
local final_hmac, err = hmac:final()
if not (final_hmac) then
return nil, tostring(err)
end
return final_hmac
end
local function h(str)
-- H(str): Apply the cryptographic hash function to the octet string
-- "str", producing an octet string as a result. The size of the
-- result depends on the hash result size for the hash function in
-- use.
local resty_sha256 = require "resty.sha256"
local openssl_digest = resty_sha256:new()
if not (openssl_digest) then
return nil, tostring("TODO err")
end
openssl_digest:update(str)
local digest, err = openssl_digest:final()
if not (digest) then
return nil, tostring(err)
end
return digest
end
local function xor(a, b)
-- XOR: Apply the exclusive-or operation to combine the octet string
-- on the left of this operator with the octet string on the right of
-- this operator. The length of the output and each of the two
-- inputs will be the same for this use.
local result = {}
for i = 1, #a do
local x = a:byte(i)
local y = b:byte(i)
if not (x) or not (y) then
return
end
result[i] = string.char(bxor(x, y))
end
return table.concat(result)
end
local function hi(str, salt, i)
-- Hi(str, salt, i):
-- U1 := HMAC(str, salt + INT(1))
-- U2 := HMAC(str, U1)
-- ...
-- Ui-1 := HMAC(str, Ui-2)
-- Ui := HMAC(str, Ui-1)
-- Hi := U1 XOR U2 XOR ... XOR Ui
-- where "i" is the iteration count, "+" is the string concatenation
-- operator, and INT(g) is a 4-octet encoding of the integer g, most
-- significant octet first.
-- Hi() is, essentially, PBKDF2 [RFC2898] with HMAC() as the
-- pseudorandom function (PRF) and with dkLen == output length of
-- HMAC() == output length of H().
local openssl_kdf = require "resty.openssl.kdf"
salt = ngx.decode_base64(salt)
local key, err = openssl_kdf.derive({
type = openssl_kdf.PBKDF2,
md = "sha256",
salt = salt,
pbkdf2_iter = i,
pass = str,
outlen = 32 -- our H() produces a 32 byte hash value (SHA-256)
})
if not (key) then
return nil, "failed to derive pbkdf2 key: " .. tostring(err)
end
return key
end
local function _sasl_auth(self, sock)
local cli_id = "worker" .. pid()
local req = request:new(request.SaslAuthenticateRequest, 0, cli_id, request.API_VERSION_V1)
local mechanism = self.config.mechanism
local user = self.config.user
local password = self.config.password
local tokenauth = tostring(self.config.tokenauth) or "false"
local msg = _encode(mechanism, user, password, tokenauth)
req:bytes(msg)
local resp, err = _sock_send_receive(sock, req)
if not resp then
return nil, err
end
local rc, err, server_first_message = _sasl_auth_decode(resp)
if not rc then
if err then
return nil, err
end
return nil, "Unkown Error during _sasl_auth"
end
if rc and server_first_message == "" then
return rc, err
end
if server_first_message then
-- presence of 'server_first_message' indicating that we're in SASL/SCRAM land
-- TODO: usernames and passwords need to be UTF-8
local nonce = "r=" .. c_nonce
local username = "n=" .. user
local client_first_message_bare = username .. "," .. nonce .. ",tokenauth=" .. tokenauth
local plus = false
local bare = false
if mechanism:match("SCRAM%-SHA%-256%-PLUS") then
plus = true
elseif mechanism:match("SCRAM%-SHA%-256") then
bare = true
else
return nil, "unsupported SCRAM mechanism name: " .. tostring(msg)
end
local gs2_cbind_flag
local gs2_header
local cbind_input
if bare == true then
gs2_cbind_flag = "n"
gs2_header = gs2_cbind_flag .. ",,"
cbind_input = gs2_header
elseif plus == true then
-- PLUS isn't implemnented by kafka yet
local cb_name = "tls-server-end-point"
gs2_cbind_flag = "p=" .. cb_name
gs2_header = gs2_cbind_flag .. ",,"
end
local cbind_data = be_tls_get_certificate_hash(sock)
cbind_input = gs2_header .. cbind_data
local channel_binding = "c=" .. ngx.encode_base64(cbind_input)
local _,user_salt,iteration_count = server_first_message:match("r=(.+),s=(.+),i=(.+)")
if tonumber(iteration_count) < 4096 then
return nil, "Iteration count < 4096 which is the suggested minimum according to RFC 5802."
end
local salted_password, err = hi(password, user_salt, tonumber(iteration_count))
-- SaltedPassword := Hi(Normalize(password), salt, i)
if not (salted_password) then
return nil, tostring(err)
end
local client_key, err = hmac(salted_password, "Client Key")
-- ClientKey := HMAC(SaltedPassword, "Client Key")
if not (client_key) then
return nil, tostring(err)
end
local stored_key, err = h(client_key)
-- StoredKey := H(ClientKey)
if not (stored_key) then
return nil, tostring(err)
end
local client_final_message_without_proof = channel_binding .. "," .. nonce
local auth_message = client_first_message_bare .. "," .. server_first_message .. "," .. client_final_message_without_proof
-- AuthMessage := client-first-message-bare + "," +
-- server-first-message + "," +
-- client-final-message-without-proof
local client_signature, err = hmac(stored_key, auth_message)
-- ClientSignature := HMAC(StoredKey, AuthMessage)
if not (client_signature) then
return nil, tostring(err)
end
local proof = xor(client_key, client_signature)
-- ClientProof := ClientKey XOR ClientSignature
if not (proof) then
return nil, "failed to generate the client proof"
end
local client_final_message = client_final_message_without_proof .. "," .. "p=" .. ngx.encode_base64(proof)
-- Constructing client-final-message
local req2 = request:new(request.SaslAuthenticateRequest, 0, cli_id, request.API_VERSION_V1)
req2:bytes(client_final_message)
-- Sending/receiving client-final-message/server-final-message
local resp, err = _sock_send_receive(sock, req2)
if not resp then
return nil, err
end
-- Decoding server-final-message
local rc, err, msg = _sasl_auth_decode(resp)
if not rc then
if err then
return nil, err
end
return nil, "Unkown Error during _sasl_auth[client-final-message]"
end
local server_key, err = hmac(salted_password, "Server Key")
-- ServerKey := HMAC(SaltedPassword, "Server Key")
if not (server_key) then
return nil, tostring(err)
end
local server_signature, err = hmac(server_key, auth_message)
-- ServerSignature := HMAC(ServerKey, AuthMessage)
if not (server_signature) then
return nil, tostring(err)
end
server_signature = ngx.encode_base64(server_signature)
local sent_server_signature = msg:match("v=([^,]+)")
if server_signature ~= sent_server_signature then
return nil, "authentication exchange unsuccessful"
end
return 0, nil
end
end
local function _sasl_handshake(self, sock)
local cli_id = "worker" .. pid()
local api_version = request.API_VERSION_V1
local req = request:new(request.SaslHandshakeRequest, 0, cli_id, api_version)
local mechanism = self.config.mechanism
req:string(mechanism)
local resp, err = _sock_send_receive(sock, req)
if not resp then
return nil, err
end
local rc, mechanism = _sasl_handshake_decode(resp)
-- the presence of mechanisms indicate that the mechanism used isn't enabled on the Kafka server.
if mechanism then
return nil, mechanism
end
return rc, nil
end
function _M.new(opts)
local self = {
config = opts
}
return setmetatable(self, mt)
end
function _M:authenticate(sock)
local ok, err = _sasl_handshake(self, sock)
if not ok then
if err then
return nil, err
end
return nil, "Unkown Error"
end
local ok, err = _sasl_auth(self, sock)
if not ok then
return nil, err
end
return 0, nil
end
return _M
|
return {
sound = "sounds/footsteps/grassright.wav",
volume = 0.25
}
|
--- @module IFactioned
local Enum = require("api.Enum")
local ICharaParty = require("api.chara.ICharaParty")
local IObject = require("api.IObject")
local IFactioned = class.interface("IFactioned", {}, IObject)
function IFactioned:init()
self.personal_relations = {}
end
--- Clears a personal relations on this character toward an
--- individual.
function IFactioned:reset_relation_towards(other)
self.personal_relations[other.uid] = nil
end
function IFactioned:set_relation_towards(other, amount)
self.personal_relations[other.uid] = amount
end
--- Clears all personal relations on this character.
function IFactioned:reset_all_relations()
self.personal_relations = {}
end
--- Modifies a personal relation toward an individual.
---
--- @tparam IFactioned other
--- @tparam int delta Can be positive or negative.
function IFactioned:set_relation_towards(other, delta)
local val = self.personal_relations[other.uid] or 0
val = val + delta
self.personal_relations[other.uid] = val
return val
end
local function compare_relations(our_relation, their_relation)
if (our_relation == Enum.Relation.Ally and their_relation == Enum.Relation.Ally)
or (our_relation == Enum.Relation.Enemy and their_relation == Enum.Relation.Enemy) then
return Enum.Relation.Ally
end
if our_relation >= Enum.Relation.Hate then
if their_relation <= Enum.Relation.Enemy then
return Enum.Relation.Enemy
end
else
if their_relation >= Enum.Relation.Hate then
return Enum.Relation.Enemy
end
end
return math.min(our_relation, their_relation)
end
--- Returns the relation of this object towards another based on
--- faction. Values above 0 indicate friendly relations; values below
--- 0 indicate hostile relations.
---
--- @tparam IFactioned other
--- @treturn Enum.Relation
function IFactioned:base_relation_towards(other)
if self == other then
-- I think we should all be allies of ourselves. This is an important
-- sentiment that I keep trying to remind myself of.
--
-- If not, one day you might get the sudden urge to cook yourself into a
-- hamburger.
return Enum.Relation.Ally
end
local our_relation = self.relation
local their_relation = other.relation
return compare_relations(our_relation, their_relation)
end
--- Returns the relation of this object towards another based on
--- faction. Values above 0 indicate friendly relations; values below
--- 0 indicate hostile relations. Characters can have personal
--- relations towards a specific individual, like from stealing an
--- item.
---
--- @tparam IFactioned other
--- @treturn Enum.Relation
function IFactioned:relation_towards(other)
if self == other then
return Enum.Relation.Ally
end
local us = self
if class.is_an(ICharaParty, self) then
us = self:get_party_leader() or us
end
local our_relation = us.relation
local our_personal = us.personal_relations[other.uid]
if our_personal then
our_relation = our_personal
end
if class.is_an(ICharaParty, other) then
other = other:get_party_leader() or other
end
local their_relation = other.relation
local their_personal = other.personal_relations[us.uid]
if their_personal then
their_relation = their_personal
end
return compare_relations(our_relation, their_relation)
end
return IFactioned
|
local _M = { }
function _M.no_credentials(service)
ngx.log(ngx.INFO, 'no credentials provided for service ', service.id)
ngx.var.cached_key = nil
ngx.status = service.auth_missing_status
ngx.header.content_type = service.auth_missing_headers
ngx.print(service.error_auth_missing)
return ngx.exit(ngx.HTTP_OK)
end
function _M.authorization_failed(service)
ngx.log(ngx.INFO, 'authorization failed for service ', service.id)
ngx.var.cached_key = nil
ngx.status = service.auth_failed_status
ngx.header.content_type = service.auth_failed_headers
ngx.print(service.error_auth_failed)
return ngx.exit(ngx.HTTP_OK)
end
function _M.limits_exceeded(service)
ngx.log(ngx.INFO, 'limits exceeded for service ', service.id)
ngx.var.cached_key = nil
ngx.status = service.limits_exceeded_status
ngx.header.content_type = service.limits_exceeded_headers
ngx.print(service.error_limits_exceeded)
return ngx.exit(ngx.HTTP_OK)
end
function _M.no_match(service)
ngx.header.x_3scale_matched_rules = ''
ngx.log(ngx.INFO, 'no rules matched for service ', service.id)
ngx.var.cached_key = nil
ngx.status = service.no_match_status
ngx.header.content_type = service.no_match_headers
ngx.print(service.error_no_match)
return ngx.exit(ngx.HTTP_OK)
end
function _M.service_not_found(host)
ngx.status = 404
ngx.print('')
ngx.log(ngx.WARN, 'could not find service for host: ', host or ngx.var.host)
return ngx.exit(ngx.status)
end
return _M
|
RPGM.RegisterScaledConstant("HUD.Padding", 30)
RPGM.RegisterScaledConstant("HUD.ContentPadding", 12) |
package.path = './src/?.lua;' .. package.path
local lu = require 'luaunit'
local Board = require 'board'
local Tetromino = require 'tetromino'
local TetrisGame = require 'tetrisgame'
local Point = require 'util'.point
local Dimension = require 'util'.dimension
function control_tetromino(tetromino, commands)
local actions = {
W = tetromino.rotate_right,
A = tetromino.move_left,
S = tetromino.move_down,
D = tetromino.move_right
}
for i = 1, #commands do
local ch = string.sub(commands, i, i)
local action = actions[ch]
if action ~= nil then
if not action() then
return false
end
else
error('Unknown command: ' .. ch)
end
end
return true
end
function control_game(game, commands)
local actions = {
W = 'ROTATE',
A = 'MOVE_LEFT',
S = 'MOVE_DOWN',
D = 'MOVE_RIGHT'
}
actions[' '] = 'DROP'
for i = 1, #commands do
local ch = string.sub(commands, i, i)
local command = actions[ch]
if command ~= nil then
game.handle_command(command)
else
error('Unknown command: ' .. ch)
end
end
end
function check_board_state(board, excepted)
check_object_state(
board.grid,
board.size,
excepted,
function(d, x, y) return d[x][y] end,
function(c) return not c end
)
end
function check_tetromino_state(tetromino, excepted)
check_object_state(
tetromino.parts,
tetromino.bounding_box,
excepted,
function(data, x, y)
for _, point in pairs(data) do
if point.x == x and point.y == y then
return point
end
end
return nil
end,
function(c) return c == nil end
)
end
function check_object_state(data, size, excepted, find_cell, check_cell_empty)
lu.assert_equals(size.width, #(excepted[1]))
lu.assert_equals(size.height, #excepted)
grid_equals_to_expected = true
horizontal_border = '+' .. string.rep('-', size.width) .. '+\n'
console_view = '\n' .. horizontal_border
for y = 0, size.height - 1 do
console_view = console_view .. '|'
for x = 0, size.width - 1 do
cell = find_cell(data, x, y)
ch = string.sub(excepted[y + 1], x + 1, x + 1)
cell_empty = check_cell_empty(cell)
cell_equals = cell_empty == (ch == '.')
if not cell_equals then
grid_equals_to_expected = false
end
if cell_equals then
console_view = console_view .. (cell_empty and '.' or '#')
else
console_view = console_view .. (cell_empty and '!' or '?')
end
end
console_view = console_view .. '|\n'
end
console_view = console_view .. horizontal_border
if not grid_equals_to_expected then
print(console_view)
end
lu.assert_true(grid_equals_to_expected)
end
function add_test_data(board)
-- .....
-- ....#
-- .#.##
-- .####
local tetromino = Tetromino(4, board)
control_tetromino(tetromino, 'WWWDSS')
board.add_tetromino(tetromino)
tetromino = Tetromino(7, board)
control_tetromino(tetromino, 'WWDDWDS')
board.add_tetromino(tetromino)
end
TestBoard = {}
function TestBoard:setUp()
self.board = Board(Dimension(5, 4))
end
function TestBoard:test_new_board_is_empty()
check_board_state(self.board, {
'.....',
'.....',
'.....',
'.....'
})
end
function TestBoard:test_add_tetrominoes()
add_test_data(self.board)
check_board_state(self.board, {
'.....',
'....#',
'.#.##',
'.####'
})
end
function TestBoard:test_moving_tetromino_inside_empty_board()
local tetromino = Tetromino(1, self.board)
lu.assert_true(control_tetromino(tetromino, 'DADDDSAADSDAD'))
end
function TestBoard:test_moving_tetromino_outside_board_box()
local tetromino = Tetromino(1, self.board)
lu.assert_false(control_tetromino(tetromino, 'A'))
lu.assert_false(control_tetromino(tetromino, 'DDDD'))
lu.assert_false(control_tetromino(tetromino, 'SSS'))
end
function TestBoard:test_invalid_tetromino_move_inside_used_board()
add_test_data(self.board)
local tetromino = Tetromino(1, self.board)
lu.assert_false(control_tetromino(tetromino, 'S'))
lu.assert_false(control_tetromino(tetromino, 'DDD'))
end
function TestBoard:test_remove_one_full_row()
add_test_data(self.board)
self.board.remove_full_rows(0, 4)
check_board_state(self.board, {
'.....',
'....#',
'.#.##',
'.####'
})
local tetromino = Tetromino(2, self.board)
self.board.add_tetromino(tetromino)
check_board_state(self.board, {
'#....',
'#...#',
'##.##',
'#####'
})
self.board.remove_full_rows(0, 4)
check_board_state(self.board, {
'.....',
'#....',
'#...#',
'##.##'
})
end
function TestBoard:test_remove_multiple_full_rows()
local tetromino
add_test_data(self.board)
self.board.remove_full_rows(0, 4)
tetromino = Tetromino(7, self.board)
control_tetromino(tetromino, 'DS')
self.board.add_tetromino(tetromino)
tetromino = Tetromino(2, self.board)
self.board.add_tetromino(tetromino)
self.board.remove_full_rows(0, 4)
check_board_state(self.board, {
'.....',
'.....',
'.....',
'#....'
})
end
TestTetromino = {}
function TestTetromino:setUp()
self.board = Board(Dimension(7, 8))
self.tetromino = nil
end
function TestTetromino:test_tetromino_type_O_grid()
self.tetromino = Tetromino(1, self.board)
check_tetromino_state(self.tetromino, {
'##',
'##'
})
end
function TestTetromino:test_tetromino_type_I_grid()
self.tetromino = Tetromino(2, self.board)
check_tetromino_state(self.tetromino, {
'#',
'#',
'#',
'#'
})
end
function TestTetromino:test_tetromino_type_L_grid()
self.tetromino = Tetromino(3, self.board)
check_tetromino_state(self.tetromino, {
'#.',
'#.',
'##'
})
end
function TestTetromino:test_tetromino_type_J_grid()
self.tetromino = Tetromino(4, self.board)
check_tetromino_state(self.tetromino, {
'.#',
'.#',
'##'
})
end
function TestTetromino:test_tetromino_type_S_grid()
self.tetromino = Tetromino(5, self.board)
check_tetromino_state(self.tetromino, {
'.##',
'##.'
})
end
function TestTetromino:test_tetromino_type_Z_grid()
self.tetromino = Tetromino(6, self.board)
check_tetromino_state(self.tetromino, {
'##.',
'.##'
})
end
function TestTetromino:test_tetromino_type_T_grid()
self.tetromino = Tetromino(7, self.board)
check_tetromino_state(self.tetromino, {
'###',
'.#.'
})
end
function TestTetromino:test_move_to_initial_position()
self.tetromino = Tetromino(7, self.board)
lu.assert_equals(self.tetromino.position, Point(0, 0))
self.tetromino.move_to_initial_pos()
lu.assert_equals(self.tetromino.position, Point(2, 0))
end
function TestTetromino:test_move_to_initial_position_rounding()
self.tetromino = Tetromino(2, self.board)
self.tetromino.rotate_right()
self.tetromino.move_to_initial_pos()
lu.assert_equals(self.tetromino.position, Point(2, 0))
end
function TestTetromino:test_rotate_type_T()
self.tetromino = Tetromino(7, self.board)
check_tetromino_state(self.tetromino, {
'###',
'.#.'
})
self.tetromino.rotate_right()
check_tetromino_state(self.tetromino, {
'#.',
'##',
'#.'
})
self.tetromino.rotate_right()
check_tetromino_state(self.tetromino, {
'.#.',
'###'
})
self.tetromino.rotate_right()
check_tetromino_state(self.tetromino, {
'.#',
'##',
'.#'
})
self.tetromino.rotate_right()
check_tetromino_state(self.tetromino, {
'###',
'.#.'
})
end
function TestTetromino:test_rotate_type_I()
self.tetromino = Tetromino(2, self.board)
check_tetromino_state(self.tetromino, {
'#',
'#',
'#',
'#'
})
self.tetromino.rotate_right()
check_tetromino_state(self.tetromino, {
'####'
})
self.tetromino.rotate_right()
check_tetromino_state(self.tetromino, {
'#',
'#',
'#',
'#'
})
end
function TestTetromino:test_cant_rotate()
self.tetromino = Tetromino(2, self.board)
control_tetromino(self.tetromino, 'DDSSSS')
self.board.add_tetromino(self.tetromino)
self.tetromino = Tetromino(7, self.board)
control_tetromino(self.tetromino, 'WSSS')
lu.assert_false(control_tetromino(self.tetromino, 'W'))
end
function TestTetromino:test_move_left_when_rotating_at_right_side()
self.tetromino = Tetromino(2, self.board)
control_tetromino(self.tetromino, 'DDDDD')
lu.assert_equals(self.tetromino.position, Point(5, 0))
control_tetromino(self.tetromino, 'W')
lu.assert_equals(self.tetromino.position, Point(3, 0))
end
function TestTetromino:test_dont_move_left_when_rotating_at_right_side_isnt_possible()
self.tetromino = Tetromino(2, self.board)
control_tetromino(self.tetromino, 'DDDSSSS')
self.board.add_tetromino(self.tetromino)
self.tetromino = Tetromino(2, self.board)
control_tetromino(self.tetromino, 'DDDDDDSSSS')
lu.assert_false(control_tetromino(self.tetromino, 'W'))
end
function TestTetromino:test_move_left()
self.tetromino = Tetromino(7, self.board)
self.tetromino.move_to_initial_pos()
control_tetromino(self.tetromino, 'A')
lu.assert_equals(self.tetromino.position, Point(1, 0))
end
function TestTetromino:test_move_down()
self.tetromino = Tetromino(7, self.board)
self.tetromino.move_to_initial_pos()
control_tetromino(self.tetromino, 'S')
lu.assert_equals(self.tetromino.position, Point(2, 1))
end
function TestTetromino:test_move_right()
self.tetromino = Tetromino(7, self.board)
self.tetromino.move_to_initial_pos()
control_tetromino(self.tetromino, 'D')
lu.assert_equals(self.tetromino.position, Point(3, 0))
end
TestTetris = {}
function TestTetris:setUp()
-- J, T, I, O
local types = {4, 7, 2, 1}
self.game = TetrisGame(Dimension(5, 6))
self.game.get_next_tetromino_type = function()
return table.remove(types, 1)
end
end
function TestTetris:test_falling()
-- Skipped in this version.
end
function TestTetris:test_board_size()
lu.assert_equals(self.game.board.size.width, 5)
lu.assert_equals(self.game.board.size.height, 6)
end
function TestTetris:test_unstarted_state()
lu.assert_false(self.game.is_running)
lu.assert_nil(self.game.falling_tetromino)
control_game(self.game, 'S')
lu.assert_nil(self.game.falling_tetromino)
end
function TestTetris:test_running_state()
self.game.start()
lu.assert_true(self.game.is_running)
lu.assert_not_nil(self.game.falling_tetromino)
end
function TestTetris:test_stopped_state()
self.game.start()
control_game(self.game, ' ')
control_game(self.game, ' ')
local tetromino1 = self.game.falling_tetromino
lu.assert_false(self.game.is_running)
control_game(self.game, ' ')
local tetromino2 = self.game.falling_tetromino
lu.assert_is(tetromino1, tetromino2)
lu.assert_equals(tetromino1.position, tetromino2.position)
end
function TestTetris:test_controlling_tetromino()
self.game.start()
local tetromino = self.game.falling_tetromino
local position1 = tetromino.position
control_game(self.game, 'A')
local position2 = tetromino.position
lu.assert_not_equals(position1, position2)
end
function TestTetris:test_tetromino_landing()
self.game.start()
local tetromino1 = self.game.falling_tetromino
control_game(self.game, ' ')
local tetromino2 = self.game.falling_tetromino
lu.assert_not_is(tetromino1, tetromino2)
lu.assert_equals(tetromino2.shape_type, 7)
check_board_state(self.game.board, {
'.....',
'.....',
'.....',
'...#.',
'...#.',
'..##.'
})
end
function TestTetris:test_remove_full_rows()
self.game.start()
control_game(self.game, 'DD ')
control_game(self.game, 'WWA ')
check_board_state(self.game.board, {
'.....',
'.....',
'.....',
'.....',
'....#',
'.#..#'
})
end
function TestTetris:test_initial_position()
self.game.start()
local tetromino = self.game.falling_tetromino
lu.assert_equals(tetromino.position, Point(2, 0))
control_game(self.game, 'D ')
tetromino = self.game.falling_tetromino
lu.assert_equals(tetromino.position, Point(1, 0))
control_game(self.game, ' ')
tetromino = self.game.falling_tetromino
lu.assert_equals(tetromino.position, Point(2, 0))
end
lu.LuaUnit.run('-v', '-o', 'tap')
os.execute 'pause' |
function Precache( context )
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_alchemist.vsndevts", context )
PrecacheResource("soundfile", "soundevents/game_sounds_custom.vsndevts", context )
end
if AIGameMode == nil then
_G.AIGameMode = class({}) -- put in the global scope
end
require('timers')
require('settings')
require('events')
require('util')
require('bot_think_modifier')
function Activate()
AIGameMode:InitGameMode()
end
function AIGameMode:InitGameMode()
AIGameMode:InitGameOptions()
AIGameMode:InitEvents()
AIGameMode:LinkLuaModifiers()
print("DOTA 2 AI Wars Loaded.")
end
function AIGameMode:InitGameOptions()
GameRules:SetCustomGameSetupAutoLaunchDelay( AUTO_LAUNCH_DELAY )
GameRules:LockCustomGameSetupTeamAssignment( LOCK_TEAM_SETUP )
GameRules:EnableCustomGameSetupAutoLaunch( ENABLE_AUTO_LAUNCH )
GameRules:SetHeroSelectionTime( HERO_SELECTION_TIME )
GameRules:SetPreGameTime( PRE_GAME_TIME )
GameRules:SetCustomGameTeamMaxPlayers(DOTA_TEAM_GOODGUYS, RADIANT_PLAYER_COUNT)
GameRules:SetCustomGameTeamMaxPlayers(DOTA_TEAM_BADGUYS, DIRE_PLAYER_COUNT)
GameRules:SetStrategyTime(20)
GameRules:SetShowcaseTime(0)
GameRules:GetGameModeEntity():SetFreeCourierModeEnabled(true)
GameRules.DropTable = LoadKeyValues("scripts/kv/item_drops.kv")
-- GameRules:SetUseBaseGoldBountyOnHeroes( true )
end
function AIGameMode:InitEvents()
ListenToGameEvent("game_rules_state_change", Dynamic_Wrap(AIGameMode, "OnGameStateChanged"), self)
ListenToGameEvent("dota_player_gained_level", Dynamic_Wrap(AIGameMode, "OnPlayerLevelUp"), self)
ListenToGameEvent("npc_spawned", Dynamic_Wrap(AIGameMode, "OnNPCSpawned"), self)
ListenToGameEvent("entity_killed", Dynamic_Wrap(AIGameMode, "OnEntityKilled"), self)
--JS events
CustomGameEventManager:RegisterListener("loading_set_options", function (eventSourceIndex, args) return AIGameMode:OnGetLoadingSetOptions(eventSourceIndex, args) end)
end
function AIGameMode:LinkLuaModifiers()
LinkLuaModifier("modifier_courier_speed", "global_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_melee_resistance", "global_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_bot_attack_tower_pick_rune", "global_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_tower_power", "global_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_tower_endure", "global_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_tower_heal", "global_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_axe_thinker", "global_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_sniper_assassinate_thinker", "global_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_out_of_world", "global_modifiers.lua", LUA_MODIFIER_MOTION_NONE)
end
function AIGameMode:PreGameOptions()
self.iDesiredRadiant = self.iDesiredRadiant or RADIANT_PLAYER_COUNT
self.iDesiredDire = self.iDesiredDire or DIRE_PLAYER_COUNT
self.fRadiantGoldMultiplier = self.fRadiantGoldMultiplier or RADIANT_GOLD_MULTIPLIER
self.fRadiantXPMultiplier = self.fRadiantXPMultiplier or RADIANT_XP_MULTIPLIER
self.fDireXPMultiplier = self.fDireXPMultiplier or DIRE_XP_MULTIPLIER
self.fDireGoldMultiplier = self.fDireGoldMultiplier or DIRE_GOLD_MULTIPLIER
self.iGoldPerTick = self.iGoldPerTick or GOLD_PER_TICK
self.iGoldTickTime = self.iGoldTickTime or GOLD_TICK_TIME
self.iRespawnTimePercentage = self.iRespawnTimePercentage or 1
self.iMaxLevel = self.iMaxLevel or MAX_LEVEL
self.iRadiantTowerPower = self.iRadiantTowerPower or 3
self.iDireTowerPower = self.iDireTowerPower or 3
self.iRadiantTowerEndure = self.iRadiantTowerEndure or 3
self.iDireTowerEndure = self.iDireTowerEndure or 3
self.iRadiantTowerHeal = self.iRadiantTowerHeal or 0
self.iDireTowerHeal = self.iDireTowerHeal or 0
self.iStartingGoldPlayer = self.iStartingGoldPlayer or 600
self.iStartingGoldBot = self.iStartingGoldBot or 600
self.bSameHeroSelection = self.bSameHeroSelection or 1
self.bFastCourier = self.bFastCourier or 1
self.fGameStartTime = 0
GameRules:SetGoldPerTick(self.iGoldPerTick)
GameRules:SetGoldTickTime(self.iGoldTickTime)
GameRules:GetGameModeEntity():SetModifyGoldFilter( Dynamic_Wrap( AIGameMode, "FilterGold" ), self )
GameRules:GetGameModeEntity():SetModifyExperienceFilter( Dynamic_Wrap( AIGameMode, "FilterXP" ), self )
GameRules:GetGameModeEntity():SetRuneSpawnFilter( Dynamic_Wrap( AIGameMode, "FilterRune" ), self )
GameRules:GetGameModeEntity():SetTowerBackdoorProtectionEnabled( true )
GameRules:GetGameModeEntity():SetMaximumAttackSpeed( 1000 )
GameRules:SetUseUniversalShopMode( true )
-------------------------
AIGameMode:SpawnNeutralCreeps30sec()
if self.bSameHeroSelection == 1 then
GameRules:SetSameHeroSelectionEnabled( true )
end
if self.iMaxLevel ~= 30 then
local tLevelRequire = {
0,
180,
510,
960,
1520,
2110,
2850,
3640,
4480,
5370,
6310,
7380,
8580,
10005,
11555,
13230,
15030,
16955,
18955,
21045,
23145,
25495,
28095,
30945,
34045,
37545,
42045,
47545,
54045,
61545,
} -- value fixed
local iRequireLevel = tLevelRequire[30]
for i = 31, self.iMaxLevel do
iRequireLevel = iRequireLevel+i*200
table.insert(tLevelRequire, iRequireLevel)
end
GameRules:GetGameModeEntity():SetUseCustomHeroLevels( true )
GameRules:SetUseCustomHeroXPValues( true )
GameRules:GetGameModeEntity():SetCustomHeroMaxLevel(self.iMaxLevel)
GameRules:GetGameModeEntity():SetCustomXPRequiredToReachNextLevel(tLevelRequire)
end
self.PreGameOptionsSet = true
end
function AIGameMode:SpawnNeutralCreeps30sec()
GameRules:SpawnNeutralCreeps()
Timers:CreateTimer(30, function ()
AIGameMode:SpawnNeutralCreeps30sec()
end)
end
------------------------------------------------------------------
-- Gold Filter --
------------------------------------------------------------------
function AIGameMode:FilterGold(tGoldFilter)
local iGold = tGoldFilter["gold"]
local iPlayerID = tGoldFilter["player_id_const"]
local iReason = tGoldFilter["reason_const"]
local bReliable = tGoldFilter["reliable"] == 1
if iReason == DOTA_ModifyGold_HeroKill then
if iGold > 500 then
iGold = 500
end
end
if PlayerResource:GetTeam(iPlayerID) == DOTA_TEAM_GOODGUYS then
tGoldFilter["gold"] = math.floor(iGold*self.fRadiantGoldMultiplier)
else
tGoldFilter["gold"] = math.floor(iGold*self.fDireGoldMultiplier)
end
return true
end
function AIGameMode:FilterXP(tXPFilter)
local iXP = tXPFilter["experience"]
local iPlayerID = tXPFilter["player_id_const"]
local iReason = tXPFilter["reason_const"]
if PlayerResource:GetTeam(iPlayerID) == DOTA_TEAM_GOODGUYS then
tXPFilter["experience"] = math.floor(iXP*self.fRadiantXPMultiplier)
else
tXPFilter["experience"] = math.floor(iXP*self.fDireXPMultiplier)
--print("Dire XP", tXPFilter["experience"], iXP)
end
return true
end
local bFirstRuneShouldSpawned = false
local bFirstRuneActuallySpawned = false
local tPossibleRunes = {
DOTA_RUNE_ILLUSION,
DOTA_RUNE_REGENERATION,
DOTA_RUNE_HASTE,
DOTA_RUNE_INVISIBILITY,
DOTA_RUNE_DOUBLEDAMAGE,
DOTA_RUNE_ARCANE
}
local tLastRunes = {}
function AIGameMode:FilterRune(tRuneFilter)
if GameRules:GetGameTime() > 2395+self.fGameStartTime then
tRuneFilter.rune_type = tPossibleRunes[RandomInt(1, 6)]
while tRuneFilter.rune_type == tLastRunes[tRuneFilter.spawner_entindex_const] do
tRuneFilter.rune_type = tPossibleRunes[RandomInt(1, 6)]
end
tLastRunes[tRuneFilter.spawner_entindex_const] = tRuneFilter.rune_type
return true
else
if bFirstRuneShouldSpawned then
if bFirstRuneActuallySpawned then
tLastRunes[tRuneFilter.spawner_entindex_const] = nil
bFirstRuneShouldSpawned = false
return false
else
tRuneFilter.rune_type = tPossibleRunes[RandomInt(1, 6)]
while tRuneFilter.rune_type == tLastRunes[tRuneFilter.spawner_entindex_const] do
tRuneFilter.rune_type = tPossibleRunes[RandomInt(1, 6)]
end
tLastRunes[tRuneFilter.spawner_entindex_const] = tRuneFilter.rune_type
bFirstRuneShouldSpawned = false
return true
end
else
if RandomInt(0,1) > 0 then
bFirstRuneActuallySpawned = true
bFirstRuneShouldSpawned = true
tRuneFilter.rune_type = tPossibleRunes[RandomInt(1, 6)]
while tRuneFilter.rune_type == tLastRunes[tRuneFilter.spawner_entindex_const] do
tRuneFilter.rune_type = tPossibleRunes[RandomInt(1, 6)]
end
tLastRunes[tRuneFilter.spawner_entindex_const] = tRuneFilter.rune_type
return true
else
bFirstRuneActuallySpawned = false
bFirstRuneShouldSpawned = true
tLastRunes[tRuneFilter.spawner_entindex_const] = nil
return false
end
end
end
end
|
------------------------------------------------------
-- cgi.lua
--
-- A CGI handler for Kirk.
------------------------------------------------------
------------------------------------------------------
-- CGI {}
--
-- Table containing values where found from above.
-- All of these need to be stored in like data.cgi
-- or something.
------------------------------------------------------
if not CGI
then
-- Make a global CGI table here.
CGI = {}
-- Move through environment variables.
for _,cv in ipairs({
"AUTH_TYPE",
"GATEWAY_INTERFACE",
"PATH_INFO",
"PATH_TRANSLATED",
"QUERY_STRING",
"REMOTE_ADDR",
"REQUEST_METHOD",
"SCRIPT_NAME",
"HTTP_COOKIE",
"HTTP_INTERNAL_SERVER_ERROR",
"SERVER_NAME",
"SERVER_PORT",
"SERVER_PROTOCOL",
"SERVER_SOFTWARE",
"REMOTE_HOST",
"REMOTE_IDENT",
"REMOTE_USER",
})
do
CGI[cv] = os.getenv(cv)
end
-- Transform each value in t with the function f.
-- Can possibly set a chain by using a table.
-- (Formerly was table.populate..., and not too
-- descriptive.)
-- table.transform(t, f)
end
------------------------------------------------------
-- Again, the absolute thinnest stack possible doesn't
-- need any of this.
--
-- You only need a response library:
-- capable of processing headers
-- and parsing a response
--
-- (i'm trying to say, that this needs to come first.)
------------------------------------------------------
if CGI
then
if CGI.REQUEST_METHOD == "HEAD" -- and REQUEST.HEADER["is_xml_http"] = true
then
-- Receiving the correct header here would really help.
-- Formulate a compliant date.
HEADERS.USER["time_to_generate"] = date.cookie(RECVD)
HEADERS.USER["time_to_ship"] = date.cookie()
-- Send the response.
response.abort({200}, "")
end
------------------------------------------------------
-- POST processing routines.
------------------------------------------------------
if CGI.REQUEST_METHOD == "POST"
then
for _,val in ipairs({"CONTENT_TYPE","CONTENT_LENGTH"})
do
CGI[val] = os.getenv(val)
end
end
------------------------------------------------------
-- POST can be accessed globally just like GET.
------------------------------------------------------
POST = require("http.post")(CGI,CLI)
------------------------------------------------------
-- Die if the server brings back an error.
------------------------------------------------------
if CGI.HTTP_INTERNAL_SERVER_ERROR then
die.with(500, { msg = CGI.HTTP_INTERNAL_SERVER_ERROR })
-- response.abort({500}, CGI.HTTP_INTERNAL_SERVER_ERROR)
end
------------------------------------------------------
-- Get the cookies available.
--
-- Being a scientist is fucking hard...
------------------------------------------------------
if CGI.HTTP_COOKIE then
-- Chop the string.
COOKIES = {}
for _,value in ipairs(table.from(CGI.HTTP_COOKIE,'; '))
do
local cookie_s = string.chop(value,'=')
COOKIES[cookie_s.key] = cookie_s.value
end
end
------------------------------------------------------
-- CGI lua
------------------------------------------------------
local function srv_default()
if pg.default and pg.default.page
then
F.asset("skel")
local f = F.exists( pg.default.page .. ".lua" )
if f.status
then
req = interpret.file( f.handle ) -- "../skel/" .. pg.default.page .. ".lua")
response.abort( {200}, req )
else
die.with(500, {
msg = "No file '" .. pg.default.page .. ".lua' could be found at path '" .. pg.path .. "/skel.'",
stacktrace = "None."
})
end
else
die.with(200, {
msg = [[Kirk is working, but no default page has been
defined in ]] .. pg.path .. "/data/definitions.lua",
stacktrace = "Try setting the value of 'page' in definitions.lua to "
.. "a file name under the \n directory " .. pg.path .. "/skel."
})
end
end
------------------------------------------------------
-- Start at everything besides the root.
------------------------------------------------------
local req
local file_check
local rname
------------------------------------------------------
-- We must be at the root, so evaluate a default
-- request.
------------------------------------------------------
if CGI.PATH_INFO == "/"
then
if pg.default and pg.default.page
then
F.asset("skel")
local f = F.exists( pg.default.page .. ".lua" )
if f.status
then
req = interpret.file( f.handle ) -- "../skel/" .. pg.default.page .. ".lua")
response.abort( {200}, req )
else
die.with(500, {
msg = "No file '" .. pg.default.page .. ".lua' could be found " ..
"at path '" .. pg.path .. "/skel.'",
stacktrace = "None."
})
end
else
die.with(200, {
msg = [[Kirk is working, but no default page has been
defined in ]] .. pg.path .. "/data/definitions.lua",
stacktrace = "Try setting the value of 'page' in definitions.lua to "
.. "a file name under the \n directory " .. pg.path .. "/skel."
})
end
------------------------------------------------------
-- Serve all resources besides /.
------------------------------------------------------
elseif CGI.PATH_INFO ~= "/"
then
------------------------------------------------------
-- Chop the path and save it.
------------------------------------------------------
local count, srv = 1, {}
local is_page
local url = string.gmatch(CGI.PATH_INFO,'/([0-9,A-Z,a-z,_,\(,\),#,-]*)')
------------------------------------------------------
-- Save GET.
------------------------------------------------------
if CGI.QUERY_STRING then
GET = require("http.get")(CGI.QUERY_STRING)
end
------------------------------------------------------
-- Make the url more accessible.
------------------------------------------------------
local urlt = {}
for v in url do
if v ~= "" then
table.insert(data.url, v)
end
end
------------------------------------------------------
-- Check the blocks of the URL.
-- Do they exist in pg.pages?
--
-- Possibly break this up so that the searches take
-- place against a table vs. iterating through
-- possible failures.
--
-- Table would be generated from everything in the
-- url.
-----------------------------------------------------
if pg.pages
then
for level = table.maxn(data.url),1,-1
do
rname = data.url[level] -- Resource name.
------------------------------------------------------
-- Serve for resources and only if we found no error.
------------------------------------------------------
if is.key(rname, pg.pages)
then
is_page = true
F.asset("skel")
-- Check a certain set of files.
if pg.default and pg.default.page
then
file_check = {
pg.pages[rname],
pg.pages[rname] .. "/" .. pg.default.page
}
else
file_check = { pg.pages[rname] }
end
------------------------------------------------------
-- Loop through each file.
------------------------------------------------------
for __,ffile in ipairs( file_check )
do
------------------------------------------------------
-- If we found the page, great.
------------------------------------------------------
srv = F.exists(ffile,".lua")
------------------------------------------------------
-- Serve the resource if it was found.
------------------------------------------------------
if srv.status == true
then
req = interpret.file(srv.handle)
response.abort({200}, req)
end -- end if srv.status == true
end -- end for _,f in ipairs({
end -- end if is.key(rname, pg.pages)
end -- for level = table.maxn(data.url),1,-1
------------------------------------------------------
-- If we've defined a resource and didn't find the
-- page, that's bad. You'll need to send a 404 back.
------------------------------------------------------
if not srv.status
and is_page
then
-- Die will be handling the other 404's...
die.with(404, {
msg = "Resource at '<i>/" .. rname .. "</i>' could not be found."
})
else
srv_default()
end
------------------------------------------------------
-- If this is our only resource, we need to serve
-- the regular backend.
-- Only needs to run if NOTHING is found.
------------------------------------------------------
else
srv_default()
-- req = interpret("../skel/" .. pg.default.page .. ".lua")
-- response.send({200}, req.msg() )
-- response.send( {200}, req )
end
end
end
|
---------
-- Proxy script for OAuth 2.0.
local config = require 'ngx-oauth.config'
local Cookies = require 'ngx-oauth.Cookies'
local either = require 'ngx-oauth.either'
local nginx = require 'ngx-oauth.nginx'
local oauth = require 'ngx-oauth.oauth2'
local util = require 'ngx-oauth.util'
local log = nginx.log
local function write_auth_header (access_token)
ngx.req.set_header('Authorization', 'Bearer '..access_token)
end
local conf, errs = config.load()
if errs then
return nginx.fail(500, 'OAuth proxy error: %s', errs)
end
local cookies = Cookies(conf)
local access_token = cookies.get_access_token()
-- Cookie with access token found; set Authorization header and we're done.
if access_token then
if not util.hasAccess(conf, { id = cookies.get_username() }) then
cookies.clear_all()
ngx.redirect(oauth.authorization_url(conf), 303)
else
write_auth_header(access_token)
end
-- Cookie with refresh token found; refresh token and set Authorization header.
elseif cookies.get_refresh_token() then
log.info('refreshing token for user: %s', cookies.get_username())
either (
function(err)
nginx.fail(503, 'Authorization server error: %s', err)
end,
function(token)
cookies.add_token(token)
write_auth_header(token.access_token)
end,
oauth.request_token('refresh_token', conf, cookies.get_refresh_token())
)
if not util.hasAccess(conf, { id = cookies.get_username() }) then
cookies.clear_all()
return ngx.redirect(oauth.authorization_url(conf), 303)
end
-- Neither access token nor refresh token found; bad luck, return HTTP 401.
else
ngx.redirect(oauth.authorization_url(conf), 303)
-- ngx.header['WWW-Authenticate'] = 'Bearer error="unauthorized"'
-- nginx.fail(401, 'No access token provided.')
end
|
return function(packedColor3: {R: Number, G: Number, B: Number}): Color3
return Color3.new(unpack(packedColor3))
end |
includeFile("tangible/furniture/house_cleanup/cts_valcyn_painting.lua")
includeFile("tangible/furniture/house_cleanup/cts_wanderhome_painting.lua")
includeFile("tangible/furniture/house_cleanup/cts_kauri_painting.lua")
includeFile("tangible/furniture/house_cleanup/cts_tarquinas_painting.lua")
includeFile("tangible/furniture/house_cleanup/xeno_rug.lua")
includeFile("tangible/furniture/house_cleanup/xeno_table.lua")
includeFile("tangible/furniture/house_cleanup/xeno_couch.lua")
includeFile("tangible/furniture/house_cleanup/cts_corbantis_painting.lua")
includeFile("tangible/furniture/house_cleanup/cts_naritus_painting.lua")
includeFile("tangible/furniture/house_cleanup/cts_kettemoor_painting.lua")
includeFile("tangible/furniture/house_cleanup/xeno_desk_lamp.lua")
includeFile("tangible/furniture/house_cleanup/cts_tempest_painting.lua")
includeFile("tangible/furniture/house_cleanup/cts_scylla_painting.lua")
includeFile("tangible/furniture/house_cleanup/xeno_desk.lua")
includeFile("tangible/furniture/house_cleanup/cts_early_settler_painting.lua")
includeFile("tangible/furniture/house_cleanup/cts_lowca_painting.lua")
includeFile("tangible/furniture/house_cleanup/cts_galaxy_painting.lua")
includeFile("tangible/furniture/house_cleanup/cts_intrepid_painting.lua")
includeFile("tangible/furniture/house_cleanup/cts_infinity_painting.lua")
|
local on_key_releases,nr = {},0
function minetest.register_on_key_release(func)
nr = nr+1
on_key_releases[nr] = func
end
local on_key_presses,np = {},0
function minetest.register_on_key_press(func)
np = np+1
on_key_presses[np] = func
end
local playerkeys = {}
minetest.register_globalstep(function()
for _,player in pairs(minetest.get_connected_players()) do
local last_keys = playerkeys[player:get_player_name()]
for key,stat in pairs(player:get_player_control()) do
if stat then
if not last_keys[key] then
for i = 1,np do
on_key_presses[i](player, key)
end
last_keys[key] = true
end
elseif last_keys[key] then
for i = 1,nr do
on_key_releases[i](player, key)
end
last_keys[key] = false
end
end
end
end)
minetest.register_on_joinplayer(function(player)
playerkeys[player:get_player_name()] = {}
end)
function fnc_go_programming(player, key)
if key=="aux1" then
local formspec = "size[1,0.0]" .. "position[0.05,0.0]" .. "label[0,0;PAUSE]"
minetest.show_formspec(player:get_player_name(), "default:team_choose", formspec)
end
end
minetest.register_on_key_release(function(player, key)
fnc_go_programming(player, key)
end)
minetest.register_on_key_press(function(player, key)
end)
|
local tenant = ngx.shared.tenant;
tenant:set("a", "121112");
|
--------------------------------------------------------------------------------
--- String-related tools
-- @module lua-nucleo.string
-- This file is a part of lua-nucleo library
-- @copyright lua-nucleo authors (see file `COPYRIGHT` for the license)
--------------------------------------------------------------------------------
local table_concat, table_insert = table.concat, table.insert
local math_floor = math.floor
local string_find, string_sub, string_format = string.find, string.sub, string.format
local string_byte, string_char = string.byte, string.char
local assert, pairs, type = assert, pairs, type
local tidentityset
= import 'lua-nucleo/table-utils.lua'
{
'tidentityset'
}
local arguments
= import 'lua-nucleo/args.lua'
{
'arguments'
}
local make_concatter -- TODO: rename, is not factory
do
make_concatter = function()
local buf = {}
local function cat(v)
buf[#buf + 1] = v
return cat
end
local concat = function(glue)
return table_concat(buf, glue or "")
end
return cat, concat
end
end
-- Remove trailing and leading whitespace from string.
-- From Programming in Lua 2 20.4
local trim = function(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
local create_escape_subst = function(string_subst, ignore)
ignore = ignore or { "\n", "\t" }
local subst = setmetatable(
tidentityset(ignore),
{
__metatable = "escape.char";
__index = function(t, k)
local v = (string_subst):format(k:byte())
t[k] = v
return v
end;
}
)
return subst
end
-- WARNING: This is not a suitable replacement for urlencode
local escape_string
do
local escape_subst = create_escape_subst("%%%02X")
escape_string = function(str)
return (str:gsub("[%c%z\128-\255]", escape_subst))
end
end
local url_encode
do
local escape_subst = create_escape_subst("%%%02X")
url_encode = function(str)
return str:gsub("([^%w-_ ])", escape_subst):gsub(" ", "+")
end
end
local htmlspecialchars = nil
do
local subst =
{
["&"] = "&";
['"'] = """;
["'"] = "'";
["<"] = "<";
[">"] = ">";
}
htmlspecialchars = function(value)
if type(value) == "number" then
return value
end
value = tostring(value)
return (value:gsub("[&\"'<>]", subst))
end
end
local cdata_wrap = function(value)
-- "]]>" is escaped as ("]]" + "]]><![CDATA[" + ">")
return '<![CDATA[' .. value:gsub("]]>", ']]]]><![CDATA[>') .. ']]>'
end
local cdata_cat = function(cat, value)
-- "]]>" is escaped as ("]]" + "]]><![CDATA[" + ">")
cat '<![CDATA[' (value:gsub("]]>", ']]]]><![CDATA[>')) ']]>'
end
-- TODO: Looks ugly and slow. Rewrite.
-- Based on http://lua-users.org/wiki/MakingLuaLikePhp
local split_by_char = function(str, div)
local result = false
if div ~= "" then
local pos = 0
result = {}
if str ~= "" then
-- for each divider found
for st, sp in function() return string_find(str, div, pos, true) end do
-- Attach chars left of current divider
table_insert(result, string_sub(str, pos, st - 1))
pos = sp + 1 -- Jump past current divider
end
-- Attach chars right of last divider
table_insert(result, string_sub(str, pos))
end
end
return result
end
local count_substrings = function(str, substr)
local count = 0
local s, e = 0, 0
while true do
s, e = str:find(substr, e + 1, true)
if s ~= nil then
count = count + 1
else
break
end
end
return count
end
local split_by_offset = function(str, offset, skip_right)
assert(offset <= #str)
return str:sub(1, offset), str:sub(offset + 1 + (skip_right or 0))
end
local fill_placeholders_ex = function(capture, str, dict)
return (str:gsub(capture, dict))
end
local fill_placeholders = function(str, dict)
return fill_placeholders_ex("%$%((.-)%)", str, dict)
end
local fill_curly_placeholders = function(str, dict)
return fill_placeholders_ex("%${(.-)}", str, dict)
end
local kv_concat = function(t, kv_glue, pair_glue, pairs_fn)
pair_glue = pair_glue or ""
pairs_fn = pairs_fn or pairs
local cat, concat = make_concatter()
local glue = ""
for k, v in pairs_fn(t) do
cat (glue) (k) (kv_glue) (v)
glue = pair_glue
end
return concat()
end
local escape_lua_pattern
do
local matches =
{
["^"] = "%^";
["$"] = "%$";
["("] = "%(";
[")"] = "%)";
["%"] = "%%";
["."] = "%.";
["["] = "%[";
["]"] = "%]";
["*"] = "%*";
["+"] = "%+";
["-"] = "%-";
["?"] = "%?";
["\0"] = "%z";
}
escape_lua_pattern = function(s)
return (s:gsub(".", matches))
end
end
local escape_for_json
do
-- Based on luajson code (comments copied verbatim).
-- https://github.com/harningt/luajson/blob/master/lua/json/encode/strings.lua
local matches =
{
['"'] = '\\"';
['\\'] = '\\\\';
-- ['/'] = '\\/'; -- TODO: ?! Do we really need to escape this?
['\b'] = '\\b';
['\f'] = '\\f';
['\n'] = '\\n';
['\r'] = '\\r';
['\t'] = '\\t';
['\v'] = '\\v'; -- not in official spec, on report, removing
}
-- Pre-encode the control characters to speed up encoding...
-- NOTE: UTF-8 may not work out right w/ JavaScript
-- JavaScript uses 2 bytes after a \u... yet UTF-8 is a
-- byte-stream encoding, not pairs of bytes (it does encode
-- some letters > 1 byte, but base case is 1)
for i = 0, 255 do
local c = string.char(i)
if c:match('[%z\1-\031\128-\255]') and not matches[c] then
-- WARN: UTF8 specializes values >= 0x80 as parts of sequences...
-- without \x encoding, do not allow encoding > 7F
matches[c] = ('\\u%.4X'):format(i)
end
end
escape_for_json = function(s)
return '"' .. s:gsub('[\\"/%z\1-\031]', matches) .. '"'
end
end
local starts_with = function(str, prefix)
if type(str) ~= 'string' or type(prefix) ~= 'string' then return false end
local plen = #prefix
return (#str >= plen) and (str:sub(1, plen) == prefix)
end
local ends_with = function(str, suffix)
if type(str) ~= 'string' or type(suffix) ~= 'string' then return false end
local slen = #suffix
return slen == 0 or ((#str >= slen) and (str:sub(-slen, -1) == suffix))
end
local integer_to_string_with_base
do
-- TODO: use arbitrary set of digits
-- https://github.com/lua-nucleo/lua-nucleo/issues/2
local digits =
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B";
"C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N";
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z";
}
integer_to_string_with_base = function(n, base)
base = base or 10
assert(type(n) == "number", "n must be a number")
assert(type(base) == "number", "base must be a number")
assert(base > 0 and base <= #digits, "base out of range")
assert(n == n, "n is nan")
assert(n ~= 1 / 0 and n ~= -1 / 0, "n is inf")
n = math_floor(n)
if base == 10 or n == 0 then
return tostring(n)
end
local sign = ""
if n < 0 then
sign = "-"
n = -n
end
local r = { }
while n ~= 0 do
r[#r + 1] = digits[(n % base) + 1]
n = math_floor(n / base)
end
return sign .. table_concat(r, ""):reverse()
end
end
local cut_with_ellipsis
do
local ellipsis = "..."
local ellipsis_length = #ellipsis
cut_with_ellipsis = function(str, max_length)
max_length = max_length or 80
arguments(
"string", str,
"number", max_length
)
assert(max_length > 0, "required string length must be positive")
if #str > max_length then
if max_length > ellipsis_length then
str = str:sub(1, max_length - ellipsis_length) .. ellipsis
else
str = str:sub(1, max_length)
end
end
return str
end
end
-- convert numbers into loadable string, including inf, -inf and nan
local number_to_string
local serialize_number
do
local t =
{
[tostring(1/0)] = "1/0";
[tostring(-1/0)] = "-1/0";
[tostring(0/0)] = "0/0";
}
number_to_string = function(number)
-- no argument checking - called very often
local text = tostring(number)
return t[text] or text
end
serialize_number = function(number)
-- no argument checking - called very often
local text = ("%.17g"):format(number)
-- on the same platform tostring() and string.format()
-- return the same results for 1/0, -1/0, 0/0
-- so we don't need separate substitution table
return t[text] or text
end
end
local get_escaped_chars_in_ranges
do
get_escaped_chars_in_ranges = function(ranges)
assert(
type(ranges) == "table",
"argument must be a table"
)
assert(
#ranges % 2 == 0,
"argument must have even number of elements"
)
local cat, concat = make_concatter()
for i = 1, #ranges, 2 do
local char_code_start = ranges[i]
local char_code_end = ranges[i + 1]
if type(char_code_start) == "string" then
char_code_start = string_byte(char_code_start)
end
if type(char_code_end) == "string" then
char_code_end = string_byte(char_code_end)
end
assert(
type(char_code_start) == "number"
and type(char_code_end) == "number",
"argument elements must be numbers or strings"
)
for i = char_code_start, char_code_end do
cat "%" (string_char(i))
end
end
return concat()
end
end
return
{
escape_string = escape_string;
make_concatter = make_concatter;
trim = trim;
create_escape_subst = create_escape_subst;
htmlspecialchars = htmlspecialchars;
fill_placeholders_ex = fill_placeholders_ex;
fill_placeholders = fill_placeholders;
fill_curly_placeholders = fill_curly_placeholders;
cdata_wrap = cdata_wrap;
cdata_cat = cdata_cat;
split_by_char = split_by_char;
split_by_offset = split_by_offset;
count_substrings = count_substrings;
kv_concat = kv_concat;
escape_lua_pattern = escape_lua_pattern;
escape_for_json = escape_for_json;
starts_with = starts_with;
ends_with = ends_with;
url_encode = url_encode;
integer_to_string_with_base = integer_to_string_with_base;
cut_with_ellipsis = cut_with_ellipsis;
number_to_string = number_to_string;
serialize_number = serialize_number;
get_escaped_chars_in_ranges = get_escaped_chars_in_ranges;
}
|
local ubus = require "ubus".connect()
local specs
if ubus then
specs = ubus:call("router", "quest", { info = "specs" })
ubus:close()
end
m = Map("layer2_interface", translate("xDSL Settings"), translate("xDSL Line settings and profiles"))
s = m:section(NamedSection, "capabilities", translate("Capabilities")) -- Configure atm interface
s:tab("modulation", translate("Modulation"))
s:tab("profile", translate("VDSL Profile"))
s:tab("capabilities", translate("Capabilities"))
e = s:taboption("modulation", Flag, "GDmt", translate("G.Dmt"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("modulation", Flag, "Glite", translate("G.lite"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("modulation", Flag, "T1413", translate("T.1413"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("modulation", Flag, "ADSL2", translate("ADSL2"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("modulation", Flag, "AnnexL", translate("AnnexL"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("modulation", Flag, "ADSL2plus", translate("ADSL2+"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("modulation", Flag, "AnnexM", translate("AnnexM"))
e.enabled = "Enabled"
e.disabled = ""
if not specs or specs.vdsl then
e = s:taboption("modulation", Flag, "VDSL2", translate("VDSL2"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("profile", Flag, "8a", translate("8a"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("profile", Flag, "8b", translate("8b"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("profile", Flag, "8c", translate("8c"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("profile", Flag, "8d", translate("8d"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("profile", Flag, "12a", translate("12a"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("profile", Flag, "12b", translate("12b"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("profile", Flag, "17a", translate("17a"))
e.enabled = "Enabled"
e.disabled = ""
e = s:taboption("capabilities", Flag, "US0", translate("US0"))
e.enabled = "on"
e.disabled = "off"
end
e = s:taboption("capabilities", Flag, "bitswap", translate("Bitswap"))
e.enabled = "on"
e.disabled = "off"
e = s:taboption("capabilities", Flag, "sra", translate("SRA"))
e.enabled = "on"
e.disabled = "off"
return m
|
g_Root = getRootElement()
g_Me = getLocalPlayer()
g_ResRoot = getResourceRootElement()
g_ScrW, g_ScrH = guiGetScreenSize()
local function initDelayed()
import("roommgr")
import("dxgui")
addEvent("onDxGUIClick",true)
triggerServerEvent("main_onReady", g_ResRoot)
end
local function init()
setTimer(initDelayed, 50, 1)
end
addEventHandler("onClientResourceStart", g_ResRoot, init)
|
-- the best way to spread holiday cheer is singing loud for all to hear
if PREFSMAN:GetPreference("EasterEggs") and MonthOfYear() == 11 then
return LoadActor(THEME:GetPathB("", "_shared background normal/snow.lua"))
end
local file = THEME:GetPathB("", "_shared background normal/" .. ThemePrefs.Get("VisualTheme") .. ".png")
-- this variable will be used within the scope of this file like (index+1) and (index-1)
-- to continue to diffuse each sprite as we shift through the colors available in SL.Colors
local index = SL.Global.ActiveColorIndex
-- time in seconds for the first NewColor (which is triggered from AF's InitCommand)
-- should be 0 so that children sprites get colored properly immediately; we'll
-- change this variable in the AF's OnCommand so that color-shifts tween appropriately
local delay = 0
local af =
Def.ActorFrame {
Def.Quad {
InitCommand = function(self)
self:FullScreen():Center():diffuse(ThemePrefs.Get("RainbowMode") and Color.White or Color.Black)
end,
BackgroundImageChangedMessageCommand = function(self)
THEME:ReloadMetrics()
SL.Global.ActiveColorIndex = ThemePrefs.Get("RainbowMode") and 3 or ThemePrefs.Get("SimplyLoveColor")
self:linear(1):diffuse(ThemePrefs.Get("RainbowMode") and Color.White or Color.Black)
end
}
}
-- --------------------------------------------------------
-- non-RainbowMode (normal) background
local file_info = {
ColorRGB = {0, 1, 1, 0, 0, 0, 1, 1, 1, 1},
diffusealpha = {0.05, 0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.05, 0.1, 0.1},
xy = {0, 40, 80, 120, 200, 280, 360, 400, 480, 560},
texcoordvelocity = {
{0.03, 0.01},
{0.03, 0.02},
{0.03, 0.01},
{0.02, 0.02},
{0.03, 0.03},
{0.02, 0.02},
{0.03, 0.01},
{-0.03, 0.01},
{0.05, 0.03},
{0.03, 0.04}
}
}
local t =
Def.ActorFrame {
InitCommand = function(self)
if ThemePrefs.Get("RainbowMode") then
self:visible(false)
else
self:diffusealpha(0)
end
end,
OnCommand = function(self)
self:accelerate(0.8):diffusealpha(1)
end,
BackgroundImageChangedMessageCommand = function(self)
if not ThemePrefs.Get("RainbowMode") then
self:visible(true):linear(0.6):diffusealpha(1)
else
self:linear(0.6):diffusealpha(0):queuecommand("Hide")
end
end,
HideCommand = function(self)
self:visible(false)
end
}
for i = 1, 10 do
t[#t + 1] =
Def.Sprite {
Texture = file,
InitCommand = function(self)
self:diffuse(ColorRGB(file_info.ColorRGB[i]))
end,
ColorSelectedMessageCommand = function(self)
self:linear(0.5):diffuse(ColorRGB(file_info.ColorRGB[i])):diffusealpha(file_info.diffusealpha[i])
end,
OnCommand = function(self)
self:zoom(1.3):xy(file_info.xy[i], file_info.xy[i]):customtexturerect(0, 0, 1, 1):texcoordvelocity(
file_info.texcoordvelocity[i][1],
file_info.texcoordvelocity[i][2]
):diffusealpha(file_info.diffusealpha[i])
end,
BackgroundImageChangedMessageCommand = function(self)
if not ThemePrefs.Get("RainbowMode") then
local new_file = THEME:GetPathB("", "_shared background normal/" .. ThemePrefs.Get("VisualTheme") .. ".png")
self:Load(new_file)
end
end
}
end
af[#af + 1] = t
-- --------------------------------------------------------
-- RainbowMode background
local rainbow =
Def.ActorFrame {
InitCommand = function(self)
if not ThemePrefs.Get("RainbowMode") then
self:visible(false)
end
end,
OnCommand = function(self)
self:Center():bob():effectmagnitude(0, 50, 0):effectperiod(8)
end,
BackgroundImageChangedMessageCommand = function(self)
if ThemePrefs.Get("RainbowMode") then
self:visible(true):linear(0.6):diffusealpha(1)
else
self:linear(0.6):diffusealpha(0):queuecommand("Hide")
end
end,
HideCommand = function(self)
self:visible(false)
end
}
--{x,y,z,texcoordvelx,texcoordvely,alpha, IsIdxPlusOne}
local hearts =
Def.ActorFrame {
OnCommand = function(self)
self:bob():effectmagnitude(0, 0, 50):effectperiod(12)
end
}
local spriteFrame =
Def.ActorFrame {
InitCommand = function(self)
self:diffusealpha(0):queuecommand("Appear"):playcommand("NewColor")
end,
OnCommand = function(self)
delay = 0.7
end,
AppearCommand = function(self)
self:linear(1):diffusealpha(1):queuecommand("Loop")
end,
BackgroundImageChangedMessageCommand = function(self)
if ThemePrefs.Get("RainbowMode") then
local children = self:GetChild("")
for _, child in ipairs(children) do
local new_file = THEME:GetPathB("", "_shared background normal/" .. ThemePrefs.Get("VisualTheme") .. ".png")
child:Load(new_file)
end
end
end,
LoopCommand = function(self)
index = index + 1
self:queuecommand("NewColor")
self:sleep(delay)
self:queuecommand("Loop")
end
}
local sprites = {
{0, 0, -30, .03, .04, .3, true},
{-50, 40, -100, .04, .01, .2, true},
{50, -80, -100, .05, .02, .2, false},
{-100, 120, -200, .06, .02, .2, false},
{100, -160, -40, .07, .01, .3, true},
{-150, 210, -50, .08, .01, .3, false},
{150, -250, -200, .03, .03, .2, false},
{-200, 290, -60, .03, .03, .3, true},
{200, -330, -100, .03, .02, .2, false},
{-250, 370, -100, .03, .03, .2, true},
{250, -410, -50, .03, .01, .3, true},
{-300, 450, -0, .03, .01, .2, false},
{300, -490, -100, .03, .01, .2, true},
{-350, 530, -100, .03, .02, .2, true},
{350, -570, -0, .03, .01, .3, false},
{-400, 610, -200, .04, .03, .2, true},
{400, -650, -100, .03, .02, .2, true},
{450, 690, -100, .02, .04, .2, true},
{450, -730, -200, .03, .02, .2, false},
{-500, 770, -200, .06, .01, .2, true},
{500, -810, -100, .04, .01, .2, false},
{-550, 850, -70, .03, .02, .2, false},
{550, -890, -200, .02, .03, .2, false},
{-600, 930, -100, .06, .02, .2, false},
{600, -970, -100, .04, .04, .2, true}
}
for i, v in ipairs(sprites) do
spriteFrame[#spriteFrame + 1] =
Def.Sprite {
Texture = file,
InitCommand = function(self)
self:zoom(1.3):x(v[1]):y(v[2]):z(v[3]):customtexturerect(0, 0, 1, 1):texcoordvelocity(v[4], v[5])
end,
NewColorCommand = function(self)
self:linear(delay):diffuse(GetHexColor(index + (v[7] and 1 or -1))):diffusealpha(v[6])
end
}
end
hearts[#hearts + 1] = spriteFrame
rainbow[#rainbow + 1] = hearts
af[#af + 1] = rainbow
return af
|
--[[
module:Rectangle
author:DylanYang
time:2021-02-09 17:14:32
]]
local super = require("patterns.structural.decorator.Shape")
local _M = Class("Rectangle")
function _M.public:Draw()
print(string.format("The shape that was just drawn is a %s.", self.name))
end
function _M.public.get:name()
return "Rectangle"
end
return _M |
--- @type StdUi
local StdUi = LibStub and LibStub('StdUi', true);
if not StdUi then
return;
end
--- @param frame Frame
function StdUi:MarkAsValid(frame, valid)
if not valid then
frame:SetBackdropBorderColor(1, 0, 0, 1);
else
frame:SetBackdropBorderColor(
self.config.backdrop.border.r,
self.config.backdrop.border.g,
self.config.backdrop.border.b,
self.config.backdrop.border.a
);
end
end
StdUi.Util = {};
--- @param self EditBox
StdUi.Util.editBoxValidator = function(self)
self.value = self:GetText();
StdUi:MarkAsValid(self, true);
return true;
end
--- @param self EditBox
StdUi.Util.moneyBoxValidator = function(self)
local text = self:GetText();
text = text:trim();
local total, gold, silver, copper, isValid = StdUi.Util.parseMoney(text);
if not isValid or total == 0 then
StdUi:MarkAsValid(self, false);
return false;
end
self:SetText(StdUi.Util.formatMoney(total));
self.value = total;
StdUi:MarkAsValid(self, true);
return true;
end
--- @param self EditBox
StdUi.Util.numericBoxValidator = function(self)
local text = self:GetText();
text = text:trim();
local value = tonumber(text);
if value == nil then
StdUi:MarkAsValid(self, false);
return false;
end
if self.maxValue and self.maxValue < value then
StdUi:MarkAsValid(self, false);
return false;
end
if self.minValue and self.minValue > value then
StdUi:MarkAsValid(self, false);
return false;
end
self.value = value;
StdUi:MarkAsValid(self, true);
return true;
end
StdUi.Util.parseMoney = function(text)
text = StdUi.Util.stripColors(text);
local total = 0;
local cFound, _, copper = string.find(text, '(%d+)c$');
if cFound then
text = string.gsub(text, '(%d+)c$', '');
text = text:trim();
total = tonumber(copper);
end
local sFound, _, silver = string.find(text, '(%d+)s$');
if sFound then
text = string.gsub(text, '(%d+)s$', '');
text = text:trim();
total = total + tonumber(silver) * 100;
end
local gFound, _, gold = string.find(text, '(%d+)g$');
if gFound then
text = string.gsub(text, '(%d+)g$', '');
text = text:trim();
total = total + tonumber(gold) * 100 * 100;
end
local left = tonumber(text:len());
local isValid = (text:len() == 0 and total > 0);
return total, gold, silver, copper, isValid;
end
StdUi.Util.formatMoney = function(money)
if type(money) ~= 'number' then
return money;
end
money = tonumber(money);
local goldColor = '|cfffff209';
local silverColor = '|cff7b7b7a';
local copperColor = '|cffac7248';
local gold = floor(money / COPPER_PER_GOLD);
local silver = floor((money - (gold * COPPER_PER_GOLD)) / COPPER_PER_SILVER);
local copper = floor(money % COPPER_PER_SILVER);
local output = '';
if gold > 0 then
output = format('%s%i%s ', goldColor, gold, '|rg')
end
if gold > 0 or silver > 0 then
output = format('%s%s%02i%s ', output, silverColor, silver, '|rs')
end
output = format('%s%s%02i%s ', output, copperColor, copper, '|rc')
return output:trim();
end
StdUi.Util.stripColors = function(text)
text = string.gsub(text, '|c%x%x%x%x%x%x%x%x', '');
text = string.gsub(text, '|r', '');
return text;
end
StdUi.Util.WrapTextInColor = function(text, r, g, b, a)
local hex = string.format(
'%02x%02x%02x%02x',
Clamp(a * 255, 0, 255),
Clamp(r * 255, 0, 255),
Clamp(g * 255, 0, 255),
Clamp(b * 255, 0, 255)
);
return WrapTextInColorCode(text, hex);
end
StdUi.Util.tableCount = function(tab)
local n = #tab;
if (n == 0) then
for _ in pairs(tab) do
n = n + 1;
end
end
return n;
end |
local __DebugAdapter = __DebugAdapter
local luaObjectLines = {
---@param stack LuaItemStack
---@param short boolean | nil
LuaItemStack = function(stack,short)
if stack.valid_for_read then
if not short then
return __DebugAdapter.stringInterp([[<LuaItemStack>{[}name={name}, count={count}{]}]],nil,stack)
else
return [[<LuaItemStack>]]
end
else
return [[<Empty LuaItemStack>]]
end
end,
LuaPlayer = [[<LuaPlayer>{[}name={name}, index={index}{]}]],
LuaSurface = [[<LuaSurface>{[}name={name}, index={index}{]}]],
LuaForce = [[<LuaForce>{[}name={name}, index={index}{]}]],
LuaGuiElement = [[<LuaGuiElement>{[}name={name}, type={type}, index={index}{]}]],
LuaStyle = [[<LuaStyle>{[}name={name}{]}]],
LuaEntity = [[<LuaEntity>{[}name={name}, type={type}, unit_number={unit_number}{]}]],
}
__DebugAdapter.stepIgnoreAll(luaObjectLines)
-- class data last updated factorio 0.18.24
return {
alwaysValid = {
LuaRemote = true,
LuaCommandProcessor = true,
LuaSettings = true,
LuaRCON = true,
LuaRendering = true,
LuaBootstrap = true,
LuaGameScript = true,
LuaMapSettings = true,
LuaDifficultySettings = true,
LuaGameViewSettings = true,
},
lineItem = luaObjectLines,
expandKeys = {
LuaAISettings = {
allow_destroy_when_commands_fail = {},
allow_try_return_to_spawner = {},
do_separation = {},
path_resolution_modifier = {},
},
LuaAccumulatorControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
output_signal = {},
},
LuaAchievementPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
allowed_without_fight = {readOnly = true},
hidden = {readOnly = true},
},
LuaAmmoCategoryPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
bonus_gui_order = {readOnly = true},
},
LuaArithmeticCombinatorControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
signals_last_tick = {readOnly = true},
parameters = {readOnly = true},
},
LuaAutoplaceControlPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
richness = {readOnly = true},
control_order = {readOnly = true},
category = {readOnly = true},
},
LuaBootstrap = {
mod_name = {readOnly = true},
active_mods = {readOnly = true},
is_game_in_debug_mode = {readOnly = true},
},
LuaBurner = {
owner = {readOnly = true},
inventory = {readOnly = true},
burnt_result_inventory = {readOnly = true},
heat = {},
heat_capacity = {readOnly = true},
remaining_burning_fuel = {},
currently_burning = {},
fuel_categories = {readOnly = true},
},
LuaBurnerPrototype = {
emissions = {readOnly = true},
render_no_network_icon = {readOnly = true},
render_no_power_icon = {readOnly = true},
effectivity = {readOnly = true},
fuel_inventory_size = {readOnly = true},
burnt_inventory_size = {readOnly = true},
smoke = {readOnly = true},
light_flicker = {readOnly = true},
fuel_categories = {readOnly = true},
},
LuaCircuitNetwork = {
entity = {readOnly = true},
wire_type = {readOnly = true},
circuit_connector_id = {readOnly = true},
signals = {readOnly = true},
network_id = {readOnly = true},
connected_circuit_count = {readOnly = true},
},
LuaCommandProcessor = {
commands = {readOnly = true},
game_commands = {readOnly = true},
},
LuaConstantCombinatorControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
parameters = {readOnly = true},
enabled = {},
signals_count = {readOnly = true},
},
LuaContainerControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
},
LuaCustomChartTag = {
icon = {},
last_user = {},
position = {readOnly = true},
text = {},
tag_number = {readOnly = true},
force = {readOnly = true},
surface = {readOnly = true},
},
LuaCustomInputPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
key_sequence = {readOnly = true},
alternative_key_sequence = {readOnly = true},
linked_game_control = {readOnly = true},
consuming = {readOnly = true},
enabled = {readOnly = true},
},
LuaDamagePrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
hidden = {readOnly = true},
},
LuaDeciderCombinatorControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
signals_last_tick = {readOnly = true},
parameters = {readOnly = true},
},
LuaDecorativePrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
collision_box = {readOnly = true},
collision_mask = {readOnly = true},
collision_mask_with_flags = {readOnly = true},
autoplace_specification = {readOnly = true},
},
LuaDifficultySettings = {
recipe_difficulty = {},
technology_difficulty = {},
technology_price_multiplier = {},
research_queue_setting = {},
},
LuaElectricEnergySourcePrototype = {
buffer_capacity = {readOnly = true},
usage_priority = {readOnly = true},
input_flow_limit = {readOnly = true},
output_flow_limit = {readOnly = true},
drain = {readOnly = true},
emissions = {readOnly = true},
render_no_network_icon = {readOnly = true},
render_no_power_icon = {readOnly = true},
},
LuaEntity = {
surface = {readOnly = true},
position = {readOnly = true},
vehicle = {readOnly = true},
force = {},
selected = {},
opened = {},
crafting_queue_size = {readOnly = true},
walking_state = {},
riding_state = {},
mining_state = {},
shooting_state = {},
picking_state = {},
repair_state = {},
cursor_stack = {readOnly = true},
cursor_ghost = {},
driving = {},
crafting_queue = {readOnly = true},
following_robots = {readOnly = true},
cheat_mode = {},
character_crafting_speed_modifier = {},
character_mining_speed_modifier = {},
character_additional_mining_categories = {},
character_running_speed_modifier = {},
character_build_distance_bonus = {},
character_item_drop_distance_bonus = {},
character_reach_distance_bonus = {},
character_resource_reach_distance_bonus = {},
character_item_pickup_distance_bonus = {},
character_loot_pickup_distance_bonus = {},
character_inventory_slots_bonus = {},
character_trash_slot_count_bonus = {},
character_maximum_following_robot_count_bonus = {},
character_health_bonus = {},
character_logistic_slot_count = {},
character_personal_logistic_requests_enabled = {},
auto_trash_filters = {},
opened_gui_type = {readOnly = true},
build_distance = {readOnly = true},
drop_item_distance = {readOnly = true},
reach_distance = {readOnly = true},
item_pickup_distance = {readOnly = true},
loot_pickup_distance = {readOnly = true},
resource_reach_distance = {readOnly = true},
in_combat = {readOnly = true},
character_running_speed = {readOnly = true},
character_mining_progress = {readOnly = true},
name = {readOnly = true},
ghost_name = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
ghost_localised_name = {readOnly = true},
ghost_localised_description = {readOnly = true},
type = {readOnly = true},
ghost_type = {readOnly = true},
active = {},
destructible = {},
minable = {},
rotatable = {},
operable = {},
health = {},
direction = {},
supports_direction = {readOnly = true},
orientation = {},
cliff_orientation = {readOnly = true},
amount = {},
initial_amount = {},
effectivity_modifier = {},
consumption_modifier = {},
friction_modifier = {},
driver_is_gunner = {},
speed = {},
effective_speed = {readOnly = true},
stack = {readOnly = true},
prototype = {readOnly = true},
ghost_prototype = {readOnly = true},
drop_position = {},
pickup_position = {},
drop_target = {},
pickup_target = {},
selected_gun_index = {},
energy = {},
temperature = {},
previous_recipe = {readOnly = true},
held_stack = {readOnly = true},
held_stack_position = {readOnly = true},
train = {readOnly = true},
neighbours = {readOnly = true},
belt_neighbours = {readOnly = true},
fluidbox = {},
backer_name = {},
time_to_live = {},
color = {},
text = {},
signal_state = {readOnly = true},
chain_signal_state = {readOnly = true},
to_be_looted = {},
crafting_speed = {readOnly = true},
crafting_progress = {},
bonus_progress = {},
productivity_bonus = {readOnly = true},
pollution_bonus = {readOnly = true},
speed_bonus = {readOnly = true},
consumption_bonus = {readOnly = true},
belt_to_ground_type = {readOnly = true},
loader_type = {},
rocket_parts = {},
logistic_network = {},
logistic_cell = {readOnly = true},
item_requests = {},
player = {readOnly = true},
unit_group = {readOnly = true},
damage_dealt = {},
kills = {},
last_user = {},
electric_buffer_size = {},
electric_input_flow_limit = {readOnly = true},
electric_output_flow_limit = {readOnly = true},
electric_drain = {readOnly = true},
electric_emissions = {readOnly = true},
unit_number = {readOnly = true},
ghost_unit_number = {readOnly = true},
mining_progress = {},
bonus_mining_progress = {},
power_production = {},
power_usage = {},
bounding_box = {readOnly = true},
secondary_bounding_box = {readOnly = true},
selection_box = {readOnly = true},
secondary_selection_box = {readOnly = true},
mining_target = {readOnly = true},
circuit_connected_entities = {readOnly = true},
circuit_connection_definitions = {readOnly = true},
request_slot_count = {readOnly = true},
filter_slot_count = {readOnly = true},
loader_container = {readOnly = true},
grid = {readOnly = true},
graphics_variation = {},
tree_color_index = {},
tree_color_index_max = {readOnly = true},
tree_stage_index = {},
tree_stage_index_max = {readOnly = true},
burner = {readOnly = true},
shooting_target = {},
proxy_target = {readOnly = true},
stickers = {readOnly = true},
sticked_to = {readOnly = true},
parameters = {},
alert_parameters = {},
electric_network_statistics = {readOnly = true},
inserter_stack_size_override = {},
products_finished = {},
spawner = {readOnly = true},
units = {readOnly = true},
power_switch_state = {},
relative_turret_orientation = {},
effects = {readOnly = true},
infinity_container_filters = {},
remove_unfiltered_items = {},
character_corpse_player_index = {},
character_corpse_tick_of_death = {},
character_corpse_death_cause = {},
associated_player = {},
tick_of_last_attack = {},
tick_of_last_damage = {},
splitter_filter = {},
inserter_filter_mode = {},
splitter_input_priority = {},
splitter_output_priority = {},
armed = {readOnly = true},
recipe_locked = {},
connected_rail = {readOnly = true},
trains_in_block = {readOnly = true},
timeout = {},
neighbour_bonus = {readOnly = true},
ai_settings = {readOnly = true},
highlight_box_type = {},
highlight_box_blink_interval = {},
status = {readOnly = true},
enable_logistics_while_moving = {},
render_player = {},
render_to_forces = {},
pump_rail_target = {readOnly = true},
moving = {readOnly = true},
electric_network_id = {readOnly = true},
allow_dispatching_robots = {},
auto_launch = {},
energy_generated_last_tick = {readOnly = true},
storage_filter = {},
request_from_buffers = {},
corpse_expires = {},
corpse_immune_to_entity_placement = {},
tags = {},
command = {readOnly = true},
distraction_command = {readOnly = true},
},
LuaEntityPrototype = {
name = {readOnly = true},
type = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
max_health = {readOnly = true},
infinite_resource = {readOnly = true},
minimum_resource_amount = {readOnly = true},
normal_resource_amount = {readOnly = true},
infinite_depletion_resource_amount = {readOnly = true},
resource_category = {readOnly = true},
mineable_properties = {readOnly = true},
items_to_place_this = {readOnly = true},
collision_box = {readOnly = true},
secondary_collision_box = {readOnly = true},
map_generator_bounding_box = {readOnly = true},
selection_box = {readOnly = true},
drawing_box = {readOnly = true},
sticker_box = {readOnly = true},
collision_mask = {readOnly = true},
collision_mask_with_flags = {readOnly = true},
order = {readOnly = true},
group = {readOnly = true},
subgroup = {readOnly = true},
healing_per_tick = {readOnly = true},
emissions_per_second = {readOnly = true},
corpses = {readOnly = true},
selectable_in_game = {readOnly = true},
selection_priority = {readOnly = true},
weight = {readOnly = true},
resistances = {readOnly = true},
fast_replaceable_group = {readOnly = true},
next_upgrade = {readOnly = true},
loot = {readOnly = true},
repair_speed_modifier = {readOnly = true},
turret_range = {readOnly = true},
autoplace_specification = {readOnly = true},
belt_speed = {readOnly = true},
result_units = {readOnly = true},
attack_result = {readOnly = true},
final_attack_result = {readOnly = true},
attack_parameters = {readOnly = true},
spawn_cooldown = {readOnly = true},
mining_drill_radius = {readOnly = true},
mining_speed = {readOnly = true},
logistic_mode = {readOnly = true},
max_underground_distance = {readOnly = true},
flags = {readOnly = true},
remains_when_mined = {readOnly = true},
additional_pastable_entities = {readOnly = true},
allow_copy_paste = {readOnly = true},
shooting_cursor_size = {readOnly = true},
created_smoke = {readOnly = true},
created_effect = {readOnly = true},
map_color = {readOnly = true},
friendly_map_color = {readOnly = true},
enemy_map_color = {readOnly = true},
build_base_evolution_requirement = {readOnly = true},
instruments = {readOnly = true},
max_polyphony = {readOnly = true},
module_inventory_size = {readOnly = true},
ingredient_count = {readOnly = true},
crafting_speed = {readOnly = true},
crafting_categories = {readOnly = true},
resource_categories = {readOnly = true},
supply_area_distance = {readOnly = true},
max_wire_distance = {readOnly = true},
max_circuit_wire_distance = {readOnly = true},
energy_usage = {readOnly = true},
max_energy_usage = {readOnly = true},
effectivity = {readOnly = true},
consumption = {readOnly = true},
friction_force = {readOnly = true},
braking_force = {readOnly = true},
tank_driving = {readOnly = true},
rotation_speed = {readOnly = true},
turret_rotation_speed = {readOnly = true},
guns = {readOnly = true},
speed = {readOnly = true},
speed_multiplier_when_out_of_energy = {readOnly = true},
max_payload_size = {readOnly = true},
draw_cargo = {readOnly = true},
energy_per_move = {readOnly = true},
energy_per_tick = {readOnly = true},
max_energy = {readOnly = true},
min_to_charge = {readOnly = true},
max_to_charge = {readOnly = true},
burner_prototype = {readOnly = true},
electric_energy_source_prototype = {readOnly = true},
heat_energy_source_prototype = {readOnly = true},
fluid_energy_source_prototype = {readOnly = true},
void_energy_source_prototype = {readOnly = true},
building_grid_bit_shift = {readOnly = true},
fluid_usage_per_tick = {readOnly = true},
maximum_temperature = {readOnly = true},
target_temperature = {readOnly = true},
fluid = {readOnly = true},
fluid_capacity = {readOnly = true},
pumping_speed = {readOnly = true},
stack = {readOnly = true},
allow_custom_vectors = {readOnly = true},
allow_burner_leech = {readOnly = true},
inserter_extension_speed = {readOnly = true},
inserter_rotation_speed = {readOnly = true},
count_as_rock_for_filtered_deconstruction = {readOnly = true},
filter_count = {readOnly = true},
production = {readOnly = true},
time_to_live = {readOnly = true},
distribution_effectivity = {readOnly = true},
explosion_beam = {readOnly = true},
explosion_rotate = {readOnly = true},
tree_color_count = {readOnly = true},
alert_when_damaged = {readOnly = true},
alert_when_attacking = {readOnly = true},
color = {readOnly = true},
collision_mask_collides_with_self = {readOnly = true},
collision_mask_collides_with_tiles_only = {readOnly = true},
collision_mask_considers_tile_transitions = {readOnly = true},
allowed_effects = {readOnly = true},
rocket_parts_required = {readOnly = true},
fixed_recipe = {readOnly = true},
construction_radius = {readOnly = true},
logistic_radius = {readOnly = true},
energy_per_hit_point = {readOnly = true},
create_ghost_on_death = {readOnly = true},
timeout = {readOnly = true},
fluidbox_prototypes = {readOnly = true},
neighbour_bonus = {readOnly = true},
neighbour_collision_increase = {readOnly = true},
container_distance = {readOnly = true},
belt_distance = {readOnly = true},
belt_length = {readOnly = true},
is_building = {readOnly = true},
automated_ammo_count = {readOnly = true},
max_speed = {readOnly = true},
darkness_for_all_lamps_on = {readOnly = true},
darkness_for_all_lamps_off = {readOnly = true},
always_on = {readOnly = true},
min_darkness_to_spawn = {readOnly = true},
max_darkness_to_spawn = {readOnly = true},
call_for_help_radius = {readOnly = true},
max_count_of_owned_units = {readOnly = true},
max_friends_around_to_spawn = {readOnly = true},
spawning_radius = {readOnly = true},
spawning_spacing = {readOnly = true},
radius = {readOnly = true},
cliff_explosive_prototype = {readOnly = true},
has_belt_immunity = {readOnly = true},
vision_distance = {readOnly = true},
pollution_to_join_attack = {readOnly = true},
min_pursue_time = {readOnly = true},
max_pursue_distance = {readOnly = true},
radar_range = {readOnly = true},
move_while_shooting = {readOnly = true},
can_open_gates = {readOnly = true},
affected_by_tiles = {readOnly = true},
distraction_cooldown = {readOnly = true},
spawning_time_modifier = {readOnly = true},
alert_icon_shift = {readOnly = true},
lab_inputs = {readOnly = true},
researching_speed = {readOnly = true},
item_slot_count = {readOnly = true},
base_productivity = {readOnly = true},
allow_access_to_all_forces = {readOnly = true},
supports_direction = {readOnly = true},
terrain_friction_modifier = {readOnly = true},
max_distance_of_sector_revealed = {readOnly = true},
max_distance_of_nearby_sector_revealed = {readOnly = true},
adjacent_tile_collision_box = {readOnly = true},
adjacent_tile_collision_mask = {readOnly = true},
adjacent_tile_collision_test = {readOnly = true},
center_collision_mask = {readOnly = true},
running_speed = {readOnly = true},
maximum_corner_sliding_distance = {readOnly = true},
build_distance = {readOnly = true},
drop_item_distance = {readOnly = true},
reach_distance = {readOnly = true},
reach_resource_distance = {readOnly = true},
item_pickup_distance = {readOnly = true},
loot_pickup_distance = {readOnly = true},
enter_vehicle_distance = {readOnly = true},
ticks_to_keep_gun = {readOnly = true},
ticks_to_keep_aiming_direction = {readOnly = true},
ticks_to_stay_in_combat = {readOnly = true},
respawn_time = {readOnly = true},
damage_hit_tint = {readOnly = true},
character_corpse = {readOnly = true},
inserter_pickup_position = {readOnly = true},
inserter_drop_position = {readOnly = true},
inserter_chases_belt_items = {readOnly = true},
},
LuaEquipment = {
name = {readOnly = true},
type = {readOnly = true},
position = {readOnly = true},
shape = {readOnly = true},
shield = {},
max_shield = {readOnly = true},
max_solar_power = {readOnly = true},
movement_bonus = {readOnly = true},
generator_power = {readOnly = true},
energy = {},
max_energy = {readOnly = true},
prototype = {readOnly = true},
burner = {readOnly = true},
},
LuaEquipmentCategoryPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
},
LuaEquipmentGrid = {
prototype = {readOnly = true},
width = {readOnly = true},
height = {readOnly = true},
equipment = {readOnly = true},
generator_energy = {readOnly = true},
max_solar_energy = {readOnly = true},
available_in_batteries = {readOnly = true},
battery_capacity = {readOnly = true},
shield = {readOnly = true},
max_shield = {readOnly = true},
inhibit_movement_bonus = {},
},
LuaEquipmentGridPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
equipment_categories = {readOnly = true},
width = {readOnly = true},
height = {readOnly = true},
locked = {readOnly = true},
},
LuaEquipmentPrototype = {
name = {readOnly = true},
type = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
shape = {readOnly = true},
take_result = {readOnly = true},
energy_production = {readOnly = true},
shield = {readOnly = true},
energy_per_shield = {readOnly = true},
logistic_parameters = {readOnly = true},
energy_consumption = {readOnly = true},
movement_bonus = {readOnly = true},
energy_source = {readOnly = true},
equipment_categories = {readOnly = true},
burner_prototype = {readOnly = true},
electric_energy_source_prototype = {readOnly = true},
background_color = {readOnly = true},
attack_parameters = {readOnly = true},
automatic = {readOnly = true},
},
LuaFlowStatistics = {
input_counts = {readOnly = true},
output_counts = {readOnly = true},
force = {readOnly = true},
},
LuaFluidBox = {
owner = {readOnly = true},
["[]"] = {readOnly = true, thisAsTable = true, iterMode = "count" }
},
LuaFluidBoxPrototype = {
entity = {readOnly = true},
index = {readOnly = true},
pipe_connections = {readOnly = true},
production_type = {readOnly = true},
base_area = {readOnly = true},
base_level = {readOnly = true},
height = {readOnly = true},
volume = {readOnly = true},
filter = {readOnly = true},
minimum_temperature = {readOnly = true},
maximum_temperature = {readOnly = true},
secondary_draw_orders = {readOnly = true},
render_layer = {readOnly = true},
},
LuaFluidEnergySourcePrototype = {
emissions = {readOnly = true},
render_no_network_icon = {readOnly = true},
render_no_power_icon = {readOnly = true},
effectivity = {readOnly = true},
burns_fluid = {readOnly = true},
scale_fluid_usage = {readOnly = true},
fluid_usage_per_tick = {readOnly = true},
smoke = {readOnly = true},
maximum_temperature = {readOnly = true},
fluid_box = {readOnly = true},
},
LuaFluidPrototype = {
name = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
default_temperature = {readOnly = true},
max_temperature = {readOnly = true},
heat_capacity = {readOnly = true},
order = {readOnly = true},
group = {readOnly = true},
subgroup = {readOnly = true},
base_color = {readOnly = true},
flow_color = {readOnly = true},
gas_temperature = {readOnly = true},
emissions_multiplier = {readOnly = true},
fuel_value = {readOnly = true},
hidden = {readOnly = true},
},
LuaForce = {
name = {readOnly = true},
technologies = {readOnly = true},
recipes = {readOnly = true},
manual_mining_speed_modifier = {},
manual_crafting_speed_modifier = {},
laboratory_speed_modifier = {},
laboratory_productivity_bonus = {},
worker_robots_speed_modifier = {},
worker_robots_battery_modifier = {},
worker_robots_storage_bonus = {},
current_research = {readOnly = true},
research_progress = {},
previous_research = {},
inserter_stack_size_bonus = {},
stack_inserter_capacity_bonus = {},
character_trash_slot_count = {},
maximum_following_robot_count = {},
following_robots_lifetime_modifier = {},
ghost_time_to_live = {},
players = {readOnly = true},
ai_controllable = {},
logistic_networks = {readOnly = true},
item_production_statistics = {readOnly = true},
fluid_production_statistics = {readOnly = true},
kill_count_statistics = {readOnly = true},
entity_build_count_statistics = {readOnly = true},
character_running_speed_modifier = {},
artillery_range_modifier = {},
character_build_distance_bonus = {},
character_item_drop_distance_bonus = {},
character_reach_distance_bonus = {},
character_resource_reach_distance_bonus = {},
character_item_pickup_distance_bonus = {},
character_loot_pickup_distance_bonus = {},
character_inventory_slots_bonus = {},
deconstruction_time_to_live = {},
character_health_bonus = {},
max_successful_attempts_per_tick_per_construction_queue = {},
max_failed_attempts_per_tick_per_construction_queue = {},
auto_character_trash_slots = {},
zoom_to_world_enabled = {},
zoom_to_world_ghost_building_enabled = {},
zoom_to_world_blueprint_enabled = {},
zoom_to_world_deconstruction_planner_enabled = {},
zoom_to_world_selection_tool_enabled = {},
character_logistic_requests = {},
rockets_launched = {},
items_launched = {readOnly = true},
connected_players = {readOnly = true, countLine = true},
mining_drill_productivity_bonus = {},
train_braking_force_bonus = {},
evolution_factor = {},
evolution_factor_by_pollution = {},
evolution_factor_by_time = {},
evolution_factor_by_killing_spawners = {},
friendly_fire = {},
share_chart = {},
research_queue_enabled = {},
index = {readOnly = true},
research_queue = {},
research_enabled = {readOnly = true},
},
LuaFuelCategoryPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
},
LuaGameScript = {
players = {readOnly = true},
map_settings = {readOnly = true},
difficulty_settings = {readOnly = true},
difficulty = {readOnly = true},
forces = {readOnly = true},
entity_prototypes = {readOnly = true},
item_prototypes = {readOnly = true},
fluid_prototypes = {readOnly = true},
tile_prototypes = {readOnly = true},
equipment_prototypes = {readOnly = true},
damage_prototypes = {readOnly = true},
virtual_signal_prototypes = {readOnly = true},
equipment_grid_prototypes = {readOnly = true},
recipe_prototypes = {readOnly = true},
technology_prototypes = {readOnly = true},
decorative_prototypes = {readOnly = true},
particle_prototypes = {readOnly = true},
autoplace_control_prototypes = {readOnly = true},
noise_layer_prototypes = {readOnly = true},
mod_setting_prototypes = {readOnly = true},
custom_input_prototypes = {readOnly = true},
ammo_category_prototypes = {readOnly = true},
named_noise_expressions = {readOnly = true},
item_subgroup_prototypes = {readOnly = true},
item_group_prototypes = {readOnly = true},
fuel_category_prototypes = {readOnly = true},
resource_category_prototypes = {readOnly = true},
achievement_prototypes = {readOnly = true},
module_category_prototypes = {readOnly = true},
equipment_category_prototypes = {readOnly = true},
trivial_smoke_prototypes = {readOnly = true},
shortcut_prototypes = {readOnly = true},
recipe_category_prototypes = {readOnly = true},
styles = {readOnly = true},
tick = {readOnly = true},
ticks_played = {readOnly = true},
tick_paused = {},
ticks_to_run = {},
finished = {readOnly = true},
speed = {},
surfaces = {readOnly = true},
active_mods = {readOnly = true},
connected_players = {readOnly = true, countLine = true},
permissions = {readOnly = true},
backer_names = {readOnly = true},
default_map_gen_settings = {readOnly = true},
enemy_has_vision_on_land_mines = {},
autosave_enabled = {},
draw_resource_selection = {},
pollution_statistics = {readOnly = true},
max_force_distraction_distance = {readOnly = true},
max_force_distraction_chunk_distance = {readOnly = true},
max_electric_pole_supply_area_distance = {readOnly = true},
max_electric_pole_connection_distance = {readOnly = true},
max_beacon_supply_area_distance = {readOnly = true},
max_gate_activation_distance = {readOnly = true},
max_inserter_reach_distance = {readOnly = true},
max_pipe_to_ground_distance = {readOnly = true},
max_underground_belt_distance = {readOnly = true},
},
LuaGameViewSettings = {
show_controller_gui = {},
show_minimap = {},
show_research_info = {},
show_entity_info = {},
show_alert_gui = {},
update_entity_selection = {},
show_rail_block_visualisation = {},
show_side_menu = {},
show_map_view_options = {},
show_quickbar = {},
show_shortcut_bar = {},
},
LuaGenericOnOffControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
disabled = {readOnly = true},
circuit_condition = {},
logistic_condition = {},
connect_to_logistic_network = {},
},
LuaGroup = {
name = {readOnly = true},
localised_name = {readOnly = true},
type = {readOnly = true},
group = {readOnly = true},
subgroups = {readOnly = true},
order_in_recipe = {readOnly = true},
order = {readOnly = true},
},
LuaGui = {
player = {readOnly = true},
children = {readOnly = true},
top = {readOnly = true},
left = {readOnly = true},
center = {readOnly = true},
goal = {readOnly = true},
screen = {readOnly = true},
},
LuaGuiElement = {
index = {readOnly = true},
gui = {readOnly = true},
parent = {readOnly = true},
name = {readOnly = true},
caption = {},
value = {},
direction = {readOnly = true},
style = {},
visible = {},
text = {},
children_names = {readOnly = true},
state = {},
player_index = {readOnly = true},
sprite = {},
resize_to_sprite = {},
hovered_sprite = {},
clicked_sprite = {},
tooltip = {},
horizontal_scroll_policy = {},
vertical_scroll_policy = {},
type = {readOnly = true},
children = {readOnly = true},
items = {},
selected_index = {},
number = {},
show_percent_for_small_numbers = {},
location = {},
auto_center = {},
badge_text = {},
position = {},
surface_index = {},
zoom = {},
minimap_player_index = {},
force = {},
elem_type = {readOnly = true},
elem_value = {},
selectable = {},
word_wrap = {},
read_only = {},
enabled = {},
ignored_by_interaction = {},
locked = {},
draw_vertical_lines = {},
draw_horizontal_lines = {},
draw_horizontal_line_after_headers = {},
column_count = {readOnly = true},
vertical_centering = {},
slider_value = {},
mouse_button_filter = {},
numeric = {},
allow_decimal = {},
allow_negative = {},
is_password = {},
lose_focus_on_confirm = {},
clear_and_focus_on_right_click = {},
drag_target = {},
selected_tab_index = {},
tabs = {readOnly = true},
entity = {},
switch_state = {},
allow_none_state = {},
left_label_caption = {},
left_label_tooltip = {},
right_label_caption = {},
right_label_tooltip = {},
},
LuaInserterControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
disabled = {readOnly = true},
circuit_condition = {},
logistic_condition = {},
connect_to_logistic_network = {},
circuit_read_hand_contents = {},
circuit_mode_of_operation = {},
circuit_hand_read_mode = {},
circuit_set_stack_size = {},
circuit_stack_control_signal = {},
},
LuaHeatEnergySourcePrototype = {
emissions = {readOnly = true},
render_no_network_icon = {readOnly = true},
render_no_power_icon = {readOnly = true},
max_temperature = {readOnly = true},
default_temperature = {readOnly = true},
specific_heat = {readOnly = true},
max_transfer = {readOnly = true},
min_temperature_gradient = {readOnly = true},
min_working_temperature = {readOnly = true},
minimum_glow_temperature = {readOnly = true},
connections = {readOnly = true},
},
LuaInventory = {
index = {readOnly = true},
entity_owner = {readOnly = true},
player_owner = {readOnly = true},
equipment_owner = {readOnly = true},
mod_owner = {readOnly = true},
["[]"] = {readOnly = true, thisAsTable = true, iterMode = "count" }
},
LuaItemPrototype = {
type = {readOnly = true},
name = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
order = {readOnly = true},
place_result = {readOnly = true},
place_as_equipment_result = {readOnly = true},
place_as_tile_result = {readOnly = true},
stackable = {readOnly = true},
default_request_amount = {readOnly = true},
stack_size = {readOnly = true},
wire_count = {readOnly = true},
fuel_category = {readOnly = true},
burnt_result = {readOnly = true},
fuel_value = {readOnly = true},
fuel_acceleration_multiplier = {readOnly = true},
fuel_top_speed_multiplier = {readOnly = true},
fuel_emissions_multiplier = {readOnly = true},
subgroup = {readOnly = true},
group = {readOnly = true},
flags = {readOnly = true},
rocket_launch_products = {readOnly = true},
can_be_mod_opened = {readOnly = true},
magazine_size = {readOnly = true},
reload_time = {readOnly = true},
equipment_grid = {readOnly = true},
resistances = {readOnly = true},
inventory_size_bonus = {readOnly = true},
capsule_action = {readOnly = true},
attack_parameters = {readOnly = true},
inventory_size = {readOnly = true},
item_filters = {readOnly = true},
item_group_filters = {readOnly = true},
item_subgroup_filters = {readOnly = true},
filter_mode = {readOnly = true},
insertion_priority_mode = {readOnly = true},
localised_filter_message = {readOnly = true},
extend_inventory_by_default = {readOnly = true},
default_label_color = {readOnly = true},
draw_label_for_cursor_render = {readOnly = true},
speed = {readOnly = true},
module_effects = {readOnly = true},
category = {readOnly = true},
tier = {readOnly = true},
limitations = {readOnly = true},
limitation_message_key = {readOnly = true},
straight_rail = {readOnly = true},
curved_rail = {readOnly = true},
repair_result = {readOnly = true},
selection_border_color = {readOnly = true},
alt_selection_border_color = {readOnly = true},
selection_mode_flags = {readOnly = true},
alt_selection_mode_flags = {readOnly = true},
selection_cursor_box_type = {readOnly = true},
alt_selection_cursor_box_type = {readOnly = true},
always_include_tiles = {readOnly = true},
show_in_library = {readOnly = true},
entity_filter_mode = {readOnly = true},
alt_entity_filter_mode = {readOnly = true},
tile_filter_mode = {readOnly = true},
alt_tile_filter_mode = {readOnly = true},
entity_filters = {readOnly = true},
alt_entity_filters = {readOnly = true},
entity_type_filters = {readOnly = true},
alt_entity_type_filters = {readOnly = true},
tile_filters = {readOnly = true},
alt_tile_filters = {readOnly = true},
entity_filter_slots = {readOnly = true},
tile_filter_slots = {readOnly = true},
durability_description_key = {readOnly = true},
durability = {readOnly = true},
infinite = {readOnly = true},
mapper_count = {readOnly = true},
},
LuaItemStack = {
prototype = {readOnly = true},
name = {readOnly = true},
type = {readOnly = true},
count = {},
grid = {readOnly = true},
health = {},
durability = {},
ammo = {},
blueprint_icons = {},
label = {},
label_color = {},
allow_manual_label_change = {},
cost_to_build = {readOnly = true},
extends_inventory = {},
prioritize_insertion_mode = {},
default_icons = {readOnly = true},
tags = {},
custom_description = {},
entity_filters = {},
tile_filters = {},
entity_filter_mode = {},
tile_filter_mode = {},
tile_selection_mode = {},
trees_and_rocks_only = {},
entity_filter_count = {readOnly = true},
tile_filter_count = {readOnly = true},
active_index = {},
item_number = {readOnly = true},
is_blueprint = {readOnly = true},
is_blueprint_book = {readOnly = true},
is_module = {readOnly = true},
is_tool = {readOnly = true},
is_mining_tool = {readOnly = true},
is_armor = {readOnly = true},
is_repair_tool = {readOnly = true},
is_item_with_label = {readOnly = true},
is_item_with_inventory = {readOnly = true},
is_item_with_entity_data = {readOnly = true},
is_selection_tool = {readOnly = true},
is_item_with_tags = {readOnly = true},
is_deconstruction_item = {readOnly = true},
is_upgrade_item = {readOnly = true},
},
LuaLampControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
disabled = {readOnly = true},
circuit_condition = {},
logistic_condition = {},
connect_to_logistic_network = {},
use_colors = {},
color = {readOnly = true},
},
LuaLogisticCell = {
logistic_radius = {readOnly = true},
logistics_connection_distance = {readOnly = true},
construction_radius = {readOnly = true},
stationed_logistic_robot_count = {readOnly = true},
stationed_construction_robot_count = {readOnly = true},
mobile = {readOnly = true},
transmitting = {readOnly = true},
charge_approach_distance = {readOnly = true},
charging_robot_count = {readOnly = true},
to_charge_robot_count = {readOnly = true},
owner = {readOnly = true},
logistic_network = {readOnly = true},
neighbours = {readOnly = true},
charging_robots = {readOnly = true},
to_charge_robots = {readOnly = true},
},
LuaLogisticContainerControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
circuit_mode_of_operation = {},
},
LuaLogisticNetwork = {
force = {readOnly = true},
available_logistic_robots = {readOnly = true},
all_logistic_robots = {readOnly = true},
available_construction_robots = {readOnly = true},
all_construction_robots = {readOnly = true},
robot_limit = {readOnly = true},
cells = {readOnly = true},
providers = {readOnly = true},
empty_providers = {readOnly = true},
requesters = {readOnly = true},
storages = {readOnly = true},
logistic_members = {readOnly = true},
provider_points = {readOnly = true},
passive_provider_points = {readOnly = true},
active_provider_points = {readOnly = true},
empty_provider_points = {readOnly = true},
requester_points = {readOnly = true},
storage_points = {readOnly = true},
robots = {readOnly = true},
construction_robots = {readOnly = true},
logistic_robots = {readOnly = true},
},
LuaLogisticPoint = {
owner = {readOnly = true},
logistic_network = {readOnly = true},
logistic_member_index = {readOnly = true},
filters = {readOnly = true},
mode = {readOnly = true},
force = {readOnly = true},
targeted_items_pickup = {readOnly = true},
targeted_items_deliver = {readOnly = true},
exact = {readOnly = true},
},
LuaMapSettings = {
pollution = {},
enemy_evolution = {},
enemy_expansion = {},
unit_group = {},
steering = {},
path_finder = {},
max_failed_behavior_count = {},
},
["LuaMapSettings.pollution"] = {
enabled = {},
diffusion_ratio = {},
min_to_diffuse = {},
ageing = {},
expected_max_per_chunk = {},
min_to_show_per_chunk = {},
min_pollution_to_damage_trees = {},
pollution_with_max_forest_damage = {},
pollution_per_tree_damage = {},
pollution_restored_per_tree_damage = {},
max_pollution_to_restore_trees = {},
enemy_attack_pollution_consumption_modifier = {},
},
["LuaMapSettings.enemy_evolution"] = {
enabled = {},
time_factor = {},
destroy_factor = {},
pollution_factor = {},
},
["LuaMapSettings.enemy_expansion"] = {
enabled = {},
max_expansion_distance = {},
friendly_base_influence_radius = {},
enemy_building_influence_radius = {},
building_coefficient = {},
other_base_coefficient = {},
neighbouring_chunk_coefficient = {},
neighbouring_base_chunk_coefficient = {};
max_colliding_tiles_coefficient = {},
settler_group_min_size = {},
settler_group_max_size = {},
min_expansion_cooldown = {},
max_expansion_cooldown = {},
},
["LuaMapSettings.unit_group"] = {
min_group_gathering_time = {},
max_group_gathering_time = {},
max_wait_time_for_late_members = {},
max_group_radius = {},
min_group_radius = {},
max_member_speedup_when_behind = {},
max_member_slowdown_when_ahead = {},
max_group_slowdown_factor = {},
max_group_member_fallback_factor = {},
member_disown_distance = {},
tick_tolerance_when_member_arrives = {},
max_gathering_unit_groups = {},
max_unit_group_size = {},
},
["LuaMapSettings.steering"] = {
default = {}, moving = {},
},
["LuaMapSettings.steering.default"] = {
radius = {},
separation_force = {},
separation_factor = {},
force_unit_fuzzy_goto_behavior = {},
},
["LuaMapSettings.steering.moving"] = {
radius = {},
separation_force = {},
separation_factor = {},
force_unit_fuzzy_goto_behavior = {},
},
["LuaMapSettings.path_finder"] = {
fwd2bwd_ratio = {},
goal_pressure_ratio = {},
max_steps_worked_per_tick = {},
max_work_done_per_tick = {},
use_path_cache = {},
short_cache_size = {},
long_cache_size = {},
short_cache_min_cacheable_distance = {},
short_cache_min_algo_steps_to_cache = {},
long_cache_min_cacheable_distance = {},
cache_max_connect_to_cache_steps_multiplier = {},
cache_accept_path_start_distance_ratio = {},
cache_accept_path_end_distance_ratio = {},
negative_cache_accept_path_start_distance_ratio = {},
negative_cache_accept_path_end_distance_ratio = {},
cache_path_start_distance_rating_multiplier = {},
cache_path_end_distance_rating_multiplier = {},
stale_enemy_with_same_destination_collision_penalty = {},
ignore_moving_enemy_collision_distance = {},
enemy_with_different_destination_collision_penalty = {},
general_entity_collision_penalty = {},
general_entity_subsequent_collision_penalty = {},
extended_collision_penalty = {},
max_clients_to_accept_any_new_request = {},
max_clients_to_accept_short_new_request = {},
direct_distance_to_consider_short_request = {},
short_request_max_steps = {},
short_request_ratio = {},
min_steps_to_check_path_find_termination = {},
start_to_goal_cost_multiplier_to_terminate_path_find = {},
},
LuaMiningDrillControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
disabled = {readOnly = true},
circuit_condition = {},
logistic_condition = {},
connect_to_logistic_network = {},
circuit_enable_disable = {},
circuit_read_resources = {},
resource_read_mode = {},
resource_read_targets = {readOnly = true},
},
LuaModSettingPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
mod = {readOnly = true},
setting_type = {readOnly = true},
default_value = {readOnly = true},
minimum_value = {readOnly = true},
maximum_value = {readOnly = true},
allowed_values = {readOnly = true},
allow_blank = {readOnly = true},
auto_trim = {readOnly = true},
hidden = {readOnly = true},
},
LuaModuleCategoryPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
},
LuaNamedNoiseExpression = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
intended_property = {readOnly = true},
expression = {readOnly = true},
},
LuaNoiseLayerPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
},
LuaParticlePrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
regular_trigger_effect = {readOnly = true},
ended_in_water_trigger_effect = {readOnly = true},
render_layer = {readOnly = true},
render_layer_when_on_ground = {readOnly = true},
life_time = {readOnly = true},
regular_trigger_effect_frequency = {readOnly = true},
movement_modifier_when_on_ground = {readOnly = true},
movement_modifier = {readOnly = true},
mining_particle_frame_speed = {readOnly = true},
},
LuaPermissionGroup = {
name = {},
players = {readOnly = true},
group_id = {readOnly = true},
},
LuaPermissionGroups = {
groups = {readOnly = true},
},
LuaPlayer = {
surface = {readOnly = true},
position = {readOnly = true},
vehicle = {readOnly = true},
force = {},
selected = {},
opened = {},
crafting_queue_size = {readOnly = true},
walking_state = {},
riding_state = {},
mining_state = {},
shooting_state = {},
picking_state = {},
repair_state = {},
cursor_stack = {readOnly = true},
cursor_ghost = {},
driving = {},
crafting_queue = {readOnly = true},
following_robots = {readOnly = true},
cheat_mode = {},
character_crafting_speed_modifier = {},
character_mining_speed_modifier = {},
character_additional_mining_categories = {},
character_running_speed_modifier = {},
character_build_distance_bonus = {},
character_item_drop_distance_bonus = {},
character_reach_distance_bonus = {},
character_resource_reach_distance_bonus = {},
character_item_pickup_distance_bonus = {},
character_loot_pickup_distance_bonus = {},
character_inventory_slots_bonus = {},
character_trash_slot_count_bonus = {},
character_maximum_following_robot_count_bonus = {},
character_health_bonus = {},
character_logistic_slot_count = {},
character_personal_logistic_requests_enabled = {},
auto_trash_filters = {},
opened_gui_type = {readOnly = true},
build_distance = {readOnly = true},
drop_item_distance = {readOnly = true},
reach_distance = {readOnly = true},
item_pickup_distance = {readOnly = true},
loot_pickup_distance = {readOnly = true},
resource_reach_distance = {readOnly = true},
in_combat = {readOnly = true},
character_running_speed = {readOnly = true},
character_mining_progress = {readOnly = true},
character = {},
index = {readOnly = true},
gui = {readOnly = true},
opened_self = {readOnly = true},
controller_type = {readOnly = true},
game_view_settings = {},
minimap_enabled = {},
color = {},
chat_color = {},
name = {readOnly = true},
tag = {},
connected = {readOnly = true},
admin = {},
entity_copy_source = {readOnly = true},
afk_time = {readOnly = true},
online_time = {readOnly = true},
last_online = {readOnly = true},
permission_group = {},
mod_settings = {readOnly = true},
ticks_to_respawn = {},
display_resolution = {readOnly = true},
display_scale = {readOnly = true},
blueprint_to_setup = {readOnly = true},
render_mode = {readOnly = true},
spectator = {},
remove_unfiltered_items = {},
infinity_inventory_filters = {},
},
LuaProfiler = {
["<translated>"] = {thisTranslated = true},
},
LuaProgrammableSpeakerControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
circuit_parameters = {},
circuit_condition = {},
},
LuaRailChainSignalControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
red_signal = {},
orange_signal = {},
green_signal = {},
blue_signal = {},
},
LuaRailPath = {
size = {readOnly = true},
current = {readOnly = true},
total_distance = {readOnly = true},
travelled_distance = {readOnly = true},
rails = {readOnly = true},
},
LuaRailSignalControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
red_signal = {},
orange_signal = {},
green_signal = {},
close_signal = {},
read_signal = {},
circuit_condition = {},
},
LuaRecipe = {
name = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
prototype = {readOnly = true},
enabled = {},
category = {readOnly = true},
ingredients = {readOnly = true},
products = {readOnly = true},
hidden = {readOnly = true},
hidden_from_flow_stats = {},
energy = {readOnly = true},
order = {readOnly = true},
group = {readOnly = true},
subgroup = {readOnly = true},
force = {readOnly = true},
},
LuaRecipeCategoryPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
},
LuaRecipePrototype = {
enabled = {readOnly = true},
name = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
category = {readOnly = true},
ingredients = {readOnly = true},
products = {readOnly = true},
main_product = {readOnly = true},
hidden = {readOnly = true},
hidden_from_flow_stats = {readOnly = true},
hidden_from_player_crafting = {readOnly = true},
always_show_made_in = {readOnly = true},
energy = {readOnly = true},
order = {readOnly = true},
group = {readOnly = true},
subgroup = {readOnly = true},
request_paste_multiplier = {readOnly = true},
overload_multiplier = {readOnly = true},
allow_as_intermediate = {readOnly = true},
allow_intermediates = {readOnly = true},
show_amount_in_title = {readOnly = true},
always_show_products = {readOnly = true},
emissions_multiplier = {readOnly = true},
allow_decomposition = {readOnly = true},
},
LuaRemote = {
interfaces = {readOnly = true},
},
LuaResourceCategoryPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
},
LuaRoboportControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
read_logistics = {},
read_robot_stats = {},
available_logistic_output_signal = {},
total_logistic_output_signal = {},
available_construction_output_signal = {},
total_construction_output_signal = {},
},
LuaSettings = {
startup = {readOnly = true},
global = {readOnly = true},
player = {readOnly = true},
},
LuaShortcutPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
action = {readOnly = true},
item_to_create = {readOnly = true},
technology_to_unlock = {readOnly = true},
toggleable = {readOnly = true},
associated_control_input = {readOnly = true},
},
LuaStorageTankControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
},
LuaStyle = {
gui = {readOnly = true},
name = {readOnly = true},
minimal_width = {},
maximal_width = {},
minimal_height = {},
maximal_height = {},
natural_width = {},
natural_height = {},
top_padding = {},
right_padding = {},
bottom_padding = {},
left_padding = {},
top_margin = {},
right_margin = {},
bottom_margin = {},
left_margin = {},
horizontal_align = {},
vertical_align = {},
font_color = {},
font = {},
top_cell_padding = {},
right_cell_padding = {},
bottom_cell_padding = {},
left_cell_padding = {},
horizontally_stretchable = {},
vertically_stretchable = {},
horizontally_squashable = {},
vertically_squashable = {},
rich_text_setting = {},
hovered_font_color = {},
clicked_font_color = {},
disabled_font_color = {},
pie_progress_color = {},
clicked_vertical_offset = {},
selected_font_color = {},
selected_hovered_font_color = {},
selected_clicked_font_color = {},
strikethrough_color = {},
horizontal_spacing = {},
vertical_spacing = {},
use_header_filler = {},
color = {},
column_alignments = {readOnly = true},
single_line = {},
extra_top_padding_when_activated = {},
extra_bottom_padding_when_activated = {},
extra_left_padding_when_activated = {},
extra_right_padding_when_activated = {},
extra_top_margin_when_activated = {},
extra_bottom_margin_when_activated = {},
extra_left_margin_when_activated = {},
extra_right_margin_when_activated = {},
stretch_image_to_widget_size = {},
badge_font = {},
badge_horizontal_spacing = {},
default_badge_font_color = {},
selected_badge_font_color = {},
disabled_badge_font_color = {},
},
LuaSurface = {
name = {},
index = {readOnly = true},
map_gen_settings = {},
always_day = {},
daytime = {},
darkness = {readOnly = true},
wind_speed = {},
wind_orientation = {},
wind_orientation_change = {},
peaceful_mode = {},
freeze_daytime = {},
ticks_per_day = {},
dusk = {},
dawn = {},
evening = {},
morning = {},
solar_power_multiplier = {},
min_brightness = {},
brightness_visual_weights = {},
},
LuaTechnology = {
force = {readOnly = true},
name = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
prototype = {readOnly = true},
enabled = {},
visible_when_disabled = {},
upgrade = {readOnly = true},
researched = {},
prerequisites = {readOnly = true},
research_unit_ingredients = {readOnly = true},
effects = {readOnly = true},
research_unit_count = {readOnly = true},
research_unit_energy = {readOnly = true},
order = {readOnly = true},
level = {},
research_unit_count_formula = {readOnly = true},
},
LuaTechnologyPrototype = {
name = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
enabled = {readOnly = true},
hidden = {readOnly = true},
visible_when_disabled = {readOnly = true},
upgrade = {readOnly = true},
prerequisites = {readOnly = true},
research_unit_ingredients = {readOnly = true},
effects = {readOnly = true},
research_unit_count = {readOnly = true},
research_unit_energy = {readOnly = true},
order = {readOnly = true},
level = {readOnly = true},
max_level = {readOnly = true},
research_unit_count_formula = {readOnly = true},
},
LuaTile = {
name = {readOnly = true},
prototype = {readOnly = true},
position = {readOnly = true},
hidden_tile = {readOnly = true},
surface = {readOnly = true},
},
LuaTilePrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
collision_mask = {readOnly = true},
collision_mask_with_flags = {readOnly = true},
layer = {readOnly = true},
autoplace_specification = {readOnly = true},
walking_speed_modifier = {readOnly = true},
vehicle_friction_modifier = {readOnly = true},
map_color = {readOnly = true},
decorative_removal_probability = {readOnly = true},
automatic_neighbors = {readOnly = true},
allowed_neighbors = {readOnly = true},
needs_correction = {readOnly = true},
mineable_properties = {readOnly = true},
next_direction = {readOnly = true},
items_to_place_this = {readOnly = true},
can_be_part_of_blueprint = {readOnly = true},
emissions_per_second = {readOnly = true},
},
LuaTrain = {
manual_mode = {},
speed = {},
max_forward_speed = {readOnly = true},
max_backward_speed = {readOnly = true},
weight = {readOnly = true},
carriages = {readOnly = true},
locomotives = {readOnly = true},
cargo_wagons = {readOnly = true},
fluid_wagons = {readOnly = true},
schedule = {},
state = {readOnly = true},
front_rail = {readOnly = true},
back_rail = {readOnly = true},
rail_direction_from_front_rail = {readOnly = true},
rail_direction_from_back_rail = {readOnly = true},
front_stock = {readOnly = true},
back_stock = {readOnly = true},
station = {readOnly = true},
has_path = {readOnly = true},
path_end_rail = {readOnly = true},
path_end_stop = {readOnly = true},
id = {readOnly = true},
passengers = {readOnly = true},
riding_state = {readOnly = true},
killed_players = {readOnly = true},
kill_count = {readOnly = true},
path = {readOnly = true},
signal = {readOnly = true},
},
LuaTrainStopControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
disabled = {readOnly = true},
circuit_condition = {},
logistic_condition = {},
connect_to_logistic_network = {},
send_to_train = {},
read_from_train = {},
read_stopped_train = {},
enable_disable = {},
stopped_train_signal = {},
},
LuaTransportBeltControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
disabled = {readOnly = true},
circuit_condition = {},
logistic_condition = {},
connect_to_logistic_network = {},
enable_disable = {},
read_contents = {},
read_contents_mode = {},
},
LuaTransportLine = {
owner = {readOnly = true},
output_lines = {readOnly = true},
input_lines = {readOnly = true},
["[]"] = {readOnly = true, thisAsTable = true, iterMode = "count" }
},
LuaTrivialSmokePrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
color = {readOnly = true},
start_scale = {readOnly = true},
end_scale = {readOnly = true},
movement_slow_down_factor = {readOnly = true},
duration = {readOnly = true},
spread_duration = {readOnly = true},
fade_away_duration = {readOnly = true},
fade_in_duration = {readOnly = true},
glow_fade_away_duration = {readOnly = true},
cyclic = {readOnly = true},
affected_by_wind = {readOnly = true},
show_when_smoke_off = {readOnly = true},
glow_animation = {readOnly = true},
render_layer = {readOnly = true},
},
LuaUnitGroup = {
members = {readOnly = true},
position = {readOnly = true},
state = {readOnly = true},
force = {readOnly = true},
surface = {readOnly = true},
group_number = {readOnly = true},
is_script_driven = {readOnly = true},
command = {readOnly = true},
distraction_command = {readOnly = true},
},
LuaVirtualSignalPrototype = {
name = {readOnly = true},
order = {readOnly = true},
localised_name = {readOnly = true},
localised_description = {readOnly = true},
special = {readOnly = true},
subgroup = {readOnly = true},
},
LuaVoidEnergySourcePrototype = {
emissions = {readOnly = true},
render_no_network_icon = {readOnly = true},
render_no_power_icon = {readOnly = true},
},
LuaWallControlBehavior = {
type = {readOnly = true},
entity = {readOnly = true},
circuit_condition = {},
open_gate = {},
read_sensor = {},
output_signal = {},
},
}
} |
--most simple entity ever
coin = class:new()
function coin:init(x, y)
self.cox = x
self.coy = y
self.active = false
self.static = true
end
function coin:draw()
love.graphics.draw(coinimage, coinquads[spriteset][coinframe], math.floor((self.cox-1-xscroll)*16*scale), ((self.coy-1-yscroll)*16-8)*scale, 0, scale, scale)
end |
local TreeSitter = require("refactoring.treesitter.treesitter")
local Nodes = require("refactoring.treesitter.nodes")
local InlineNode = Nodes.InlineNode
local StringNode = Nodes.StringNode
local FieldNode = Nodes.FieldNode
local JavaScript = {}
function JavaScript.new(bufnr, ft)
return TreeSitter:new({
filetype = ft,
bufnr = bufnr,
scope_names = {
program = "program",
function_declaration = "function",
method_definition = "function",
arrow_function = "function",
class_declaration = "class",
},
block_scope = {
statement_block = true,
function_declaration = true,
},
variable_scope = {
variable_declaration = true,
lexical_declaration = true,
},
local_var_names = {
InlineNode("(variable_declarator name: (_) @tmp_capture)"),
},
function_args = {
InlineNode(
"(formal_parameters (identifier) @definition.function_argument)"
),
},
local_var_values = {
InlineNode("(variable_declarator value: (_) @tmp_capture)"),
},
local_declarations = {
InlineNode("(lexical_declaration) @definition.local_declarator"),
},
debug_paths = {
function_declaration = FieldNode("name"),
method_definition = FieldNode("name"),
class_declaration = FieldNode("name"),
arrow_function = function(node)
return FieldNode("name")(node:parent(), "(anon)")
end,
if_statement = StringNode("if"),
for_statement = StringNode("for"),
for_in_statement = StringNode("for_in"),
while_statement = StringNode("while"),
do_statement = StringNode("do"),
},
indent_scopes = {
program = true,
function_declaration = true,
method_definition = true,
arrow_function = true,
class_declaration = true,
if_statement = true,
for_statement = true,
for_in_statement = true,
while_statement = true,
do_statement = true,
},
statements = {
InlineNode("(expression_statement) @tmp_capture"),
InlineNode("(return_statement) @tmp_capture"),
InlineNode("(if_statement) @tmp_capture"),
InlineNode("(for_statement) @tmp_capture"),
InlineNode("(for_in_statement) @tmp_capture"),
InlineNode("(do_statement) @tmp_capture"),
InlineNode("(while_statement) @tmp_capture"),
InlineNode("(lexical_declaration) @tmp_capture"),
InlineNode("(variable_declaration) @tmp_capture"),
},
function_body = {
InlineNode("(statement_block (_) @tmp_capture)"),
},
}, bufnr)
end
return JavaScript
|
------------------------------------------------------------------
--
-- Author: Alexey Melnichuk <[email protected]>
--
-- Copyright (C) 2015 Alexey Melnichuk <[email protected]>
--
-- Licensed according to the included 'LICENSE' document
--
-- This file is part of lua-lluv-websocket library.
--
------------------------------------------------------------------
local uv = require 'lluv'
local ut = require 'lluv.utils'
local websocket = require 'lluv.websocket'
local ocall = function (f, ...) if f then return f(...) end end
local TEXT, BINARY = websocket.TEXT, websocket.BINARY
local Client = ut.class() do
local cleanup = function(self)
if self._sock then self._sock:close() end
self._sock = nil
end
local on_close = function(self, was_clean, code, reason)
cleanup(self)
ocall(self._on_close, self, was_clean, code, reason or '')
end
local on_error = function(self, err, dont_cleanup)
if not dont_cleanup then cleanup(self) end
ocall(self._on_error, self, err)
end
local on_open = function(self)
self._state = 'OPEN'
ocall(self._on_open, self)
end
local handle_socket_err = function(self, err)
self._sock:close(function(self, clean, code, reason)
on_error(self, err)
end)
end
function Client:__init(ws)
self._ws = ws or {}
self._on_send_done = function(sock, err)
if err then handle_socket_err(self, err) end
end
return self
end
function Client:connect(url, proto)
if self._sock then return end
self._sock = websocket.new{ssl = self._ws.ssl, utf8 = self._ws.utf8,
extensions = self._ws.extensions, auto_ping_response = self._ws.auto_ping_response,
}
self._sock:connect(url, proto, function(sock, err)
if err then return on_error(self, err) end
on_open(self)
sock:start_read(function(sock, err, message, opcode)
if err then
return self._sock:close(function(sock, clean, code, reason)
on_close(self, clean, code, reason)
end)
end
if opcode == TEXT or opcode == BINARY then
return ocall(self._on_message, self, message, opcode)
end
end)
end)
return self
end
function Client:on_close(handler)
self._on_close = handler
end
function Client:on_error(handler)
self._on_error = handler
end
function Client:on_open(handler)
self._on_open = handler
end
function Client:on_message(handler)
self._on_message = handler
end
function Client:send(message, opcode)
self._sock:write(message, opcode, self._on_send_done)
end
function Client:close(code, reason, timeout)
self._sock:close(code, reason, function(sock, clean, code, reason)
on_close(self, clean, code, reason)
end)
return self
end
end
local ok, sync = pcall(require, 'websocket.client_lluv_sync')
if not ok then sync = nil end
return setmetatable({sync = sync},{__call = function(_, ...)
return Client.new(...)
end})
|
------------------------------------------
-------- Language Server Protocol --------
------------------------------------------
local lsp = require ('lspconfig')
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.snippetSupport = true
-------- C/C++ --------
lsp.clangd.setup{
capabilities = capabilities
}
-------- Python --------
lsp.pyright.setup{
capabilities = capabilities
}
-------- Lua --------
local sumneko_root_path = vim.fn.stdpath('cache')..'/lspconfig/sumneko_lua/lua-language-server'
local sumneko_binary = "lua-language-server"
lsp.sumneko_lua.setup{
capabilities = capabilities,
cmd = {sumneko_binary, "-E", sumneko_root_path .. "/main.lua"},
settings = {
Lua = {
runtime = {
version = 'LuaJIT',
-- Setup your lua path
path = vim.split(package.path, ';'),
},
diagnostics = {
globals = {'vim'},
},
workspace = {
library = {
[vim.fn.expand('$VIMRUNTIME/lua')] = true,
[vim.fn.expand('$VIMRUNTIME/lua/vim/lsp')] = true,
},
},
},
},
}
-------- Rust --------
lsp.rust_analyzer.setup{
capabilities = capabilities
}
-------- Haskell --------
lsp.hls.setup{
capabilities = capabilities
}
-------- Vue --------
lsp.vuels.setup{
capabilities = capabilities
}
-------- Typescript/Javascript --------
lsp.tsserver.setup{
capabilities = capabilities
}
-------- HTML/CSS --------
lsp.html.setup{
capabilities = capabilities
}
lsp.cssls.setup{
capabilities = capabilities
}
-------- JSON --------
lsp.jsonls.setup{
capabilities = capabilities
}
-------- Nix --------
lsp.rnix.setup{
capabilities = capabilities
}
-------- Bash --------
lsp.bashls.setup{
capabilities = capabilities
}
-------- Docker --------
lsp.dockerls.setup{
capabilities = capabilities
}
-------- YAML --------
lsp.yamlls.setup{
capabilities = capabilities
}
|
-----------------------------------
-- Area: Mhaura
-- NPC: Numi Adaligo
-- Involved In Quest: RYCHARDE_THE_CHEF
-----------------------------------
require("scripts/globals/settings")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local rovOptionEnable = 0
if player:getCurrentMission(ROV) == tpz.mission.id.rov.EMISSARY_FROM_THE_SEAS and player:getCharVar("RhapsodiesStatus") == 2 then
rovOptionEnable = 1
end
player:startEvent(50, 0, 0, 0, 0, 0, 0, 0, rovOptionEnable)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
local RychardetheChef = player:getQuestStatus(OTHER_AREAS_LOG, tpz.quest.id.otherAreas.RYCHARDE_THE_CHEF)
local QuestStatus=player:getCharVar("QuestRychardetheChef_var")
if ((option == 2) and (RychardetheChef == QUEST_AVAILABLE) and (tonumber(QuestStatus) == 0)) then
player:setCharVar("QuestRychardetheChef_var", 1); -- first stage of rycharde the chef quest
elseif csid == 50 and option == 1 then
player:completeMission(ROV, tpz.mission.id.rov.EMISSARY_FROM_THE_SEAS)
player:addMission(ROV, tpz.mission.id.rov.SET_FREE)
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.