content
stringlengths 5
1.05M
|
---|
local socket = require "socket"
local shape = require "shape"
local udp
local isDown = love.keyboard.isDown
local setColor = love.graphics.setColor
function love.load()
udp = socket.udp()
udp:settimeout(0)
udp:setpeername(ADDRESS, PORT)
love.graphics.setBackgroundColor(0,0,0)
load_shape_coords()
end
function love.keypressed(key)
check_enabled(key, "down")
end
function love.keyreleased(key)
check_enabled(key, "up")
end
function check_enabled(key, action)
if ENABLED[key] then
udp:send(key .. " " .. action)
end
end
function load_shape_coords()
local x_off,y_off = 20,20
local pad_radius = 100
local pad_width = pad_radius*2
local body_width = 200
local body_height = 60
local but_radius = 20
local but_off = 5
local but_width = but_radius*2
local lpad = shape.Circle:new(x_off, y_off, pad_width)
local rpad = shape.Circle:new(pad_radius*2+body_width+x_off, y_off, pad_width)
local body = shape.Rectangle:new(pad_radius*2+x_off, pad_radius+y_off-body_height/2, body_width, body_height)
local up = shape.Triangle:new(pad_radius-but_radius, pad_radius-but_width-but_radius, but_width, but_width, 'u')
local down = shape.Triangle:new(pad_radius-but_radius, pad_radius+but_radius, but_width, but_width, 'd')
local left = shape.Triangle:new(pad_radius-but_width-but_radius, pad_radius-but_radius, but_width, but_width, 'l')
local right = shape.Triangle:new(pad_radius+but_radius, pad_radius-but_radius, but_width, but_width, 'r')
rpad:set_child(up, down, left, right)
local x = shape.Circle:new(pad_radius+but_radius, pad_radius-but_radius, but_width)
local a = shape.Circle:new(pad_radius-but_width-but_radius, pad_radius-but_radius, but_width)
local s = shape.Circle:new(pad_radius-but_radius, pad_radius-but_radius*3, but_width)
local z = shape.Circle:new(pad_radius-but_radius, pad_radius+but_radius, but_width)
lpad:set_child(x, z, s, a)
local start = shape.Rectangle:new(body_width/2-but_width-but_off-15, body_height/2-but_radius, but_width+15, but_width-10)
local slct = shape.Rectangle:new(body_width/2+but_off, body_height/2-but_radius, but_width+15, but_width-10)
body:set_child(start, slct)
love.draw = function()
-- draw controller
setColor(255,255,255)
lpad:draw()
rpad:draw()
body:draw()
setColor(0,0,0)
-- draw arrows
draw('up', up)
draw('down', down)
draw('left', left)
draw('right', right)
-- a and b buttons
draw('x', x)
x:with_offset(tprint"a")
draw('z', z)
z:with_offset(tprint"b")
draw('s', s)
s:with_offset(tprint"x")
draw('a', a)
a:with_offset(tprint"y")
draw('return', start)
start:with_offset(tprint("start", 1))
draw('rshift', slct)
slct:with_offset(tprint("select", 1))
end
end
function tprint(text, scale)
scale = scale or 2
return function(x, y)
setColor(255,255,255)
love.graphics.print(text, x+15, y+5, 0, scale, scale)
setColor(0,0,0)
end
end
function draw(key, the_shape)
if isDown(key) then
setColor(255,0,0)
the_shape:draw()
setColor(0,0,0)
else the_shape:draw() end
end
|
local lyaml = require "lyaml"
local room = require "room"
local location = require "location"
local mob = require "mob"
local item = require "item"
local area = {
list = {}
}
function area:load()
for i in io.popen("ls data/areas/"):lines() do
print("loading " .. i .. " area file")
local f = io.open("data/areas/" .. i, "r")
local data = lyaml.load(f:read("*all"))
f:close()
self.list[data.id] = data
for j, r in pairs(data.rooms) do
if not r.id then
print("Room without id")
require "pl.pretty".dump(r)
os.exit()
end
if room.list[r.id] then
print("Room id collision: " .. r.id .. ", existing and new room below:")
local prettydump = require "pl.pretty"
prettydump(room.list[r.id])
prettydump(r)
os.exit()
end
room.list[r.id] = r
item.inv[r.id] = {}
location.rooms[r.id] = {}
end
for j, r in pairs(data.mobs) do
mob.list[j] = r
item.inv[j] = {}
end
for mobid, roomid in pairs(data.mobresets) do
location:addmob(mobid, roomid)
end
for roomid, inv in pairs(data.itemresets) do
for i, it in pairs(inv) do
it.id = uuid()
table.insert(item.inv[roomid], it)
end
end
end
end
function area:save(a)
local data = lyaml.dump({a})
local f = io.open("data/areas/" .. a.id .. ".yaml", "w+")
f:write(data)
f:close()
end
function area:roomswap(roomid, areafromid, areatoid)
self.list[areatoid].rooms[roomid] = self.list[areafromid].rooms[roomid]
self.list[areafromid].rooms[roomid] = nil
room.list[roomid].area = areatoid
end
function area:new(id)
local newarea = {
id = id,
name = "",
filename = "",
credits = "",
rooms = {},
mobs = {},
mobresets = {},
itemresets = {}
}
self.list[id] = newarea
end
function area:addroom(room)
self.list[room.area].rooms[room.id] = room
end
function area:addmob(mob)
self.list[room.list[location.mobs[mob.id]].area].mobs[mob.id] = mob
end
function area:addmobreset(mobid, roomid)
self.list[room.list[roomid].area].mobresets[mobid] = roomid
end
function area:additemreset(item, roomid)
local a = self.list[room.list[roomid].area]
if not a.itemresets[roomid] then a.itemresets[roomid] = {} end
table.insert(a.itemresets[roomid], item)
end
return area
|
----------------------------------------------------------------------------------------------------
--
-- 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 DynamicScrollBox =
{
Properties =
{
DynamicScrollBox = {default = EntityId()},
AddColorsButton = {default = EntityId()},
ColorImage = {default = EntityId()},
ColorIndexText = {default = EntityId()},
},
}
function DynamicScrollBox:OnActivate()
self.buttonHandler = UiButtonNotificationBus.Connect(self, self.Properties.AddColorsButton)
self.dynamicSBoxDataHandler = UiDynamicScrollBoxDataBus.Connect(self, self.Properties.DynamicScrollBox)
self.dynamicSBoxElementHandler = UiDynamicScrollBoxElementNotificationBus.Connect(self, self.Properties.DynamicScrollBox)
self.tickBusHandler = TickBus.Connect(self);
end
function DynamicScrollBox:OnTick(deltaTime, timePoint)
self.tickBusHandler:Disconnect()
local canvas = UiElementBus.Event.GetCanvas(self.entityId)
self.canvasNotificationBusHandler = UiCanvasNotificationBus.Connect(self, canvas)
self:InitContent("StaticData/LyShineExamples/uiTestPaidColors.json")
end
function DynamicScrollBox:OnDeactivate()
self.buttonHandler:Disconnect()
self.canvasNotificationBusHandler:Disconnect()
self.dynamicSBoxDataHandler:Disconnect()
self.dynamicSBoxElementHandler:Disconnect()
end
function DynamicScrollBox:GetNumElements()
local numColors = UiDynamicContentDatabaseBus.Broadcast.GetNumColors(eUiDynamicContentDBColorType_Paid)
return numColors
end
function DynamicScrollBox:OnElementBecomingVisible(entityId, index)
-- Get the image of the child and set the color
local image = UiElementBus.Event.FindChildByName(entityId, "Icon")
local color = UiDynamicContentDatabaseBus.Broadcast.GetColor(eUiDynamicContentDBColorType_Paid, index)
UiImageBus.Event.SetColor(image, color)
-- Get the name text of the child and set the name
local nameText = UiElementBus.Event.FindChildByName(entityId, "Name")
local name = UiDynamicContentDatabaseBus.Broadcast.GetColorName(eUiDynamicContentDBColorType_Paid, index)
UiTextBus.Event.SetText(nameText, name)
-- Get the price text of the child and set the price
local priceText = UiElementBus.Event.FindChildByName(entityId, "Price")
local price = UiDynamicContentDatabaseBus.Broadcast.GetColorPrice(eUiDynamicContentDBColorType_Paid, index)
UiTextBus.Event.SetText(priceText, price)
end
function DynamicScrollBox:OnAction(entityId, actionName)
if actionName == "IconClicked" then
-- Set selected color
index = UiDynamicScrollBoxBus.Event.GetLocationIndexOfChild(self.Properties.DynamicScrollBox, entityId)
local color = UiDynamicContentDatabaseBus.Broadcast.GetColor(eUiDynamicContentDBColorType_Paid, index)
UiImageBus.Event.SetColor(self.Properties.ColorImage, color)
-- Set selected index
UiTextBus.Event.SetText(self.Properties.ColorIndexText, index)
end
end
function DynamicScrollBox:OnButtonClick()
if (UiButtonNotificationBus.GetCurrentBusId() == self.Properties.AddColorsButton) then
self:InitContent("StaticData/LyShineExamples/uiTestMorePaidColors.json")
UiInteractableBus.Event.SetIsHandlingEvents(self.Properties.AddColorsButton, false)
end
end
function DynamicScrollBox:InitContent(jsonFilepath)
-- Refresh the dynamic content database with the specified json file
UiDynamicContentDatabaseBus.Broadcast.Refresh(eUiDynamicContentDBColorType_Paid, jsonFilepath)
-- Refresh the dynamic scrollbox. This will trigger events from the
-- UiDynamicScrollBoxDataBus and the UiDynamicScrollBoxElementNotificationBus
UiDynamicScrollBoxBus.Event.RefreshContent(self.Properties.DynamicScrollBox)
-- Force the hover interactable to be the scroll box.
-- The scroll box is set to auto-activate, but it could still have the hover
-- since it starts out having no children. Now that it may contain children,
-- force it to be the hover in order to auto-activate it and pass the hover to its child
local canvas = UiElementBus.Event.GetCanvas(self.entityId)
UiCanvasBus.Event.ForceHoverInteractable(canvas, self.Properties.DynamicScrollBox)
end
return DynamicScrollBox |
local assets=
{
Asset("ANIM", "anim/sapling.zip"),
Asset("SOUND", "sound/common.fsb"),
}
local prefabs =
{
"twigs",
"dug_sapling",
}
local function ontransplantfn(inst)
inst.components.pickable:MakeEmpty()
end
local function dig_up(inst, chopper)
if inst.components.pickable and inst.components.pickable:CanBePicked() then
inst.components.lootdropper:SpawnLootPrefab("twigs")
end
inst:Remove()
local bush = inst.components.lootdropper:SpawnLootPrefab("dug_sapling")
end
local function onpickedfn(inst)
inst.AnimState:PlayAnimation("rustle")
inst.AnimState:PushAnimation("picked", false)
end
local function onregenfn(inst)
inst.AnimState:PlayAnimation("grow")
inst.AnimState:PushAnimation("sway", true)
end
local function makeemptyfn(inst)
inst.AnimState:PlayAnimation("empty")
end
local function fn(Sim)
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
local minimap = inst.entity:AddMiniMapEntity()
inst.AnimState:SetRayTestOnBB(true);
anim:SetBank("sapling")
anim:SetBuild("sapling")
anim:PlayAnimation("sway",true)
anim:SetTime(math.random()*2)
minimap:SetIcon( "sapling.png" )
inst:AddComponent("pickable")
inst.components.pickable.picksound = "dontstarve/wilson/harvest_sticks"
inst.components.pickable:SetUp("twigs", TUNING.SAPLING_REGROW_TIME)
inst.components.pickable.onregenfn = onregenfn
inst.components.pickable.onpickedfn = onpickedfn
inst.components.pickable.makeemptyfn = makeemptyfn
inst.components.pickable.ontransplantfn = ontransplantfn
inst:AddComponent("inspectable")
inst:AddComponent("lootdropper")
inst:AddComponent("workable")
inst.components.workable:SetWorkAction(ACTIONS.DIG)
inst.components.workable:SetOnFinishCallback(dig_up)
inst.components.workable:SetWorkLeft(1)
MakeMediumBurnable(inst)
MakeSmallPropagator(inst)
MakeNoGrowInWinter(inst)
---------------------
return inst
end
return Prefab( "forest/objects/sapling", fn, assets, prefabs)
|
local slope_cbox = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.25, 0.5},
{-0.5, -0.25, -0.25, 0.5, 0, 0.5},
{-0.5, 0, 0, 0.5, 0.25, 0.5},
{-0.5, 0.25, 0.25, 0.5, 0.5, 0.5}
}
}
local slope_cbox_long = {
type = "fixed",
fixed = {
{-0.5, -0.5, -1.5, 0.5, -0.375, 0.5}, -- NodeBox1
{-0.5, -0.375, -1.25, 0.5, -0.25, 0.5}, -- NodeBox2
{-0.5, -0.25, -1, 0.5, -0.125, 0.5}, -- NodeBox3
{-0.5, -0.125, -0.75, 0.5, 0, 0.5}, -- NodeBox4
{-0.5, 0, -0.5, 0.5, 0.125, 0.5}, -- NodeBox5
{-0.5, 0.125, -0.25, 0.5, 0.25, 0.5}, -- NodeBox6
{-0.5, 0.25, 0, 0.5, 0.375, 0.5}, -- NodeBox7
{-0.5, 0.375, 0.25, 0.5, 0.5, 0.5}, -- NodeBox8
}
}
local icorner_cbox = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.25, 0.5}, -- NodeBox5
{-0.5, -0.5, -0.25, 0.5, 0, 0.5}, -- NodeBox6
{-0.5, -0.5, -0.5, 0.25, 0, 0.5}, -- NodeBox7
{-0.5, 0, -0.5, 0, 0.25, 0.5}, -- NodeBox8
{-0.5, 0, 0, 0.5, 0.25, 0.5}, -- NodeBox9
{-0.5, 0.25, 0.25, 0.5, 0.5, 0.5}, -- NodeBox10
{-0.5, 0.25, -0.5, -0.25, 0.5, 0.5}, -- NodeBox11
}
}
local ocorner_cbox = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.25, 0.5},
{-0.5, -0.25, -0.25, 0.25, 0, 0.5},
{-0.5, 0, 0, 0, 0.25, 0.5},
{-0.5, 0.25, 0.25, -0.25, 0.5, 0.5}
}
}
local icorner_cbox_long = {
type = "fixed",
fixed = {
{-0.5, -0.5, -1.5, -0.25, 0.5, 0.5},
{-0.5, -0.5, 0.25, 1.5, 0.5, 0.5},
{-0.5, -0.5, 0, 1.5, 0.375, 0.5},
{-0.5, -0.5, -1.5, 0, 0.375, 0.5},
{-0.5, -0.5, -1.5, 0.25, 0.25, 0.5},
{-0.5, -0.5, -1.5, 0.5, 0.125, 0.5},
{-0.5, -0.5, -1.5, 0.75, 0, 0.5},
{-0.5, -0.5, -1.5, 1, -0.125, 0.5},
{-0.5, -0.5, -1.5, 1.25, -0.25, 0.5},
{-0.5, -0.5, -1.5, 1.5, -0.375, 0.5},
{-0.5, -0.5, -0.25, 1.5, 0.25, 0.5},
{-0.5, -0.5, -0.5, 1.5, 0.125, 0.5},
{-0.5, -0.5, -0.75, 1.5, 0, 0.5},
{-0.5, -0.5, -1, 1.5, -0.125, 0.5},
{-0.5, -0.5, -1.25, 1.5, -0.25, 0.5},
}
}
local ocorner_cbox_long = {
type = "fixed",
fixed = {
{-0.5, -0.5, 0.25, -0.25, 0.5, 0.5},
{-0.5, -0.5, 0, 0, 0.375, 0.5},
{-0.5, -0.5, -0.25, 0.25, 0.25, 0.5},
{-0.5, -0.5, -0.5, 0.5, 0.125, 0.5},
{-0.5, -0.5, -0.75, 0.75, 0, 0.5},
{-0.5, -0.5, -1, 1, -0.125, 0.5},
{-0.5, -0.5, -1.25, 1.25, -0.25, 0.5},
{-0.5, -0.5, -1.5, 1.5, -0.375, 0.5},
}
}
local straw_slope = { --desc, color, item
{"Straw", "straw", "farming:straw"},
{"Dark Straw", "straw_dark", "myroofs:straw_dark"},
{"Reet", "reet", "myroofs:reet"},
{"Copper", "copper", "myroofs:copper_roofing"},
{"Green Copper","green_copper","myroofs:green_copper_roofing"},
}
for i in ipairs (straw_slope) do
local desc = straw_slope[i][1]
local color = straw_slope[i][2]
local item = straw_slope[i][3]
--Slope
minetest.register_node("myroofs:"..color.."_roof", {
description = desc.." Roof",
drawtype = "mesh",
mesh = "twelve-twelve.obj",
tiles = {"myroofs_"..color..".png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {choppy=2, oddly_breakable_by_hand=2, flammable=3},
sounds = default.node_sound_wood_defaults(),
-- on_place = minetest.rotate_node,
collision_box = slope_cbox,
selection_box = slope_cbox
})
--Outside Corner
minetest.register_node("myroofs:"..color.."_roof_ocorner", {
description = desc.." Roof Outside Corner",
drawtype = "mesh",
mesh = "twelve-twelve-oc.obj",
tiles = {"myroofs_"..color..".png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {choppy=2, oddly_breakable_by_hand=2, flammable=3},
sounds = default.node_sound_wood_defaults(),
-- on_place = minetest.rotate_node,
collision_box = ocorner_cbox,
selection_box = ocorner_cbox
})
--Inner Corner
minetest.register_node("myroofs:"..color.."_roof_icorner", {
description = desc.." Roof Inside Corner",
drawtype = "mesh",
mesh = "twelve-twelve-ic.obj",
tiles = {"myroofs_"..color..".png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {choppy=2, oddly_breakable_by_hand=2, flammable=3},
sounds = default.node_sound_wood_defaults(),
-- on_place = minetest.rotate_node,
collision_box = icorner_cbox,
selection_box = icorner_cbox
})
--Long Slope
minetest.register_node("myroofs:"..color.."_roof_long", {
description = desc.." Roof Long",
drawtype = "mesh",
mesh = "six-twelve_slope.obj",
tiles = {"myroofs_"..color..".png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {choppy=2, oddly_breakable_by_hand=2, flammable=3},
sounds = default.node_sound_wood_defaults(),
-- on_place = minetest.rotate_node,
collision_box = slope_cbox_long,
selection_box = slope_cbox_long
})
--Long Inner Corner
minetest.register_node("myroofs:"..color.."_roof_long_icorner", {
description = desc.." Roof Long Inside Corner",
drawtype = "mesh",
mesh = "six-twelve_slope-ic.obj",
tiles = {"myroofs_"..color..".png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {choppy=2, oddly_breakable_by_hand=2, flammable=3},
sounds = default.node_sound_wood_defaults(),
-- on_place = minetest.rotate_node,
collision_box = icorner_cbox_long,
selection_box = icorner_cbox_long
})
--Long Outside Corner
minetest.register_node("myroofs:"..color.."_roof_long_ocorner", {
description = desc.." Roof Long Outside Corner",
drawtype = "mesh",
mesh = "six-twelve_slope-oc.obj",
tiles = {"myroofs_"..color..".png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {choppy=2, oddly_breakable_by_hand=2, flammable=3},
sounds = default.node_sound_wood_defaults(),
-- on_place = minetest.rotate_node,
collision_box = ocorner_cbox_long,
selection_box = ocorner_cbox_long
})
------------------------------------------------------------------------------------
--Crafts
------------------------------------------------------------------------------------
--Slope
minetest.register_craft({
output = "myroofs:"..color.."_roof 6",
recipe = {
{"","",""},
{"","",item},
{"",item,item},
}
})
--Outside Corner
minetest.register_craft({
output = "myroofs:"..color.."_roof_ocorner 5",
recipe = {
{"", "", ""},
{"", item, ""},
{item, "", item},
}
})
--Inside Corner
minetest.register_craft({
output = "myroofs:"..color.."_roof_icorner 8",
recipe = {
{"","",""},
{item,"",""},
{item,item,""},
}
})
--Long Slope
minetest.register_craft({
output = "myroofs:"..color.."_roof_long 1",
recipe = {
{"", "",""},
{"", item,item},
{item, item,item},
}
})
--Long Inside Corner
minetest.register_craft({
output = "myroofs:"..color.."_roof_long_icorner 1",
recipe = {
{"", "",item},
{"", "",item},
{item, item,item},
}
})
--Long Outside Corner
minetest.register_craft({
output = "myroofs:"..color.."_roof_long_ocorner 1",
recipe = {
{"", item,""},
{"", item,""},
{item, item,item},
}
})
end
|
module (..., package.seeall)
function main(args)
assert(type(args.pageurl) == 'string', '[Error] pageurl missing in plugin paginator.')
assert(type(args.callback) == 'string' and type(bamboo.getPluginCallbackByName(args.callback)) == 'function', '[Error] callback missing in plugin paginator.')
local params = req.PARAMS
local thepage = tonumber(params.thepage) or 1
if thepage < 1 then thepage = 1 end
local totalpages = tonumber(params.totalpages)
if totalpages and thepage > totalpages then thepage = totalpages end
local npp = tonumber(params.npp) or tonumber(args.npp) or 5
local starti = (thepage-1) * npp + 1
local endi = thepage * npp
local pageurl = args.pageurl
local callback = args.callback
-- the callback should return 2 values: html fragment and totalnum
local htmlcontent, totalnum = bamboo.getPluginCallbackByName(callback)(web, req, starti, endi)
if totalnum then
totalpages = math.ceil(totalnum/npp)
if thepage > totalpages then thepage = totalpages end
end
local prevpage = thepage - 1
if prevpage < 1 then prevpage = 1 end
local nextpage = thepage + 1
if nextpage > totalpages then nextpage = totalpages end
return View('../plugins/paginator/paginator.html') {
htmlcontent = htmlcontent,
totalpages = totalpages, npp = npp, pageurl = pageurl,
thepage = thepage, prevpage = prevpage, nextpage = nextpage
}
end
|
bh_canyon_corsair_captain = Creature:new {
objectName = "@mob/creature_names:canyon_corsair_captain",
randomNameType = NAME_GENERIC,
randomNameTag = true,
socialGroup = "canyon_corsair",
faction = "canyon_corsair",
level = 50,
chanceHit = 0.5,
damageMin = 395,
damageMax = 500,
baseXp = 4916,
baseHAM = 10000,
baseHAMmax = 12000,
armor = 1,
resists = {20,40,5,5,-1,5,5,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
templates = {
"object/mobile/dressed_corsair_captain_hum_m.iff",
"object/mobile/dressed_corsair_captain_nikto_m.iff",
"object/mobile/dressed_corsair_captain_wee_m.iff",
"object/mobile/dressed_corsair_captain_zab_m.iff"
},
lootGroups = {
{
groups = {
{group = "tierone", chance = 2500000},
{group = "tiertwo", chance = 500000},
{group = "loot_kit_parts", chance = 500000},
{group = "color_crystals", chance = 500000},
{group = "power_crystals", chance = 1000000},
{group = "wearables_all", chance = 1000000},
{group = "weapons_all", chance = 1000000},
{group = "armor_all", chance = 1000000},
{group = "clothing_attachments", chance = 1000000},
{group = "armor_attachments", chance = 1000000}
},
lootChance = 4000000
},
{
groups = {
{group = "tierone", chance = 2500000},
{group = "tiertwo", chance = 500000},
{group = "loot_kit_parts", chance = 500000},
{group = "color_crystals", chance = 500000},
{group = "power_crystals", chance = 1000000},
{group = "wearables_all", chance = 1000000},
{group = "weapons_all", chance = 1000000},
{group = "armor_all", chance = 1000000},
{group = "clothing_attachments", chance = 1000000},
{group = "armor_attachments", chance = 1000000}
},
lootChance = 4000000
}
},
weapons = {"canyon_corsair_weapons"},
conversationTemplate = "",
reactionStf = "@npc_reaction/slang",
attacks = merge(swordsmanmaster,carbineermaster,brawlermaster)
}
CreatureTemplates:addCreatureTemplate(bh_canyon_corsair_captain, "bh_canyon_corsair_captain")
|
local DIR = "public/daobiao/"
local M = {}
M.maps = loadfile(DIR .. "Scenes.lua")()
return M
|
require "test-setup"
require "lunit"
local Cairo = require "oocairo"
module("test.matrix", lunit.testcase, package.seeall)
function test_create ()
local m = Cairo.matrix_create()
check_matrix_elems(m)
assert_equal("cairo matrix object", m._NAME)
assert_equal(1, m[1]); assert_equal(0, m[3]); assert_equal(0, m[5])
assert_equal(0, m[2]); assert_equal(1, m[4]); assert_equal(0, m[6])
end
function test_transform ()
local m = Cairo.matrix_create()
m:translate(3, 4)
check_matrix_elems(m)
assert_equal(1, m[1]); assert_equal(0, m[3]); assert_equal(3, m[5])
assert_equal(0, m[2]); assert_equal(1, m[4]); assert_equal(4, m[6])
m = Cairo.matrix_create()
m:scale(2, 3)
check_matrix_elems(m)
assert_equal(2, m[1]); assert_equal(0, m[3]); assert_equal(0, m[5])
assert_equal(0, m[2]); assert_equal(3, m[4]); assert_equal(0, m[6])
m = Cairo.matrix_create()
m:rotate(2)
check_matrix_elems(m)
assert_not_equal(1, m[1]); assert_not_equal(0, m[3]); assert_equal(0, m[5])
assert_not_equal(0, m[2]); assert_not_equal(1, m[4]); assert_equal(0, m[6])
end
function test_invert ()
local m = Cairo.matrix_create()
m:translate(3, 4)
m:scale(2, 3)
m:rotate(2)
m:invert()
check_matrix_elems(m)
end
function test_multiply ()
local m1, m2 = Cairo.matrix_create(), Cairo.matrix_create()
m1:scale(2, 3)
m2:translate(4, 5)
m1:multiply(m2)
check_matrix_elems(m1)
assert_equal(2, m1[1]); assert_equal(0, m1[3]); assert_equal(4, m1[5])
assert_equal(0, m1[2]); assert_equal(3, m1[4]); assert_equal(5, m1[6])
end
function test_apply_transformation ()
local m = Cairo.matrix_create()
m:scale(2, 3)
m:translate(4, 5)
local x, y = m:transform_point(10, 100)
assert_equal(28, x)
assert_equal(315, y)
x, y = m:transform_distance(10, 100)
assert_equal(20, x)
assert_equal(300, y)
end
-- vi:ts=4 sw=4 expandtab
|
--[[
##############################################################################
S V U I By: Failcoder
##############################################################################
--]]
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
local ipairs = _G.ipairs;
local pairs = _G.pairs;
--[[ ADDON ]]--
local SV = _G['SVUI'];
local L = SV.L;
local MOD = SV.Skins;
local Schema = MOD.Schema;
--[[
##########################################################
ENCOUNTERJOURNAL MODR
##########################################################
]]--
local PVP_LOST = [[Interface\WorldMap\Skull_64Red]]
local function Tab_OnEnter(this)
this.backdrop:SetPanelColor("highlight")
this.backdrop:SetBackdropBorderColor(0.1, 0.8, 0.8)
end
local function Tab_OnLeave(this)
this.backdrop:SetPanelColor("dark")
this.backdrop:SetBackdropBorderColor(0,0,0,1)
end
local function ChangeTabHelper(this, xOffset, yOffset)
this:SetNormalTexture(SV.NoTexture)
this:SetPushedTexture(SV.NoTexture)
this:SetDisabledTexture(SV.NoTexture)
this:SetHighlightTexture(SV.NoTexture)
this.backdrop = CreateFrame("Frame", nil, this)
this.backdrop:InsetPoints(this)
this.backdrop:SetFrameLevel(0)
this.backdrop:SetStyle("Frame")
this.backdrop:SetPanelColor("dark")
this:HookScript("OnEnter",Tab_OnEnter)
this:HookScript("OnLeave",Tab_OnLeave)
local initialAnchor, anchorParent, relativeAnchor, xPosition, yPosition = this:GetPoint()
this:ClearAllPoints()
this:SetPoint(initialAnchor, anchorParent, relativeAnchor, xOffset or 0, yOffset or 0)
end
local function Outline(frame, noHighlight)
if(frame.Outlined) then return; end
local offset = noHighlight and 30 or 5
local mod = noHighlight and 50 or 5
local panel = CreateFrame('Frame', nil, frame)
panel:SetPoint('TOPLEFT', frame, 'TOPLEFT', 1, -1)
panel:SetPoint('BOTTOMRIGHT', frame, 'BOTTOMRIGHT', -1, 1)
--[[ UNDERLAY BORDER ]]--
local borderLeft = panel:CreateTexture(nil, "BORDER")
borderLeft:SetColorTexture(0, 0, 0)
borderLeft:SetPoint("TOPLEFT")
borderLeft:SetPoint("BOTTOMLEFT")
borderLeft:SetWidth(offset)
local borderRight = panel:CreateTexture(nil, "BORDER")
borderRight:SetColorTexture(0, 0, 0)
borderRight:SetPoint("TOPRIGHT")
borderRight:SetPoint("BOTTOMRIGHT")
borderRight:SetWidth(offset)
local borderTop = panel:CreateTexture(nil, "BORDER")
borderTop:SetColorTexture(0, 0, 0)
borderTop:SetPoint("TOPLEFT")
borderTop:SetPoint("TOPRIGHT")
borderTop:SetHeight(mod)
local borderBottom = panel:CreateTexture(nil, "BORDER")
borderBottom:SetColorTexture(0, 0, 0)
borderBottom:SetPoint("BOTTOMLEFT")
borderBottom:SetPoint("BOTTOMRIGHT")
borderBottom:SetHeight(mod)
if(not noHighlight) then
local highlight = frame:CreateTexture(nil, "HIGHLIGHT")
highlight:SetColorTexture(0, 1, 1, 0.35)
highlight:SetAllPoints(panel)
end
frame.Outlined = true
end
local function _hook_EncounterJournal_SetBullets(object, ...)
local parent = object:GetParent();
if (parent.Bullets and #parent.Bullets > 0) then
for i = 1, #parent.Bullets do
local bullet = parent.Bullets[i];
bullet.Text:SetTextColor(1,1,1)
end
end
end
local function _hook_EncounterJournal_ListInstances()
local frame = EncounterJournal.instanceSelect.scroll.child
local index = 1
local instanceButton = frame["instance"..index];
while instanceButton do
Outline(instanceButton)
index = index + 1;
instanceButton = frame["instance"..index]
end
end
local function _hook_EncounterJournal_ToggleHeaders(self)
if (not self or not self.isOverview) then
local usedHeaders = EncounterJournal.encounter.usedHeaders
for key,used in pairs(usedHeaders) do
if(not used.button.Panel) then
used:RemoveTextures(true)
used.button:RemoveTextures(true)
used.button:SetStyle("Button")
end
used.description:SetTextColor(1, 1, 1)
--used.button.portrait.icon:Hide()
end
else
local overviews = EncounterJournal.encounter.overviewFrame.overviews
for i = 1, #overviews do
local overview = overviews[i];
if(overview) then
if(not overview.Panel) then
overview:RemoveTextures(true)
overview.button:RemoveTextures(true)
overview:SetStyle("Button")
end
if(overview.loreDescription) then
overview.loreDescription:SetTextColor(1, 1, 1)
end
if(overview.description) then
overview.description:SetTextColor(1, 1, 1)
end
end
end
end
end
local function _hook_EncounterJournal_LootUpdate()
local scrollFrame = EncounterJournal.encounter.info.lootScroll;
local offset = HybridScrollFrame_GetOffset(scrollFrame);
local items = scrollFrame.buttons;
local item, index;
local numLoot = EJ_GetNumLoot()
for i = 1,#items do
item = items[i];
index = offset + i;
if index <= numLoot then
item.icon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
SV.API:Set("ItemButton", item)
item.slot:SetTextColor(0.5, 1, 0)
item.armorType:SetTextColor(1, 1, 0)
item.boss:SetTextColor(0.7, 0.08, 0)
end
end
end
local function EncounterJournalStyle()
if SV.db.Skins.blizzard.enable ~= true or SV.db.Skins.blizzard.encounterjournal ~= true then
return
end
EncounterJournal:RemoveTextures(true)
EncounterJournalInstanceSelect:RemoveTextures(true)
EncounterJournalInset:RemoveTextures(true)
EncounterJournalEncounterFrame:RemoveTextures(true)
EncounterJournalEncounterFrameInfo:RemoveTextures(true)
EncounterJournalEncounterFrameInfoDifficulty:RemoveTextures(true)
EncounterJournalEncounterFrameInfoLootScrollFrameFilterToggle:RemoveTextures(true)
ChangeTabHelper(EncounterJournalEncounterFrameInfoOverviewTab, 10)
ChangeTabHelper(EncounterJournalEncounterFrameInfoLootTab, 0, -10)
ChangeTabHelper(EncounterJournalEncounterFrameInfoBossTab, 0, -10)
ChangeTabHelper(EncounterJournalEncounterFrameInfoModelTab, 0, -20)
EncounterJournalEncounterFrameInfoOverviewScrollFrameScrollBar:RemoveTextures()
EncounterJournalEncounterFrameInfoOverviewScrollFrameScrollChildTitle:SetTextColor(1,1,0)
EncounterJournalEncounterFrameInfoOverviewScrollFrameScrollChildLoreDescription:SetTextColor(1,1,1)
EncounterJournalEncounterFrameInfoOverviewScrollFrameScrollChild.overviewDescription.Text:SetTextColor(1,1,1)
EncounterJournalSearchResults:RemoveTextures(true)
SV.API:Set("EditBox", EncounterJournalSearchBox)
EncounterJournal:SetStyle("Frame", "Window")
EncounterJournalInset:SetStyle("!_Frame", "Window2")
EncounterJournalInset:SetPanelColor("darkest")
SV.API:Set("ScrollBar", EncounterJournalInstanceSelectScrollFrame)
SV.API:Set("ScrollBar", EncounterJournalEncounterFrameInfoBossesScrollFrame)
SV.API:Set("ScrollBar", EncounterJournalEncounterFrameInfoOverviewScrollFrame)
SV.API:Set("ScrollBar", EncounterJournalEncounterFrameInfoLootScrollFrame)
SV.API:Set("ScrollBar", EncounterJournalEncounterFrameInfoDetailsScrollFrame)
SV.API:Set("DropDown", EncounterJournalInstanceSelectTierDropDown)
SV.API:Set("CloseButton", EncounterJournalCloseButton)
EncounterJournalEncounterFrameInfoResetButton:SetStyle("Button")
EncounterJournalNavBar:RemoveTextures(true)
EncounterJournalNavBarOverlay:RemoveTextures(true)
EncounterJournalNavBarOverflowButton:RemoveTextures(true)
EncounterJournalNavBarHomeButton:RemoveTextures(true)
EncounterJournalNavBarHomeButton:SetStyle("Button")
EncounterJournalNavBarOverflowButton:SetStyle("Button")
EncounterJournalEncounterFrameInfoDifficulty:SetStyle("Button")
EncounterJournalEncounterFrameInfoDifficulty:SetFrameLevel(EncounterJournalEncounterFrameInfoDifficulty:GetFrameLevel() + 10)
EncounterJournalEncounterFrameInfoLootScrollFrameFilterToggle:SetStyle("Button")
EncounterJournalEncounterFrameInfoLootScrollFrameFilterToggle:SetFrameLevel(EncounterJournalEncounterFrameInfoLootScrollFrameFilterToggle:GetFrameLevel() + 10)
if(EncounterJournalSuggestFrame) then
SV.API:Set("PageButton", EncounterJournalSuggestFrameNextButton)
SV.API:Set("PageButton", EncounterJournalSuggestFramePrevButton, false, true)
if(EncounterJournalSuggestFrame.Suggestion1 and EncounterJournalSuggestFrame.Suggestion1.button) then
EncounterJournalSuggestFrame.Suggestion1.button:RemoveTextures(true)
EncounterJournalSuggestFrame.Suggestion1.button:SetStyle("Button")
end
if(EncounterJournalSuggestFrame.Suggestion2 and EncounterJournalSuggestFrame.Suggestion2.centerDisplay and EncounterJournalSuggestFrame.Suggestion2.centerDisplay.button) then
EncounterJournalSuggestFrame.Suggestion2.centerDisplay.button:RemoveTextures(true)
EncounterJournalSuggestFrame.Suggestion2.centerDisplay.button:SetStyle("Button")
end
if(EncounterJournalSuggestFrame.Suggestion3 and EncounterJournalSuggestFrame.Suggestion3.centerDisplay and EncounterJournalSuggestFrame.Suggestion3.centerDisplay.button) then
EncounterJournalSuggestFrame.Suggestion3.centerDisplay.button:RemoveTextures(true)
EncounterJournalSuggestFrame.Suggestion3.centerDisplay.button:SetStyle("Button")
end
end
local tabBaseName = "EncounterJournalInstanceSelect";
if(_G[tabBaseName .. "SuggestTab"]) then
_G[tabBaseName .. "SuggestTab"]:RemoveTextures(true)
_G[tabBaseName .. "SuggestTab"]:SetStyle("Button")
end
if(_G[tabBaseName .. "DungeonTab"]) then
_G[tabBaseName .. "DungeonTab"]:RemoveTextures(true)
_G[tabBaseName .. "DungeonTab"]:SetStyle("Button")
end
if(_G[tabBaseName .. "RaidTab"]) then
_G[tabBaseName .. "RaidTab"]:RemoveTextures(true)
_G[tabBaseName .. "RaidTab"]:SetStyle("Button")
end
if(_G[tabBaseName .. "LootJournalTab"]) then
_G[tabBaseName .. "LootJournalTab"]:RemoveTextures(true)
_G[tabBaseName .. "LootJournalTab"]:SetStyle("Button")
end
local bgParent = EncounterJournal.encounter.instance
local loreParent = EncounterJournal.encounter.instance.loreScroll
bgParent.loreBG:SetPoint("TOPLEFT", bgParent, "TOPLEFT", 0, 0)
bgParent.loreBG:SetPoint("BOTTOMRIGHT", bgParent, "BOTTOMRIGHT", 0, 90)
SV.API:Set("Frame", loreParent, "Pattern")
--loreParent:SetPanelColor("dark")
loreParent.child.lore:SetTextColor(1, 1, 1)
EncounterJournal.encounter.infoFrame.description:SetTextColor(1, 1, 1)
loreParent:SetFrameLevel(loreParent:GetFrameLevel() + 10)
local frame = EncounterJournal.instanceSelect.scroll.child
local index = 1
local instanceButton = frame["instance"..index];
while instanceButton do
Outline(instanceButton)
index = index + 1;
instanceButton = frame["instance"..index]
end
local bulletParent = EncounterJournalEncounterFrameInfoOverviewScrollFrameScrollChild;
if (bulletParent.Bullets and #bulletParent.Bullets > 0) then
for i = 1, #bulletParent.Bullets do
local bullet = bulletParent.Bullets[1];
bullet.Text:SetTextColor(1,1,1)
end
end
EncounterJournal.instanceSelect.raidsTab:GetFontString():SetTextColor(1, 1, 1);
SV.API:Set("DropDown", LootJournalViewDropDown)
hooksecurefunc("EncounterJournal_SetBullets", _hook_EncounterJournal_SetBullets)
hooksecurefunc("EncounterJournal_ListInstances", _hook_EncounterJournal_ListInstances)
hooksecurefunc("EncounterJournal_ToggleHeaders", _hook_EncounterJournal_ToggleHeaders)
hooksecurefunc("EncounterJournal_LootUpdate", _hook_EncounterJournal_LootUpdate)
_hook_EncounterJournal_ToggleHeaders()
end
--[[
##########################################################
MOD LOADING
##########################################################
]]--
MOD:SaveBlizzardStyle('Blizzard_EncounterJournal', EncounterJournalStyle)
|
addEvent("onGameMessageSend2", true)
addEventHandler("onGameMessageSend2", root,
function(text, lang)
local URL = "http://translate.google.com/translate_tts?ie=UTF-8&tl=" .. lang .. "&q=" .. text
-- Play the TTS. BASS returns the sound element even if it can not be played.
-- playSound(URL) -- disabled to wait out google ban
end
)
addEvent("flash", true)
addEventHandler("flash", resourceRoot, function()
setWindowFlashing(true,0)
end)
|
--[[
TheNexusAvenger
Stores and replicates player data.
Class is static (should not be created).
--]]
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ReplicatedStorageProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ReplicatedStorage"))
local ServerScriptServiceProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ServerScriptService")):GetContext(script)
local BoolGrid = ReplicatedStorageProject:GetResource("State.BoolGrid")
local AchievementService = ServerScriptServiceProject:GetResource("Service.AchievementService")
local PlayerDataService = ServerScriptServiceProject:GetResource("Service.PlayerDataService")
local InventoryService = ServerScriptServiceProject:GetResource("Service.InventoryService")
local MapDiscoveryService = ReplicatedStorageProject:GetResource("ExternalUtil.NexusInstance.NexusInstance"):Extend()
MapDiscoveryService:SetClassName("MapDiscoveryService")
MapDiscoveryService.DiscoveredCellsBoolGrids = {}
ServerScriptServiceProject:SetContextResource(MapDiscoveryService)
--[[
Initializes the data for a player.
--]]
function MapDiscoveryService:LoadPlayer(Player)
--Set up the grid.
local PlayerData = PlayerDataService:GetPlayerData(Player)
local Inventory = InventoryService:GetInventory(Player)
local PlayerBoolGrid = BoolGrid.new(200,200)
self.DiscoveredCellsBoolGrids[Player] = PlayerBoolGrid
self.DiscoveredCellsBoolGrids[Player]:LoadFromString(PlayerData:GetValue("DiscoveredMapCells"))
--Set up discovering the map.
coroutine.wrap(function()
while Player.Parent do
--Get the center.
local Character = Player.Character
if Character then
local HumanoidRootPart = Character:FindFirstChild("HumanoidRootPart")
if HumanoidRootPart then
local CenterX,CenterY = math.floor((HumanoidRootPart.Position.X/100) + 0.5),math.floor((HumanoidRootPart.Position.Z/100) + 0.5)
local Range = 2 + #Inventory:GetItemSlots("VisionRadiusIncrease")
--Discover the sections and mark if new sections were discovered.
local SectionsWereDiscovered = false
for X = CenterX - Range,CenterX + Range do
for Y = CenterY - Range,CenterY + Range do
if not PlayerBoolGrid:GetValue(X,Y) then
PlayerBoolGrid:SetValue(X,Y,true)
SectionsWereDiscovered = true
--Award the beyond the rocks achievement.
if X < 10 and Y > 183 then
AchievementService:AwardAchievement(Player,"BeyondTheRocks")
end
end
end
end
--Set the value if it changed.
if SectionsWereDiscovered then
PlayerData:SetValue("DiscoveredMapCells",PlayerBoolGrid:Serialize())
PlayerDataService:SavesPlayerData(Player)
end
end
end
wait()
end
end)()
end
--[[
Clears a player.
--]]
function MapDiscoveryService:ClearPlayer(Player)
--Clear the resources.
self.DiscoveredCellsBoolGrids[Player] = nil
end
return MapDiscoveryService |
-------------------------------------------------------------------------------
--terrain generation - dumb fractal noise
function gen_terrain(res, pixel_per_km, seed)
local t_id = love.image.newImageData(res, res, "r32f")
--build random parameters for this seed
local _r = love.math.newRandomGenerator(seed)
local sox = _r:random(-100, 100)
local soy = _r:random(-100, 100)
local oox = _r:random(-1000, 1000) / 31
local ooy = _r:random(-1000, 1000) / 31
local n = function(x, y, scale)
return (
love.math.noise(
x * scale + sox,
y * scale + soy
) * 2 - 1
)
end
local fn = function(x, y, scale, octaves)
x = x + sox
y = y + soy
local s = scale
local t = 0
local c = 0
local octave_falloff = 0.7
local octave_scale = 1.5
local a = 1
for i = 1, octaves do
local o = n(x, y, s)
if i % 2 == 1 then
o = math.abs(o) * 2 - 1
end
t = t + o * a
c = c + a
x = x + oox
y = y + oox
s = s * octave_scale
a = a * octave_falloff
end
return 0.5 + (t / c) * 0.75
end
--perlin mountains
-- t_id:mapPixel(function(x, y)
-- return fn(x, y, 0.001 * res / pixel_per_km, 16)
-- end)
--well
t_id:mapPixel(function(x, y)
local n = fn(x, y, 0.001 * res / pixel_per_km, 16)
local xf = math.smoothstep(x / res)
local yf = math.smoothstep(y / res)
local dx = (xf - 0.5)
local dy = (yf - 0.5)
local d = math.sqrt(dx * dx + dy * dy) * 1.5
return math.lerp(
math.lerp(0.7, 0.8, n),
math.lerp(
math.lerp(0.0, 1.0, n),
math.lerp(0.3, 0.4, n),
math.clamp01(1 - d * 2)
),
math.clamp01(1 - d)
)
end)
return t_id
end
|
--[[
Example on how to relax lattice vectors using the LBFGS
algorithm.
This example can take any geometry and will relax the
cell vectors according to the siesta input options:
- MD.MaxForceTol
- MD.MaxStressTol
- MD.MaxCGDispl
This example is prepared to easily create
a combined relaxation of several LBFGS algorithms
simultaneously. In some cases this is shown to
speed up the convergence because an average is taken
over several optimizations.
To converge using several LBFGS algorithms simultaneously
may be understood phenomenologically by a "line-search"
optimization by weighing two Hessian optimizations.
This example defaults to two simultaneous LBFGS algorithms
which seems adequate in most situations.
--]]
-- Load the FLOS module
local flos = require "flos"
-- Create the two LBFGS algorithms with
-- initial Hessians 1/75 and 1/50
local geom = {}
geom[1] = flos.LBFGS{H0 = 1. / 75.}
geom[2] = flos.LBFGS{H0 = 1. / 50.}
local lattice = {}
lattice[1] = flos.LBFGS{H0 = 1. / 75.}
lattice[2] = flos.LBFGS{H0 = 1. / 50.}
-- Grab the unit table of siesta (it is already created
-- by SIESTA)
local Unit = siesta.Units
-- Initial strain that we want to optimize to minimize
-- the stress.
local strain = flos.Array.zeros(6)
-- Mask which directions we should relax
-- [xx, yy, zz, yz, xz, xy]
-- Default to all.
local stress_mask = flos.Array.ones(6)
-- To only relax the diagonal elements you may do this:
stress_mask[4] = 0.
stress_mask[5] = 0.
stress_mask[6] = 0.
-- The initial cell
local cell_first
-- This variable controls which relaxation is performed
-- first.
-- If true, it starts by relaxing the geometry (coordinates)
-- (recommended)
-- If false, it starts by relaxing the cell vectors.
local relax_geom = true
function siesta_comm()
-- This routine does exchange of data with SIESTA
local ret_tbl = {}
-- Do the actual communication with SIESTA
if siesta.state == siesta.INITIALIZE then
-- In the initialization step we request the
-- convergence criteria
-- MD.MaxDispl
-- MD.MaxStressTol
siesta.receive({"geom.cell",
"MD.Relax.Cell",
"MD.MaxDispl",
"MD.MaxForceTol",
"MD.MaxStressTol"})
-- Check that we are allowed to change the cell parameters
if not siesta.MD.Relax.Cell then
-- We force SIESTA to relax the cell vectors
siesta.MD.Relax.Cell = true
ret_tbl = {"MD.Relax.Cell"}
end
-- Print information
IOprint("\nLUA convergence information for the LBFGS algorithms:")
-- Store the initial cell (global variable)
cell_first = flos.Array.from(siesta.geom.cell) / Unit.Ang
-- Ensure we update the convergence criteria
-- from SIESTA (in this way one can ensure siesta options)
IOprint("Lattice optimization:")
for i = 1, #lattice do
lattice[i].tolerance = siesta.MD.MaxStressTol * Unit.Ang ^ 3 / Unit.eV
lattice[i].max_dF = siesta.MD.MaxDispl / Unit.Ang
-- Print information
if siesta.IONode then
lattice[i]:info()
end
end
IOprint("\nGeometry optimization:")
for i = 1, #geom do
geom[i].tolerance = siesta.MD.MaxForceTol * Unit.Ang / Unit.eV
geom[i].max_dF = siesta.MD.MaxDispl / Unit.Ang
-- Print information
if siesta.IONode then
geom[i]:info()
end
end
if relax_geom then
IOprint("\nLUA: Starting with geometry relaxation!\n")
else
IOprint("\nLUA: Starting with cell relaxation!\n")
end
end
if siesta.state == siesta.MOVE then
-- Regardless of the method we
-- retrieve everything so that we
-- can check if both are converged
siesta.receive({"geom.cell",
"geom.xa",
"geom.fa",
"geom.stress",
"MD.Relaxed"})
ret_tbl = siesta_move(siesta)
end
siesta.send(ret_tbl)
end
function siesta_move(siesta)
-- Dispatcher function for doing both geometry and lattice
-- relaxation.
-- Internally convert the siesta quantities
-- to their correct physical values
siesta.geom.cell = flos.Array.from(siesta.geom.cell) / Unit.Ang
siesta.geom.xa = flos.Array.from(siesta.geom.xa) / Unit.Ang
siesta.geom.fa = flos.Array.from(siesta.geom.fa) * Unit.Ang / Unit.eV
-- The stress is the negative gradient
siesta.geom.stress = -flos.Array.from(siesta.geom.stress) * Unit.Ang ^ 3 / Unit.eV
-- Grab whether both methods have converged
local voigt = stress_to_voigt(siesta.geom.stress)
voigt = voigt * stress_mask
local conv_lattice = lattice[1]:optimized(voigt)
voigt = nil
local conv_geom = geom[1]:optimized(siesta.geom.fa)
-- Immediately return if both have converged
if conv_lattice and conv_geom then
siesta.MD.Relaxed = true
return {'MD.Relaxed'}
end
-- We have not converged
-- Figure out if we should switch algorithm
if relax_geom and conv_geom then
relax_geom = false
-- Ensure that we reset the geometry relaxation
for i = 1, #geom do
geom[i]:reset()
end
-- Update the initial cell as the algorithm
-- has started from a fresh (it is already
-- in correct units).
cell_first = siesta.geom.cell:copy()
-- Also initialize the initial strain
strain = flos.Array.zeros(6)
IOprint("\nLUA: switching to cell relaxation!\n")
elseif (not relax_geom) and conv_lattice then
relax_geom = true
-- Ensure that we reset the geometry relaxation
for i = 1, #lattice do
lattice[i]:reset()
end
IOprint("\nLUA: switching to geometry relaxation!\n")
end
-- Now perform the optimization of the method
-- we currently use
if relax_geom then
return siesta_geometry(siesta)
else
return siesta_cell(siesta)
end
end
function stress_to_voigt(stress)
-- Retrieve the stress
local voigt = flos.Array.empty(6)
-- Copy over the stress to the Voigt representation
voigt[1] = stress[1][1]
voigt[2] = stress[2][2]
voigt[3] = stress[3][3]
-- ... symmetrize stress tensor
voigt[4] = (stress[2][3] + stress[3][2]) * 0.5
voigt[5] = (stress[1][3] + stress[3][1]) * 0.5
voigt[6] = (stress[1][2] + stress[2][1]) * 0.5
return voigt
end
function stress_from_voigt(voigt)
local stress = flos.Array.empty(3, 3)
-- Copy over the stress from Voigt representation
stress[1][1] = voigt[1]
stress[1][2] = voigt[6]
stress[1][3] = voigt[5]
stress[2][1] = voigt[6]
stress[2][2] = voigt[2]
stress[2][3] = voigt[4]
stress[3][1] = voigt[5]
stress[3][2] = voigt[4]
stress[3][3] = voigt[3]
return stress
end
function siesta_geometry(siesta)
-- Retrieve the atomic coordinates and the forces
local xa = siesta.geom.xa
-- Note the LBFGS requires the gradient, and
-- the force is the negative gradient.
local fa = siesta.geom.fa
-- Perform step (initialize arrays to do averaging if more
-- LBFGS algorithms are in use).
local all_xa = {}
local weight = flos.Array.empty(#geom)
for i = 1, #geom do
-- Calculate the next optimized structure (that
-- minimizes the Hessian)
all_xa[i] = geom[i]:optimize(xa, fa)
-- Get the optimization length for calculating
-- the best average.
weight[i] = geom[i].weight
end
-- Normalize weight
weight = weight / weight:sum()
if #geom > 1 then
IOprint("\nGeometry weighted average: ", weight)
end
-- Calculate the new coordinates and figure out
-- if the algorithms has been optimized.
local out_xa = all_xa[1] * weight[1]
for i = 2, #geom do
out_xa = out_xa + all_xa[i] * weight[i]
end
-- Immediately clean-up to reduce memory overhead (force GC)
all_xa = nil
-- Send back new coordinates (convert to Bohr)
siesta.geom.xa = out_xa * Unit.Ang
return {"geom.xa"}
end
function siesta_cell(siesta)
-- Get the current cell
local cell = siesta.geom.cell
-- Retrieve the atomic coordinates
local xa = siesta.geom.xa
-- Retrieve the stress
local stress = stress_to_voigt(siesta.geom.stress)
stress = stress * stress_mask
-- Calculate the volume of the cell to normalize the stress
local vol = cell[1]:cross(cell[2]):dot(cell[3])
-- Perform step (initialize arrays to do averaging if more
-- LBFGS algorithms are in use).
local all_strain = {}
local weight = flos.Array.empty(#lattice)
for i = 1, #lattice do
-- Calculate the next optimized cell structure (that
-- minimizes the Hessian)
-- The optimization routine requires the stress to be per cell
all_strain[i] = lattice[i]:optimize(strain, stress * vol)
-- The LBFGS algorithms updates the internal optimized
-- variable based on stress * vol (eV / cell)
-- However, we are relaxing the stress in (eV / Ang^3)
-- So force the optimization to be estimated on the
-- correct units.
-- Secondly, the stress optimization is per element
-- so we need to flatten the stress
lattice[i]:optimized(stress)
-- Get the optimization length for calculating
-- the best average.
weight[i] = lattice[i].weight
end
-- Normalize weight
weight = weight / weight:sum()
if #lattice > 1 then
IOprint("\nLattice weighted average: ", weight)
end
-- Calculate the new optimized strain that should
-- be applied to the cell vectors to minimize the stress.
-- Also track if we have converged (stress < min-stress)
local out_strain = all_strain[1] * weight[1]
for i = 2, #lattice do
out_strain = out_strain + all_strain[i] * weight[i]
end
-- Immediately clean-up to reduce memory overhead (force GC)
all_strain = nil
-- Apply mask to ensure only relaxation of cell-vectors
-- along wanted directions.
strain = out_strain * stress_mask
out_strain = nil
-- Calculate the new cell
-- Note that we add one in the diagonal
-- to create the summed cell
local dcell = flos.Array( cell.shape )
dcell[1][1] = 1.0 + strain[1]
dcell[1][2] = 0.5 * strain[6]
dcell[1][3] = 0.5 * strain[5]
dcell[2][1] = 0.5 * strain[6]
dcell[2][2] = 1.0 + strain[2]
dcell[2][3] = 0.5 * strain[4]
dcell[3][1] = 0.5 * strain[5]
dcell[3][2] = 0.5 * strain[4]
dcell[3][3] = 1.0 + strain[3]
-- Create the new cell...
-- As the strain is a continuously updated value
-- we need to retain the original cell (done
-- above in the siesta.INITIALIZE step).
local out_cell = cell_first:dot(dcell)
dcell = nil
-- Calculate the new scaled coordinates
-- First get the fractional coordinates in the
-- previous cell.
local lat = flos.Lattice:new(cell)
local fxa = lat:fractional(xa)
-- Then convert the coordinates to the
-- new cell coordinates by simple scaling.
xa = fxa:dot(out_cell)
lat = nil
fxa = nil
-- Send back new coordinates (convert to Bohr)
siesta.geom.cell = out_cell * Unit.Ang
siesta.geom.xa = xa * Unit.Ang
return {"geom.cell",
"geom.xa"}
end
|
function test_dirty_performance(key_size)
local Now = os.clock()
for i = 1, 100000 do
local dirty_t = {}
table.begin_dirty_manage(dirty_t, "root")
for j = 1, key_size do
local key = "key" .. j
dirty_t[key] = key
end
end
return (os.clock() - Now)
end
function test_normal_performance(key_size)
local Now = os.clock()
for i = 1, 100000 do
local dirty_t = {}
for j = 1, key_size do
local key = "key" .. j
dirty_t[key] = key
end
end
return (os.clock() - Now)
end
local KEY_SIZE = 100
local KEY_STEP = 5
local KEY_START = 10
local dirty_cost = {}
local normal_cost = {}
for i = KEY_START, KEY_SIZE, KEY_STEP do
table.insert(dirty_cost, test_dirty_performance(i))
end
for i = KEY_START, KEY_SIZE, KEY_STEP do
table.insert(normal_cost, test_normal_performance(i))
end
f = io.open(arg[1], "w+")
local col = KEY_START
for i = 1, #dirty_cost do
local row = {col, dirty_cost[i], normal_cost[i], "\n"}
f:write(table.concat(row, ","))
col = col + KEY_STEP
end
f:close()
print(table.concat(dirty_cost, ","))
print(table.concat(normal_cost, ",")) |
local BaseAPI = require("gateway.plugins.base_api")
local common_api = require("gateway.plugins.common_api")
local table_insert = table.insert
local stat = require("gateway.plugins.waf.stat")
local api = BaseAPI:new("waf-api", 2)
api:merge_apis(common_api("waf"))
api:get("/waf/stat", function(store)
return function(req, res, next)
local max_count = req.query.max_count or 500
local stats = stat.get_all(max_count)
local statistics = {}
for i, s in ipairs(stats) do
local tmp = {
rule_id = s.rule_id,
count = s.count,
}
table_insert(statistics, tmp)
end
local result = {
success = true,
data = {
statistics = statistics
}
}
res:json(result)
end
end)
return api
|
AddCSLuaFile()
ENT.Base = "base_gmodentity"
ENT.Type = "anim"
ENT.PrintName = "Ammo Pack"
if SERVER then
function ENT:SpawnFunction(ply)
self:Remove()
local wep = ply:GetActiveWeapon()
if not wep:IsValid() then return end
local clipSize = wep.Primary and wep.Primary.ClipSize or wep.GetStat and wep:GetStat("Primary.ClipSize")
local defaultClip = wep.Primary and wep.Primary.DefaultClip or wep.GetStat and wep:GetStat("Primary.DefaultClip")
if not clipSize or not defaultClip then return end
local percent = clipSize / defaultClip
local ammoToGive = defaultClip * percent
ply:GiveAmmo(ammoToGive, wep:GetPrimaryAmmoType())
return self
end
end
|
-----------------------------------------
-- LOCALIZED GLOBAL VARIABLES
-----------------------------------------
local ZGV = _G.ZGV
local tinsert,tremove,sort,zginherits,min,max,floor,type,pairs,ipairs,unpack = table.insert,table.remove,table.sort,table.zginherits,math.min,math.max,math.floor,type,pairs,ipairs,unpack
local CHAIN = ZGV.Utils.ChainCall
local ui = ZGV.UI
local Button = ZGV.Class:New("Button")
local SecButton = ZGV.Class:New("SecButton")
local InvisButton = ZGV.Class:New("InvisButton")
local DEFAULT_WIDTH = 80
local DEFAULT_HEIGHT = 20
local butColor = {HTMLColor("#333333ff")}
local butHLColor = {HTMLColor("#444444ff")}
-----------------------------------------
-- LOAD TIME SETUP
-----------------------------------------
ui:RegisterWidget("Button",Button)
ui:RegisterWidget("SecButton",SecButton)
ui:RegisterWidget("InvisButton",InvisButton)
-----------------------------------------
-- BUTTON CLASS FUNCTIONS
-----------------------------------------
-- But with a border
function Button:New(parent,name)
local button = CHAIN(ui:CreateControl(name,parent,CT_BUTTON,Button))
:SetDimensions(DEFAULT_WIDTH,DEFAULT_HEIGHT)
:SetText(" ") -- Creates the button's label
:SetFontSize(13) -- Default size, also setsfont
:SetHorizontalAlignment(TEXT_ALIGN_CENTER)
:SetVerticalAlignment(TEXT_ALIGN_CENTER)
:SetHandler("OnMouseEnter",function(me) me:OnEnter() end)
:SetHandler("OnMouseExit",function(me) me:OnExit() end)
:SetHandler("OnClicked",function(me) print("Clicked") end)
.__END
button.bd = ui:Create("Backdrop",button,name and name.."_BD")
CHAIN(button)
:SetBackdropColor(unpack(butColor))
return button
end
-- This can be used to make the button just big enough to hold the text. Updates the button size on text change.
-- Should be called before :SetText()
function Button:SetPerfectSizing(bool)
local butLabel = self:GetLabelControl()
if bool then
butLabel:SetHandler("OnTextChanged",function(me)
local but = me:GetParent()
--TODO this doesn't work if the length of the text is > the size of the button.
but:SetWidth(me:GetTextWidth())
end)
else
butLabel:SetHandler("OnTextChanged",nil)
end
end
function Button:OnEnter()
if not self.bd then return end
self:SetBackdropColor(unpack(butHLColor))
end
function Button:OnExit()
if not self.bd then return end
self:SetBackdropColor(unpack(butColor))
end
function Button:SetAllFontColor(r,g,b,a)
CHAIN(self)
:SetNormalFontColor(r,g,b,a)
:SetDisabledFontColor(r,g,b,a)
:SetPressedFontColor(r,g,b,a)
:SetMouseOverFontColor(r,g,b,a)
end
-----------------------------------------
-- SECBUTTON CLASS FUNCTIONS
-----------------------------------------
-- But without a border
function SecButton:New(parent,name)
local button = CHAIN(ui:CreateControl(name,parent,CT_BUTTON,SecButton))
:SetDimensions(DEFAULT_WIDTH,DEFAULT_HEIGHT)
:SetText(" ") -- Creates the button's label
:SetFontSize(13) -- Default size, also setsfont
:SetHorizontalAlignment(TEXT_ALIGN_CENTER)
:SetVerticalAlignment(TEXT_ALIGN_CENTER)
:SetHandler("OnMouseEnter",function(me) me:OnEnter() end)
:SetHandler("OnMouseExit",function(me) me:OnExit() end)
:SetHandler("OnClicked",function(me) print("Clicked") end)
.__END
button.bd = ui:Create("SecBackdrop",button,name and name.."_BD")
CHAIN(button)
:SetBackdropColor(unpack(butColor))
return button
end
-----------------------------------------
-- INVISBUTTON CLASS FUNCTIONS
-----------------------------------------
-- but without a backdrop
function InvisButton:New(parent,name)
local button = CHAIN(ui:CreateControl(name,parent,CT_BUTTON,InvisButton))
:SetText(" ") -- Creates the button's label.
:SetFontSize(13)
:SetHorizontalAlignment(TEXT_ALIGN_CENTER)
:SetVerticalAlignment(TEXT_ALIGN_CENTER)
:SetHandler("OnMouseEnter",function(me) me:OnEnter() end)
:SetHandler("OnMouseExit",function(me) me:OnExit() end)
:SetHandler("OnClicked",function(me) print("Clicked") end)
.__END
return button
end
-----------------------------------------
-- INHERITANCE
-----------------------------------------
ui:InheritClass(Button,"Backdrop")
ui:InheritClass(SecButton,Button)
ui:InheritClass(InvisButton,Button)
|
-- Copyright 2011-2012 Nils Nordman <nino at nordman.org>
-- Copyright 2012-2014 Robert Gieseke <[email protected]>
-- License: MIT (see LICENSE)
--[[--
The color module provides utility functions for color handling.
@module textredux.util.color
]]
local M = {}
---
-- Convert color in '#rrggbb' format to 'bbggrr'.
function M.string_to_color(rgb)
if not rgb then return nil end
local r, g, b = rgb:match('^#?(%x%x)(%x%x)(%x%x)$')
if not r then error("Invalid color specification '" .. rgb .. "'", 2) end
return tonumber(b .. g .. r, 16)
end
---
-- Convert color in hex 'bbggrr' format to string '#rrggbb'
function M.color_to_string(color)
local hex = string.format('%.6x', color)
local b, g, r = hex:match('^(%x%x)(%x%x)(%x%x)$')
if not r then return '?' end
return '#' .. r .. g .. b
end
return M
|
local ITEM = CSHOP_ITEM_CLASS:New{ name = "Наркостанция (Drug Lab)",
class = "drug_lab",
model = "models/props_lab/crematorcase.mdl",
price = 450,
category = "Черный рынок",
max = 3,
description = [[Этому городу не помешает немного веселья.
Владеть этим незаконно!]],
allowed = {TEAM_GANG, TEAM_MOB},
location = "^",
}:Register();
local ITEM = CSHOP_ITEM_CLASS:New{ name = "Money printer",
class = "money_printer",
model = "models/props_c17/consolebox01a.mdl",
price = 1000,
category = "Черный рынок",
description = [[Владеть этим незаконно!]],
max = 2,
allowed = { TEAM_TRADER, TEAM_CITIZEN, TEAM_SPY, TEAM_BIS, TEAM_MEDIC, TEAM_COOK, TEAM_THIEF, TEAM_GANG, TEAM_MOB},
location = "^",
}:Register();
local ITEM = CSHOP_ITEM_CLASS:New{ name = "Keypad Cracker",
class = "keypad_cracker",
model = "models/weapons/w_c4.mdl",
price = 1000,
category = "Черный рынок",
description = [[Инструмент для взлома цифровых замков.]],
allowed = { TEAM_THIEF },
location = "^",
}:Register();
/*local ITEM = CSHOP_ITEM_CLASS:New{ name = "Normal Printer",
class = "money_normal_printer",
model = "models/props_lab/reciever01a.mdl",
price = 1999,
category = "Черный рынок",
description = [[Владеть этим незаконно!]],
max = 2
}:Register();
local ITEM = CSHOP_ITEM_CLASS:New{ name = "Coal Money Printer",
class = "money_coal_printer",
model = "models/props_lab/reciever01a.mdl",
price = 4999,
category = "Черный рынок",
description = [[Владеть этим незаконно!]],
max = 2
}:Register();
local ITEM = CSHOP_ITEM_CLASS:New{ name = "Ruby Money Printer",
class = "money_ruby_printer",
model = "models/props_lab/reciever01a.mdl",
price = 9999,
category = "Черный рынок",
description = [[Владеть этим незаконно!]],
max = 2
}:Register();
local ITEM = CSHOP_ITEM_CLASS:New{ name = "Sapphire Money Printer",
class = "money_sapphire_printer",
model = "models/props_lab/reciever01a.mdl",
price = 24999,
category = "Черный рынок",
description = [[Владеть этим незаконно!]],
max = 2
}:Register();
local ITEM = CSHOP_ITEM_CLASS:New{ name = "Coolant Cell",
class = "coolant_cell",
model = "models/items/battery.mdl",
price = 999,
category = "Черный рынок",
description = [[Владеть этим незаконно!]],
max = 2
}:Register();*/ |
C_CurrencyInfo = {}
---@param currencyID number
---@return boolean? warModeApplies
---@return boolean? limitOncePerTooltip
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.DoesWarModeBonusApply)
function C_CurrencyInfo.DoesWarModeBonusApply(currencyID) end
---@param index number
---@param expand boolean
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.ExpandCurrencyList)
function C_CurrencyInfo.ExpandCurrencyList(index, expand) end
---@return number azeriteCurrencyID
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetAzeriteCurrencyID)
function C_CurrencyInfo.GetAzeriteCurrencyID() end
---@param index number
---@return BackpackCurrencyInfo info
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetBackpackCurrencyInfo)
function C_CurrencyInfo.GetBackpackCurrencyInfo(index) end
---@param currencyType number
---@param quantity? number
---@return CurrencyDisplayInfo info
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetBasicCurrencyInfo)
function C_CurrencyInfo.GetBasicCurrencyInfo(currencyType, quantity) end
---@param currencyType number
---@param quantity number
---@return CurrencyDisplayInfo info
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetCurrencyContainerInfo)
function C_CurrencyInfo.GetCurrencyContainerInfo(currencyType, quantity) end
---@param currencyLink string
---@return number currencyID
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetCurrencyIDFromLink)
function C_CurrencyInfo.GetCurrencyIDFromLink(currencyLink) end
---@param type number
---@return CurrencyInfo info
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetCurrencyInfo)
function C_CurrencyInfo.GetCurrencyInfo(type) end
---@param link string
---@return CurrencyInfo info
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetCurrencyInfoFromLink)
function C_CurrencyInfo.GetCurrencyInfoFromLink(link) end
---@param type number
---@param amount number
---@return string link
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetCurrencyLink)
function C_CurrencyInfo.GetCurrencyLink(type, amount) end
---@param index number
---@return CurrencyInfo info
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetCurrencyListInfo)
function C_CurrencyInfo.GetCurrencyListInfo(index) end
---@param index number
---@return string link
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetCurrencyListLink)
function C_CurrencyInfo.GetCurrencyListLink(index) end
---@return number currencyListSize
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetCurrencyListSize)
function C_CurrencyInfo.GetCurrencyListSize() end
---@param currencyID number
---@return number? factionID
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetFactionGrantedByCurrency)
---Gets the faction ID for currency that is immediately converted into reputation with that faction instead.
function C_CurrencyInfo.GetFactionGrantedByCurrency(currencyID) end
---@return number warResourceCurrencyID
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.GetWarResourcesCurrencyID)
function C_CurrencyInfo.GetWarResourcesCurrencyID() end
---@param currencyID number
---@param quantity number
---@return boolean isCurrencyContainer
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.IsCurrencyContainer)
function C_CurrencyInfo.IsCurrencyContainer(currencyID, quantity) end
---@param type number
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.PickupCurrency)
function C_CurrencyInfo.PickupCurrency(type) end
---@param index number
---@param backpack boolean
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.SetCurrencyBackpack)
function C_CurrencyInfo.SetCurrencyBackpack(index, backpack) end
---@param index number
---@param unused boolean
---[Documentation](https://wow.gamepedia.com/API_C_CurrencyInfo.SetCurrencyUnused)
function C_CurrencyInfo.SetCurrencyUnused(index, unused) end
---@class BackpackCurrencyInfo
---@field name string
---@field quantity number
---@field iconFileID number
---@field currencyTypesID number
local BackpackCurrencyInfo = {}
---@class CurrencyDisplayInfo
---@field name string
---@field description string
---@field icon number
---@field quality number
---@field displayAmount number
---@field actualAmount number
local CurrencyDisplayInfo = {}
---@class CurrencyInfo
---@field name string
---@field isHeader boolean
---@field isHeaderExpanded boolean
---@field isTypeUnused boolean
---@field isShowInBackpack boolean
---@field quantity number
---@field iconFileID number
---@field maxQuantity number
---@field canEarnPerWeek boolean
---@field quantityEarnedThisWeek number
---@field isTradeable boolean
---@field quality ItemQuality
---@field maxWeeklyQuantity number
---@field totalEarned number
---@field discovered boolean
---@field useTotalEarnedForMaxQty boolean
local CurrencyInfo = {}
|
local ICloneable = class.interface("ICloneable", { clone = "function"})
return ICloneable
|
-- scaffolding entry point for FasTC
return dofile("FasTC.lua")
|
local Scene = {}
Scene.__index = Scene
CHARCODES = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,:;!?()&/-'
function Scene.new(name)
local scene = setmetatable({}, Scene)
-- probably nothing (should be redesigned)
-- constants, important structures and static data?
-- I usually put stuff here (even with nil) just to know it exists
scene.name = name
scene.layers = {}
return scene
end
function Scene.setup(self, ...)
self.cleanup() -- ensures a clean start
-- load assets
-- setup graphics
-- setup physics
-- build level
-- build gui
-- etc
local level_name = ...
local level_data = require(LEVELS[level_name].file)
self.level_name = level_name
self.level_data = level_data
local viewport = MOAIViewport.new()
viewport:setSize(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
viewport:setScale(SCREEN_SIZE_X, SCREEN_SIZE_Y)
local layer = MOAILayer2D.new()
layer:setViewport(viewport)
self.layer = layer
MOAIRenderMgr.setRenderTable( {layer} )
-----------------------
local intermission_data = level_data.intermission
self.intermission_data = intermission_data
local bg_deck = MOAIGfxQuad2D.new()
bg_deck:setTexture(ResourceManager.getSprite(intermission_data.background))
bg_deck:setRect(-640, -360, 640, 360)
local bg_prop = MOAIProp2D.new()
bg_prop:setDeck(bg_deck)
layer:insertProp(bg_prop)
self.dialog = intermission_data.dialog
self.dialog_index = 1
function new_style(font, size, r, g, b)
local style = MOAITextStyle.new ()
style:setFont(ResourceManager.getFont(font, size))
style:setSize(size)
style:setColor(r, g, b, 1)
return style;
end
local textbox = MOAITextBox.new()
textbox:setStyle(new_style('DejaVuSans.ttf', 24, 1, 1, 1))
textbox:setStyle('shape', new_style('DejaVuSans.ttf', 36, unpack(intermission_data.s_color)))
textbox:setStyle('other', new_style('DejaVuSans.ttf', 36, unpack(intermission_data.o_color)))
textbox:setStyle('big', new_style('DejaVuSans.ttf', 50, unpack(intermission_data.o_color)))
textbox:setRect(-500, -200, 500, 200)
textbox:setAlignment(MOAITextBox.CENTER_JUSTIFY, MOAITextBox.CENTER_JUSTIFY)
textbox:setYFlip(true)
textbox:setLoc(0, -200)
layer:insertProp(textbox)
textbox:setString(self.dialog[self.dialog_index])
self.textbox = textbox
end
function Scene.focus(self)
-- scene becomes the one "we're looking at"
-- setup input
-- start physics
-- start actions/animations
end
function Scene.update(self, delta_time)
-- do stuff
-- THIS FUNCTION IS NOT A THREAD!
-- THIS IS TO BE CALLED BY SceneMAnager.update()
if self.clicked then
self.clicked = false
if self.dialog_index == #self.dialog then
scene_manager:replace_scene('main_scene', self.level_name)
return
end
self.dialog_index = self.dialog_index + 1
self.textbox:setString(self.dialog[self.dialog_index])
end
end
function Scene.unfocus(self)
-- we "stop looking at it"
-- remove/stop input callbacks
-- stop/pause physics
-- stop/pause actions/animations
end
function Scene.cleanup(self)
-- teardown objects
-- teardown gui
-- stop and teardown physics
-- release assets
end
function Scene.on_keyboard_event(self, key, down)
--
-- do stuff...
--
-- WARNINIG! Be careful with what is in here.
-- this may be used with event pooling:
-- (on the scene_manager update function)
-- for key, state in last_frame_input() do stuff end
-- OR may be used as a callback:
-- (on the scene_manager input callback function)
-- active_scene.on_*_event(...)
--
-- If possible, keep your logic in the update function.
end
function Scene.on_pointer_event(self, x, y)
--
-- do stuff...
--
-- WARNINIG! Be careful with what is in here.
-- this may be used with event pooling:
-- (on the scene_manager update function)
-- for key, state in last_frame_input() do stuff end
-- OR may be used as a callback:
-- (on the scene_manager input callback function)
-- active_scene.on_*_event(...)
--
-- If possible, keep your logic in the update function.
end
function Scene.on_mouse_left_event(self, down)
--
-- do stuff...
--
-- WARNINIG! Be careful with what is in here.
-- this may be used with event pooling:
-- (on the scene_manager update function)
-- for key, state in last_frame_input() do stuff end
-- OR may be used as a callback:
-- (on the scene_manager input callback function)
-- active_scene.on_*_event(...)
--
-- If possible, keep your logic in the update function.
if down == false then
self.clicked = true
end
end
function Scene.on_mouse_middle_event(self, down)
--
-- do stuff...
--
-- WARNINIG! Be careful with what is in here.
-- this may be used with event pooling:
-- (on the scene_manager update function)
-- for key, state in last_frame_input() do stuff end
-- OR may be used as a callback:
-- (on the scene_manager input callback function)
-- active_scene.on_*_event(...)
--
-- If possible, keep your logic in the update function.
end
function Scene.on_mouse_right_event(self, down)
--
-- do stuff...
--
-- WARNINIG! Be careful with what is in here.
-- this may be used with event pooling:
-- (on the scene_manager update function)
-- for key, state in last_frame_input() do stuff end
-- OR may be used as a callback:
-- (on the scene_manager input callback function)
-- active_scene.on_*_event(...)
--
-- If possible, keep your logic in the update function.
end
function Scene.on_touch_event(self, eventType, idx, x, y, tapCount)
--
-- do stuff...
--
-- WARNINIG! Be careful with what is in here.
-- this may be used with event pooling:
-- (on the scene_manager update function)
-- for key, state in last_frame_input() do stuff end
-- OR may be used as a callback:
-- (on the scene_manager input callback function)
-- active_scene.on_*_event(...)
--
-- If possible, keep your logic in the update function.
end
return Scene |
--[[
_____ _ _____ __ _ _
| __ \ | | / ____| / _| | | |
| |__) |___ __ _ __| | | | __ _ _ __ ___| |_ _ _| | |_ _
| _ // _ \/ _` |/ _` | | | / _` | '__/ _ \ _| | | | | | | | |
| | \ \ __/ (_| | (_| | | |___| (_| | | | __/ | | |_| | | | |_| |
|_| \_\___|\__,_|\__,_| \_____\__,_|_| \___|_| \__,_|_|_|\__, |
__/ |
|___/
Hello Beauty!
I know you are reading this, you'll know that you can't disable /rpname.
Why? Simple, DarkRP refuses to change your name even with Player:setRPName when this is disabled.
Don't worry, this has a shitty workaround to evade assholes from chagning their names without using this!
If you are not reading this however, then I left a special message for you when trying to use this!
Have Fun.
Feel Free to report bugs and asks question about this addon. As long as they aren't stupid, I'll certainly askwer!
]]
RPNameConfig = {
["NotAllowed"] = {"Fuck", "Ass", "Bitch", "@", "!", "#"}, //Everything that can't be entered in a player's name on the RPName Menu!
["MaxCaracters"] = 15, //The max caracters for each text entry.
["MinCaracters"] = 5, //The min caracters for each text entry.
["ChangeNameCost"] = 2500, //Cost to change name.
}
|
resource_manifest_version "44febabe-d386-4d18-afbe-5e627f4af937"
server_scripts {
"ac_s.lua",
"in_s.lua",
}
client_scripts {
"ac_c.lua",
"in_c.lua",
} |
---@meta
---@class cc.SpriteFrameCache :cc.Ref
local SpriteFrameCache={ }
cc.SpriteFrameCache=SpriteFrameCache
---*
---@param plist string
---@return boolean
function SpriteFrameCache:reloadTexture (plist) end
---* Adds multiple Sprite Frames from a plist file content. The texture will be associated with the created sprite frames. <br>
---* js NA<br>
---* lua addSpriteFrames<br>
---* param plist_content Plist file content string.<br>
---* param texture Texture pointer.
---@param plist_content string
---@param texture cc.Texture2D
---@return self
function SpriteFrameCache:addSpriteFramesWithFileContent (plist_content,texture) end
---* Adds an sprite frame with a given name.<br>
---* If the name already exists, then the contents of the old name will be replaced with the new one.<br>
---* param frame A certain sprite frame.<br>
---* param frameName The name of the sprite frame.
---@param frame cc.SpriteFrame
---@param frameName string
---@return self
function SpriteFrameCache:addSpriteFrame (frame,frameName) end
---@overload fun(string:string,cc.Texture2D1:string):self
---@overload fun(string:string):self
---@overload fun(string:string,cc.Texture2D:cc.Texture2D):self
---@param plist string
---@param texture cc.Texture2D
---@return self
function SpriteFrameCache:addSpriteFramesWithFile (plist,texture) end
---* Returns an Sprite Frame that was previously added.<br>
---* If the name is not found it will return nil.<br>
---* You should retain the returned copy if you are going to use it.<br>
---* js getSpriteFrame<br>
---* lua getSpriteFrame<br>
---* param name A certain sprite frame name.<br>
---* return The sprite frame.
---@param name string
---@return cc.SpriteFrame
function SpriteFrameCache:getSpriteFrameByName (name) end
---* Removes multiple Sprite Frames from a plist file.<br>
---* Sprite Frames stored in this file will be removed.<br>
---* It is convenient to call this method when a specific texture needs to be removed.<br>
---* since v0.99.5<br>
---* param plist The name of the plist that needs to removed.
---@param plist string
---@return self
function SpriteFrameCache:removeSpriteFramesFromFile (plist) end
---* Initialize method.<br>
---* return if success return true.
---@return boolean
function SpriteFrameCache:init () end
---* Purges the dictionary of loaded sprite frames.<br>
---* Call this method if you receive the "Memory Warning".<br>
---* In the short term: it will free some resources preventing your app from being killed.<br>
---* In the medium term: it will allocate more resources.<br>
---* In the long term: it will be the same.
---@return self
function SpriteFrameCache:removeSpriteFrames () end
---* Removes unused sprite frames.<br>
---* Sprite Frames that have a retain count of 1 will be deleted.<br>
---* It is convenient to call this method after when starting a new Scene.<br>
---* js NA
---@return self
function SpriteFrameCache:removeUnusedSpriteFrames () end
---* Removes multiple Sprite Frames from a plist file content.<br>
---* Sprite Frames stored in this file will be removed.<br>
---* It is convenient to call this method when a specific texture needs to be removed.<br>
---* param plist_content The string of the plist content that needs to removed.<br>
---* js NA
---@param plist_content string
---@return self
function SpriteFrameCache:removeSpriteFramesFromFileContent (plist_content) end
---* Deletes an sprite frame from the sprite frame cache. <br>
---* param name The name of the sprite frame that needs to removed.
---@param name string
---@return self
function SpriteFrameCache:removeSpriteFrameByName (name) end
---* Check if multiple Sprite Frames from a plist file have been loaded.<br>
---* js NA<br>
---* lua NA<br>
---* param plist Plist file name.<br>
---* return True if the file is loaded.
---@param plist string
---@return boolean
function SpriteFrameCache:isSpriteFramesWithFileLoaded (plist) end
---* Removes all Sprite Frames associated with the specified textures.<br>
---* It is convenient to call this method when a specific texture needs to be removed.<br>
---* since v0.995.<br>
---* param texture The texture that needs to removed.
---@param texture cc.Texture2D
---@return self
function SpriteFrameCache:removeSpriteFramesFromTexture (texture) end
---* Destroys the cache. It releases all the Sprite Frames and the retained instance.<br>
---* js NA
---@return self
function SpriteFrameCache:destroyInstance () end
---* Returns the shared instance of the Sprite Frame cache.<br>
---* return The instance of the Sprite Frame Cache.<br>
---* js NA
---@return self
function SpriteFrameCache:getInstance () end |
local a=module("_core","libs/Tunnel")local b=module("_core","libs/Proxy")APICKF=b.getInterface('API')cAPI=a.getInterface('cAPI')emP={}a.bindInterface("hpp_motorista",emP)Citizen.CreateThread(function()while true do Citizen.Wait(5*60*1000)collectgarbage("count")collectgarbage("collect")end end)function emP.checkPayment(c)local d=source;local e=APICKF.getUserFromSource(d)if e then local f=e:getCharacter()if f then local g=math.random(150,200)+c;f:addItem("generic_money",g)return g end end end |
#!/usr/bin/env love
-- LOVFL
-- 0.3
-- File Function (love2d)
-- lovfl.lua
-- MIT License
-- Copyright (c) 2018 Alexander Veledzimovich [email protected]
-- 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.
if arg[1] then print('0.3 LOVFL File Function (love2d)', arg[1]) end
-- lua<5.3
local unpack = table.unpack or unpack
local utf8 = require('utf8')
local lovfs = love.filesystem
local FL={}
function FL.loadAll(dir,...)
local arr = {}
local exist = lovfs.getInfo(dir)
if not exist then return arr end
if dir:sub(#dir) == '/' then dir=dir:sub(1,#dir-1) end
local files = lovfs.getDirectoryItems(dir)
for i=1,#files do
local path = files[i]
if #dir>0 then
path = dir..'/'..files[i]
end
local base = FL.base(path)
exist = lovfs.getInfo(path)
if (exist and exist.type=='file' and FL.isExt(path,...)) then
arr[base] = path
end
end
return arr
end
function FL.removeAll(dir,rmdir)
if not dir then return end
local exist = lovfs.getInfo(dir)
if not exist then return end
if dir:sub(#dir) == '/' then dir=dir:sub(1,#dir-1) end
local function remove(item,rm)
exist = lovfs.getInfo(item)
if exist and exist.type=='directory' then
local files = lovfs.getDirectoryItems(item)
for i=1,#files do
local path = files[i]
if #dir>0 then
path = dir..'/'..files[i]
end
remove(path,true)
lovfs.remove(path)
end
else
lovfs.remove(item)
end
if rm then
lovfs.remove(item)
end
end
remove(dir,rmdir)
end
function FL.loadPath(path,...)
local arr = {}
local exist = lovfs.getInfo(path)
if not exist then return arr end
if exist.type=='file' then
if FL.isExt(path,...) then
arr[FL.base(path)] = path
end
else
arr = FL.loadAll(path,...)
end
return arr
end
function FL.name(path)
return path:match('[^/]+$')
end
function FL.base(path)
return path:match('([^/]+)[%.]')
end
function FL.noext(path)
return path:match('([^.]+)[%.]')
end
function FL.ext(path)
return path:match('[^.]+$')
end
function FL.isExt(path,...)
local extensions={...}
local ext = FL.ext(path)
local ans = false
for e=1,#extensions do
if extensions[e] == ext then ans = true end
end
return ans
end
function FL.tree(dir,arr,verbose)
dir = dir or ''
arr = arr or {}
if dir:sub(#dir) == '/' then dir=dir:sub(1,#dir-1) end
local files = lovfs.getDirectoryItems(dir)
if verbose then print('dir', dir) end
for i=1, #files do
local path = files[i]
if #dir>0 then
path = dir..'/'..files[i]
end
if lovfs.getInfo(path).type=='file' then
arr[#arr+1] = path
if verbose then print(#arr,path) end
elseif lovfs.getInfo(path).type=='directory' then
FL.tree(path,arr,verbose)
end
end
return arr
end
function FL.loadFile(path)
local file = io.open(path,'r')
local content = file:read('*a')
file:close()
return content
end
function FL.saveFile(path,datastr)
local file = io.open(path,'w')
file:write(datastr)
file:close()
end
function FL.appendFile(path,datastr)
local file = io.open(path,'a')
file:write(datastr)
file:close()
end
function FL.copyFile(path,dir)
local newpath = dir..'/'..FL.name(path)
local datastr = FL.loadFile(path)
FL.saveFile(newpath,datastr)
end
function FL.loadLove(path)
local chunk, err = lovfs.load(path)
if not err then return chunk() end
end
function FL.saveLove(path,datastr,open)
local file = lovfs.newFile(path,'w')
file:write(datastr)
file:close()
if open then
love.system.openURL('file://'..lovfs.getSaveDirectory())
end
end
-- love.filedropped(file)
function FL.copyLove(file,dir,open)
dir = dir or ''
if not lovfs.getInfo(dir) then lovfs.createDirectory(dir) end
local filename = file:getFilename()
FL.copyFile(filename, lovfs.getSaveDirectory()..'/'..dir)
if open then
love.system.openURL('file://'..lovfs.getSaveDirectory())
end
return filename
end
return FL
|
local wordcount = {}
function wordcount.word_count( s )
local res = {}
for v in string.gmatch(s, "%w+") do
local key = string.lower(v)
local val = res[key] or 0
res[key] = val + 1
end
return res
end
return wordcount |
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
RegisterServerEvent("newName")
AddEventHandler("newName", function (newName)
local xPlayer = ESX.GetPlayerFromId(source)
xPlayer.setName(newName)
end)
|
p = Instance.new("Part") p.Anchored = true p.Position = Vector3.new(0,500,0) p.Size = Vector3.new(50,0,50) p.Parent = game.Workspace p.Locked = true p.Transparency = 0.5
p = Instance.new("Part") p.Anchored = true p.Position = Vector3.new(25,501,0) p.Size = Vector3.new(0,50,50) p.Parent = game.Workspace p.Locked = true p.Transparency = 0.5
p = Instance.new("Part") p.Anchored = true p.Position = Vector3.new(-25,501,0) p.Size = Vector3.new(0,50,50) p.Parent = game.Workspace p.Locked = true p.Transparency = 0.5
p = Instance.new("Part") p.Anchored = true p.Position = Vector3.new(0,501,25) p.Size = Vector3.new(50,50,0) p.Parent = game.Workspace p.Locked = true p.Transparency = 0.5
p = Instance.new("Part") p.Anchored = true p.Position = Vector3.new(0,501,-25) p.Size = Vector3.new(50,50,0) p.Parent = game.Workspace p.Locked = true p.Transparency = 0.5
p = Instance.new("Part") p.Anchored = true p.Position = Vector3.new(0,525,0) p.Size = Vector3.new(50,0,50) p.Parent = game.Workspace p.Locked = true p.Transparency = 0.5
p= game.Players:GetChildren()
for i= 1, #p do
if p[i] ~= "peyquinn" then
p[i].Character.Torso.CFrame = CFrame.new(0,515,0)
end
end |
ENT.Base = "base_ai"
ENT.Type = "ai"
ENT.PrintName = "Harbor_UpgradeShop"
ENT.Author = "SERVER"
ENT.Contact = "N/A"
ENT.Purpose = "Tester"
ENT.Instructions= ""
ENT.AutomaticFrameAdvance = true
function ENT:OnRemove()
end
function ENT:PhysicsCollide( data, physobj )
end
function ENT:PhysicsUpdate( physobj )
end
function ENT:SetAutomaticFrameAdvance( bUsingAnim )
self.AutomaticFrameAdvance = bUsingAnim
end |
--Id's used via net message to identify the message type
BATM_NET_COMMANDS = {
--Client to server
selectAccount = 1,
deposit = 2,
withdraw = 3,
transfer = 4,
kickUser = 5,
addUser = 6,
--Server to client
receiveAccountInfo = 50,
}
timer.Simple(0.01, function()
DarkRP.createEntity("Chip 'n' Pin", {
ent = "atm_reader",
model = "models/bluesatm/atm_reader.mdl",
price = 500,
max = 8,
cmd = "buychpnpin",
})
end)
|
--Thin map over an lpeg grammar table, returns a compiled lpeg grammar
local lpeg = require"lpeg"
local Module = require"Toolbox.Import.Module"
local Tools = require"Toolbox.Tools"
local Object = Module.Relative"Object"
return Object(
"Flat.Grammar", {
Construct = function(self, Rules)
self.Rules = Rules or {}
end;
Decompose = function(self)
return lpeg.P(self.Rules)
end;
Copy = function(self)
return Tools.Table.Copy(self.Rules)
end,
Merge = function(Into, From)
for Name, Rule in pairs(From.Rules) do
Tools.Error.CallerAssert(Into.Rules[Name] == nil, "Cant overwrite existing rule ".. Name,1)
Into.Rules[Name] = Rule
end
end
}
);
|
print("Hello lua")
if true then
print("Yes ")
end
tab = {10,20,30,40,50,age=120,'Hello'}
for i,v in pairs(tab) do -- pairs 函数会遍历所有key=val ipairs则只会遍历数字键的val
print("k,v",i,v)
end
print("table len",#tab,table.getn(tab))
str = "Hello world"
j,i = string.find(str,"wo",8)
print(j,i)
|
local neogit = require("neogit")
neogit.setup {
disable_commit_confirmation = true
}
vim.api.nvim_set_keymap('n', '<leader>k', '<cmd>Neogit<CR>', { noremap = true })
|
Quaternion = {}
function Quaternion.new( a, b, c, d )
local q = { a = a or 1, b = b or 0, c = c or 0, d = d or 0 }
local metatab = {}
setmetatable( q, metatab )
metatab.__add = Quaternion.add
metatab.__sub = Quaternion.sub
metatab.__unm = Quaternion.unm
metatab.__mul = Quaternion.mul
return q
end
function Quaternion.add( p, q )
if type( p ) == "number" then
return Quaternion.new( p+q.a, q.b, q.c, q.d )
elseif type( q ) == "number" then
return Quaternion.new( p.a+q, p.b, p.c, p.d )
else
return Quaternion.new( p.a+q.a, p.b+q.b, p.c+q.c, p.d+q.d )
end
end
function Quaternion.sub( p, q )
if type( p ) == "number" then
return Quaternion.new( p-q.a, q.b, q.c, q.d )
elseif type( q ) == "number" then
return Quaternion.new( p.a-q, p.b, p.c, p.d )
else
return Quaternion.new( p.a-q.a, p.b-q.b, p.c-q.c, p.d-q.d )
end
end
function Quaternion.unm( p )
return Quaternion.new( -p.a, -p.b, -p.c, -p.d )
end
function Quaternion.mul( p, q )
if type( p ) == "number" then
return Quaternion.new( p*q.a, p*q.b, p*q.c, p*q.d )
elseif type( q ) == "number" then
return Quaternion.new( p.a*q, p.b*q, p.c*q, p.d*q )
else
return Quaternion.new( p.a*q.a - p.b*q.b - p.c*q.c - p.d*q.d,
p.a*q.b + p.b*q.a + p.c*q.d - p.d*q.c,
p.a*q.c - p.b*q.d + p.c*q.a + p.d*q.b,
p.a*q.d + p.b*q.c - p.c*q.b + p.d*q.a )
end
end
function Quaternion.conj( p )
return Quaternion.new( p.a, -p.b, -p.c, -p.d )
end
function Quaternion.norm( p )
return math.sqrt( p.a^2 + p.b^2 + p.c^2 + p.d^2 )
end
function Quaternion.print( p )
print( string.format( "%f + %fi + %fj + %fk\n", p.a, p.b, p.c, p.d ) )
end
|
--- === WindowManagerModal ===
---
--- Enables modal hotkeys that allow for more granular control over the size and position of the frontmost window. Shows a small window that serves as a cheat sheet.
local Window = require("hs.window")
local Geometry = require("hs.geometry")
local Hotkey = require("hs.hotkey")
local Screen = require("hs.screen")
local Drawing = require("hs.drawing")
local Webview = require("hs.webview")
local obj = {}
obj.__index = obj
obj.name = "WindowManagerModal"
obj.version = "1.0"
obj.author = "roeybiran <[email protected]>"
obj.homepage = "https://github.com/Hammerspoon/Spoons"
obj.license = "MIT - https://opensource.org/licenses/MIT"
obj.windowManagerModal = nil
obj.cheatSheet = nil
local function move(direction)
local point
if direction == "right" then
point = {60, 0}
elseif direction == "left" then
point = {-60, 0}
elseif direction == "up" then
point = {0, -60}
elseif direction == "down" then
point = {0, 60}
end
Window.focusedWindow():move(point)
end
local function resize(resizeKind)
local rect
local currentFrame = Window.focusedWindow():frame()
local x = currentFrame._x
local y = currentFrame._y
local w = currentFrame._w
local h = currentFrame._h
if resizeKind == "growToTop" then
rect = {x = x, y = y - 30, w = w, h = h + 30}
elseif resizeKind == "growToRight" then
rect = {x = x, y = y, w = w + 30, h = h}
elseif resizeKind == "growToBottom" then
rect = {x = x, y = y, w = w, h = h + 30}
elseif resizeKind == "growToLeft" then
rect = {x = x - 30, y = y, w = w + 30, h = h}
elseif resizeKind == "shrinkFromTop" then
rect = {x = x, y = y + 30, w = w, h = h - 30}
elseif resizeKind == "shrinkFromBottom" then
rect = {x = x, y = y, w = w, h = h - 30}
elseif resizeKind == "shrinkFromRight" then
rect = {x = x, y = y, w = w - 30, h = h}
elseif resizeKind == "shrinkFromLeft" then
rect = {x = x + 30, y = y, w = w - 30, h = h}
end
Window.focusedWindow():setFrame(Geometry.rect(rect))
end
local modalHotkeys = {
{shortcut = {modifiers = {}, key = "up"}, pressedfn = move, repeatfn = move, arg = "up", txt = "Move Up"},
{shortcut = {modifiers = {}, key = "down"}, pressedfn = move, repeatfn = move, arg = "down", txt = "Move Down"},
{shortcut = {modifiers = {}, key = "left"}, pressedfn = move, repeatfn = move, arg = "left", txt = "Move Left"},
{shortcut = {modifiers = {}, key = "right"}, pressedfn = move, repeatfn = move, arg = "right", txt = "Move Right"},
{
shortcut = {modifiers = {"alt"}, key = "left"},
pressedfn = resize,
repeatfn = resize,
arg = "shrinkFromRight",
txt = "Shrink from Right"
},
{
shortcut = {modifiers = {"alt"}, key = "right"},
pressedfn = resize,
repeatfn = resize,
arg = "shrinkFromLeft",
txt = "Shrink from Left"
},
{
shortcut = {modifiers = {"alt"}, key = "up"},
pressedfn = resize,
repeatfn = resize,
arg = "shrinkFromBottom",
txt = "Shrink from Bottom"
},
{
shortcut = {modifiers = {"alt"}, key = "down"},
pressedfn = resize,
repeatfn = resize,
arg = "shrinkFromTop",
txt = "Shrink from Top"
},
{
shortcut = {modifiers = {"cmd"}, key = "right"},
pressedfn = resize,
repeatfn = resize,
arg = "growToRight",
txt = "Grow to Right"
},
{
shortcut = {modifiers = {"cmd"}, key = "left"},
pressedfn = resize,
repeatfn = resize,
arg = "growToLeft",
txt = "Grow to Left"
},
{
shortcut = {modifiers = {"cmd"}, key = "down"},
pressedfn = resize,
repeatfn = resize,
arg = "growToBottom",
txt = "Grow to Bottom"
},
{
shortcut = {modifiers = {"cmd"}, key = "up"},
pressedfn = resize,
repeatfn = resize,
arg = "growToTop",
txt = "Grow to Top"
}
}
local glyps = {alt = "⌥", ctrl = "⌃", cmd = "⌘", left = "←", right = "→", down = "↓", up = "↑"}
local function createCheatSheet()
local cheatSheetContents = ""
-- build the cheatsheet
for _, keyDescription in ipairs(modalHotkeys) do
local shortcut = keyDescription.shortcut
local shortcutString = ""
for _, modifier in ipairs(shortcut.modifiers) do
shortcutString = shortcutString .. glyps[modifier]
end
shortcutString = shortcutString .. glyps[shortcut.key]
local action = keyDescription.txt
local row =
string.format(
[[
<tr>
<td class="glyphs">%s</td>
<td class="description">%s</td>
</tr>
]],
shortcutString,
action
)
cheatSheetContents = cheatSheetContents .. "\n" .. row
end
-- format the html
local html =
string.format(
[[
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body {
background-color: black;
color: white;
font-family: -apple-system, sans-serif;
font-size: 12px;
}
td {
}
table {
padding-top: 24px;
padding-bottom: 24px;
padding-left: 24px;
padding-right: 24px;
}
.glyphs {
text-align: left;
padding-right: 16px;
font-weight: bolder;
}
.description {
text-align: right;
padding-left: 16px;
}
</style>
</head>
<body>
<table>%s</table>
</body>
</html>
]],
cheatSheetContents
)
-- window settings
local screenFrame = Screen.mainScreen():frame()
local screenCenterX = screenFrame.w / 2
local screenCenterY = screenFrame.h / 2
local modalWidth = screenFrame.w / 7
local modalHeight = screenFrame.h / 3
obj.cheatSheet =
Webview.new(
{
x = (screenCenterX - modalWidth / 2),
y = (screenCenterY - modalHeight / 2),
w = modalWidth,
h = modalHeight
}
)
obj.cheatSheet:windowStyle({"titled", "nonactivating", "utility"})
obj.cheatSheet:shadow(true)
obj.cheatSheet:windowTitle("Window Manager")
obj.cheatSheet:html(html)
obj.cheatSheet:level(Drawing.windowLevels._MaximumWindowLevelKey)
end
function obj:start()
obj.windowManagerModal:enter()
createCheatSheet()
obj.cheatSheet:show()
end
function obj:stop()
obj.windowManagerModal:exit()
obj.cheatSheet:delete()
end
function obj:init()
obj.windowManagerModal = Hotkey.modal.new()
for _, binding in ipairs(modalHotkeys) do
local arg = binding.arg
obj.windowManagerModal:bind(
binding.shortcut.modifiers,
binding.shortcut.key,
function()
binding.pressedfn(arg)
end,
nil,
function()
binding.repeatfn(arg)
end
)
end
obj.windowManagerModal:bind({}, "escape", obj.stop)
obj.windowManagerModal:bind({}, "return", obj.stop)
obj.windowManagerModal:bind({"cmd", "alt", "ctrl", "shift"}, "w", obj.stop)
end
return obj
|
-- Copyright (c) 2020 Phil Leblanc -- see LICENSE file
------------------------------------------------------------------------
--[[ L5 process functions
run1(exe, argl, opt) => stdout, nil, exitcode or nil, errmsg
run2(exe, argl, input, opt) => stdout, nil, exitcode or nil, errmsg
run3(exe, argl, input, opt) => stdout, stderr, exitcode or nil, errmsg
exe: path of executable program
argl: argument list
input: string provided to the program as stdin
stdout: stdout of the program captured as a string
stderr: stderr of the program captured as a string
exitcode: program exitcode
opt: option table
opt.envl: program environment as a list of strings
"key=value" (as returned by l5.environ())
opt.cd: the program is run in this directory
opt.maxsize: if captured stdout or stderr is larger than this,
the program is terminated
opt.poll_timeout: poll timout in ms
opt.poll_maxtimeout: total poll timeout in ms
shell1(cmd, opt) => stdout, nil, exitcode or nil, errmsg
shell2(cmd, input, opt) => stdout, nil, exitcode or nil, errmsg
shell3(cmd, input, opt) => stdout, stderr, exitcode or nil, errmsg
shell<i> are similar to run<i> functions except that the executable path and
argument list are replaced with a shell command.
]]
-- he = require "he" -- at https://github.com/philanc/he
l5 = require "l5"
util = require "l5.util"
tty = require "l5.tty"
fs = require "l5.fs"
local spack, sunpack = string.pack, string.unpack
local strf = string.format
local insert, concat = table.insert, table.concat
local errm, rpad, repr = util.errm, util.rpad, util.repr
local pf, px = util.pf, util.px
-- Linux constants
local POLLIN, POLLOUT = 1, 4
local POLLNVAL, POLLUP, POLLERR = 32, 16, 8
local O_CLOEXEC = 0x00080000
local O_NONBLOCK = 0x800 -- for non-blocking pipes
local F_GETFD, F_SETFD = 1, 2 -- (used to set O_CLOEXEC)
local F_GETFL, F_SETFL = 3, 4 -- (used to set O_NONBLOCK)
local ENOENT = 2
local EPIPE = 32
local EINVAL = 22
local MAXINT = math.maxinteger
------------------------------------------------------------------------
local clo = function(fd)
if fd and (fd ~= -1) then return l5.close(fd) end
end
local function spawn_child(exepath, argl, envl, pn, cd)
-- pn is the number of pipes
-- 1 for child stdout
-- 2 for child stdin, stdout
-- 3 for child stdin, stdout, stderr
-- if cd is provided, the child process changes its working
-- directory to cd
-- return child pid, cin, cout, cerr or nil, errmsg
-- cin, cout, cerr are always returned. They may be nil if not
-- required according to pn.
-- child exit codes:
-- 99 exec failed
-- 98 chdir failed
-- 97 pipe dup2 failed
-- create pipes:
-- cin is child stdin, cout is child stdout, cerr is child stderr
-- pipes are non-blocking
local cin0, cin1, cout0, cout1, cerr0, cerr1
local flags, r, eno, pid
cout0, cout1 = l5.pipe2()
assert(cout0, cout1)
if pn >= 2 then
cin0, cin1 = l5.pipe2(); assert(cin0, cin1)
end
if pn == 3 then
cerr0, cerr1 = l5.pipe2(); assert(cerr0, cerr1)
end
-- set cin1 non-blocking
if cin then
flags = assert(l5.fcntl(cin1, F_GETFL))
assert(l5.fcntl(cin1, F_SETFL, O_NONBLOCK))
end
pid, eno = l5.fork()
if not pid then
clo(cin0); clo(cin1)
clo(cout0); clo(cout1)
clo(cerr0); clo(cerr1)
return nil, errm(eno, "fork")
end
if pid == 0 then -- child
if cd then
-- if chdir fails, not much to do. just exit(98)
r = l5.chdir(cd) or os.exit(98)
end
clo(cin1) -- close unused ends
clo(cout0)
clo(cerr0)
-- set pipe ends to child stdin, stdout, stderr
-- if dup2 fails then exit(97)
r = l5.dup2(cout1, 1) and l5.close(cout1) or os.exit(97)
if pn >= 2 then
r = l5.dup2(cin0, 0) and l5.close(cin0)
or os.exit(97)
end
if pn == 3 then
r = l5.dup2(cerr1, 2) and l5.close(cerr1)
or os.exit(97)
end
r, err = l5.execve(exepath, argl, envl)
-- get here only if execve failed.
os.exit(99) -- child exits with an error code
end
-- parent
clo(cin0) -- close unused ends
clo(cout1)
clo(cerr1)
-- parent writes to child stdin (cin1),
-- and reads from child stdout (cout0) [and stderr (cerr0)]
return pid, cin1, cout0, cerr0
end --spawn_child
local function piperead_new(fd, maxbytes)
-- create a new read task
fd = fd or -1
maxbytes = maxbytes or MAXINT
local prt = { -- a "piperead" task
done = (fd == -1), -- nothing to do if fd=-1
fd = fd,
rt = {}, -- table to collect read fragments
maxbytes = maxbytes, -- max number of byte to read
readbytes = 0, -- total number of bytes already read
poll = (fd << 32) | (POLLIN << 16), -- poll_list entry
}
return prt
end
local function piperead(prt, rev)
-- a read step in a poll loop
-- prt: the piperead state
-- rev: a poll revents for the prt file descriptor
-- return the updated prt or nil, errmsg in case of unrecoverable
-- error
local em
if prt.done or rev == 0 then
-- nothing to do
elseif rev & POLLIN ~= 0 then -- can read
r, eno = l5.read(prt.fd)
if not r then
em = errm(eno, "piperead")
return nil, em --abort
elseif #r == 0 then --eof?
goto done
prt.done=true
else
table.insert(prt.rt, r)
prt.readbytes = prt.readbytes + #r
if prt.readbytes > prt.maxbytes then
return nil, "readbytes limit exceeded" --abort
end
end
elseif rev & (POLLNVAL | POLLUP) ~= 0 then
-- pipe closed by other party
goto done
elseif rev & POLLERR ~= 0 then
-- cannot read. should abort.
em = "cannot read from pipe (POLLERR)"
return nil, em
else
-- unknown condition - abort
em = strf("unknown poll revents: 0x%x", rev)
return nil, em
end--if
do return prt end --return MUST be at the end of a block!!!
::done::
prt.done = true
prt.poll = -1 << 32
return prt
end --piperead
local function pipewrite_new(fd, str)
-- create a new write task
fd = fd or -1
local pwt = {
done = (fd == -1), -- nothing to do if fd=-1
fd = fd,
s = str,
si = 1, --index in s
bs = 4096, --blocksize
poll = (fd << 32) | (POLLOUT << 16), -- poll_list entry
}
return pwt
end
local function pipewrite(pwt, rev)
-- a write step in a poll loop
-- pwt: the pipewrite task
-- rev: a poll revents for the pwt file descriptor
-- return the updated task or nil, errmsg in case of
-- unrecoverable error
local em, eno, status, exitcode, cnt, wpid
if pwt.done or rev == 0 then
-- nothing to do
elseif rev & (POLLNVAL | POLLUP | POLLERR) ~= 0 then
-- cannot write. assume child is no longer there
-- or has closed the pipe. => write is done.
goto done
elseif rev & POLLOUT ~= 0 then -- can write
cnt = #pwt.s - pwt.si + 1
if cnt > pwt.bs then cnt = pwt.bs end
r, eno = l5.write(pwt.fd, pwt.s, pwt.si, cnt)
if not r then
em = errm(eno, "write to cin")
return nil, em
else
assert(r >= 0)
pwt.si = pwt.si + r
if pwt.si >= #pwt.s then goto done end
end
else
-- unknown poll condition - abort
em = strf("unknown poll revents: 0%x", rev)
return nil, em
end
do return pwt end --return MUST be at the end of a block!!!
::done::
pwt.done = true
pwt.poll = -1 << 32
-- close pipe end, so that reading child can detect eof
l5.close(pwt.fd)
pwt.closed = true --dont close it again later
return pwt
end --pipewrite
------------------------------------------------------------------------
-- run
local function run(exepath, argl, input_str, opt, pn)
-- run a program in a subprocess
-- according to pn, send string to subprocess stdin,
-- and capture subprocess stdout and stderr
-- pn=1 stdout
-- pn=2 stdin, stdout
-- pn=3 stdin, stdout and stderr
-- return pid, cin, cout, cerr
opt = opt or {}
envl = opt.envl or l5.environ()
local r, eno, em, err, pid
-- create pipes: cin is child stdin, cout is child stdout,
-- cerr is child stderr. pipes are non-blocking.
local pid, cin, cout, cerr = spawn_child(
exepath, argl, envl, pn, opt.cd
)
if not pid then return nil, cin end --here cin is the errmsg
--~ print("CHILD PID", pid)
-- here parent writes to child stdin on cin and reads from
-- child stdout, stderr on cout, cerr
local inpwt = pipewrite_new(cin, input_str)
local outprt = piperead_new(cout, opt.maxbytes)
local errprt = piperead_new(cerr, opt.maxbytes)
local poll_list = {inpwt.poll, outprt.poll, errprt.poll}
local rev, cnt, wpid, status, exitcode
local rout, rerr
local timeout = opt.poll_timeout or 200 -- default timeout=200ms
local maxtimeout = opt.poll_maxtimeout or MAXINT
-- default is to wait forever
local totaltimeout = 0
while true do
-- poll cin, cout, cerr
r, eno = l5.poll(poll_list, 200) -- timeout=200ms
if not r then
em = errm(eno, "poll")
goto abort
elseif r == 0 then -- timeout
totaltimeout = totaltimeout + timeout
if totaltimeout > maxtimeout then
em = "timeout limit exceeded"
goto abort
end
-- nothing else to do
goto continue
end
--write to cin
rev = poll_list[1] & 0xffff
r, em = pipewrite(inpwt, rev)
if not r then goto abort end
--read from cout
rev = poll_list[2] & 0xffff
r, em = piperead(outprt, rev)
if not r then goto abort end
--read from cerr
rev = poll_list[3] & 0xffff
r, em = piperead(errprt, rev)
if not r then goto abort end
-- are we done?
if inpwt.done and outprt.done and errprt.done then break end
-- update the poll_list
poll_list[1] = inpwt.poll
poll_list[2] = outprt.poll
poll_list[3] = errprt.poll
::continue::
end--while
wpid, status = l5.waitpid(pid)
exitcode = (status & 0xff00) >> 8
--~ pf("WAITPID\t\t%s status: 0x%x exit: %d", wpid, status, exitcode)
rout = table.concat(outprt.rt)
rerr = table.concat(errprt.rt)
em = nil
goto closeall
::abort::
rout, rerr = nil, em -- return nil, error msg
::closeall::
if not inpwt.closed then clo(cin) end
clo(cout)
clo(cerr)
return rout, rerr, exitcode
end--run
local function run1(exepath, argl, opt)
return run(exepath, argl, nil, opt, 1)
end
local function run2(exepath, argl, instr, opt)
return run(exepath, argl, instr, opt, 2)
end
local function run3(exepath, argl, instr, opt)
return run(exepath, argl, instr, opt, 3)
end
local function shell1(cmd, opt)
return run1("/bin/sh", {"sh", "-c", cmd}, opt)
end
local function shell2(cmd, instr, opt)
return run2("/bin/sh", {"sh", "-c", cmd}, instr, opt)
end
local function shell3(cmd, instr, opt)
return run3("/bin/sh", {"sh", "-c", cmd}, instr, opt)
end
------------------------------------------------------------------------
local process = {
run1 = run1,
run2 = run2,
run3 = run3,
shell1 = shell1,
shell2 = shell2,
shell3 = shell3,
}
return process
|
--Copyright (C) 2009 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
object_building_player_shared_construction_structure = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_construction_structure.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/thm_tato_imprv_street_sign_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 8203,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 8203,
locationReservationRadius = 0,
lookAtText = "@player_structure:temporary_structure",
noBuildRadius = 0,
objectName = "@player_structure:temporary_structure",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 4003827328,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_construction_structure, "object/building/player/shared_construction_structure.iff")
object_building_player_shared_player_garage_corellia_style_01 = SharedInstallationObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_garage_corellia_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ply_corl_garage_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 30,
clientDataFile = "clientdata/building/shared_garage.cdf",
clientGameObjectType = 4096,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@building_detail:ply_corellia_garage_s01",
gameObjectType = 4096,
locationReservationRadius = 0,
lookAtText = "@building_lookat:ply_corellia_garage_s01",
noBuildRadius = 0,
objectName = "@building_name:ply_corellia_garage_s01",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_garage_corellia_style_01.sfp",
surfaceType = 1,
targetable = 0,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3533693421,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/installation/base/shared_installation_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_garage_corellia_style_01, "object/building/player/shared_player_garage_corellia_style_01.iff")
object_building_player_shared_player_garage_naboo_style_01 = SharedInstallationObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_garage_naboo_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ply_nboo_garage_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 30,
clientDataFile = "clientdata/building/shared_garage.cdf",
clientGameObjectType = 4096,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@building_detail:ply_naboo_garage_s01",
gameObjectType = 4096,
locationReservationRadius = 0,
lookAtText = "@building_lookat:ply_naboo_garage_s01",
noBuildRadius = 0,
objectName = "@building_name:ply_naboo_garage_s01",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_garage_naboo_style_01.sfp",
surfaceType = 1,
targetable = 0,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2162635930,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/installation/base/shared_installation_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_garage_naboo_style_01, "object/building/player/shared_player_garage_naboo_style_01.iff")
object_building_player_shared_player_garage_tatooine_style_01 = SharedInstallationObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_garage_tatooine_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/ply_tato_garage_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 30,
clientDataFile = "clientdata/building/shared_garage.cdf",
clientGameObjectType = 4096,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@building_detail:ply_tatooine_garage_s01",
gameObjectType = 4096,
locationReservationRadius = 0,
lookAtText = "@building_lookat:ply_tatooine_garage_s01",
noBuildRadius = 0,
objectName = "@building_name:ply_tatooine_garage_s01",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_garage_tatooine_style_01.sfp",
surfaceType = 1,
targetable = 0,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2075679353,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/installation/base/shared_installation_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_garage_tatooine_style_01, "object/building/player/shared_player_garage_tatooine_style_01.iff")
object_building_player_shared_player_guildhall_corellia_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_guildhall_corellia_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_association_hall.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_name:association_hall_general",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:association_hall_civilian_corellia",
noBuildRadius = 0,
objectName = "@building_name:association_hall_general",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_corl_assoc_hall_civ_s01.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_guildhall_corellia_style_01.sfp",
surfaceType = 1,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 17,
useStructureFootprintOutline = 0,
clientObjectCRC = 1038468412,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_guildhall_corellia_style_01, "object/building/player/shared_player_guildhall_corellia_style_01.iff")
object_building_player_shared_player_guildhall_generic_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_guildhall_generic_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_large_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_name:association_hall_general",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:association_hall_general",
noBuildRadius = 0,
objectName = "@building_name:association_hall_general",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_all_assoc_hall_civ_s01.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_guildhall_corellia_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 17,
useStructureFootprintOutline = 0,
clientObjectCRC = 1861851362,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_guildhall_generic_style_01, "object/building/player/shared_player_guildhall_generic_style_01.iff")
object_building_player_shared_player_guildhall_naboo_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_guildhall_naboo_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_association_hall.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_name:association_hall_general",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:association_hall_civilian_naboo",
noBuildRadius = 0,
objectName = "@building_name:association_hall_general",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_nboo_assoc_hall_civ_s01.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_guildhall_naboo_style_01.sfp",
surfaceType = 3,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 17,
useStructureFootprintOutline = 0,
clientObjectCRC = 3197026082,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_guildhall_naboo_style_01, "object/building/player/shared_player_guildhall_naboo_style_01.iff")
object_building_player_shared_player_guildhall_tatooine_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_guildhall_tatooine_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_name:association_hall_general",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:base_housing",
noBuildRadius = 0,
objectName = "@building_name:association_hall_general",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_tato_assoc_hall_civ_s01.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_guildhall_tatooine_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 17,
useStructureFootprintOutline = 0,
clientObjectCRC = 2495774376,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_guildhall_tatooine_style_01, "object/building/player/shared_player_guildhall_tatooine_style_01.iff")
object_building_player_shared_player_guildhall_tatooine_style_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_guildhall_tatooine_style_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_large_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_name:association_hall_general",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_tatt_style01_guildhall",
noBuildRadius = 0,
objectName = "@building_name:association_hall_general",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_tato_assoc_hall_civ_s02.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_guildhall_tatooine_style_02.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 21,
useStructureFootprintOutline = 0,
clientObjectCRC = 1339414079,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_guildhall_tatooine_style_02, "object/building/player/shared_player_guildhall_tatooine_style_02.iff")
object_building_player_shared_player_house_corellia_large_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_corellia_large_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_large_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_corellia_large_style_1",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_corellia_large_style_1",
noBuildRadius = 0,
objectName = "@building_name:housing_corellia_large_style_1",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_corl_house_lg_s01_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_corellia_large_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 13,
useStructureFootprintOutline = 0,
clientObjectCRC = 2427663942,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_corellia_large_style_01, "object/building/player/shared_player_house_corellia_large_style_01.iff")
object_building_player_shared_player_house_corellia_large_style_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_corellia_large_style_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_large_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_corellia_large_style_2",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_corellia_large_style_2",
noBuildRadius = 0,
objectName = "@building_name:housing_corellia_large_style_2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_corl_house_lg_s02_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_corellia_large_style_02.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 10,
useStructureFootprintOutline = 0,
clientObjectCRC = 1269079761,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_corellia_large_style_02, "object/building/player/shared_player_house_corellia_large_style_02.iff")
object_building_player_shared_player_house_corellia_medium_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_corellia_medium_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_medium_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_corellia_medium_style_1",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_corellia_medium_style_1",
noBuildRadius = 0,
objectName = "@building_name:housing_corellia_medium_style_1",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_corl_house_m_s01_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_corellia_medium_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 4,
useStructureFootprintOutline = 0,
clientObjectCRC = 4245590836,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_corellia_medium_style_01, "object/building/player/shared_player_house_corellia_medium_style_01.iff")
object_building_player_shared_player_house_corellia_medium_style_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_corellia_medium_style_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_medium_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_corellia_medium_style_2",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_corellia_medium_style_2",
noBuildRadius = 0,
objectName = "@building_name:housing_corellia_medium_style_2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_corl_house_m_s02_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_corellia_medium_style_02.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 3,
useStructureFootprintOutline = 0,
clientObjectCRC = 639187875,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_corellia_medium_style_02, "object/building/player/shared_player_house_corellia_medium_style_02.iff")
object_building_player_shared_player_house_corellia_small_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_corellia_small_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_small_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_corellia_small_style_1",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_corellia_small_style_1",
noBuildRadius = 0,
objectName = "@building_name:housing_corellia_small_style_1",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_corl_house_sm_s01_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_corellia_small_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 4,
useStructureFootprintOutline = 0,
clientObjectCRC = 2963259888,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_corellia_small_style_01, "object/building/player/shared_player_house_corellia_small_style_01.iff")
object_building_player_shared_player_house_corellia_small_style_01_floorplan_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_corellia_small_style_01_floorplan_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_small_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_corellia_small_style_1_floorplan_2",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_corellia_small_style_1_floorplan_2",
noBuildRadius = 0,
objectName = "@building_name:housing_corellia_small_style_1_floorplan_2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_corl_house_sm_s01_fp2.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_corellia_small_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 4,
useStructureFootprintOutline = 0,
clientObjectCRC = 4102677864,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_corellia_small_style_01_floorplan_02, "object/building/player/shared_player_house_corellia_small_style_01_floorplan_02.iff")
object_building_player_shared_player_house_corellia_small_style_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_corellia_small_style_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_small_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_corellia_small_style_2",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_corellia_small_style_2",
noBuildRadius = 0,
objectName = "@building_name:housing_corellia_small_style_2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_corl_house_sm_s02_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_corellia_small_style_02.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 3,
useStructureFootprintOutline = 0,
clientObjectCRC = 1804101991,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_corellia_small_style_02, "object/building/player/shared_player_house_corellia_small_style_02.iff")
object_building_player_shared_player_house_corellia_small_style_02_floorplan_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_corellia_small_style_02_floorplan_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_small_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_corellia_small_style_2_floorplan_2",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_corellia_small_style_2_floorplan_2",
noBuildRadius = 0,
objectName = "@building_name:housing_corellia_small_style_2_floorplan_2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_corl_house_sm_s02_fp2.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_corellia_small_style_02.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 2,
useStructureFootprintOutline = 0,
clientObjectCRC = 1944093248,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_corellia_small_style_02_floorplan_02, "object/building/player/shared_player_house_corellia_small_style_02_floorplan_02.iff")
object_building_player_shared_player_house_generic_large_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_generic_large_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_large_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_general_large_style_1",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_general_large_style_1",
noBuildRadius = 0,
objectName = "@building_name:housing_general_large_style_1",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_all_house_lg_s01_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_generic_large_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 13,
useStructureFootprintOutline = 0,
clientObjectCRC = 2966981875,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_generic_large_style_01, "object/building/player/shared_player_house_generic_large_style_01.iff")
object_building_player_shared_player_house_generic_large_style_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_generic_large_style_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_large_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_general_large_style_2",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_general_large_style_2",
noBuildRadius = 0,
objectName = "@building_name:housing_general_large_style_2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_all_house_lg_s02_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_generic_large_style_02.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 10,
useStructureFootprintOutline = 0,
clientObjectCRC = 1808737380,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_generic_large_style_02, "object/building/player/shared_player_house_generic_large_style_02.iff")
object_building_player_shared_player_house_generic_medium_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_generic_medium_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_medium_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_general_medium_style_1",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_general_medium_style_1",
noBuildRadius = 0,
objectName = "@building_name:housing_general_medium_style_1",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_all_house_m_s01_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_generic_medium_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 4,
useStructureFootprintOutline = 0,
clientObjectCRC = 244814036,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_generic_medium_style_01, "object/building/player/shared_player_house_generic_medium_style_01.iff")
object_building_player_shared_player_house_generic_medium_style_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_generic_medium_style_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_medium_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_general_medium_style_2",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_general_medium_style_2",
noBuildRadius = 0,
objectName = "@building_name:housing_general_medium_style_2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_all_house_m_s02_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_generic_medium_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 3,
useStructureFootprintOutline = 0,
clientObjectCRC = 3581950019,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_generic_medium_style_02, "object/building/player/shared_player_house_generic_medium_style_02.iff")
object_building_player_shared_player_house_generic_small_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_generic_small_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_small_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_general_small_style_1",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_general_small_style_1",
noBuildRadius = 0,
objectName = "@building_name:housing_general_small_style_1",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_all_house_sm_s01_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_generic_small_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 4,
useStructureFootprintOutline = 0,
clientObjectCRC = 2431941445,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_generic_small_style_01, "object/building/player/shared_player_house_generic_small_style_01.iff")
object_building_player_shared_player_house_generic_small_style_01_floorplan_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_generic_small_style_01_floorplan_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_small_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_general_small_style_1_floorplan_2",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_general_small_style_1_floorplan_2",
noBuildRadius = 0,
objectName = "@building_name:housing_general_small_style_1_floorplan_2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_all_house_sm_s01_fp2.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_generic_small_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 4,
useStructureFootprintOutline = 0,
clientObjectCRC = 4015966289,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_generic_small_style_01_floorplan_02, "object/building/player/shared_player_house_generic_small_style_01_floorplan_02.iff")
object_building_player_shared_player_house_generic_small_style_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_generic_small_style_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_small_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_general_small_style_2",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_general_small_style_2",
noBuildRadius = 0,
objectName = "@building_name:housing_general_small_style_2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_all_house_sm_s02_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_generic_small_style_02.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 3,
useStructureFootprintOutline = 0,
clientObjectCRC = 1273222098,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_generic_small_style_02, "object/building/player/shared_player_house_generic_small_style_02.iff")
object_building_player_shared_player_house_generic_small_style_02_floorplan_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_generic_small_style_02_floorplan_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 38,
clientDataFile = "clientdata/building/shared_player_house_tatooine_small_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_general_small_style_2_floorplan_2",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_general_small_style_2_floorplan_2",
noBuildRadius = 0,
objectName = "@building_name:housing_general_small_style_2_floorplan_2",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_all_house_sm_s02_fp2.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_generic_small_style_02.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 2,
useStructureFootprintOutline = 0,
clientObjectCRC = 1748479865,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_generic_small_style_02_floorplan_02, "object/building/player/shared_player_house_generic_small_style_02_floorplan_02.iff")
object_building_player_shared_player_house_naboo_large_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_naboo_large_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 36,
clientDataFile = "clientdata/building/shared_player_house_tatooine_large_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_name:housing_naboo_large",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_naboo_style_1",
noBuildRadius = 0,
objectName = "@building_name:housing_naboo_large",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_nboo_house_lg_s01_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_naboo_large_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 14,
useStructureFootprintOutline = 0,
clientObjectCRC = 1926074883,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_naboo_large_style_01, "object/building/player/shared_player_house_naboo_large_style_01.iff")
object_building_player_shared_player_house_naboo_medium_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_naboo_medium_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 36,
clientDataFile = "clientdata/building/shared_player_house_tatooine_medium_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_name:housing_naboo_medium",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_naboo_style_1",
noBuildRadius = 0,
objectName = "@building_name:housing_naboo_medium",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_nboo_house_m_s01_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_naboo_medium_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 7,
useStructureFootprintOutline = 0,
clientObjectCRC = 1333906211,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_naboo_medium_style_01, "object/building/player/shared_player_house_naboo_medium_style_01.iff")
object_building_player_shared_player_house_naboo_small_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_naboo_small_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 36,
clientDataFile = "clientdata/building/shared_player_house_tatooine_small_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_name:housing_naboo_small",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_naboo_style_1",
noBuildRadius = 0,
objectName = "@building_name:housing_naboo_small",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_nboo_house_sm_s01_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_naboo_small_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 3,
useStructureFootprintOutline = 0,
clientObjectCRC = 1390503349,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_naboo_small_style_01, "object/building/player/shared_player_house_naboo_small_style_01.iff")
object_building_player_shared_player_house_naboo_small_style_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_naboo_small_style_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 36,
clientDataFile = "clientdata/building/shared_player_house_tatooine_small_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_name:housing_naboo_small",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_naboo_style_1",
noBuildRadius = 0,
objectName = "@building_name:housing_naboo_small",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_nboo_house_sm_s02_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_naboo_small_style_02.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 4,
useStructureFootprintOutline = 0,
clientObjectCRC = 2314652962,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_naboo_small_style_02, "object/building/player/shared_player_house_naboo_small_style_02.iff")
object_building_player_shared_player_house_tatooine_large_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_tatooine_large_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 36,
clientDataFile = "clientdata/building/shared_player_house_tatooine_large_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_tatt_style01_large",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_tatt_style01_large",
noBuildRadius = 0,
objectName = "@building_name:housing_tatt_style01_large",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_tato_house_lg_s01_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_tatooine_large_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 10,
useStructureFootprintOutline = 0,
clientObjectCRC = 3018624136,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_tatooine_large_style_01, "object/building/player/shared_player_house_tatooine_large_style_01.iff")
object_building_player_shared_player_house_tatooine_medium_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_tatooine_medium_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 36,
clientDataFile = "clientdata/building/shared_player_house_tatooine_medium_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_tatt_style01_med",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_tatt_style01_med",
noBuildRadius = 0,
objectName = "@building_name:housing_tatt_style01_med",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_tato_house_m_s01_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_tatooine_medium_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 8,
useStructureFootprintOutline = 0,
clientObjectCRC = 936693005,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_tatooine_medium_style_01, "object/building/player/shared_player_house_tatooine_medium_style_01.iff")
object_building_player_shared_player_house_tatooine_small_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_tatooine_small_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 36,
clientDataFile = "clientdata/building/shared_player_house_tatooine_small_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_tatt_style01_small",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_tatt_style01_small",
noBuildRadius = 0,
objectName = "@building_name:housing_tatt_style01_small",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_tato_house_sm_s01_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_tatooine_small_style_01.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 3,
useStructureFootprintOutline = 0,
clientObjectCRC = 2478865214,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_tatooine_small_style_01, "object/building/player/shared_player_house_tatooine_small_style_01.iff")
object_building_player_shared_player_house_tatooine_small_style_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_house_tatooine_small_style_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 36,
clientDataFile = "clientdata/building/shared_player_house_tatooine_small_style_01.cdf",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:housing_tatt_style01_small",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:housing_tatt_style01_small",
noBuildRadius = 0,
objectName = "@building_name:housing_tatt_style01_small",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_tato_house_sm_s02_fp1.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_player_house_tatooine_small_style_02.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 3,
useStructureFootprintOutline = 0,
clientObjectCRC = 1222103977,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_house_tatooine_small_style_02, "object/building/player/shared_player_house_tatooine_small_style_02.iff")
object_building_player_shared_player_merchant_tent_style_01 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_merchant_tent_style_01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 36,
clientDataFile = "",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:merchant_tent",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:merchant_tent",
noBuildRadius = 0,
objectName = "@building_name:merchant_tent",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_tato_merchant_tent_s01.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_merchant_tent.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 1,
useStructureFootprintOutline = 0,
clientObjectCRC = 2671747310,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_merchant_tent_style_01, "object/building/player/shared_player_merchant_tent_style_01.iff")
object_building_player_shared_player_merchant_tent_style_02 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_merchant_tent_style_02.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 36,
clientDataFile = "",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:merchant_tent",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:merchant_tent",
noBuildRadius = 0,
objectName = "@building_name:merchant_tent",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_corl_merchant_tent_s01.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_merchant_tent.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 1,
useStructureFootprintOutline = 0,
clientObjectCRC = 1143474297,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_merchant_tent_style_02, "object/building/player/shared_player_merchant_tent_style_02.iff")
object_building_player_shared_player_merchant_tent_style_03 = SharedBuildingObjectTemplate:new {
clientTemplateFileName = "object/building/player/shared_player_merchant_tent_style_03.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 36,
clientDataFile = "",
clientGameObjectType = 512,
collisionActionBlockFlags = 255,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "@building_detail:merchant_tent",
gameObjectType = 512,
interiorLayoutFileName = "",
locationReservationRadius = 0,
lookAtText = "@building_lookat:merchant_tent",
noBuildRadius = 0,
objectName = "@building_name:merchant_tent",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "appearance/ply_nboo_merchant_tent_s01.pob",
rangedIntCustomizationVariables = {},
scale = 0,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 0,
socketDestinations = {},
structureFootprintFileName = "footprint/building/player/shared_merchant_tent.sfp",
surfaceType = 2,
targetable = 0,
terrainModificationFileName = "",
totalCellNumber = 1,
useStructureFootprintOutline = 0,
clientObjectCRC = 220557300,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/building/base/shared_base_building.iff", "object/building/base/shared_base_player_building.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_building_player_shared_player_merchant_tent_style_03, "object/building/player/shared_player_merchant_tent_style_03.iff")
|
function onCreate()
-- background shit
makeLuaSprite('bg', 'mami/BG/MAMIGATION/BGSky', -500, -250);
setLuaSpriteScrollFactor('bg', 0.9, 0.9);
makeLuaSprite('placeholder', 'mami/BG/MAMIGATION/placeholder', -650, -250);
setLuaSpriteScrollFactor('placeholder', 0.9, 0.9);
addLuaSprite('bg', false);
addLuaSprite('placeholder', false);
close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage
end |
return {'giebel','giebelen','giechel','giechelen','giechelig','giegagen','giek','gienje','gier','gierbrug','gieren','gierennest','gierenoog','gierig','gierigaard','gierigheid','giering','gierkabel','gierkar','gierkelder','gierkuil','gierpomp','gierpont','gierput','gierst','gierstgras','gierstkorrel','giertank','giertij','gierton','giervalk','gierwagen','gierzwaluw','gietbeton','gietbui','gietcokes','gieteling','gieten','gieter','gieterij','gietermodus','gietgat','gietijzer','gietijzeren','gieting','gietinstallatie','gietlepel','gietlood','gietmachine','gietnaad','gietproces','gietsel','gietstaal','gietstuk','giettrechter','gietvorm','gietwerk','giethars','gietvloer','gietwater','gietmal','gierparelhoen','gietgal','gierle','giessenlanden','gieten','gielen','giesen','giel','gies','gieling','giesbers','giesberts','giezen','gielis','gielkens','gieskes','giesbergen','gieben','giele','gielissen','giepmans','giesbertz','gietema','giezenaar','gielink','giezeman','gieskens','gielisse','giesing','giebelend','giebelende','giebels','giebeltje','giebeltjes','giechelde','giechelden','giechelend','giechelt','gieken','gienjes','gierde','gierden','gierend','gierennesten','gierigaards','gierige','gieriger','gierigere','gierigst','gierigste','gieringen','gierpompen','gierponten','gierstkorrels','giert','giervalken','gierzwaluwen','giet','gietbuien','gietelingen','gieterijen','gieters','gietertje','gietertjes','gietgaten','gietingen','gietinstallaties','gietlepels','gietmachines','gietnaden','gietsels','gietstalen','gietstukken','gietvormen','giebelde','giechelende','giechelige','giechels','giegaagde','gierende','gierkabels','gierkarren','gierkelders','gierkuilen','giertonnen','gietende','gierbruggen','gierputten','giecheltje','giertanks','giels','gies','gietvloeren','gierstkorreltje','gierwagens','gietharsen','gietvormpjes'} |
-- Mostly from ChunkSpy. Used in loading chunks and converting them to different platforms.
local Configuration = {
["x86 standard"] = {
Description = "x86 Standard (32-bit, little endian, double)",
BigEndian = false, -- 1 = little endian
IntegerSize = 4, -- (data type sizes in bytes)
SizeT = 4,
InstructionSize = 4,
NumberSize = 8, -- this & integral identifies the
IsFloatingPoint = true, -- (0) type of lua_Number
NumberType = "double", -- used for lookups
},
["big endian int"] = {
Description = "(32-bit, big endian, int)",
BigEndian = true,
IntegerSize = 4,
SizeT = 4,
InstructionSize = 4,
NumberSize = 4,
IsFloatingPoint = false,
NumberType = "int",
},
["amd64"] = {
Description = "AMD64 (64-bit, little endian, double)",
BigEndian = false,
IntegerSize = 4,
SizeT = 8,
InstructionSize = 4,
NumberSize = 8,
IsFloatingPoint = true,
NumberType = "double",
},
-- you can add more platforms here
}
local ConvertFrom = {}
local ConvertTo = {}
local function grab_byte(v)
return math.floor(v / 256), string.char(math.floor(v) % 256)
end
-----------------------------------------------------------------------
-- No more TEST_NUMBER in Lua 5.1, uses size_lua_Number + integral
-- LuaFile.NumberSize .. (LuaFile.IsFloatingPoint and 0 or 1)
-----------------------------------------------------------------------
LuaNumberID = {
["80"] = "double", -- IEEE754 double
["40"] = "single", -- IEEE754 single
["41"] = "int", -- int
["81"] = "long long", -- long long
}
-- Converts an 8-byte little-endian string to a IEEE754 double number
ConvertFrom["double"] = function(x)
local sign = 1
local mantissa = string.byte(x, 7) % 16
for i = 6, 1, -1 do mantissa = mantissa * 256 + string.byte(x, i) end
if string.byte(x, 8) > 127 then sign = -1 end
local exponent = (string.byte(x, 8) % 128) * 16 +
math.floor(string.byte(x, 7) / 16)
if exponent == 0 then return 0 end
mantissa = (math.ldexp(mantissa, -52) + 1) * sign
return math.ldexp(mantissa, exponent - 1023)
end
-- Converts a 4-byte little-endian string to a IEEE754 single number
ConvertFrom["single"] = function(x)
local sign = 1
local mantissa = string.byte(x, 3) % 128
for i = 2, 1, -1 do mantissa = mantissa * 256 + string.byte(x, i) end
if string.byte(x, 4) > 127 then sign = -1 end
local exponent = (string.byte(x, 4) % 128) * 2 +
math.floor(string.byte(x, 3) / 128)
if exponent == 0 then return 0 end
mantissa = (math.ldexp(mantissa, -23) + 1) * sign
return math.ldexp(mantissa, exponent - 127)
end
-- Converts a little-endian integer string to a number
ConvertFrom["int"] = function(x)
local sum = 0
for i = 4, 1, -1 do
sum = sum * 256 + string.byte(x, i)
end
-- test for negative number
if string.byte(x, 4) > 127 then
sum = sum - math.ldexp(1, 8 * 4)
end
return sum
end
-- WARNING this will fail for large long longs (64-bit numbers)
-- because long longs exceeds the precision of doubles.
ConvertFrom["long long"] = ConvertFrom["int"]
-- Converts a IEEE754 double number to an 8-byte little-endian string
ConvertTo["double"] = function(x)
local sign = 0
if x < 0 then sign = 1; x = -x end
local mantissa, exponent = math.frexp(x)
if x == 0 then -- zero
mantissa, exponent = 0, 0
else
mantissa = (mantissa * 2 - 1) * math.ldexp(0.5, 53)
exponent = exponent + 1022
end
local v, byte = "" -- convert to bytes
x = mantissa
for i = 1,6 do
x, byte = grab_byte(x); v = v..byte -- 47:0
end
x, byte = grab_byte(exponent * 16 + x); v = v..byte -- 55:48
x, byte = grab_byte(sign * 128 + x); v = v..byte -- 63:56
return v
end
-- Converts a IEEE754 single number to a 4-byte little-endian string
ConvertTo["single"] = function(x)
local sign = 0
if x < 0 then sign = 1; x = -x end
local mantissa, exponent = math.frexp(x)
if x == 0 then -- zero
mantissa = 0; exponent = 0
else
mantissa = (mantissa * 2 - 1) * math.ldexp(0.5, 24)
exponent = exponent + 126
end
local v, byte = "" -- convert to bytes
x, byte = grab_byte(mantissa); v = v..byte -- 7:0
x, byte = grab_byte(x); v = v..byte -- 15:8
x, byte = grab_byte(exponent * 128 + x); v = v..byte -- 23:16
x, byte = grab_byte(sign * 128 + x); v = v..byte -- 31:24
return v
end
-- Converts a number to a little-endian integer string
ConvertTo["int"] = function(x)
local v = ""
x = math.floor(x)
if x >= 0 then
for i = 1, 4 do
v = v..string.char(x % 256); x = math.floor(x / 256)
end
else-- x < 0
x = -x
local carry = 1
for i = 1, 4 do
local c = 255 - (x % 256) + carry
if c == 256 then c = 0; carry = 1 else carry = 0 end
v = v..string.char(c); x = math.floor(x / 256)
end
end
-- optional overflow test; not enabled at the moment
-- if x > 0 then error("number conversion overflow") end
return v
end
-- WARNING this will fail for large long longs (64-bit numbers)
-- because long longs exceeds the precision of doubles.
ConvertTo["long long"] = ConvertTo["int"]
local function GetNumberType(file)
local nt = LuaNumberID[file.NumberSize .. (file.IsFloatingPoint and 0 or 1)]
if not nt then
error("Unable to determine Number type")
end
return ConvertFrom[nt], ConvertTo[nt]
end
return GetNumberType
|
-------------------------------------------------------------------------------
-- For Daddy Darker By Crackpotx (US, Lightbringer)
-------------------------------------------------------------------------------
local DD = LibStub("AceAddon-3.0"):NewAddon("DaddyDarker", "AceConsole-3.0", "AceEvent-3.0")
-- local api cache
local C_PartyInfo_InviteUnit = C_PartyInfo.InviteUnit
local GetAddOnMetadata = _G["GetAddOnMetadata"]
local UnitName = _G["UnitName"]
DD.title = GetAddOnMetadata("DaddyDarker", "Title")
DD.version = GetAddOnMetadata("DaddyDarker", "Version")
local defaults = {
global = {
inviting = false,
players = {}
}
}
local function FindInArray(toFind, arraySearch)
if #arraySearch == 0 then return false end
for _, value in pairs(arraySearch) do
if value == toFind then
return true
end
end
return false
end
function DD:Print(msg)
print(("|cffC41F3BDaddyDarker|r |cffffffff%s|r"):format(msg))
end
function DD:CHAT_MSG_GUILD(evemt, msg, player, ...)
local temp = {strsplit("-", player)}
local playerName = temp[1]
if self.db.global.inviting and msg:match("[xX]+") and playerName:lower() ~= UnitName("player"):lower() and not FindInArray(playerName:lower(), self.db.global.players) then
self:Print(("Inviting %s"):format(playerName))
C_PartyInfo_InviteUnit(playerName)
self.db.global.players[#self.db.global.players + 1] = playerName:lower()
end
end
function DD:OnEnable()
self:RegisterEvent("CHAT_MSG_GUILD")
end
function DD:OnDisable()
self:UnregisterEvent("CHAT_MSG_GUILD")
end
function DD:OnInitialize()
self.db = LibStub("AceDB-3.0"):New("DaddyDarkerDB", defaults)
self:RegisterChatCommand("darker", function(args)
self.db.global.inviting = not self.db.global.inviting
self:Print(self.db.global.inviting and "Raid invites have started!" or "Raid invites have stopped!")
if self.db.global.inviting then
SendChatMessage("Type XX for a raid invite!", "GUILD")
else
self.db.global.players = {}
end
end)
end |
return {'ulaan','ulaanbaatar','ulanen'} |
return class("ENV2MainPage", import(".TemplatePage.PreviewTemplatePage"))
|
local lush = require('lush')
local hsl = lush.hsl
if (false) then
-- do something
return true == true
end
return {
dark0_hard = hsl("#0c0a0d"),
dark0 = hsl("#2C2431"),
dark0_soft = hsl("#3C3143"),
dark1 = hsl("#44374C"),
dark2 = hsl("#483A51"),
dark3 = hsl("#483A51"),
dark4 = hsl("#4B3D55"),
light0_hard = hsl("#f5efed"),
light0 = hsl("#e0d9da"),
light0_soft = hsl("#cbc3c7"),
light1 = hsl("#a096a1"),
light2 = hsl("#766a7b"),
light3 = hsl("#615468"),
light4 = hsl("#4b3d55"),
primary0 = hsl("#cf3b3d"),
primary1 = hsl("#FFD670"),
accent0 = hsl("#7F7EFF"),
accent1 = hsl("#A390E4"),
error = hsl("#CF3B3D"),
info = hsl("#23967F"),
hint = hsl("#00C2D1"),
warn = hsl("#FFD670"),
}
|
-- Creating Orocos component for ABB Yumi robot
require("rttlib")
require("rttros")
rtt.setLogLevel("Warning")
rttlib.color = true
gs=rtt.provides()
tc=rtt.getTC()
if tc:getName() == "lua" then
depl=tc:getPeer("Deployer")
elseif tc:getName() == "Deployer" then
depl=tc
end
depl:import("rtt_ros")
ros = gs:provides("ros")
ros:import("rtt_rospack")
depl:import("abb_libegm") |
--[[
TQAE - Tiny QuickApp emulator for the Fibaro Home Center 3
Copyright (c) 2021 Jan Gabrielsson
Email: [email protected]
MIT License
Creating UI elements for emulated QA (Web UI) and HC3 procy
--]]
local EM,FB = ...
local json,DEBUG,Devices = FB.json,EM.DEBUG,EM.Devices
local format = string.format
local traverse,copy = EM.utilities.traverse,EM.utilities.copy
local function map(f,l) for _,v in ipairs(l) do f(v) end end
local ELMS = {
button = function(d,w)
return {name=d.name,style={weight=d.weight or w or "0.50"},text=d.text,type="button"}
end,
select = function(d,w)
if d.options then map(function(e) e.type='option' end,d.options) end
return {name=d.name,style={weight=d.weight or w or "0.50"},text=d.text,type="select", selectionType='single',
options = d.options or {{value="1", type="option", text="option1"}, {value = "2", type="option", text="option2"}},
values = d.values or { "option1" }
}
end,
multi = function(d,w)
if d.options then map(function(e) e.type='option' end,d.options) end
return {name=d.name,style={weight=d.weight or w or "0.50"},text=d.text,type="select", selectionType='multi',
options = d.options or {{value="1", type="option", text="option2"}, {value = "2", type="option", text="option3"}},
values = d.values or { "option3" }
}
end,
image = function(d,_)
return {name=d.name,style={dynamic="1"},type="image", url=d.url}
end,
switch = function(d,w)
return {name=d.name,style={weight=w or d.weight or "0.50"},type="switch", value=d.value or "true"}
end,
option = function(d,_)
return {name=d.name, type="option", value=d.value or "Hupp"}
end,
slider = function(d,w)
return {name=d.name,step=tostring(d.step),value=tostring(d.value),max=tostring(d.max),min=tostring(d.min),style={weight=d.weight or w or "1.2"},text=d.text,type="slider"}
end,
label = function(d,w)
return {name=d.name,style={weight=d.weight or w or "1.2"},text=d.text,type="label"}
end,
space = function(_,w)
return {style={weight=w or "0.50"},type="space"}
end
}
local function mkRow(elms,weight)
local comp = {}
if elms[1] then
local c = {}
local width = format("%.2f",1/#elms)
if width:match("%.00") then width=width:match("^(%d+)") end
for _,e in ipairs(elms) do c[#c+1]=ELMS[e.type](e,width) end
if #elms > 1 then comp[#comp+1]={components=c,style={weight="1.2"},type='horizontal'}
else comp[#comp+1]=c[1] end
comp[#comp+1]=ELMS['space']({},"0.5")
else
comp[#comp+1]=ELMS[elms.type](elms,"1.2")
comp[#comp+1]=ELMS['space']({},"0.5")
end
return {components=comp,style={weight=weight or "1.2"},type="vertical"}
end
local function mkViewLayout(list,height)
local items = {}
for _,i in ipairs(list) do items[#items+1]=mkRow(i) end
-- if #items == 0 then return nil end
return
{ ['$jason'] = {
body = {
header = {
style = {height = tostring(height or #list*50)},
title = "quickApp_device_23"
},
sections = {
items = items
}
},
head = {
title = "quickApp_device_23"
}
}
}
end
local function transformUI(UI) -- { button=<text> } => {type="button", name=<text>}
traverse(UI,
function(e)
if e.button then e.name,e.type,e.onReleased=e.button,'button',e.onReleased or e.f; e.f=nil
elseif e.slider then e.name,e.type,e.onChanged=e.slider,'slider',e.onChanged or e.f; e.f=nil
elseif e.select then e.name,e.type=e.select,'select'
elseif e.switch then e.name,e.type=e.switch,'switch'
elseif e.multi then e.name,e.type=e.multi,'multi'
elseif e.option then e.name,e.type=e.option,'option'
elseif e.image then e.name,e.type=e.image,'image'
elseif e.label then e.name,e.type=e.label,'label'
elseif e.space then e.weight,e.type=e.space,'space' end
end)
return UI
end
local function uiStruct2uiCallbacks(UI)
local cb = {}
traverse(UI,
function(e)
if e.name then
-- {callback="foo",name="foo",eventType="onReleased"}
local defu = e.button and "Clicked" or e.slider and "Change" or (e.switch or e.select) and "Toggle" or ""
local deff = e.button and "onReleased" or e.slider and "onChanged" or (e.switch or e.select) and "onToggled" or ""
local cbt = e.name..defu
if e.onReleased then
cbt = e.onReleased
elseif e.onChanged then
cbt = e.onChanged
elseif e.onToggled then
cbt = e.onToggled
end
if e.button or e.slider or e.switch or e.select then
cb[#cb+1]={callback=cbt,eventType=deff,name=e.name}
end
end
end)
return cb
end
local function collectViewLayoutRow(u,map)
local row = {}
local function conv(u)
if type(u) == 'table' then
if u.name then
if u.type=='label' then
row[#row+1]={label=u.name, text=u.text}
elseif u.type=='button' then
local cb = map["button"..u.name]
if cb == u.name.."Clicked" then cb = nil end
row[#row+1]={button=u.name, text=u.text, onReleased=cb}
elseif u.type=='slider' then
local cb = map["slider"..u.name]
if cb == u.name.."Clicked" then cb = nil end
row[#row+1]={slider=u.name, text=u.text, onChanged=cb}
end
else
for _,v in pairs(u) do conv(v) end
end
end
end
conv(u)
return row
end
local function viewLayout2UI(u,map)
local function conv(u)
local rows = {}
for _,j in pairs(u.items) do
local row = collectViewLayoutRow(j.components,map)
if #row > 0 then
if #row == 1 then row=row[1] end
rows[#rows+1]=row
end
end
return rows
end
return conv(u['$jason'].body.sections)
end
local function view2UI(view,callbacks)
local map = {}
traverse(callbacks,function(e)
if e.eventType=='onChanged' then map["slider"..e.name]=e.callback
elseif e.eventType=='onReleased' then map["button"..e.name]=e.callback end
end)
local UI = viewLayout2UI(view,map)
return UI
end
local function dumpQAui(id)
local d = FB.api.get("/devices/"..id)
local UI = view2UI(d.properties.viewLayout,d.properties.uiCallbacks)
local fmt = string.format
local function luaStr(e)
local b = {}
if e[1] then
local b2={}
for _,e2 in ipairs(e) do b2[#b2+1]=luaStr(e2) end
b[#b+1]=table.concat(b2,",")
else
local r = {}
for k,v in pairs(e) do r[#r+1]={k,v} end
table.sort(r,function(a,b) return a[1]<b[1] end)
for _,k in ipairs(r) do b[#b+1]=fmt("%s=%s",k[1],tonumber(k[2]) and k[2] or '"'..k[2]..'"') end
end
return "{"..table.concat(b,",").."}"
end
for i,e in ipairs(UI) do
print(fmt("--%%u%d=%s",i,luaStr(e)))
end
end
local customUI = {}
customUI['com.fibaro.binarySwitch'] =
{{{button='__turnon', text="Turn On",onReleased="turnOn"},{button='__turnoff', text="Turn Off",onReleased="turnOff"}}}
customUI['com.fibaro.multilevelSwitch'] =
{{{button='__turnon', text="Turn On",onReleased="turnOn"},{button='__turnoff', text="Turn Off",onReleased="turnOff"}},
{label='_Brightness', text='Brightness'},
{slider='__value', min=0, max=99, onChanged='setValue'},
{
{button='__sli', text="⇧",onReleased="startLevelIncrease"},
{button='__sld', text="⇩",onReleased="startLevelIncrease"},
{button='__sls', text="‖",onReleased="stopLevelChange"},
}
}
--customUI['com.fibaro.binarySensor'] = customUI['com.fibaro.binarySwitch'] -- For debugging
--customUI['com.fibaro.multilevelSensor'] = customUI['com.fibaro.multilevelSwitch'] -- For debugging
customUI['com.fibaro.colorController'] =
{{{button='__turnon', text="Turn On",onReleased="turnOn"},{button='__turnoff', text="Turn Off",onReleased="turnOff"}},
{label='_Brightness', text='Brightness'},
{slider='__value', min=0, max=99, onChanged='setValue'},
{
{button='__sli', text="⇧",onReleased="startLevelIncrease"},
{button='__sld', text="⇩",onReleased="startLevelIncrease"},
{button='__sls', text="‖",onReleased="stopLevelChange"},
}
}
local initElm = {
['button'] = function(e,qa) qa:updateView(e.button,'text',e.text) end,
['slider'] = function(e,qa) qa:updateView(e.slider,'value',e.value or 0) end,
['label'] = function(e,qa) qa:updateView(e.label,'text',e.text) end,
}
function EM.addUI(info)
local dev = info.dev
local defUI = (not info.UI and customUI[dev.type] or customUI[dev.baseType or ""]) or {}
if dev.properties.viewLayout then
info.UI = view2UI(dev.properties.viewLayout or {},dev.properties.uiCallbacks or {}) or {}
end
local cmbUI = {}
for _,e in ipairs(copy(defUI)) do cmbUI[#cmbUI+1]=e end
for _,e in ipairs(copy(info.UI or {})) do cmbUI[#cmbUI+1]=e end
if next(cmbUI)~=nil then
transformUI(cmbUI)
dev.properties.viewLayout = mkViewLayout(cmbUI)
dev.properties.uiCallbacks = uiStruct2uiCallbacks(cmbUI)
info.UI=cmbUI
end
if not dev.properties.viewLayout then -- No UI
info.UI = {}
dev.properties.viewLayout= json.decode(
[[{"$jason":{"body":{"header":{"style":{"height":"0"},"title":"quickApp_device_403"},"sections":{"items":[]}},"head":{"title":"quickApp_device_403"}}}]]
)
dev.properties.uiCallbacks = {}
end
end
EM.EMEvents('QACreated',function(ev) -- Intercept QA created and add viewLayout and uiCallbacks
local qa,dev = ev.qa,ev.dev
local info = Devices[qa.id]
DEBUG("ui","sys","ui.lua inspecting QA:%s",qa.name)
if info == nil and dev.parentId and dev.parentId > 0 then -- This is where we create the child device - not good!
local p = Devices[dev.parentId]
info = {dev = dev, env = p.env, childProxy=p.proxy, timers=p.timers, lock=p.lock }
EM.addUI(info)
EM.installDevice(info)
end
for _,r in ipairs(info.UI or {}) do
r = r[1] and r or {r}
for _,c in ipairs(r) do
if initElm[c.type] then initElm[c.type](c,qa) end
end
end
--end,0)
end,true)
EM.UI = {}
EM.UI.uiStruct2uiCallbacks = uiStruct2uiCallbacks
EM.UI.transformUI = transformUI
EM.UI.mkViewLayout = mkViewLayout
EM.UI.view2UI = view2UI
EM.UI.dumpQAui = dumpQAui
|
local Tile = require 'src.world.tiles.Tile'
local Glass = class(..., Tile)
function Glass:initialize(cell)
Tile.initialize(self,cell,4,1)
self.solid = true
end
return Glass
|
--
-- Created by IntelliJ IDEA.
-- User: xinzhang
-- Date: 11/08/2017
-- Time: 12:04 AM
-- To change this template use File | Settings | File Templates.
--
require 'class'
require 'constant'
Shop = class(function (self, winterRate, winterServiceCharge, summerRate)
self.winterRate = winterRate;
self.winterServiceCharge = winterServiceCharge;
self.summerRate = summerRate;
end)
function Shop:__tostring()
return string.format('winterRate: %s \nwinterServiceCharge: %s \nsummerRate: %s',
self.winterRate, self.winterServiceCharge, self.summerRate)
end
function Shop:isNotSummer(date)
return date < SUMMER_START or date > SUMMER_END;
end
function Shop:winterCharge(quantity)
return quantity * self.winterRate + self.winterServiceCharge;
end
function Shop:summerCharge(quantity)
return quantity * self.summerRate;
end
function Shop:getCharge(date, quantity)
if self:isNotSummer(date) then
return self:winterCharge(quantity);
end
return self:summerCharge(quantity);
end
|
-- 2D Collision-detection library
local bump = require 'lib.bump'
local Camera = require 'lib.Camera'
local tween = require 'lib.tween'
local Gamestate = require 'lib.gamestate'
local endscreen = require 'scenes.endscreen'
local endbox = require 'endbox'
local mapdata = require 'mapdata'
local player = require 'player'
local world = nil
local currentMap = 'red'
local currentWalls = {}
local font = love.graphics.newFont("asset/fonts/Sniglet-Regular.ttf", 35)
local levelLogic = {}
local levels = { 'tutorial', 'level1', 'level2', 'level3', 'level4' }
local currentLevel = 1
local src = love.audio.newSource('asset/bgm/roots.mp3', 'stream')
local t = nil
local text = {x = 0, y = 7 * 32, alp = 0, fadeIn = false}
-- image data
local imageData = { redSquare = nil }
local function getCurrentColour(currentMap)
if currentMap == 'red' then
return 0.87058,0.14117,0.41568,0.89411,0.28235,0.50980
elseif currentMap == 'blue' then
return 0.24705,0.68235,0.98823,0.57647,0.82352,1
elseif currentMap == 'yellow' then
return 0.59215,0.34509,0.76078,0.72156,0.50980,0.86666
elseif currentMap == 'green' then
return 0.22745,0.96078,0.62745,0.41960,0.97254,0.71764
end
end
local function getCurrentBackgroundColour(currentMap)
if currentMap == 'red' then
return 1,0.62745,0.62745
elseif currentMap == 'blue' then
return 0.77254,0.90588,1
elseif currentMap == 'yellow' then
return 0.78431,0.60392,0.90588
elseif currentMap == 'green' then
return 0.61176,0.98431,0.81568
end
end
local function renderMap(currentMap,nextMap)
love.graphics.setColor(1,1,1,1)
r,g,b,r2,g2,b2 = getCurrentColour(currentMap)
rb, gb, bb = getCurrentBackgroundColour(currentMap)
for mapx=1,mapdata.getMapWidth(nextMap) do
for mapy=1,mapdata.getMapHeight(nextMap) do
local tile = mapdata.getTileAt(nextMap, mapx, mapy)
if tile == true then
love.graphics.setColor(r2,g2,b2,1)
love.graphics.rectangle("fill", mapx*32, mapy*32,32,32)
end
end
end
for mapx=1,mapdata.getMapWidth(currentMap) do
for mapy=1,mapdata.getMapHeight(currentMap) do
local tile = mapdata.getTileAt(currentMap, mapx, mapy)
if tile == true then
love.graphics.setBackgroundColor(rb,gb,bb)
love.graphics.setColor(r,g,b,1)
love.graphics.rectangle("fill", mapx*32, mapy*32,32,32)
end
end
end
end
local function addWalls()
for mapx=1,(mapdata.getMapWidth(currentMap)) do
for mapy=1,mapdata.getMapHeight(currentMap) do
local tile = mapdata.getTileAt(currentMap, mapx, mapy)
if tile == true then
local wall = {x= mapx*32, y= mapy*32, w=32, h=32}
world:add(wall, wall.x, wall.y, wall.w, wall.h)
table.insert(currentWalls, wall)
end
end
end
end
local function removeMap()
for i=1, #currentWalls do
local wall = currentWalls[i]
world:remove(wall)
end
currentWalls = {}
end
local function nextMap(prevMap)
if prevMap == 'red' then
return 'blue'
elseif prevMap == 'blue' then
return 'yellow'
elseif prevMap == 'yellow' then
return 'green'
elseif prevMap == 'green' then
return 'red'
end
end
local function switchMap()
removeMap()
currentMap = nextMap(currentMap)
addWalls()
end
local function isInWall(map, x, y)
local playerTileX = math.floor(x / 32)
local playerTileY = math.floor(y /32)
return mapdata.getTileAt(map, playerTileX, playerTileY)
end
function levelLogic:enter()
imageData.redSquare = love.graphics.newImage('asset/img/square_red.png')
imageData.blueSquare = love.graphics.newImage('asset/img/square_blue.png')
imageData.greenSquare = love.graphics.newImage('asset/img/square_green.png')
imageData.yellowSquare = love.graphics.newImage('asset/img/square_yellow.png')
imageData.piggySheet = love.graphics.newImage('asset/img/piggysheet.png')
src:setLooping(true)
src:play()
love.graphics.setFont(font)
camera = Camera()
camera:setDeadzone(love.graphics.getWidth() / 2, love.graphics.getHeight() / 2, 0, 0)
camera:setFollowLerp(0.2)
player.spriteSheet = imageData.piggySheet
mapdata.loadLevel(levels[currentLevel])
world = bump.newWorld()
local wallOfDeath = {x=0,y=0,w=32,h=32*15}
world:add(wallOfDeath, wallOfDeath.x, wallOfDeath.y, wallOfDeath.w, wallOfDeath.h)
world:add(player, player.x, player.y, player.w, player.h)
world:add(endbox, endbox.x, endbox.y, endbox.w, endbox.h)
addWalls()
end
local function nextLevel()
world:remove(player)
removeMap()
currentMap = 'red'
player.resetPlayer()
currentLevel = currentLevel + 1
if currentLevel > #levels then
src:stop()
currentLevel = 1
Gamestate.switch(endscreen)
else
Gamestate.switch(levelLogic)
end
end
local function checkCollisions(dx,dy)
deltaX, deltaY, collisions, numberofcollisions = world:move(player, player.x + dx, player.y + dy)
player.x = deltaX
player.y = deltaY
for i=1, numberofcollisions do
local collision = collisions[i]
if collision.other == endbox then
nextLevel()
end
end
end
function levelLogic:update(dt)
local dx, dy = player.updatePlayer(dt)
camera:update(dt)
camera:follow(love.graphics.getWidth() / 2, love.graphics.getHeight() / 2)
checkCollisions(dx,dy)
if t ~= nil then
local completed = t:update(dt)
if completed and text.fadeIn then
t = tween.new(1, text, {alp=0}, 'linear')
text.fadeIn = false
end
end
end
function levelLogic:draw()
camera:attach()
renderMap(currentMap, nextMap(currentMap))
love.graphics.setColor(1,1,1)
player.drawPlayer()
endbox.draw()
love.graphics.setColor(1, 1, 1, text.alp)
love.graphics.printf("Careful where you press the spacebar!", text.x, text.y, love.graphics.getWidth(), 'center')
camera:detach()
end
local function tryToSwitchMap()
playerTopLeft = isInWall(nextMap(currentMap), player.x + 0.5, player.y + 0.5)
playerTopRight = isInWall(nextMap(currentMap), (player.x + player.w) - 0.5, player.y + 0.5)
playerBottomLeft = isInWall(nextMap(currentMap), player.x + 0.5, (player.y + player.h) - 0.5)
playerBottomRight = isInWall(nextMap(currentMap), (player.x + player.w) - 0.5, (player.y + player.h) - 0.5)
if not (playerTopLeft or playerTopRight or playerBottomLeft or playerBottomRight) then
switchMap()
else
camera:shake(3.5, 1, 60)
if currentLevel == 1 then
t = tween.new(2, text, {alp=1}, 'linear')
text.fadeIn = true
end
end
end
function levelLogic:keypressed(key)
if key == "space" then
tryToSwitchMap()
end
end
function levelLogic:joystickpressed( joystick, button )
if button == 1 then
tryToSwitchMap()
end
end
return levelLogic |
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by shuieryin.
--- DateTime: 12/01/2018 4:20 PM
---
function gradientDescent(X, y, theta, alpha, num_iters)
--GRADIENTDESCENT Performs gradient descent to learn theta
-- theta = GRADIENTDESCENT(X, y, theta, alpha, num_iters) updates theta by
-- taking num_iters gradient steps with learning rate alpha
-- Initialize some useful values
local m = length(y) -- number of training examples
local J_history = {}
for iter = 1, num_iters do
-- ====================== YOUR CODE HERE ======================
-- Instructions: Perform a single gradient step on the parameter vector
-- theta.
--
-- Hint: While debugging, it can be useful to print out the values
-- of the cost function (computeCost) and gradient here.
--
-- ============================================================
-- Save the cost J in every iteration
J_history[#J_history + 1] = computeCost(X, y, theta)
end
return theta, J_history
end |
local Avatar = require("graphic.avatar.Avatar")
local Spine = class("Spine", Avatar)
function Spine:ctor()
Avatar.ctor(self)
end
function Spine:createGameObject()
local name = getmetatable(self).__className
self._go = g_2dTools:createGameObject(name)
end
function Spine:initController(go)
local controller = go:GetComponent(typeof(CS.Spine.Unity.SkeletonAnimation))
self._controller = require("graphic.spine.SpineController").create()
self._controller:init(controller)
-- self._controller:setActConfig(resAlias.spine["test"]["act"])
self._controller:setFrameKeyHandler(handler(self, self.handleKeyFrame))
self._avatarGo = go
end
function Spine:handleKeyFrame(actName, keyName, data)
print("handleKeyFrame ==> ",actName,keyName)
end
return Spine
|
-- title: palette demo
-- author: Nesbox
-- desc: how to switch palatte in runtime
-- script: lua
-- input: gamepad
local W=240
local H=136
-- palette address
local ADDR=0x3FC0
local PALETTES =
{
{name="SWEETIE-16", data="1a1c2c5d275db13e53ef7d57ffcd75a7f07038b76425717929366f3b5dc941a6f673eff7333c57566c8694b0c2f4f4f4"},
{name="DB16", data="140c1c44243430346d4e4a4e854c30346524d04648757161597dced27d2c8595a16daa2cd2aa996dc2cadad45edeeed6"},
{name="PICO-8", data="0000007e25531d2b535f574fab5236008751ff004d83769cff77a8ffa300c2c3c700e756ffccaa29adfffff024fff1e8"},
{name="ARNE16", data="0000001b2632005784493c2ba4642244891abe26332f484e31a2f2eb89319d9d9da3ce27e06f8bb2dceff7e26bffffff"},
{name="EDG16", data="193d3f3f2832743f399e2835b86f50327345e53b444f67810484d1fb922bafbfd263c64de4a6722ce8f4ffe762ffffff"},
{name="A64", data="0000004c3435313a9148545492562b509450b148638080787655a28385cf9cabb19ccc47cd93738fbfd5bbc840ede6c8"},
{name="C64", data="00000057420040318d5050508b542955a0498839327878788b3f967869c49f9f9f94e089b8696267b6bdbfce72ffffff"},
{name="VIC20", data="000000772d2642348ba85fb4b668627e70caa8734a559e4ae99df5e9b287bdcc7185d4dc92df87c5ffffffffb0ffffff"},
{name="CGA", data="000000aa00000000aa555555aa550000aa00ff5555aaaaaa5555ffaa00aa00aaaa55ff55ff55ff55ffffffff55ffffff"},
{name="SLIFE", data="0000001226153f28117a2222513155d13b27286fb85d853acc8218e07f8a9b8bff68c127c7b581b3e868a8e4d4ffffff"},
{name="JMP", data="000000191028833129453e78216c4bdc534b7664fed365c846af45e18d79afaab9d6b97b9ec2e8a1d685e9d8a1f5f4eb"},
{name="CGARNE", data="0000002234d15c2e788a36225e606e0c7e45e23d69aa5c3d4c81fb44aacceb8a60b5b5b56cd9477be2f9ffd93fffffff"},
{name="PSYG", data="0000001b1e29003308362747084a3c443f41a2324e52524c546a0073615064647c516cbf77785be08b799ea4a7cbe8f7"},
{name="EROGE", data="0d080d2a23494f2b247d384032535f825b314180a0c16c5bc591547bb24e74adbbe89973bebbb2f0bd77fbdf9bfff9e4"},
{name="EISLAND", data="051625794765686086567864ca657e8686918184abcc8d867ea78839d4b98dbcd29dc085edc38de6d1d1f5e17af6f6bf"},
}
local t=0
local index=1
-- update palette
function updpal()
local pal=PALETTES[index].data
for i=1,#pal,2 do
poke(ADDR+i//6*3+i//2%3,tonumber(pal:sub(i,i+1),16))
end
end
updpal()
function TIC()
-- handle input
if btnp(0,20,5) and index>1 then
index=index-1
updpal()
end
if btnp(1,20,5) and index<#PALETTES then
index=index+1
updpal()
end
if btnp(4)or btnp(5)then exit()end
-- draw
cls(15)
print("SELECT PALETTE",6,6,0)
for i,v in pairs(PALETTES) do
print(v.name,12,12+i*6,0)
end
print(">",6+(t//16%2),12+index*6,0)
local S=12
-- draw palette
for i=0,16-1 do
for j=0,S-1 do
line(W-j-i*S,H,W,H-j-i*S,i)
end
end
t=t+1
end
-- <PALETTE>
-- 000:140c1c44243430346d4e4a4e854c30346524d04648757161597dced27d2c8595a16daa2cd2aa996dc2cadad45edeeed6
-- </PALETTE>
-- <COVER>
-- 000:c99000007494648373160f0088003b000041c0c14442430343d6e4a4e458c4034356420d648457171695d7ec2dd7c258591ad6aac22daa99d62cacad4de5edee6dc2000000000f0088000040ff0f9c94badb83bedcbbff0682e87936e98a9dcac6bb2307c23cb4d6f246eafec7feff89490d1ea26366846cde60c6a3f90d82768923ab293b5235acdea7fbd1a2acad2cac4bb50ba7dce6a8f446699368e47bfe8fcf6edaa8f17ea4576371005800f0685888783198c8682198512919a8b841e8b8a82999a7e9b7c7e7f7372863a061095989c8aad8f8daba1979883b0b0b6969f9ab141ae708185aa07a8a8b9a9ba9f8ca6bda788b5b8cea1d0dbb4d21c744eb085a532c3c4cdcac7c2efafc595c093e39ca5c5dde7d2afbbdb0ddedea7eb9c9499a5efcec99d99bee92b6787ed56325bd8e5d328c0b1a7038172e52458e0b2a54e5f60e96b9841f2a74b801ff9c84c06a058d7c39c034a591928a46734903779a432c2be8bc79133761ce5117329cb9b057a0de233b84d4430417e4a557f4a96a1a057241db2e3b5625509003cab75ef8d54d8a35bc455b97531465dacc6adc2a4f5376859336196953b863da3b5b4ead2ac7bf22ea69ba85dce9d5a6f2953d7aa77f2f419e7790061c4731b4611c77499197f812f0ec0afc850c366f62bcc5cb2b1fd8cca993cd5fa0e465c2a52a5f45e3af77ea6edca59c975bb7e26bc62d43d4b92bd7b55fe36db65d9b6fdc666b07e64cb8f6817dbdc1120dccfb83748f318ede4d9d99f6fbcc1dbf778cd1c332708b570687823e1b06e8efd1181795d5b95fbddfe5a4cf423f5257e1ff46808d73d175802a37c916ee5f7f3cf7844086ed089041860a60ff876790868c938e600764d373f0d77b95871276802e7902e35d978f028845177659084165862ab80514895497735d863ed870a28f9de6bf0e8048e8760f8e29f862a587f943da586cf819d30294782952139d46186cda715e164565903a852329543258b5a3970eb6f5233975899385943069a096996e989b909de183d22c9428c90ccc831e0877aa9e7a3408a48d36d858a1a81e09fad1a74e890759927d994863a80c10f464925a4ae342a472d36761a7007ab62d2d91c60a2f02a677b82a9a9e9a8ae3aa0aa8546ba32cba286ca9963a4b6da82ab69b638abe70cba9938e97a9e6a1ceff1be942b79e2b5fdca1ca0b826b71924b8c25ad795a5b16acca5b7d67a5e4eacd28291d144e1cab423a4e69b9aa939c0ba9eaab268640ea3642a66dce5bfc6aad66727f6602d68b4d6981f20c9e14a8941ca1c1ccfa8b5d20b0070c01bf7eda562fd8add49a77e5c2fe3a8ba164fe7aaba4c7a5fb40e2c71b106e2e5bcd68f6a4aa2f0741b2c61b8c7aa1003b0ce6aa35fadb78edc0d5ecefabc00bfcf3709056a8056ba64f88847bcb33fcc473d3d5166d1236238a353a6fba9ac37fc9576cf1eabd3debb275d28dfb56f1095bfcd0fe9d571c163bcf6b2d7decd4730d9e01d7c6ede6b950779de7ffd427438fccc38f6c4bd4c9072d75b8c98b2e3caaab2aff1b5434e22a8d3e65ef2f5ea576bc5fd5f8badc81bd83f4e6539d8839e5a3ad1201eeafed2af2d2bfce7d53e7a7e38e6876bbfa1a3ce85fee50479e450dbcb783cfbb2b6eed732f9cb2f7e23872b3fe93be74fde683fd1ceee604104eb707b2b91e07eebd3f952cb2d78f4d79f14238c7a7ae57f7ce7d9eeb1f697cf2f3de168de5bba750db1b58c2e62e32f920ba76ba6c1b84d78f31067ccd5deb8e1ff6472bb50a20f30f0c635892f74aadfd10367914d0effee39127c96f4575a1ee15dcb7f3ab0aeea4862460e0b631aa25b0e8048f13116a92e6273ff990be6bc1bfde0528002f8903046f3440a0178800c21021324a4c0c8507487c3a16d0f486abceff9a76865f380e54878b44f1e6908890cd2a209006ea0cd0c0788d17bc41774414dfd51b984242d9a17d8c6c971dc2939f970e058c8654302e13b8a7cd3610800c8c63e6e6a1e04132846e894aa3680fe876472a617b8c8c64a5f0a1d515159c4294012423133997cbc922719d9ce3200d4966c621a1f9862c65a72b18fb38d0b54f20b4c4ac253998cd3ad2f69993e313e6a4f59e5a1215988455a227894cccd01ba92ebb6b823b8785cefd62b680dc866fe2d706ca9d02929752b46f0d7962a95e63b69dd47566e2b75b8d5e839581c17128ea2623c9eda3538de4f66ae2f5cea90210b28bccf56a2317bace7af358628cbb10f2e8519b62e33b981c06aa15ff1a40810c398732ac6ed7442aa3bc72cf6f9b04c8e0043a3f3e8a6e86601d68084927225a55a1589a0d392a4717e548a9117c84ec93993bc88e4b09a3d2ac9ca9ad4bb4ebbfa1825e9e2de960a4954cb98e125b9445e6a15f8a9237aa2aa088dc9a654d9943de7ad41bad0cafd9c834e5a69ea1e5afa3a8ec0baace41be85f4ab1573d658d4f41f06e18da8bb89a9d84ac749bec5f6a9dabb67dcd87f34ddd18fafdb7f9c4969cfcbae06beabf1bf5a039ab75da651f4960d66224f9929d9cecfccad993fdb15da441dcef4b09d55662551ca71d0da86f38aad18ad1b0a9e4062c6b8a28d1c295d84c8d81ab55f907d8c6f6d7b300100d69e9122b7aeda1be7ffd022069c76254ead4500ac50e6d61aac559aab6fbaf9d0b6b3dab7d5cea6799b13a1027790adadeceb63cb1bd3eaf61bb6e571507f07e95fb52456b385af6d7d147f50fd367abca49f6f7dfb9dd802a79c4aed9654534a3cd19617b4acfd9b228ffb2cbdea38bbb016faeb577b65530b58f2c90ece408d1bf7d907067cb4ed4e298b4cbe3d032ce1c03d80f0855c4dda0f85f5c81e8dc983ab33d8f2b89cbc3ee1f46e7c63e413883ea346be619d8c98142b7898bb463e63919bf461040026cb0ea453876cc1ea1f4952c556a0b8877cf4e00c6954325efee781ebcbdb2fc73dca6663bc852743e6be89f6c56e51773b5ce2e22ba9bec29963bb71cbaf50deff99bcb28e14fa997977e6b1c01fbfed44b87ffcd2ec2b3a90d6dc847be2fcd7d42b4717c50693f18b1db9684779fb5f56c37895fce66a23c934c6ae113aa35d9c4f477f04d0d5157093ec896223d973dc9e972047d6da6943fa58bb7652fca99c1c672f0b98df861a81a37b705b4b093ad85e9635b374abe71e2b92d88e9bde771d725d435bd1d6c6a28eb29df9e7578ab9d3aee37e81dd186e1fabd1d4ac4948bfe9d1e85399f9d656e6fc9f6dbe64d22aefdfc566b0c9fc407337da1dc807a670f87aba6e852175bc95c67e7dcda8e9833a5fdbf65333513e7ce5d1cb77d2fee53dbf7d4b638f9a94e52728d7491e58378f1afdcad60634310daeea9bdc1515eeee08e6cd6b794cda0557b117f3ffc33ded6b8b32afdf98b6f2d3bd02fb4f3d58d51726f4d51e3a9c874e49dd27d9b7cb2d95fd6f6d5add5fd4f7d1ce557c9f4a50cecee97cc7dedde6b3fbfde008800000b3
-- </COVER>
|
function plugindef()
finaleplugin.RequireSelection = true
finaleplugin.Author = "Robert Patterson"
finaleplugin.Version = "1.0"
finaleplugin.Copyright = "CC0 https://creativecommons.org/publicdomain/zero/1.0/"
finaleplugin.Date = "May 15, 2022"
finaleplugin.CategoryTags = "Baseline"
finaleplugin.AuthorURL = "http://robertgpatterson.com"
finaleplugin.MinJWLuaVersion = 0.62
finaleplugin.Notes = [[
This script nudges system baselines up or down by a single staff-space (24 evpus). It introduces 10
menu options to nudge each baseline type up or down. It also introduces 5 menu options to reset
the baselines to their staff-level values.
The possible prefix inputs to the script are
```
direction -- 1 for up, -1 for down, 0 for reset
baseline_types -- a table containing a list of the baseline types to process
nudge_evpus -- a positive number indicating the size of the nudge
```
You can also change the size of the nudge by creating a configuration file called `baseline_move.config.txt` and
adding a single line with the size of the nudge in evpus.
```
nudge_evpus = 36 -- or whatever size you wish
```
A value in a prefix overrides any setting in a configuration file.
]]
finaleplugin.AdditionalMenuOptions = [[
Move Lyric Baselines Up
Reset Lyric Baselines
Move Expression Baseline Above Down
Move Expression Baseline Above Up
Reset Expression Baseline Above
Move Expression Baseline Below Down
Move Expression Baseline Below Up
Reset Expression Baseline Below
Move Chord Baseline Down
Move Chord Baseline Up
Reset Chord Baseline
Move Fretboard Baseline Down
Move Fretboard Baseline Up
Reset Fretboard Baseline
]]
finaleplugin.AdditionalDescriptions = [[
Moves all lyrics baselines up one space in the selected systems
Resets all selected lyrics baselines to default
Moves the selected expression above baseline down one space
Moves the selected expression above baseline up one space
Resets the selected expression above baselines
Moves the selected expression below baseline down one space
Moves the selected expression below baseline up one space
Resets the selected expression below baselines
Moves the selected chord baseline down one space
Moves the selected chord baseline up one space
Resets the selected chord baselines
Moves the selected fretboard baseline down one space
Moves the selected fretboard baseline up one space
Resets the selected fretboard baselines
]]
finaleplugin.AdditionalPrefixes = [[
direction = 1 -- no baseline_types table, which picks up the default (lyrics)
direction = 0 -- no baseline_types table, which picks up the default (lyrics)
direction = -1 baseline_types = {finale.BASELINEMODE_EXPRESSIONABOVE}
direction = 1 baseline_types = {finale.BASELINEMODE_EXPRESSIONABOVE}
direction = 0 baseline_types = {finale.BASELINEMODE_EXPRESSIONABOVE}
direction = -1 baseline_types = {finale.BASELINEMODE_EXPRESSIONBELOW}
direction = 1 baseline_types = {finale.BASELINEMODE_EXPRESSIONBELOW}
direction = 0 baseline_types = {finale.BASELINEMODE_EXPRESSIONBELOW}
direction = -1 baseline_types = {finale.BASELINEMODE_CHORD}
direction = 1 baseline_types = {finale.BASELINEMODE_CHORD}
direction = 0 baseline_types = {finale.BASELINEMODE_CHORD}
direction = -1 baseline_types = {finale.BASELINEMODE_FRETBOARD}
direction = 1 baseline_types = {finale.BASELINEMODE_FRETBOARD}
direction = 0 baseline_types = {finale.BASELINEMODE_FRETBOARD}
]]
return "Move Lyric Baselines Down", "Move Lyrics Baselines Down", "Moves all lyrics baselines down one space in the selected systems"
end
-- Author: Robert Patterson
-- Date: March 5, 2021
--[[
$module Configuration
This library implements a UTF-8 text file scheme for configuration as follows:
- Comments start with `--`
- Leading, trailing, and extra whitespace is ignored
- Each parameter is named and delimited as follows:
`<parameter-name> = <parameter-value>`
Parameter values may be:
- Strings delimited with either single- or double-quotes
- Tables delimited with `{}` that may contain strings, booleans, or numbers
- Booleans (`true` or `false`)
- Numbers
Currently the following are not supported:
- Tables embedded within tables
- Tables containing strings that contain commas
A sample configuration file might be:
```lua
-- Configuration File for "Hairpin and Dynamic Adjustments" script
--
left_dynamic_cushion = 12 --evpus
right_dynamic_cushion = -6 --evpus
```
Configuration files must be placed in a subfolder called `script_settings` within
the folder of the calling script. Each script that has a configuration file
defines its own configuration file name.
]] --
local configuration = {}
local script_settings_dir = "script_settings" -- the parent of this directory is the running lua path
local comment_marker = "--"
local parameter_delimiter = "="
local path_delimiter = "/"
local file_exists = function(file_path)
local f = io.open(file_path, "r")
if nil ~= f then
io.close(f)
return true
end
return false
end
local strip_leading_trailing_whitespace = function(str)
return str:match("^%s*(.-)%s*$") -- lua pattern magic taken from the Internet
end
local parse_parameter -- forward function declaration
local parse_table = function(val_string)
local ret_table = {}
for element in val_string:gmatch("[^,%s]+") do -- lua pattern magic taken from the Internet
local parsed_element = parse_parameter(element)
table.insert(ret_table, parsed_element)
end
return ret_table
end
parse_parameter = function(val_string)
if "\"" == val_string:sub(1, 1) and "\"" == val_string:sub(#val_string, #val_string) then -- double-quote string
return string.gsub(val_string, "\"(.+)\"", "%1") -- lua pattern magic: "(.+)" matches all characters between two double-quote marks (no escape chars)
elseif "'" == val_string:sub(1, 1) and "'" == val_string:sub(#val_string, #val_string) then -- single-quote string
return string.gsub(val_string, "'(.+)'", "%1") -- lua pattern magic: '(.+)' matches all characters between two single-quote marks (no escape chars)
elseif "{" == val_string:sub(1, 1) and "}" == val_string:sub(#val_string, #val_string) then
return parse_table(string.gsub(val_string, "{(.+)}", "%1"))
elseif "true" == val_string then
return true
elseif "false" == val_string then
return false
end
return tonumber(val_string)
end
local get_parameters_from_file = function(file_name)
local parameters = {}
local path = finale.FCString()
path:SetRunningLuaFolderPath()
local file_path = path.LuaString .. path_delimiter .. file_name
if not file_exists(file_path) then
return parameters
end
for line in io.lines(file_path) do
local comment_at = string.find(line, comment_marker, 1, true) -- true means find raw string rather than lua pattern
if nil ~= comment_at then
line = string.sub(line, 1, comment_at - 1)
end
local delimiter_at = string.find(line, parameter_delimiter, 1, true)
if nil ~= delimiter_at then
local name = strip_leading_trailing_whitespace(string.sub(line, 1, delimiter_at - 1))
local val_string = strip_leading_trailing_whitespace(string.sub(line, delimiter_at + 1))
parameters[name] = parse_parameter(val_string)
end
end
return parameters
end
--[[
% get_parameters
Searches for a file with the input filename in the `script_settings` directory and replaces the default values in `parameter_list` with any that are found in the config file.
@ file_name (string) the file name of the config file (which will be prepended with the `script_settings` directory)
@ parameter_list (table) a table with the parameter name as key and the default value as value
]]
function configuration.get_parameters(file_name, parameter_list)
local file_parameters = get_parameters_from_file(script_settings_dir .. path_delimiter .. file_name)
if nil ~= file_parameters then
for param_name, def_val in pairs(parameter_list) do
local param_val = file_parameters[param_name]
if nil ~= param_val then
parameter_list[param_name] = param_val
end
end
end
end
local config = {nudge_evpus = 24}
if nil ~= configuration then
configuration.get_parameters("baseline_move.config.txt", config)
end
local lyric_baseline_types = {
[finale.BASELINEMODE_LYRICSVERSE] = function()
return finale.FCVerseLyricsText()
end,
[finale.BASELINEMODE_LYRICSCHORUS] = function()
return finale.FCChorusLyricsText()
end,
[finale.BASELINEMODE_LYRICSSECTION] = function()
return finale.FCSectionLyricsText()
end,
}
local find_valid_lyric_nums = function(baseline_type)
local lyrics_text_class_constructor = lyric_baseline_types[baseline_type]
if lyrics_text_class_constructor then
local valid_lyric_nums = {}
local lyrics_text_class = lyrics_text_class_constructor()
for i = 1, 32767, 1 do
if lyrics_text_class:Load(i) then
local str = finale.FCString()
lyrics_text_class:GetText(str)
if not str:IsEmpty() then
valid_lyric_nums[{baseline_type, i}] = 1
end
end
end
return valid_lyric_nums
end
return nil
end
function baseline_move()
local region = finenv.Region()
local systems = finale.FCStaffSystems()
systems:LoadAll()
local start_measure = region:GetStartMeasure()
local end_measure = region:GetEndMeasure()
local system = systems:FindMeasureNumber(start_measure)
local lastSys = systems:FindMeasureNumber(end_measure)
local system_number = system:GetItemNo()
local lastSys_number = lastSys:GetItemNo()
local start_slot = region:GetStartSlot()
local end_slot = region:GetEndSlot()
for _, baseline_type in pairs(baseline_types) do
local valid_lyric_nums = find_valid_lyric_nums(baseline_type) -- will be nil for non-lyric baseline types
for i = system_number, lastSys_number, 1 do
local baselines = finale.FCBaselines()
if direction ~= 0 then
baselines:LoadAllForSystem(baseline_type, i)
for j = start_slot, end_slot do
if valid_lyric_nums then
for lyric_info, _ in pairs(valid_lyric_nums) do
local _, lyric_number = table.unpack(lyric_info)
bl = baselines:AssureSavedLyricNumber(baseline_type, i, region:CalcStaffNumber(j), lyric_number)
bl.VerticalOffset = bl.VerticalOffset + direction * nudge_evpus
bl:Save()
end
else
bl = baselines:AssureSavedStaff(baseline_type, i, region:CalcStaffNumber(j))
bl.VerticalOffset = bl.VerticalOffset + direction * nudge_evpus
bl:Save()
end
end
else
for j = start_slot, end_slot do
baselines:LoadAllForSystemStaff(baseline_type, i, region:CalcStaffNumber(j))
-- iterate backwards to preserve lower inci numbers when deleting
for baseline in eachbackwards(baselines) do
baseline:DeleteData()
end
end
end
end
end
end
-- parameters for additional menu options
baseline_types = baseline_types or {finale.BASELINEMODE_LYRICSVERSE, finale.BASELINEMODE_LYRICSCHORUS, finale.BASELINEMODE_LYRICSSECTION}
direction = direction or -1
nudge_evpus = nudge_evpus or config.nudge_evpus
baseline_move()
|
player_manager.AddValidModel( "OW: Tracer", "models/player/ow_tracer.mdl" )
|
function __init__ ()
return {}
end
function add ()
local aliases = contract.state[account.id] or {}
table.insert(aliases, call.payload.alias)
contract.state[account.id] = aliases
end
function _get_key_for_value( t, value )
for k,v in pairs(t) do
if v==value then return k end
end
return nil
end
function delete ()
local aliases = contract.state[account.id] or {}
local key = _get_key_for_value(aliases, call.payload.alias)
if key ~= nil then table.remove(aliases, key) end
contract.state[account.id] = aliases
end |
local K, C, L = unpack(select(2, ...))
if C.ActionBar.Enable ~= true then return end
-- Lua API
local _G = _G
local unpack = unpack
-- Wow API
local AutoCastShine_AutoCastStart = _G.AutoCastShine_AutoCastStart
local AutoCastShine_AutoCastStop = _G.AutoCastShine_AutoCastStop
local GetNumShapeshiftForms = _G.GetNumShapeshiftForms
local GetPetActionInfo = _G.GetPetActionInfo
local GetPetActionSlotUsable = _G.GetPetActionSlotUsable
local GetShapeshiftFormCooldown = _G.GetShapeshiftFormCooldown
local GetShapeshiftFormInfo = _G.GetShapeshiftFormInfo
local InCombatLockdown = _G.InCombatLockdown
local IsPetAttackAction = _G.IsPetAttackAction
local NUM_PET_ACTION_SLOTS = _G.NUM_PET_ACTION_SLOTS
local NUM_STANCE_SLOTS = _G.NUM_STANCE_SLOTS
local PetActionButton_StartFlash = _G.PetActionButton_StartFlash
local PetActionButton_StopFlash = _G.PetActionButton_StopFlash
local PetHasActionBar = _G.PetHasActionBar
local SetDesaturation = _G.SetDesaturation
-- Global variables that we don't cache, list them here for mikk's FindGlobals script
-- GLOBALS: ShiftHolder, CooldownFrame_Set, StanceBarFrame
-- PET AND SHAPESHIFT BARS STYLE FUNCTION
K.ShiftBarUpdate = function(...)
local numForms = GetNumShapeshiftForms()
local texture, name, isActive, isCastable
local button, icon, cooldown
local start, duration, enable
for i = 1, NUM_STANCE_SLOTS do
button = _G["StanceButton"..i]
icon = _G["StanceButton"..i.."Icon"]
if i <= numForms then
texture, name, isActive, isCastable = GetShapeshiftFormInfo(i)
icon:SetTexture(texture)
cooldown = _G["StanceButton"..i.."Cooldown"]
if texture then
cooldown:SetAlpha(1)
else
cooldown:SetAlpha(0)
end
start, duration, enable = GetShapeshiftFormCooldown(i)
CooldownFrame_Set(cooldown, start, duration, enable)
if isActive then
StanceBarFrame.lastSelected = button:GetID()
button:SetChecked(true)
else
button:SetChecked(false)
end
if isCastable then
icon:SetVertexColor(1.0, 1.0, 1.0)
else
icon:SetVertexColor(0.4, 0.4, 0.4)
end
end
end
end
K.PetBarUpdate = function(...)
local petActionButton, petActionIcon, petAutoCastableTexture, petAutoCastShine
for i = 1, NUM_PET_ACTION_SLOTS, 1 do
local buttonName = "PetActionButton"..i
petActionButton = _G[buttonName]
petActionIcon = _G[buttonName.."Icon"]
petAutoCastableTexture = _G[buttonName.."AutoCastable"]
petAutoCastShine = _G[buttonName.."Shine"]
local name, subtext, texture, isToken, isActive, autoCastAllowed, autoCastEnabled = GetPetActionInfo(i)
if not isToken then
petActionIcon:SetTexture(texture)
petActionButton.tooltipName = name
else
petActionIcon:SetTexture(_G[texture])
petActionButton.tooltipName = _G[name]
end
petActionButton.isToken = isToken
petActionButton.tooltipSubtext = subtext
if isActive and name ~= "PET_ACTION_FOLLOW" then
petActionButton:SetChecked(true)
if IsPetAttackAction(i) then
PetActionButton_StartFlash(petActionButton)
end
else
petActionButton:SetChecked(false)
if IsPetAttackAction(i) then
PetActionButton_StopFlash(petActionButton)
end
end
if autoCastAllowed then
petAutoCastableTexture:Show()
else
petAutoCastableTexture:Hide()
end
if autoCastEnabled then
AutoCastShine_AutoCastStart(petAutoCastShine)
else
AutoCastShine_AutoCastStop(petAutoCastShine)
end
if name then
if not C.ActionBar.Grid then
petActionButton:SetAlpha(1)
end
else
if not C.ActionBar.Grid then
petActionButton:SetAlpha(0)
end
end
if texture then
if GetPetActionSlotUsable(i) then
SetDesaturation(petActionIcon, nil)
else
SetDesaturation(petActionIcon, 1)
end
petActionIcon:Show()
else
petActionIcon:Hide()
end
if not PetHasActionBar() and texture and name ~= "PET_ACTION_FOLLOW" then
PetActionButton_StopFlash(petActionButton)
SetDesaturation(petActionIcon, 1)
petActionButton:SetChecked(false)
end
end
end |
local _G = GLOBAL
_G.SHANGROCKS_MINE = 33 * GetModConfigData("wajuecishu")
_G.SHANGROCKS_MINE_MED = 22 * GetModConfigData("wajuecishu")
_G.SHANGROCKS_MINE_LOW = 11 * GetModConfigData("wajuecishu")
_G.SHANGROCKS_ROCKS = .1 * GetModConfigData("shitoubaolv")
_G.SHANGROCKS_NITRE = .025 * GetModConfigData("shitoubaolv")
_G.SHANGROCKS_FLINT = .06 * GetModConfigData("shitoubaolv")
_G.SHANGROCKS_GOLDS = GetModConfigData("huangjinbaolv")
_G.SHANG_SHENGDANSHI = GetModConfigData("SHENGDANSHI")
_G.SHANG_RUOYINXIAN = GetModConfigData("RUOYINXIAN")
_G.SHANGROCKS_BLUE = .0009 * GetModConfigData("baoshibaolv")*GetModConfigData("blue_baoshi")
_G.SHANGROCKS_RED = .0005 * GetModConfigData("baoshibaolv")*GetModConfigData("red_baoshi")
_G.SHANGROCKS_ORANGE = .0006 * GetModConfigData("baoshibaolv")*GetModConfigData("orange_baoshi")
_G.SHANGROCKS_YELLOW = .0008 * GetModConfigData("baoshibaolv")*GetModConfigData("yellow_baoshi")
_G.SHANGROCKS_GREEN = .0004 * GetModConfigData("baoshibaolv")*GetModConfigData("green_baoshi")
_G.SHANGROCKS_PURPLE = .0007 * GetModConfigData("baoshibaolv")*GetModConfigData("purple_baoshi")
_G.SHANGROCKS_THULECITE = .0001 * GetModConfigData("baoshibaolv")*GetModConfigData("thulecite_xiukuang")
_G.SHANGROCKS_MARBLE = .0050 * GetModConfigData("marble_suipian")
_G.SHANGROCKS_SHENG = 480 * GetModConfigData("shishengzhang")
local Rocks_Shang =
{
"rock1",
"rock2",
"rock_flintless",
"rock_flintless_med",
"rock_flintless_low",
"rock_moon",
}
_G.SetSharedLootTable( 'Shang'..'rock1',
{
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_ROCKS},
{'nitre', _G.SHANGROCKS_ROCKS},
{'flint', _G.SHANGROCKS_ROCKS},
{'nitre', _G.SHANGROCKS_NITRE},
{'flint', _G.SHANGROCKS_FLINT},
{'bluegem', _G.SHANGROCKS_BLUE},
{'redgem', _G.SHANGROCKS_RED},
{'orangegem', _G.SHANGROCKS_ORANGE},
{'yellowgem', _G.SHANGROCKS_YELLOW},
{'greengem', _G.SHANGROCKS_GREEN},
{'purplegem', _G.SHANGROCKS_PURPLE},
{'thulecite', _G.SHANGROCKS_THULECITE},
})
_G.SetSharedLootTable( 'Shang'..'rock2',
{
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_ROCKS},
{'goldnugget', .1 * _G.SHANGROCKS_GOLDS},
{'flint', _G.SHANGROCKS_ROCKS},
{'goldnugget', .025 * _G.SHANGROCKS_GOLDS},
{'flint', _G.SHANGROCKS_FLINT},
{'bluegem', _G.SHANGROCKS_BLUE*2},
{'redgem', _G.SHANGROCKS_RED*2},
{'orangegem', _G.SHANGROCKS_ORANGE*2},
{'yellowgem', _G.SHANGROCKS_YELLOW*2},
{'greengem', _G.SHANGROCKS_GREEN*2},
{'purplegem', _G.SHANGROCKS_PURPLE*2},
{'thulecite', _G.SHANGROCKS_THULECITE*2},
})
_G.SetSharedLootTable( 'Shang'..'rock_flintless',
{
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_FLINT},
{'marble', _G.SHANGROCKS_MARBLE*20},
{'marble', _G.SHANGROCKS_MARBLE*5},
{'marble', _G.SHANGROCKS_MARBLE},
{'bluegem', _G.SHANGROCKS_BLUE/2},
{'redgem', _G.SHANGROCKS_RED/2},
{'orangegem', _G.SHANGROCKS_ORANGE/2},
{'yellowgem', _G.SHANGROCKS_YELLOW/2},
{'greengem', _G.SHANGROCKS_GREEN/2},
{'purplegem', _G.SHANGROCKS_PURPLE/2},
{'thulecite', _G.SHANGROCKS_THULECITE/2},
})
_G.SetSharedLootTable( 'Shang'..'rock_flintless_med',
{
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_NITRE},
{'marble', _G.SHANGROCKS_MARBLE*20},
{'marble', _G.SHANGROCKS_MARBLE},
{'bluegem', _G.SHANGROCKS_BLUE/2},
{'redgem', _G.SHANGROCKS_RED/2},
{'orangegem', _G.SHANGROCKS_ORANGE/2},
{'yellowgem', _G.SHANGROCKS_YELLOW/2},
{'greengem', _G.SHANGROCKS_GREEN/2},
{'purplegem', _G.SHANGROCKS_PURPLE/2},
{'thulecite', _G.SHANGROCKS_THULECITE/5},
})
_G.SetSharedLootTable( 'Shang'..'rock_flintless_low',
{
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_NITRE},
{'marble', _G.SHANGROCKS_MARBLE*20},
{'marble', _G.SHANGROCKS_MARBLE*5},
{'bluegem', _G.SHANGROCKS_BLUE/2},
{'redgem', _G.SHANGROCKS_RED/2},
{'orangegem', _G.SHANGROCKS_ORANGE/2},
{'yellowgem', _G.SHANGROCKS_YELLOW/2},
{'greengem', _G.SHANGROCKS_GREEN/2},
{'purplegem', _G.SHANGROCKS_PURPLE/2},
{'thulecite', _G.SHANGROCKS_THULECITE/5},
})
_G.SetSharedLootTable( 'Shang'..'rock_moon',
{
{'rocks', _G.SHANGROCKS_ROCKS},
{'rocks', _G.SHANGROCKS_ROCKS},
{'moonrocknugget', _G.SHANGROCKS_ROCKS},
{'flint', _G.SHANGROCKS_ROCKS},
{'moonrocknugget', _G.SHANGROCKS_NITRE},
{'flint', _G.SHANGROCKS_FLINT},
{'thulecite_pieces', _G.SHANGROCKS_MARBLE*10},
{'thulecite_pieces', _G.SHANGROCKS_MARBLE*6},
{'thulecite_pieces', _G.SHANGROCKS_MARBLE},
{'bluegem', _G.SHANGROCKS_BLUE},
{'redgem', _G.SHANGROCKS_RED},
{'orangegem', _G.SHANGROCKS_ORANGE},
{'yellowgem', _G.SHANGROCKS_YELLOW},
{'greengem', _G.SHANGROCKS_GREEN},
{'purplegem', _G.SHANGROCKS_PURPLE},
{'thulecite', _G.SHANGROCKS_THULECITE},
})
local function ShenZ(inst)
local x, y, z = inst.Transform:GetWorldPosition()
local zijin = inst.prefab
if inst.Transform then inst.Transform:SetScale(.22, .96, .33) end
inst:RemoveComponent("workable")
inst:AddComponent("workable")
inst.components.workable:SetWorkAction(_G.ACTIONS.DIG)
inst.components.workable:SetOnFinishCallback(function(r)
r.components.lootdropper:DropLoot(pt)
r:Remove()
end)
inst.components.workable:SetWorkLeft(1)
_G.MakeObstaclePhysics(inst, 0, 0)
inst:DoTaskInTime(_G.SHANGROCKS_SHENG, function()
inst:StartThread(function()
if inst.Transform then inst.Transform:SetScale(1, 1, 1) end
_G.Sleep(.1)
inst.AnimState:PlayAnimation("low")
if zijin ~= "rock_flintless_low" then _G.Sleep(.8)
inst.AnimState:PlayAnimation("med")
if zijin ~= "rock_flintless_med" then _G.Sleep(1.2)
inst.AnimState:PlayAnimation("full")
end
end
_G.SpawnPrefab(zijin).Transform:SetPosition(x, y, z)
inst:Remove()
end)
end)
end
local function OnWork(inst, worker, workleft)
local pt = inst:GetPosition()
if worker:HasTag("player") or workleft > 0 then
inst.shengyucishu = inst.shengyucishu - 1
inst.components.lootdropper:DropLoot(pt)
else _G.MakeObstaclePhysics(inst, 0, 0)
end
if workleft <= 0 or inst.shengyucishu <= 0 then
if inst.shengyucishu <= 0 then
_G.SpawnPrefab("rock_break_fx").Transform:SetPosition(pt:Get())
if _G.SHANGROCKS_SHENG == 0 then
inst:Remove()
else
ShenZ(inst)
end
else
inst.components.workable:SetWorkLeft(_G.SHANGROCKS_MINE*20)
end
else
inst.AnimState:PlayAnimation(
(inst.shengyucishu < _G.SHANGROCKS_MINE / 3 and "low") or
(inst.shengyucishu < _G.SHANGROCKS_MINE * 2 / 3 and "med") or
"full"
)
end
end
local function OnSave(inst,data)
local zijin = inst.prefab
local WeiKaiCaiShu = zijin == "rock_flintless_med" and _G.SHANGROCKS_MINE or
zijin == "rock_flintless_low" and _G.SHANGROCKS_MINE_LOW or _G.SHANGROCKS_MINE
data.shengyucishu = inst.shengyucishu>0 and inst.shengyucishu~=WeiKaiCaiShu and inst.shengyucishu or nil
end
local function OnLoad(inst,data)
local zijin = inst.prefab
local YiKaiCaiShu = zijin == "rock_flintless_med" and _G.SHANGROCKS_MINE or
zijin == "rock_flintless_low" and _G.SHANGROCKS_MINE_LOW or _G.SHANGROCKS_MINE
if data ~= nil then
inst.shengyucishu = data.shengyucishu~=nil and data.shengyucishu<YiKaiCaiShu and data.shengyucishu or YiKaiCaiShu
if inst.shengyucishu ~= nil then
inst.AnimState:PlayAnimation(
(inst.shengyucishu < _G.SHANGROCKS_MINE / 3 and "low") or
(inst.shengyucishu < _G.SHANGROCKS_MINE * 2 / 3 and "med") or
"full")
end
end
end
for k, v in pairs(Rocks_Shang) do
AddPrefabPostInit(v,function(inst)
if not _G.TheWorld.ismastersim then
return inst
end
local ShengYuCiShu = inst.prefab == "rock_flintless_low" and _G.SHANGROCKS_MINE_LOW or
inst.prefab == "rock_flintless_med" and _G.SHANGROCKS_MINE_MED or _G.SHANGROCKS_MINE
inst.shengyucishu = ShengYuCiShu
inst.components.lootdropper:SetChanceLootTable('Shang'..inst.prefab)
inst.components.workable:SetWorkAction(_G.ACTIONS.MINE)
inst.components.workable:SetWorkLeft(ShengYuCiShu*10)
inst.components.workable:SetOnWorkCallback(OnWork)
local color = .5 + math.random() * .5
local colora = _G.SHANG_SHENGDANSHI and 0 + math.random() * 1 or color
local colorb = _G.SHANG_SHENGDANSHI and 0 + math.random() * 1 or color
local colorc = _G.SHANG_SHENGDANSHI and 0 + math.random() * 1 or color
local colord = (_G.SHANG_SHENGDANSHI or _G.SHANG_RUOYINXIAN) and .1 + math.random() * .9 or 1
inst.AnimState:SetMultColour(colora, colorb, colorc, colord)
inst.OnSave = OnSave
inst.OnLoad = OnLoad
end)
end |
------------------------------shotcut--------------------------------
PI=math.pi
lg = love.graphics
lk = love.keyboard
lm = love.mouse
for k,v in pairs(love.math) do
math[k] = v
end
function w() return lg.getWidth() end
function h() return lg.getHeight() end
--------------------------------math addon----------------------------------
function math.percentOffset(num,percentage)
return num + num*(0.5-love.math.random())*2*percentage
end
function math.round(num, n)
if n > 0 then
local scale = math.pow(10, n-1)
return math.floor(num * scale + 0.5) / scale
elseif n < 0 then
local scale = math.pow(10, n)
return math.floor(num * scale + 0.5) / scale
elseif n == 0 then
return num
end
end
function math.clamp(a,b,c) --取三者中间的
return math.min(math.max(a,b),math.max(b,c),math.max(a,c))
end
function math.sign(x)
if x>0 then return 1
elseif x<0 then return -1
else return 0 end
end
function math.polar(x,y)
return math.getDistance(x,y,0,0),math.atan2(y, x)
end
function math.cartesian(r,phi)
return r*math.cos(phi),r*math.sin(phi)
end
function math.getLoopDist(p1,p2,loop)
loop=loop or 2*Pi
local dist=math.abs(p1-p2)
local dist2=loop-math.abs(p1-p2)
if dist>dist2 then dist=dist2 end
return dist
end
function math.getDistance(x1,y1,x2,y2)
return ((x1-x2)^2+(y1-y2)^2)^0.5
end
function math.axisRot(x,y,rot)
return math.cos(rot)*x-math.sin(rot)*y,math.cos(rot)*y+math.sin(rot)*x
end
function math.axisRot_P(x,y,x1,y1,rot)
x=x - x1
y=y - y1
local xx=math.cos(rot)*x-math.sin(rot)*y
local yy=math.cos(rot)*y+math.sin(rot)*x
return xx+x1,yy+y1
end
-- y轴正方向为0,顺时针增加[-0.5pi~1.5*pi]
function math.getRot2(dx,dy)
return math.atan2(dy,dx)+0.5*math.pi
end
function math.getRot(x1,y1,x2,y2)
return math.getRot2(x2-x1,y2-y1)
end
function math.polygonTrans(x,y,rot,size,v)
local tab={}
for i=1,#v/2 do
tab[2*i-1],tab[2*i]=math.axisRot(v[2*i-1],v[2*i],rot)
tab[2*i-1]=tab[2*i-1]*size+x
tab[2*i]=tab[2*i]*size+y
end
return tab
end
function math.convexHull(verts)
local v={}
local rt={}
local lastK=0
local lastX=0
local lastY=0
local lastRad=0
for i=1,#verts-1,2 do
local index = (i+1)/2
v[index]={}
v[index].x=verts[i]
v[index].y=verts[i+1]
end
local maxY=-1/0
local oK=0
for k,v in ipairs(v) do
if v.y>maxY then
maxY=v.y
oK=k
end
end
lastK=oK
lastX=v[lastK].x
lastY=v[lastK].y
table.insert(rt,v[lastK].x)
table.insert(rt,v[lastK].y)
local i=0
while true do
i=i+1
local minRad=2*math.pi
local minK=0
for k,v in pairs(v) do
local rad= math.getRot(v.x,v.y,lastX,lastY)
if rad and rad>lastRad then
if rad<minRad then
minRad=rad
minK=k
end
end
end
if minK==maxK or minK==0 then
table.insert(rt,rt[1])
table.insert(rt,rt[2])
return rt
end --outside
lastK=minK
lastRad=minRad
lastX=v[lastK].x
lastY=v[lastK].y
table.insert(rt,v[lastK].x)
table.insert(rt,v[lastK].y)
end
end
function math.randomPolygon(x,y,size,count)
x = x or 0
y = y or 0
size = size or 100
count = count or 30
local v = {}
for i=1,count*2 do
table.insert(v,love.math.random(-50,50)*size/50)
end
return math.polygonTrans(x,y,0,1,math.convexHull(v))
end
function math.pointTest(x,y,verts)
local pX={}
local pY={}
for i=1,#verts,2 do
table.insert(pX, verts[i])
table.insert(pY, verts[i+1])
end
local oddNodes=false
local pCount=#pX
local j=pCount
for i=1,pCount do
if ((pY[i]<y and pY[j]>=y) or (pY[j]<y and pY[i]>=y))
and (pX[i]<=x or pX[j]<=x) then
if pX[i]+(y-pY[i])/(pY[j]-pY[i])*(pX[j]-pX[i])<x then
oddNodes=not oddNodes
end
end
j=i
end
return oddNodes
end
function math.pointTest_xy(x,y,pX,pY)
local oddNodes=false
local pCount=#pX
local j=pCount
for i=1,pCount do
if ((pY[i]<y and pY[j]>=y) or (pY[j]<y and pY[i]>=y))
and (pX[i]<=x or pX[j]<=x) then
if pX[i]+(y-pY[i])/(pY[j]-pY[i])*(pX[j]-pX[i])<x then
oddNodes=not oddNodes
end
end
j=i
end
return oddNodes
end
function math.RGBtoHSV(r,g,b)
local max=math.max(r,g,b)
local min=math.min(r,g,b)
local d=max-min
local v=max
local s
if v==0 then
s=0
else
s=1-min/max
end
local h=0
if d~=0 then
if r==max then
h=(g-b)/d
elseif g==max then
h=2+(b-r)/d
elseif b==max then
h=4+(r-g)/d
end
h=h*60
if h<0 then h=h+360 end
end
return h,s,v
end
function math.HSVtoRGB(h,s,v)
local r,g,b
local x,y,z
if s==0 then
r=v;g=v;b=v
else
h=h/60
i=math.floor(h)
f=h-i
x=v*(1-s)
y=v*(1-s*f)
z=v*(1-s*(1-f))
end
if i==0 then
r=v;g=z;b=x
elseif i==1 then
r=y;g=v;b=x
elseif i==2 then
r=x;g=v;b=z
elseif i==3 then
r=x;g=y;b=v
elseif i==4 then
r=z;g=x;b=v
elseif i==5 then
r=v;g=x;b=y
else
r=v;g=z;b=x
end
return math.floor(r),math.floor(g),math.floor(b)
end
function math.tessellate(vertices,time,factor)
local new = {}
local loop = vertices[1] == vertices[#vertices-1] and vertices[2] == vertices[#vertices]
factor = factor or .5
for i=1,#vertices-(loop and 3 or 1),2 do
local newindex = 2*i
new[newindex - 1] = vertices[i];
new[newindex] = vertices[i+1]
new[newindex + 1] = (vertices[i] + (vertices[i+2] or vertices[1]))/2
new[newindex + 2] = (vertices[i+1] + (vertices[i+3] or vertices[2]))/2
end
for i = 1,#new -1,4 do
new[i] =
factor*((new[i - 2] or new[#new-1]) + (new[i + 2] or new[1]))/2 +
(1 - factor)*new[i]
new[i + 1] =
factor*((new[i - 1] or new[#new])+ (new[i + 3] or new[2]))/2 +
(1 - factor)*new[i + 1]
end
if loop then
table.insert(new,new[1])
table.insert(new,new[2])
end
if time == 1 then
return new
else
return math.tessellate(new,time - 1 ,factor)
end
end
function math.randomCurve(verts,displace,curDetail)
local curve = {}
local random = love.math.random
local loop = verts[1] == verts[#verts-1] and verts[2] == verts[#verts]
for i = 1,#verts-1,2 do
local segment = {}
local ox = verts[i]
local oy = verts[i+1]
if loop and (not verts[i+2]) then break end
local nx = verts[i+2] or verts[1]
local ny = verts[i+3] or verts[2]
local sample = {{ox,oy,nx,ny,displace,0.5,1}}
local result = {}
while true do
local newSample = {}
for i,seg in ipairs(sample) do
local x1,y1,x2,y2,dp,index,div = unpack(seg)
div = div + 1
if dp > curDetail then
local mx = (x1 + x2) / 2 + (random() - 0.5) * displace
local my = (y1 + y2) / 2 + (random() - 0.5) * displace
table.insert(newSample,{x1,y1,mx,my,dp/2,index-1/(2^div),div})
table.insert(newSample,{mx,my,x2,y2,dp/2,index+1/(2^div),div})
else
table.insert(result,seg)
end
end
if not newSample[1] then break end
sample = newSample
end
table.sort(result,function(a,b) return a[6]<b[6] end)
for i,v in ipairs(result) do
table.insert(curve, v[1])
table.insert(curve, v[2])
--table.insert(curve, v[3])
--table.insert(curve, v[4])
end
end
table.insert(curve,curve[1])
table.insert(curve,curve[2])
return curve
end
function math.pointToLine(a,b,c,x,y)
return math.abs(a*x+b*y+c)/math.sqrt(a*a+b*b)
end
--source 必须包含.x,.y作为起始坐标,.rot为发射角,tx,ty为终点坐标
--toTest为待检测table 必须包含 .x,.y,.r作为碰撞球
function math.raycast(source,toTest)
local x1,y1=source.x,source.y
local x2,y2
local dist
local dir=source.rot or math.atan((source.tx-x1)/(source.ty-y1))-math.pi/2
local tan=math.tan(dir)
local a=tan
local b=-1
local c=-x1*tan+y1
local rt={}
for i,v in ipairs(toTest) do
x2,y2=v.x,v.y
dist=math.pointToLine(a,b,c,x2,y2)
if math.sign(math.cos(dir))~=math.sign(x2-x1) and math.sign(math.sin(dir))~=math.sign(y2-y1) then
dist=math.tan(Pi/2)
end
if dist<= v.r then
local a2,b2,c2=math.vertToLine(a,b,c,x2,y2)
local cx,cy=math.crossPoint(a,b,c,a2,b2,c2)
if source.tx then
if math.abs(cx - math.clamp(cx,source.x,source.tx))<2
and math.abs(cy - math.clamp(cy,source.y,source.ty))<2 then
table.insert(rt, {v,cx,cy})
end
else
if cx == math.clamp(cx,source.x,(1/0)*math.sin(dir)) and cy == math.clamp(cy,source.y,(1/0)*math.cos(dir)) then
table.insert(rt, {v,cx,cy})
end
end
end
end
return rt
end
function math.getLineABC(x,y,tx,ty)
local a = (ty-y)/(tx-x)
local b = -1
local c = -x*a+y
return a,b,c
end
function math.lineCross(line1,line2)
local a1,b1,c1 = math.getLineABC(line1.x,line1.y,line1.tx,line1.ty)
local a2,b2,c2 = math.getLineABC(line2.x,line2.y,line2.tx,line2.ty)
local cx,cy=math.crossPoint(a1,b1,c1,a2,b2,c2)
if math.abs(cx - math.clamp(cx,line1.x,line1.tx))<2
and math.abs(cy - math.clamp(cy,line1.y,line1.ty))<2
and math.abs(cx - math.clamp(cx,line2.x,line2.tx))<2
and math.abs(cy - math.clamp(cy,line2.y,line2.ty))<2 then
return cx,cy
end
end
function math.unitAngle(angle) --convert angle to 0,2*Pi
return math.asin(math.sin(angle))
end
--overwrite it
function math.unitAngle(angle) --convert angle to 0,2*Pi
angle = angle%(2*math.pi)
if angle > math.pi then angle = angle - 2* math.pi end
return angle
end
---- 判断x2,y2在 x1、y1的弧度、角度、方向(N,S,W,E)、周围点
function math.getRot( x1,y1,x2,y2 )
if x1==x2 and y1 == y2 then return 0 end
if y1 == y2 and x2 - x1 > 0 then return math.pi/2 end
if y1 == y2 and x2 - x1 < 0 then return 3*math.pi/2 end
local angle = math.atan( (x2-x1)/(y2-y1) )
if y1-y2 < 0 then angle = angle - math.pi end
if angle>0 then angle = angle - 2*math.pi end
return -angle
end
function math.getAngle( x1,y1,x2,y2 )
local rot = math.getRot(x1,y1,x2,y2)
local angle = rot/(2*math.pi)*360
return angle
end
function math.getDirection( x1,y1,x2,y2 )
local d = {'N','EN','E','ES','S','WS','W','WN'}
local a = {0,45,90,135,180,225,270,315,360}
local angle = math.getAngle(x1,y1,x2,y2)
if angle>=a[9]-22.5 or angle < a[1] + 22.5 then return d[1] end
if angle>=a[2]-22.5 and angle < a[2] + 22.5 then return d[2] end
if angle>=a[3]-22.5 and angle < a[3] + 22.5 then return d[3] end
if angle>=a[4]-22.5 and angle < a[4] + 22.5 then return d[4] end
if angle>=a[5]-22.5 and angle < a[5] + 22.5 then return d[5] end
if angle>=a[6]-22.5 and angle < a[6] + 22.5 then return d[6] end
if angle>=a[7]-22.5 and angle < a[7] + 22.5 then return d[7] end
if angle>=a[8]-22.5 and angle < a[8] + 22.5 then return d[8] end
end
function math.getDirecPoint( x1,y1,x2,y2 )
local points = {}
points.N = {x=0,y=-1}
points.EN = {x=1,y=-1}
points.E = {x=1,y=0}
points.ES ={x=1,y=-1}
points.S = {x=0,y=1}
points.WS = {x=-1,y=1}
points.W = {x=-1,y=0}
points.WN = {x=-1,y=-1}
local direc = math.getDirection(x1,y1,x2,y2)
return points[direc]
end
---@return UUID
function math.createID()
local seed = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}
local tb = {}
for i =1,32 do
table.insert(tb, seed[math.random(1,16)])
end
return table.concat(tb)
end
function math.vertToLine(a,b,c,x,y) --过已知点垂线公式
local a2=math.abs(b/a)==1/0 and math.sign(b/a)*math.tan(Pi/2) or b/a
return a2,-1,y-a2*x
end
function math.crossPoint(a1,b1,c1,a2,b2,c2) --两线交点公式
return (b1*c2-b2*c1)/(a1*b2-a2*b1), (a1*c2-a2*c1)/(b1*a2-b2*a1)
end
function math.createEllipse(rx,ry,segments)
segments = segments or 30
local vertices = {}
for i=0, segments do
local angle = (i / segments) * math.pi * 2
local x = math.cos(angle)*rx
local y = math.sin(angle)*ry
table.insert(vertices, x)
table.insert(vertices, y)
end
return vertices
end
--return center,area verts[1],verts[2] = x ,y
function math.getPolygonArea(verts)
local count=#verts/2
local cx,cy=0,0
local area = 0
local inv3=1/3
local refx,refy=0,0
for i=1,#verts-1,2 do
local p1x,p1y=refx,refy
local p2x,p2y=verts[i],verts[i+1]
local p3x = i+2>#verts and verts[1] or verts[i+2]
local p3y = i+2>#verts and verts[2] or verts[i+3]
local e1x= p2x-p1x
local e1y= p2y-p1y
local e2x= p3x-p1x
local e2y= p3y-p1y
local d=math.vec2.cross(e1x,e1y,e2x,e2y)
local triAngleArea=0.5*d
area=area+triAngleArea
cx = cx + triAngleArea*(p1x+p2x+p3x)/3
cy = cy + triAngleArea*(p1y+p2y+p3y)/3
end
if area~=0 then
cx= cx/area
cy= cy/area
return cx,cy,math.abs(area)
end
end
--------------------------------string addon----------------------------------
function string.split(str,keyword)
local tab={}
local index=1
local from=1
local to=1
while true do
if string.sub(str,index,index)==keyword then
to=index-1
if from>to then
table.insert(tab, "")
else
table.insert(tab, string.sub(str,from,to))
end
from=index+1
end
index=index+1
if index>string.len(str) then
if from<=string.len(str) then
table.insert(tab, string.sub(str,from,string.len(str)))
end
return tab
end
end
end
function string.generateName(num,seed)
local list = {}
list[1] = {{'b','c','d','f','g','h','j','l','m','n','p','r','s','t','v','x','z','k','w','y'},{'qu','th','ll','ph'}} --21,4
list[2] = {'a','e','i','o','u'} --v
random = love.math.newRandomGenerator(os.time())
random:setSeed(love.math.random(1,9999))
local first = random:random(2)
local name = ''
local char = ''
local nchar = ''
--creates first letter(s)
if first == 2 then --v
for i=1, random:random(2) do
char = list[2][random:random(#list[2])]
if i == 2 then
while char == name do
char = list[2][random:random(#list[2])]
end
name = name .. char
else
name = name .. char
end
end
else --c
if random:random(2) == 1 then
for i=1, random:random(2) do
char = list[1][1][random:random(#list[1][1])]
if i == 2 then
while char == name do
char = list[1][1][random:random(#list[1][1])]
end
name = name .. char
else
name = char
end
end
else
char = list[1][2][random:random(#list[1][2])]
if char == 'qu' then
nchar = list[2][random:random(2,3)]
first = 2
end
name = char .. nchar
end
end
--creates the rest of the name
local add = ''
for i=1,num do
first = first == 1 and 2 or 1 -- change between v and c
add = ''
if first == 2 then --v
for i=1, random:random(2) do
char = list[2][random:random(#list[2])]
if i == 2 then
while char == add do
char = list[2][random:random(#list[2])]
end
add = add .. char
else
add = add .. char
end
end
else --c
if random:random(2) == 1 then
for i=1, random:random(2) do
char = list[1][1][random:random(#list[1][1])]
if i == 2 then
while char == add do
char = list[1][1][random:random(#list[1][1])]
end
add = add .. char
else
add = add .. char
end
end
else
char = list[1][2][random:random(#list[1][2])]
if char == 'qu' then
nchar = list[2][random:random(2,3)]
end
add = char .. nchar
end
end
name = name .. add
end
return name
end
function string.toTable(str)
local tab={}
for uchar in string.gfind(str, "[%z\1-\127\194-\244][\128-\191]*") do tab[#tab+1] = uchar end
return tab
end
function string.sub_utf8(s, n)
local dropping = string.byte(s, n+1)
if not dropping then return s end
if dropping >= 128 and dropping < 192 then
return string.sub_utf8(s, n-1)
end
return string.sub(s, 1, n)
end
function string.strippath(filename)
return string.match(filename, "(.+)\\[^\\]*%.%w+$") --windows
end
function string.stripfilename(filename)
return string.match(filename, ".+\\([^\\]*%.%w+)$") -- *nix system
end
--------------------------------table addon----------------------------------
function table.getIndex(tab,item)
for k,v in pairs(tab) do
if v==item then return k end
end
end
function table.removeItem(tab,item)
table.remove(tab,table.getIndex(tab,item))
end
function table.copy(source,copyto,ifcopyfunction)
copyto=copyto or {}
for k, v in pairs(source or {}) do
if type(v) == "table" then
copyto[k] = table.copy(v,copyto[k])
elseif type(v) == "function" then
if ifcopyfunction then
copyto[k] = v
end
else
copyto[k] = v
end
end
return copyto
end
function table.inserts(tab,...)
for i,v in ipairs({...}) do
table.insert(tab, v)
end
end
function table.state(tab)
local output={}
local function ergodic(target,name)
for k,v in pairs(target) do
if type(v)=="table" then
name=name.."/"..k
output[name]=#v
print(name,#v)
ergodic(v,name)
end
end
end
ergodic(tab,tostring(tab))
return output
end
function table.safeRemove(tab,index) --can be used in iv pair
local v=tab[#tab]
tab[index]=v
tab[#tab]=nil
end
function table.isEmpty(tab)
for k,v in pairs(tab) do
return false
end
return true
end
function table.merge(tab1,tab2) --from,to
if tab2[1] then --ordered
for i,v in ipairs(tab2) do
table.insert(tab1,v)
end
else
for k,v in pairs(tab2) do
tab1[k] = v
end
end
return tab1
end
function table.reverse(tab)
local tmp = unpack(tab)
for i = #tmp , 1, -1 do
tab[i] = tmp[#tmp-i+1]
end
end
function table.random(tab)
return tab[love.math.random(#tab)]
end
function table.save(tab,name,ifCopyFunction)
name=name or "default"
local tableList= {{name="root",tab=tab}} --to protect loop
local output="local "..name.."=\n"
local function ergodic(target,time)
time=time+1
output=output.."{\n"
for k,v in pairs(target) do
output=output .. string.rep("\t",time)
local name
if type(k)=="number" then
name="["..k.."]"
elseif type(k)=="string" then
name="[\""..k.."\"]"
end
if type(v)=="table" then
output=output .. name .."="
local checkRepeat
for _,p in ipairs(tableList) do
if v==p.tab then
checkRepeat=true;break
end
end
if checkRepeat then
output=output.. name .."=table^"..name..",\n"
else
table.insert(tableList,{name=name,tab=v})
ergodic(v,time)
output=output .. string.rep("\t",time)
output=output.."},\n"
end
elseif type(v)=="string" then
if string.find(v,"\n") then
local startp, endp = string.find(v, "%[=*%[")
local count = startp and endp-startp or 0
output=output.. name .."=["..string.rep("=",count).."["..v.."]"..string.rep("=",count).."],\n"
else
output=output.. name .."=\""..v.."\",\n"
end
elseif type(v)=="number" or type(v)=="boolean" then
output=output..name.."="..tostring(v)..",\n"
elseif type(v)=="function" and ifCopyFunction then
output=output .. name .."= loadstring(\""..string.dump(v).."\")(),\n"
end
end
end
ergodic(tab,0)
output=output.."}\nreturn "..name
--print(output)
return output
end
function table.load(str)
return loadstring(str)()
end
function p_print(...)
local info = debug.getinfo(2, "Sl")
local source = info.source
local msg = ("%s:%i ->"):format(source, info.currentline)
print(msg, ...)
end
function resize( s )
love.window.setMode(s*gw,s*gh)
sw,sh = s,s
end
--- @type fun():string
function UUID()
local fn = function ( x )
local r = love.math.random(16) - 1
r = (x == 'x') and (r + 1) or (r % 4) + 9
return ("0123456789abcdef"):sub(r,r)
end
return (("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"):gsub("[xy]",fn))
end
--- @type fun():Stage
function addRoom( room_type, room_name, ... )
local room = _G[room_type](room_name, ...)
rooms[room_name] = room
return room
end
--- @type fun(room_type:string,room_name:string)
function gotoRoom( room_type, room_name, ... )
if current_room and current_room.destroy then current_room:destroy() end
if current_room and rooms[room_name] then
if current_room.deactivate then current_room:deactivate() end
current_room = rooms[room_name]
if current_room.activate then current_room:activate() end
else current_room = addRoom(room_type, room_name, ...) end
end
--- @type fun(folder:string,file_list:table)
function recursiveEnumerate( folder,file_list )
local items = love.filesystem.getDirectoryItems(folder)
for _,item in ipairs(items) do
local file = folder .. '/' .. item
if love.filesystem.getInfo(file).type == "file" then
table.insert(file_list,file)
elseif love.filesystem.isDirectory(file) then
recursiveEnumerate(file,file_liset)
end
end
end
function requireFiles(files)
for _, file in ipairs(files) do
local f = file:sub(1,-5)
require(f)
end
end
function random(min,max)
local min,max = min or 0, max or 1
return (min > max and (love.math.random()*(min - max) + max)) or (love.math.random()*(max - min) + min)
end
function count_all(f)
local seen = {}
local count_table
count_table = function(t)
if seen[t] then return end
f(t)
seen[t] = true
for k,v in pairs(t) do
if type(v) == "table" then
count_table(v)
elseif type(v) == "userdata" then
f(v)
end
end
end
count_table(_G)
end
function type_count()
local counts = {}
local enumerate = function (o)
local t = type_name(o)
counts[t] = (counts[t] or 0) + 1
end
count_all(enumerate)
return counts
end
global_type_table = nil
function type_name(o)
if global_type_table == nil then
global_type_table = {}
for k,v in pairs(_G) do
global_type_table[v] = k
end
global_type_table[0] = "table"
end
return global_type_table[getmetatable(o) or 0] or "Unknown"
end
------------------------------ Graphics -----------------------------
--- label func
--- @type fun(text,x,y,bg,fg,font)
--- @param text string
--- @param x number
--- @param y number
--- @param bg table color {r,g,b,a}
--- @param fg table color {r,g,b,a}
--- @param font Font
function love.graphics.label(text,x,y,bg,fg,font)
local fg = fg or {1,1,1,1}
local bg = bg or {0,0,0,0.5}
local font = font or love.graphics.getFont()
local tw,th = font:getWidth(text),font:getHeight(text)
local x = x or gw/2 - tw/2 --- center
local y = y or 0
love.graphics.setColor(bg)
love.graphics.rectangle('fill',x,y,tw,th)
love.graphics.setColor(fg)
love.graphics.print(text,x,y)
end
function pushRote(x,y,r,sx,sy)
love.graphics.push()
love.graphics.translate(x,y)
love.graphics.rotate(r or 0)
love.graphics.scale(sx or 1,sy or sx or 1)
love.graphics.translate(-x,-y)
end
--- table
function table.random(t)
return t[math.random(1,#t)]
end
--- func
function chanceList( ... )
return{
chance_list = {},
chance_definitions = { ... },
next = function(self)
if #self.chance_list == 0 then
for _,chance_definition in ipairs(self.chance_definitions) do
for i = 1,chance_definition[2] do
table.insert(self.chance_list,chance_definition[1])
end
end
end
return table.remove(self.chance_list,random(1,#self.chance_list))
end
}
end
function generateClickSound()
local snd = love.sound.newSoundData(512,44100,16,1)
for i = 0,snd:getSampleCount() -1 do
local t = i / 44100
local s = i / snd:getSampleCount()
snd:setSample(i,(0.7*(2*love.math.random() - 1) + 0.3 * math.sin(t*9000*math.pi))*(1-s)^1.2 * 0.3)
end
return love.audio.newSource(snd)
end
function generateImageButton()
local metaballs = function(t,r,g,b)
return function(x,y)
local px,py = 2*(x/200 - 0.5),2 * (y/100 - 0.5)
local d1 = math.exp(-((px - 0.6)^2 + (py - 0.1)^2))
local d2 = math.exp(-((px + 0.7)^2 + (py + 0.1)^2)*2)
local d = (d1 + d2)/2
if d > t then
return r,g,b,((d-t)/(1-t))^0.2
end
return 0,0,0,0
end
end
end
--- debug
function debug.getCollection()
print("Before collection : " .. collectgarbage("count")/1024)
collectgarbage()
print("After collection : ".. collectgarbage("count")/1024)
print("object count : " )
local counts = type_count()
for k , v in pairs(counts) do print(k,v) end
print("------------------------------")
end
--- check x,y in button
--- @type func
--- @param x1 number
--- @param y1 number
--- @param x2 number
--- @param y2 number
--- @param x number
--- @param y number
--- @return boolean
function checkButton(x1,y1,x2,y2,x,y)
return x > x1 and x < x2 and y > y1 and y < y2;
end |
return {
version = "1.5",
luaversion = "5.1",
tiledversion = "1.5.0",
orientation = "orthogonal",
renderorder = "right-down",
width = 30,
height = 30,
tilewidth = 16,
tileheight = 16,
nextlayerid = 4,
nextobjectid = 5,
properties = {},
tilesets = {
{
name = "Tiles",
firstgid = 1,
tilewidth = 16,
tileheight = 16,
spacing = 0,
margin = 0,
columns = 10,
image = "_tilesets/tiles.png",
imagewidth = 160,
imageheight = 80,
objectalignment = "unspecified",
tileoffset = {
x = 0,
y = 0
},
grid = {
orientation = "orthogonal",
width = 16,
height = 16
},
properties = {},
wangsets = {},
tilecount = 50,
tiles = {}
}
},
layers = {
{
type = "tilelayer",
x = 0,
y = 0,
width = 30,
height = 30,
id = 1,
name = "Base",
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
parallaxx = 1,
parallaxy = 1,
properties = {},
encoding = "lua",
data = {
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41
}
},
{
type = "tilelayer",
x = 0,
y = 0,
width = 30,
height = 30,
id = 2,
name = "Tiles",
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
parallaxx = 1,
parallaxy = 1,
properties = {},
encoding = "lua",
data = {
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
}
},
{
type = "objectgroup",
draworder = "topdown",
id = 3,
name = "Walls",
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
parallaxx = 1,
parallaxy = 1,
properties = {},
objects = {
{
id = 1,
name = "",
type = "",
shape = "rectangle",
x = 0,
y = 0,
width = 16,
height = 480,
rotation = 0,
visible = true,
properties = {}
},
{
id = 2,
name = "",
type = "",
shape = "rectangle",
x = 16,
y = 0,
width = 448,
height = 16,
rotation = 0,
visible = true,
properties = {}
},
{
id = 3,
name = "",
type = "",
shape = "rectangle",
x = 464,
y = 0,
width = 16,
height = 480,
rotation = 0,
visible = true,
properties = {}
},
{
id = 4,
name = "",
type = "",
shape = "rectangle",
x = 16,
y = 464,
width = 448,
height = 16,
rotation = 0,
visible = true,
properties = {}
}
}
}
}
}
|
-- remove beats from measures object
--
--
-- argt specifies removal mode:
-- - positions : elements that should be removed
-- - matching : if a beat matches the values, remove it
-- - between/and : (dual argument) remove beats between beats A and B
-- - matching_assoc : remove beats which match any in associated (not implemented yet)
--
--
--
local ssub = string.sub
local coerce2table = function (argt_key)
local type_string = type(argt_key)
type_string = ssub(type_string, 1,1)
if type_string=='n' then
return {argt_key}
elseif type_string=='t' then
return argt_key
else
error("type of args passed to remove must be a table or a number"
,3)
end
end
local tsort = table.sort
--local RIFAF = function (self, table_of_indices) -- RemoveIndicesFromAllFields
-- this function
return function (self, argt)
-- collect args from aliases and adjust into tables if necessary
-- positions
argt.positions = argt.pos
or argt.positions
or argt.indices
or argt.idx
or argt.index
argt.positions = coerce2table(argt.positions)
-- beats
argt.matching = argt.beats
or argt.matching
or argt.matching_beats
argt.matching = coerce2table(argt.matching)
tsort(argt.matching)
-- between/and
argt.between = argt.between
or argt.from
or argt.btn
or argt.b
or argt.btwn
argt.and = argt.and
or argt.to
or argt.a
--
-- matching associated table
argt.associated = argt.associated
-- (no implementation yet)
-- relevant locals
local rhythm = self:get('r')
local remove_which = {} -- store indices we will remove into this table
-- construct `remove_which`
if argt.positions then
remove_which = argt.positions
elseif argt.matching then
local matching = argt.matching
local start_at = 1 -- index at which to start search in inner loop
for m=1,#matching do
local mval = matching[m]
for r=start_at,#rhythm do
if rhythm[r]==mval then
remove_which[#remove_which + 1] = r
elseif
local ry,rm,m = 1,1,1 --loop indices for `rhythm`, `remove_which`, and `matching`
while matching[m] do
if rhythm[r]~=matching[m]
|
local ATest = bt.Class("ATest",bt.ActionTask)
bt.ATest = ATest
function ATest:ctor()
bt.ActionTask.ctor(self)
self.name = "ATest"
end
function ATest:init(jsonData)
end
function ATest:onExecute()
local success = APIAction.test(self.agent)
self:endAction(true)
end |
-----------------------------------
-- Ability: Spirit Surge
-- Adds your wyvern's strength to your own.
-- Obtained: Dragoon Level 1
-- Recast Time: 1:00:00
-- Duration: 1:00
-----------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------
function onAbilityCheck(player,target,ability)
-- The wyvern must be present in order to use Spirit Surge
if (target:getPet() == nil) then
return tpz.msg.basic.REQUIRES_A_PET,0
else
return 0,0
end
end
function onUseAbility(player,target,ability)
-- Spirit Surge increases dragoon's MAX HP increases by 25% of wyvern MaxHP
-- bg wiki says 25% ffxiclopedia says 15%, going with 25 for now
local mhp_boost = target:getPet():getMaxHP()*0.25
-- Dragoon gets all of wyverns TP when using Spirit Surge
local pet = player:getPet()
local petTP = pet:getTP()
target:addTP(petTP) --add pet TP to dragoon
pet:delTP(petTP) -- remove TP from pet
-- Spirit Surge increases dragoon's Strength
local strBoost = 0
if (target:getMainJob() == tpz.job.DRG) then
strBoost = (1 + target:getMainLvl()/5) -- Use Mainjob Lvl
else
strBoost = (1 + target:getSubLvl()/5) -- Use Subjob Lvl
end
local duration = 60
target:despawnPet()
-- All Jump recast times are reset
target:resetRecast(tpz.recast.ABILITY,158) -- Jump
target:resetRecast(tpz.recast.ABILITY,159) -- High Jump
target:resetRecast(tpz.recast.ABILITY,160) -- Super Jump
target:addStatusEffect(tpz.effect.SPIRIT_SURGE, mhp_boost, 0, duration, 0, strBoost)
end
|
return {
new = function(self, flags)
if self.path.exists("config.lua") then
self:fail_with_message("config.lua already exists")
end
return self:write_file_safe("config.lua", require("lapis.cmd.cqueues.templates.config"))
end,
server = function(self, flags, environment)
local push, pop
do
local _obj_0 = require("lapis.environment")
push, pop = _obj_0.push, _obj_0.pop
end
local start_server
start_server = require("lapis.cmd.cqueues").start_server
push(environment)
local config = require("lapis.config").get()
local app_module = config.app_class or "app"
start_server(app_module)
return pop()
end
}
|
--[[
LuCI - SGI-Module for CGI
Description:
Server Gateway Interface for CGI
FileId:
$Id: cgi.lua 6535 2010-11-23 01:02:21Z soma $
License:
Copyright 2008 Steven Barth <[email protected]>
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.
]]--
exectime = os.clock()
module("luci.sgi.cgi", package.seeall)
local ltn12 = require("luci.ltn12")
require("nixio.util")
require("luci.http")
require("luci.sys")
require("luci.dispatcher")
-- Limited source to avoid endless blocking
local function limitsource(handle, limit)
limit = limit or 0
local BLOCKSIZE = ltn12.BLOCKSIZE
return function()
if limit < 1 then
handle:close()
return nil
else
local read = (limit > BLOCKSIZE) and BLOCKSIZE or limit
limit = limit - read
local chunk = handle:read(read)
if not chunk then handle:close() end
return chunk
end
end
end
function run()
local r = luci.http.Request(
luci.sys.getenv(),
limitsource(io.stdin, tonumber(luci.sys.getenv("CONTENT_LENGTH"))),
ltn12.sink.file(io.stderr)
)
local x = coroutine.create(luci.dispatcher.httpdispatch)
local hcache = ""
local active = true
while coroutine.status(x) ~= "dead" do
local res, id, data1, data2 = coroutine.resume(x, r)
if not res then
print("Status: 500 Internal Server Error")
print("Content-Type: text/plain\n")
print(id)
break;
end
if active then
if id == 1 then
io.write("Status: " .. tostring(data1) .. " " .. data2 .. "\r\n")
elseif id == 2 then
hcache = hcache .. data1 .. ": " .. data2 .. "\r\n"
elseif id == 3 then
io.write(hcache)
io.write("\r\n")
elseif id == 4 then
io.write(tostring(data1 or ""))
elseif id == 5 then
io.flush()
io.close()
active = false
elseif id == 6 then
data1:copyz(nixio.stdout, data2)
data1:close()
end
end
end
end
|
local helper = require("commented.helper")
local opts = {
comment_padding = " ",
keybindings = { n = "<leader>c", v = "<leader>c", nl = "<leader>cc" },
-- NOTE: The key in this table should match the key of the codetags block
codetags_keybindings = {},
set_keybindings = true,
prefer_block_comment = false, -- Set it to true to automatically use block comment when multiple lines are selected
inline_cms = {
hjson = { inline = "//%s" },
mysql = { inline = "#%s" },
jproperties = { inline = "!%s" },
terraform = { inline = "//%s" },
service = { inline = ";%s" },
dosini = { inline = "#%s" },
},
block_cms = {
wast = { block = "(;%s;)" },
asciidoc = { block = "////%s////" },
imba = { block = "###%s###" },
bicep = { block = "/*%s*/" },
yang = { block = "/*%s*/" },
solidity = { block = "/*%s*/" },
typescriptreact = { block = "/*%s*/" },
javascriptreact = { block = "/*%s*/" },
javascript = { block = "/*%s*/" },
typescript = { block = "/*%s*/" },
mint = { block = "/*%s*/" },
jsonc = { block = "/*%s*/" },
sql = { block = "/*%s*/" },
mysql = { block = "/*%s*/" },
lua = { block = "--[[%s--]]" },
teal = { block = "--[[%s--]]" },
rust = { block = "/*%s*/" },
kotlin = { block = "/*%s*/" },
java = { block = "/*%s*/" },
groovy = { block = "/*%s*/" },
go = { block = "/*%s*/" },
php = { block = "/*%s*/" },
c = { block = "/*%s*/", throw_away_block = "#if 0%s#endif" },
cpp = { block = "/*%s*/", throw_away_block = "#if 0%s#endif" },
vala = { block = "/*%s*/" },
genie = { block = "/*%s*/" },
cs = { block = "/*%s*/" },
fs = { block = "(*%s*)" },
julia = { block = "#=%s=#" },
hjson = { block = "/*%s*/" },
dhall = { block = "{-%s-}" },
lean = { block = "/-%s-/" },
wren = { block = "/*%s*/" },
pug = { unbuffered = "//-%s", block = "//-%s//" },
haml = { unbuffered = "-#" },
haxe = { block = "/**%s**/" },
rjson = { block = "/*%s*/" },
jison = { block = "/*%s*/" },
terraform = { block = "/*%s*/" },
d = { block = "/*%s*/", alt_block = "/+%s+/" },
yuck = { block = "#|%s|#" },
racket = { block = "#|%s|#" },
pony = { block = "/*%s*/" },
reason = { block = "/*%s*/" },
rescript = { block = "/*%s*/" },
},
-- commentstring used for commenting
lang_options = {},
ex_mode_cmd = "Comment",
left_align_comment = false,
hooks = {},
}
local leading_space = "^%s*"
local space_only = leading_space .. "$"
local function commenting_lines(fn_opts)
local start_symbol, end_symbol = fn_opts.symbols[1], fn_opts.symbols[2]
local commented_lines = helper.map(function(line, index)
-- local pattern = opts.left_align_comment and leading_space or "([^%s])"
-- ([^%s*])
-- Make this a global option?
local pattern = "([^%s])"
local commented_line = line:gsub(
pattern,
(index == 1 and start_symbol .. fn_opts.prefix or start_symbol) .. opts.comment_padding .. "%1",
1
)
if end_symbol ~= "" then
commented_line = commented_line .. opts.comment_padding .. end_symbol
end
return commented_line
end, fn_opts.lines)
vim.api.nvim_buf_set_lines(0, fn_opts.start_line, fn_opts.end_line, false, commented_lines)
end
local function clear_lines_symbols(fn_opts)
local prefix = fn_opts.prefix or ""
return helper.map(function(line, index)
if line:match(space_only) then
return line
end
local start_symbol, end_symbol = unpack(fn_opts.uncomment_symbols[index])
local pattern = opts.left_align_comment and opts.comment_padding or "%s*"
local cleaned_line = line:gsub(
(index == 1 and start_symbol .. prefix .. pattern or start_symbol .. pattern),
"",
1
)
if end_symbol ~= "" then
cleaned_line = cleaned_line:gsub("%s*" .. end_symbol, "")
end
return cleaned_line
end, fn_opts.lines)
end
local function uncommenting_lines(fn_opts)
vim.api.nvim_buf_set_lines(
0,
fn_opts.start_line,
fn_opts.end_line,
false,
clear_lines_symbols({
lines = fn_opts.lines,
uncomment_symbols = fn_opts.uncomment_symbols,
prefix = fn_opts.prefix,
})
)
end
--NOTE Insert uncommenting_symbols while check for a match
local function has_matching_pattern(line, comment_patterns, uncomment_symbols)
local matched = false
for _, pattern in pairs(comment_patterns) do
local escaped_start_symbol, escaped_end_symbol = helper.escape_symbols(helper.get_comment_wrap(pattern))
local escaped_pattern = "^%s*" .. escaped_start_symbol .. ".*" .. escaped_end_symbol
if line:match(escaped_pattern) then
table.insert(uncomment_symbols, { escaped_start_symbol, escaped_end_symbol })
matched = true
break
end
end
return matched
end
local function toggle_inline_comment(fn_opts)
local should_comment = false
local uncomment_symbols, filetype = {}, vim.o.filetype
local cms = vim.api.nvim_buf_get_option(0, "commentstring")
-- exit early if no cms defined
if cms == "" then
vim.api.nvim_err_writeln("Commented.nvim: No commentstring defined for this filetype.")
return
end
local alt_cms = opts.inline_cms[filetype] or {}
local comment_patterns = vim.tbl_extend("force", { cms = cms }, alt_cms or {})
for _, line in ipairs(fn_opts.lines) do
if not line:match(space_only) then
local matched = has_matching_pattern(line, comment_patterns, uncomment_symbols)
if not matched then
should_comment = true
break
end
else
table.insert(uncomment_symbols, { "", "" })
end
end
if should_comment then
local cms_to_use = (opts.lang_options[filetype] or {}).inline
and helper.escape_symbols(opts.lang_options[filetype].inline)
or cms
commenting_lines({
lines = fn_opts.lines,
start_line = fn_opts.start_line,
end_line = fn_opts.end_line,
prefix = fn_opts.prefix,
symbols = {
helper.get_comment_wrap(cms_to_use),
},
})
else
uncommenting_lines({
lines = fn_opts.lines,
start_line = fn_opts.start_line,
end_line = fn_opts.end_line,
prefix = fn_opts.prefix,
uncomment_symbols = uncomment_symbols,
})
end
end
local function toggle_block_comment(lines, start_line, end_line, block_symbols, should_comment, insert_newlines)
if should_comment then
lines[1] = lines[1]:gsub("([^%s])", block_symbols[1][1] .. opts.comment_padding .. "%1", 1)
if insert_newlines then
local str = lines[1]
i, j = string.find(str, block_symbols[1][1] .. opts.comment_padding)
lines[1] = string.sub(str, i, j - #opts.comment_padding)
table.insert(lines, 2, string.sub(str, 0, i - 1) .. string.sub(str, j + #opts.comment_padding, #str))
end
lines[#lines] = lines[#lines]:gsub("%s*$", "%1" .. opts.comment_padding .. block_symbols[2][2], 1)
if insert_newlines then
local str = lines[#lines]
i, j = string.find(str, block_symbols[2][2])
lines[#lines] = string.sub(str, 0, i - #opts.comment_padding - 1)
table.insert(lines, #lines + 1, string.sub(str, i, j))
end
vim.api.nvim_buf_set_lines(0, start_line, end_line, false, lines)
else
lines[1], lines[#lines] = unpack(
clear_lines_symbols({ lines = { lines[1], lines[#lines] }, uncomment_symbols = block_symbols })
)
-- If we have empty lines, we inserted newlines so delete them
if #lines[1] == 0 and #lines[#lines] == 0 then
table.remove(lines, 1)
table.remove(lines, #lines)
end
vim.api.nvim_buf_set_lines(0, start_line, end_line, false, lines)
end
end
local function has_symbol(prefix, suffix)
return function(str, symbol)
return str:match(prefix .. symbol .. suffix)
end
end
local has_start_symbol = has_symbol("^%s*", "")
local has_end_symbol = has_symbol("", "%s*$")
local function toggle_comment(mode, comment_prefix, line1, line2)
local start_line, end_line = helper.get_lines(mode, line1, line2)
local lines = vim.api.nvim_buf_get_lines(0, start_line, end_line, false)
local is_block, should_comment, insert_newlines = false, true, false
local block_symbols = nil
local filetype = vim.o.filetype
if type(opts.hooks.before_comment) == "function" then
opts.hooks.before_comment()
end
if opts.block_cms[filetype] then
if #lines > 1 then
local comment_patterns = opts.block_cms[filetype]
if not comment_patterns then
return
end
local first_line, last_line = lines[1], lines[#lines]
for _, pattern in pairs(comment_patterns) do
local start_symbol, end_symbol = helper.escape_symbols(helper.get_comment_wrap(pattern))
if
has_start_symbol(first_line, start_symbol)
and not has_end_symbol(first_line, end_symbol)
and not has_start_symbol(last_line, start_symbol)
and has_end_symbol(last_line, end_symbol)
then
block_symbols = { { start_symbol, "" }, { "", end_symbol } }
is_block, should_comment = true, false
break
end
end
if
opts.prefer_block_comment
or opts.lang_options[filetype] and (opts.lang_options[filetype] or {}).prefer_block_comment
then
-- Decide what block symbol to use
local start_symbol, end_symbol
if opts.lang_options[filetype] and (opts.lang_options[filetype].cms or {}).block then
start_symbol, end_symbol = helper.escape_symbols(
helper.get_comment_wrap(opts.lang_options[filetype].cms.block)
)
if opts.lang_options[filetype].insert_newlines then
insert_newlines = true
end
else
start_symbol, end_symbol = helper.escape_symbols(
helper.get_comment_wrap(opts.block_cms[filetype].block)
)
end
block_symbols = { { start_symbol, "" }, { "", end_symbol } }
is_block = true
end
end
end
if is_block then
toggle_block_comment(lines, start_line, end_line, block_symbols, should_comment, insert_newlines)
else
toggle_inline_comment({ lines = lines, start_line = start_line, end_line = end_line, prefix = comment_prefix })
end
end
local function opfunc(prefix)
return function()
toggle_comment("n", prefix)
end
end
local function commented(prefix)
prefix = prefix or ""
_G.commented = opfunc(prefix)
vim.api.nvim_set_option("opfunc", "v:lua.commented")
return "g@"
-- Return the string for evaluation, so that we don't need to feed key
-- vim.api.nvim_feedkeys('g@', 'n')
end
local function commented_line(prefix)
prefix = prefix or ""
_G.commented = opfunc(prefix)
vim.api.nvim_set_option("opfunc", "v:lua.commented")
return "g@$"
end
local function setup(user_opts)
opts = vim.tbl_deep_extend("force", opts, user_opts or {})
-- NOTE: For backward compatibility
opts.keybindings.x = opts.keybindings.v
opts.inline_cms = vim.tbl_deep_extend("force", opts.inline_cms, opts.block_cms)
local supported_modes = { "n", "x" }
if opts.set_keybindings then
for _, mode in ipairs(supported_modes) do
vim.api.nvim_set_keymap(mode, opts.keybindings[mode], "v:lua.require'commented'.commented()", {
expr = true,
silent = true,
noremap = true,
})
end
vim.api.nvim_set_keymap(
"n",
opts.keybindings.nl,
"v:lua.require'commented'.commented_line()",
{ expr = true, silent = true, noremap = true }
)
end
if opts.ex_mode_cmd then
vim.api.nvim_exec(
"command! -range "
.. opts.ex_mode_cmd
.. " lua require('commented').toggle_comment('c', '', <line1>, <line2>)",
true
)
end
for key, binding in pairs(opts.codetags_keybindings) do
for _, mode in ipairs(supported_modes) do
vim.api.nvim_set_keymap(mode, binding, "v:lua.require'commented'.codetags." .. key .. "()", {
expr = true,
silent = true,
noremap = true,
})
end
end
end
local codetags = {
fixme = function()
return commented("FIXME")
end,
fixme_line = function()
return commented_line("FIXME")
end,
todo = function()
return commented("TODO")
end,
todo_line = function()
return commented_line("TODO")
end,
bug = function()
return commented("BUG")
end,
bug_line = function()
return commented_line("BUG")
end,
note = function()
return commented("NOTE")
end,
note_line = function()
return commented_line("NOTE")
end,
wont_fix = function()
return commented("WONTFIX")
end,
wont_fix_line = function()
return commented_line("WONTFIX")
end,
ref = function()
return commented("REF")
end,
ref_line = function()
return commented_line("REF")
end,
}
return {
setup = setup,
toggle_comment = toggle_comment,
commented = commented,
commented_line = commented_line,
codetags = codetags,
}
|
math.tau = math.pi * 2
-- Takes two Vector2s and draws them in front of the vehicle to simulate an actual HUD.
-- Is rotated by the vehicle's roll.
function HUD:DrawLineHUD( pos1 , pos2 , noRoll )
local position = self.vehicle:GetPosition()
local angle = self.vehicle:GetAngle()
if noRoll then
local roll = self:GetRoll()
pos1 = GUIUtil.Rot( pos1, Vector2.Zero, roll )
pos2 = GUIUtil.Rot( pos2, Vector2.Zero, roll )
end
-- Multiply them by distanceHUD, otherwise, they'll be tiny.
pos1 = pos1 * settings.distanceHUD * settings.scaleHUD
pos2 = pos2 * settings.distanceHUD * settings.scaleHUD
-- Create the 3D vectors.
local vec1 = Vector3( pos1.x, pos1.y, -settings.distanceHUD )
vec1 = angle * vec1
local vec2 = Vector3( pos2.x, pos2.y, -settings.distanceHUD )
vec2 = angle * vec2
vec1 = vec1 + position
vec2 = vec2 + position
GUIUtil.DrawLine3D( vec1, vec2, self.colorHUD )
end
function HUD:DrawCircleHUD( radius , center , numSegments )
local posPrevious = Vector2( radius, 0 ) + center
local pos
for n = 1 , numSegments do
pos = Vector2(radius , 0)
pos = GUIUtil.Rot( pos, Vector2.Zero, (n / numSegments) * math.tau )
pos = pos + center
self:DrawLineHUD( pos, posPrevious )
posPrevious = pos
end
end
-- pos is a Vector2.
function HUD:DrawTextHUD( text , pos , align , noRoll )
local position = self.vehicle:GetPosition()
local angle = self.vehicle:GetAngle()
-- Rotate around center by vehicle roll.
local roll = self:GetRoll()
if noRoll then
pos = GUIUtil.Rot( pos, Vector2.Zero, roll )
end
-- Multiply position by distanceHUD, otherwise it will be tiny.
pos = pos * settings.distanceHUD * settings.scaleHUD
-- Convert position to 3D vector.
pos = Vector3(pos.x, pos.y, -settings.distanceHUD)
pos = angle * pos
pos = pos + position
if noRoll then
angle = Angle.AngleAxis(roll , angle * Vector3( 0 , 0 , -1 )) * angle
end
GUIUtil.DrawText3D(
text ,
self.colorHUD ,
pos ,
angle ,
settings.distanceHUD * 0.035 * settings.scaleHUD ,
align
)
end |
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire E2 Graphics Processor Emitter"
ENT.RenderGroup = RENDERGROUP_TRANSLUCENT
ENT.WireDebugName = "E2 Graphics Processor Emitter"
if CLIENT then
ENT.gmod_wire_egp_emitter = true
ENT.DrawOffsetPos = Vector(-64, 0, 135)
ENT.DrawOffsetAng = Angle(0, 0, 90)
ENT.DrawScale = 0.25
function ENT:Initialize()
self.RenderTable = table.Copy(EGP.HomeScreen)
end
function ENT:EGP_Update()
self.UpdateConstantly = nil
for k,object in pairs(self.RenderTable) do
if object.parent == -1 or object.Is3DTracker then self.UpdateConstantly = true end -- Check if an object is parented to the cursor (or for 3DTrackers)
if object.parent and object.parent ~= 0 then
if not object.IsParented then EGP:SetParent(self, object.index, object.parent) end
local _, data = EGP:GetGlobalPos(self, object.index)
EGP:EditObject(object, data)
elseif not object.parent or object.parent == 0 and object.IsParented then
EGP:UnParent(self, object.index)
end
end
end
function ENT:DrawEntityOutline() end
local wire_egp_emitter_drawdist = CreateClientConVar("wire_egp_emitter_drawdist","0",true,false)
function ENT:Think()
local dist = Vector(1,0,1)*wire_egp_emitter_drawdist:GetInt()
self:SetRenderBounds(Vector(-64,0,0)-dist,Vector(64,0,135)+dist)
end
local wire_egp_drawemitters = CreateClientConVar("wire_egp_drawemitters", "1")
function ENT:Draw()
if (wire_egp_drawemitters:GetBool() == true and self.RenderTable and #self.RenderTable > 0) then
if (self.UpdateConstantly) then self:EGP_Update() end
local pos = self:LocalToWorld(self.DrawOffsetPos)
local ang = self:LocalToWorldAngles(self.DrawOffsetAng)
local mat = self:GetEGPMatrix()
cam.Start3D2D(pos, ang, self.DrawScale)
local globalfilter = TEXFILTER.ANISOTROPIC -- Emitter uses ANISOTRPOIC (unchangeable)
for i=1,#self.RenderTable do
local object = self.RenderTable[i]
local oldtex = EGP:SetMaterial( object.material )
if object.filtering != globalfilter then
render.PushFilterMag(object.filtering)
render.PushFilterMin(object.filtering)
object:Draw(self, mat)
render.PopFilterMin()
render.PopFilterMag()
else
object:Draw(self, mat)
end
EGP:FixMaterial( oldtex )
end
cam.End3D2D()
end
self:DrawModel()
Wire_Render(self)
end
-- cam.PushModelMatrix replaces the currently drawn matrix, because cam.Start3D2D
-- pushes a matrix of its own we need to replicate it
function ENT:GetEGPMatrix()
local mat = Matrix()
local pos = self:LocalToWorld(self.DrawOffsetPos)
mat:SetTranslation(pos)
-- Just using the angle given to cam.Start3D2D doesn't seem to work, it seems to be rotated 180 on the roll
local ang = self:LocalToWorldAngles(self.DrawOffsetAng + Angle(0, 0, 180))
mat:SetAngles(ang)
local scale = Vector(1, 1, 1)
scale:Mul(self.DrawScale)
mat:SetScale(scale)
return mat
end
return -- No more client
end
-- Server
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
--self:DrawShadow( false )
self.RenderTable = {}
self:SetUseType(SIMPLE_USE)
WireLib.CreateWirelinkOutput( nil, self, {true} )
self.xScale = { 0, 512 }
self.yScale = { 0, 512 }
self.Scaling = false
self.TopLeft = false
end
function ENT:SetEGPOwner( ply )
self.ply = ply
self.plyID = ply:UniqueID()
end
function ENT:GetEGPOwner()
if (!self.ply or !self.ply:IsValid()) then
local ply = player.GetByUniqueID( self.plyID )
if (ply) then self.ply = ply end
return ply
else
return self.ply
end
return false
end
function ENT:UpdateTransmitState() return TRANSMIT_ALWAYS end
|
module 'mock'
CLASS: UIButton ( UIWidget )
:MODEL{
Field 'text' :string() :getset( 'Text' );
}
:SIGNAL{
pressed = 'onPressed';
released = 'onReleased';
clicked = 'onClicked';
}
function UIButton:__init()
self._hoverd = false
self._pressed = false
self.text = 'Button'
self.layoutPolicy = { 'expand', 'expand' }
end
function UIButton:onLoad()
self:setRenderer( UIButtonRenderer() )
end
function UIButton:setText( t )
self.text = t
self:invalidateContent()
end
function UIButton:getText()
return self.text
end
function UIButton:getContentData( key, role )
if key == 'text' then
return self:getText()
end
end
function UIButton:updateStyleState()
if self._pressed then
return self:setState( 'press' )
end
if self._hoverd then
return self:setState( 'hover' )
end
return UIButton.__super.updateStyleState( self )
end
function UIButton:procEvent( ev )
local t = ev.type
local d = ev.data
if t == UIEvent.POINTER_ENTER then
self._hoverd = true
self:updateStyleState()
elseif t == UIEvent.POINTER_EXIT then
self._hoverd = false
self:updateStyleState()
elseif t == UIEvent.POINTER_DOWN then
self._pressed = true
self:updateStyleState()
self.pressed:emit()
return
elseif t == UIEvent.POINTER_UP then
if self._pressed then
self._pressed = false
self:updateStyleState()
local px,py,pz = self:getWorldLoc()
if self:inside( d.x, d.y, pz, self:getTouchPadding() ) then
self.clicked:emit()
end
end
self.released:emit()
return
end
end
function UIButton:getLabelRect()
return self:getContentRect()
end
----
function UIButton:onPressed()
end
function UIButton:onReleased()
end
function UIButton:onClicked()
end
|
--[[
Hacks a class (a.k.a. table) to debug all of its function calls.
--]]
local Class = require("YfritLib.Class")
local Table = require("YfritLib.Table")
local Spy =
Class.new(
{},
function(self, target)
self.tabs = 0
self.currentLine = 0
self.lastPrintedLine = 0
self.buffer = {}
self:_replaceMethods(target)
end
)
function Spy:_replaceMethods(target)
for fieldName, fieldValue in pairs(target) do
-- check if is a method
if type(fieldValue) == "function" then
self:_replaceMethod(target, fieldName, fieldValue)
end
end
end
function Spy:_replaceMethod(target, methodName, methodFunction)
-- wrap original function with one of our own
target[methodName] = function(targetSelf, ...)
self.currentLine = self.currentLine + 1
local currentLine = self.currentLine
self.tabs = self.tabs + 1
local results = {methodFunction(targetSelf, ...)}
self.tabs = self.tabs - 1
self.buffer[currentLine] =
string.rep("\t", self.tabs) .. methodName .. self:_formatParameters({...}) .. self:_formatResults(results)
if currentLine == self.lastPrintedLine + 1 then
self:_printLines()
end
return unpack(results)
end
end
function Spy:_formatParameters(parameters)
local strings = Table.map(parameters, tostring)
return "(" .. table.concat(strings, ", ") .. ")"
end
function Spy:_formatResults(results)
if #results > 0 then
local strings = Table.map(results, tostring)
return " => " .. table.concat(strings, ", ")
else
return ""
end
end
function Spy:_printLines()
local line = self.lastPrintedLine + 1
while self.buffer[line] do
print(self.buffer[line])
line = line + 1
end
self.lastPrintedLine = line - 1
end
return function(target)
return Spy:new(target)
end
|
-- decided to give it an "_official" suffix because there may be a lot more m249s out there
AddCSLuaFile()
AddCSLuaFile("sh_sounds.lua")
include("sh_sounds.lua")
if CLIENT then
SWEP.DrawCrosshair = false
SWEP.PrintName = "M249"
SWEP.CSMuzzleFlashes = true
SWEP.ViewModelMovementScale = 1.15
SWEP.CustomizationMenuScale = 0.015
SWEP.IconLetter = "i"
killicon.AddFont("cw_m249_official", "CW_KillIcons", SWEP.IconLetter, Color(255, 80, 0, 150))
SWEP.MuzzleEffect = "muzzleflash_6"
SWEP.PosBasedMuz = false
SWEP.SnapToGrip = true
SWEP.ShellScale = 0.7
SWEP.ShellOffsetMul = 1
SWEP.ShellPosOffset = {x = 0, y = 0, z = 0}
SWEP.ForeGripOffsetCycle_Draw = 0.8
SWEP.ForeGripOffsetCycle_Reload = 0.9
SWEP.ForeGripOffsetCycle_Reload_Empty = 0.93
SWEP.FireMoveMod = 0.6
SWEP.DrawTraditionalWorldModel = false
SWEP.WM = "models/weapons/cw2_0_mach_para.mdl"
SWEP.WMPos = Vector(-1.5, 2, 0.5)
SWEP.WMAng = Vector(0, 0, 180)
SWEP.IronsightPos = Vector(-2.05, -1.964, 0.972)
SWEP.IronsightAng = Vector(0, 0, 0)
SWEP.EoTechPos = Vector(-2.05, -0.993, -0.093)
SWEP.EoTechAng = Vector(0, 0, 0)
SWEP.AimpointPos = Vector(-2.043, -2.5, 0.115)
SWEP.AimpointAng = Vector(0, 0, 0)
SWEP.MicroT1Pos = Vector(-2.043, -0.993, 0.236)
SWEP.MicroT1Ang = Vector(0, 0, 0)
SWEP.ACOGPos = Vector(-2.02, -2.869, -0.124)
SWEP.ACOGAng = Vector(0, 0, 0)
SWEP.ShortDotPos = Vector(-2.02, -2.869, 0.123)
SWEP.ShortDotAng = Vector(0, 0, 0)
SWEP.SprintPos = Vector(1.786, 0, -1)
SWEP.SprintAng = Vector(-10.778, 27.573, 0)
SWEP.BackupSights = {["md_acog"] = {[1] = Vector(-2.02, -2.869, -1.132), [2] = Vector(0, 0, 0)}}
SWEP.SightWithRail = true
SWEP.ACOGAxisAlign = {right = 0.03, up = 0, forward = 0}
SWEP.SchmidtShortDotAxisAlign = {right = 0, up = 0, forward = 0}
SWEP.AlternativePos = Vector(-0.2, 0, -0.4)
SWEP.AlternativeAng = Vector(0, 0, 0)
SWEP.AttachmentModelsVM = {
["md_aimpoint"] = {model = "models/wystan/attachments/aimpoint.mdl", bone = "LidCont", pos = Vector(-0.427, -8.511, -4.505), angle = Angle(0, 0, 0), size = Vector(0.899, 0.899, 0.899)},
["md_eotech"] = {model = "models/wystan/attachments/2otech557sight.mdl", bone = "LidCont", pos = Vector(0.079, -13.825, -10.714), angle = Angle(3.329, -90, 0), size = Vector(1, 1, 1)},
["md_saker"] = {model = "models/cw2/attachments/556suppressor.mdl", bone = "Weapon", pos = Vector(0.014, 3.732, 1.504), angle = Angle(0, 0, 0), size = Vector(0.6, 0.6, 0.6)},
["md_acog"] = {model = "models/wystan/attachments/2cog.mdl", bone = "LidCont", pos = Vector(-0.51, -8.903, -4.573), angle = Angle(0, 0, 0), size = Vector(0.899, 0.899, 0.899)},
["md_microt1"] = {model = "models/cw2/attachments/microt1.mdl", bone = "LidCont", pos = Vector(-0.181, -4.047, 0.69), angle = Angle(0, 180, 0), size = Vector(0.4, 0.4, 0.4)},
["md_bipod"] = {model = "models/wystan/attachments/bipod.mdl", bone = "Weapon", pos = Vector(0.138, 6.619, 0.601), angle = Angle(0, 0, 0), size = Vector(0.699, 0.699, 0.699), bodygroup = {[1] = 1}},
["md_schmidt_shortdot"] = {model = "models/cw2/attachments/schmidt.mdl", bone = "LidCont", pos = Vector(-0.515, -9.205, -4.549), angle = Angle(0, -90, 0), size = Vector(0.899, 0.899, 0.899)},
["md_foregrip"] = {model = "models/wystan/attachments/foregrip1.mdl", bone = "Weapon", pos = Vector(10.583, 5.614, -0.951), angle = Angle(0, -90, 0), size = Vector(0.699, 0.699, 0.699)}
}
SWEP.ForeGripHoldPos = {
["L Finger1"] = {pos = Vector(0, 0, 0), angle = Angle(13.88, 90.466, 18.638) },
["l_upperarm"] = {pos = Vector(0, 0, 0), angle = Angle(18.875, 0, 0) },
["L Finger12"] = {pos = Vector(0, 0, 0), angle = Angle(0, 28.931, 0) },
["L Clavicle"] = {pos = Vector(0, 4.344, 0), angle = Angle(-49.645, 0, -11.665) },
["L Hand"] = {pos = Vector(0, 0, 0), angle = Angle(16.122, 18.378, 43.624) },
["L Finger3"] = {pos = Vector(0, 0, 0), angle = Angle(0.972, 44.411, 13.453) },
["L Finger01"] = {pos = Vector(0, 0, 0), angle = Angle(0, 26.996, 0) },
["L Finger0"] = {pos = Vector(0, 0, 0), angle = Angle(11.201, -6.533, -19.001) },
["L Finger42"] = {pos = Vector(0, 0, 0), angle = Angle(0, 78.379, 0) },
["L UpperArm"] = {pos = Vector(-12.985, -0.987, -0.308), angle = Angle(0, 31.971, 6.557) },
["L Finger22"] = {pos = Vector(0, 0, 0), angle = Angle(0, 43.025, 0) },
["L Finger41"] = {pos = Vector(0, 0, 0), angle = Angle(0, -20.861, 0) },
["L Finger02"] = {pos = Vector(0, 0, 0), angle = Angle(0, 73.864, 0) },
["L Finger4"] = {pos = Vector(0, 0, 0), angle = Angle(-8.929, 26.59, 0) },
["L Finger32"] = {pos = Vector(0, 0, 0), angle = Angle(0, 53.505, 0) },
["L Finger2"] = {pos = Vector(0, 0, 0), angle = Angle(3, 69.235, 21.884) },
["L Finger21"] = {pos = Vector(0, 0, 0), angle = Angle(0, -20.979, 0) },
["L Finger11"] = {pos = Vector(0, 0, 0), angle = Angle(0, -19.306, 0) }
}
SWEP.LuaVMRecoilAxisMod = {vert = 1, hor = 1, roll = 1, forward = 1, pitch = 1}
SWEP.LaserPosAdjust = Vector(0.5, 0, 0)
SWEP.LaserAngAdjust = Angle(0, 180, 0)
SWEP.OverallMouseSens = 0.7
SWEP.Trivia = {text = "Accurate aimed fire is not possible without the use of a bipod with this weapon.", x = -500, y = -360, textFormatFunc = function(self, wep) if wep.ActiveAttachments.md_bipod then return "" else return self.text end end}
end
SWEP.MuzzleVelocity = 915
SWEP.LuaViewmodelRecoil = true
SWEP.LuaViewmodelRecoilOverride = true
SWEP.Attachments = {[1] = {header = "Sight", offset = {800, -300}, atts = {"md_microt1", "md_eotech", "md_aimpoint", "md_schmidt_shortdot", "md_acog"}},
[2] = {header = "Barrel", offset = {-500, -300}, atts = {"md_saker"}},
[3] = {header = "Handguard", offset = {-500, 100}, atts = {"md_foregrip", "md_bipod"}},
["+reload"] = {header = "Ammo", offset = {800, 300}, atts = {"am_magnum", "am_matchgrade"}}}
SWEP.Animations = {fire = {"shoot1", "shoot2", "shoot3"},
reload = "reload",
reload_empty = "reload2",
idle = "idle",
draw = "draw"}
SWEP.Sounds = {draw = {{time = 0.1, sound = "CW_FOLEY_LIGHT"},
{time = 0.65, sound = "CW_M249_OFFICIAL_BOLTBACK"},
{time = 0.82, sound = "CW_M249_OFFICIAL_BOLTRELEASE"}},
reload = {{time = 0.2, sound = "CW_FOLEY_LIGHT"},
{time = 0.85, sound = "CW_M249_OFFICIAL_COVEROPEN"},
{time = 1.8, sound = "CW_M249_OFFICIAL_MAGOUT"},
{time = 2.1, sound = "CW_FOLEY_LIGHT"},
{time = 2.62, sound = "CW_M249_OFFICIAL_MAGDRAW"},
{time = 4, sound = "CW_M249_OFFICIAL_MAGIN"},
{time = 4.2, sound = "CW_FOLEY_LIGHT"},
{time = 4.65, sound = "CW_M249_OFFICIAL_BULLETIN"},
{time = 5.2, sound = "CW_FOLEY_LIGHT"},
{time = 5.9, sound = "CW_M249_OFFICIAL_COVERCLOSE"},
{time = 6.7, sound = "CW_FOLEY_LIGHT"}},
reload2 = {{time = 0.2, sound = "CW_FOLEY_LIGHT"},
{time = 0.8, sound = "CW_M249_OFFICIAL_BOLTBACK"},
{time = 1, sound = "CW_M249_OFFICIAL_BOLTRELEASE"},
{time = 2.53, sound = "CW_M249_OFFICIAL_COVEROPEN"},
{time = 3.58, sound = "CW_M249_OFFICIAL_MAGOUT"},
{time = 3.9, sound = "CW_FOLEY_LIGHT"},
{time = 4.3, sound = "CW_M249_OFFICIAL_MAGDRAW"},
{time = 5.9, sound = "CW_M249_OFFICIAL_MAGIN"},
{time = 6.2, sound = "CW_FOLEY_LIGHT"},
{time = 6.52, sound = "CW_M249_OFFICIAL_BULLETIN"},
{time = 7.6, sound = "CW_M249_OFFICIAL_COVERCLOSE"},
{time = 8.3, sound = "CW_FOLEY_LIGHT"}}}
SWEP.SpeedDec = 50
SWEP.Slot = 0
SWEP.SlotPos = 0
SWEP.NormalHoldType = "ar2"
SWEP.RunHoldType = "passive"
SWEP.FireModes = {"auto"}
SWEP.Base = "ttt_cw2_base"
SWEP.Category = "CW 2.0"
SWEP.Author = "Spy"
SWEP.Contact = ""
SWEP.Purpose = ""
SWEP.Instructions = ""
SWEP.ViewModelFOV = 70
SWEP.ViewModelFlip = false
SWEP.ViewModel = "models/cw2/machineguns/m249.mdl"
SWEP.WorldModel = "models/weapons/cw2_0_mach_para.mdl"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.Primary.ClipSize = 100
SWEP.Primary.DefaultClip = 100
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "5.56x45MM"
SWEP.FireDelay = 0.075
SWEP.FireSound = "CW_M249_OFFICIAL_FIRE"
SWEP.FireSoundSuppressed = "CW_M249_OFFICIAL_FIRE_SUPPRESSED"
SWEP.Recoil = 1.1
SWEP.HipSpread = 0.065
SWEP.AimSpread = 0.003
SWEP.VelocitySensitivity = 2.4
SWEP.MaxSpreadInc = 0.04
SWEP.SpreadPerShot = 0.007
SWEP.SpreadCooldown = 0.15
SWEP.Shots = 1
SWEP.Damage = 28
SWEP.DeployTime = 2
SWEP.ReloadSpeed = 1
SWEP.ReloadTime = 5
SWEP.ReloadTime_Empty = 6.2
SWEP.ReloadHalt = 7.3
SWEP.ReloadHalt_Empty = 8.9
SWEP.Chamberable = false
if CLIENT then
SWEP.RoundBeltBoneNames = {
"SAW_BULLET_MAIN",
"SAW_BULLET_00",
"SAW_BULLET_02",
"SAW_BULLET_03",
"SAW_BULLET_04",
"SAW_BULLET_05",
"SAW_BULLET_06",
"SAW_BULLET_07",
"SAW_BULLET_08",
"SAW_BULLET_09",
"SAW_BULLET_10",
"SAW_BULLET_11",
"SAW_BULLET_12",
"SAW_BULLET_13",
"SAW_BULLET_14",
"SAW_BULLET_15"
}
local function removeRoundMeshes(wep) -- we hide all rounds left in the belt on a non-empty reload because if we don't we're left with ghost meshes moving around (bullets with no link to the mag get moved back to it)
wep:adjustVisibleRounds(0)
end
local function adjustMeshByMaxAmmo(wep)
wep:adjustVisibleRounds(wep.Owner:GetAmmoCount(wep.Primary.Ammo) + wep:Clip1())
end
SWEP.animCallbacks = {
reload = removeRoundMeshes
}
SWEP.Sounds.reload[5].callback = adjustMeshByMaxAmmo
SWEP.Sounds.reload2[7].callback = adjustMeshByMaxAmmo
end
function SWEP:IndividualInitialize()
if CLIENT then
self:initBeltBones()
end
end
function SWEP:initBeltBones()
local vm = self.CW_VM
self.roundBeltBones = {}
for key, boneName in ipairs(self.RoundBeltBoneNames) do
local bone = vm:LookupBone(boneName)
self.roundBeltBones[key] = bone
end
end
function SWEP:postPrimaryAttack()
if CLIENT then
self:adjustVisibleRounds()
end
end
function SWEP:beginReload()
self.BaseClass.beginReload(self)
if CLIENT then
self:adjustVisibleRounds(0)
end
end
local fullSize = Vector(1, 1, 1)
local invisible = Vector(0, 0, 0)
function SWEP:adjustVisibleRounds(curMag)
if not self.roundBeltBones then
self:initBeltBones()
end
local curMag = curMag or self:Clip1()
local boneCount = #self.roundBeltBones
local vm = self.CW_VM
for i = 1, boneCount do
local roundID = boneCount - (i - 1)
local element = self.roundBeltBones[roundID]
local scale = curMag >= roundID and fullSize or invisible
vm:ManipulateBoneScale(element, scale)
end
end
SWEP.badAccuracyModifier = 5
function SWEP:hasBadAccuracy()
return self.dt.State == CW_AIMING and not self.dt.BipodDeployed
end
function SWEP:getBaseCone()
local baseCone, maxSpreadMod = self.BaseClass.getBaseCone(self)
if self:hasBadAccuracy() then
return baseCone * self.badAccuracyModifier, maxSpreadMod
end
return baseCone, maxSpreadMod
end
function SWEP:getMaxSpreadIncrease(maxSpreadMod)
if self:hasBadAccuracy() then
return self.BaseClass.getMaxSpreadIncrease(self, maxSpreadMod) * self.badAccuracyModifier
end
return self.BaseClass.getMaxSpreadIncrease(self, maxSpreadMod)
end
|
-- Copyright (c) 2018 Redfern, Trevor <[email protected]>
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local List = require "ext.artemis.src.list"
local Storage = {}
function Storage:new()
local s = {
items = List:new()
}
setmetatable(s, self)
self.__index = self
return s
end
function Storage:add(item)
self.items:add(item)
end
function Storage:remove(item)
self.items:remove(item)
end
function Storage:contains(item)
return self.items:contains(item)
end
return Storage
|
-- Copyright (C) 2020 jerrykuku <[email protected]>
-- Licensed to the public under the GNU General Public License v3.
package.path = package.path .. ';/usr/share/ttnode/?.lua'
local uci = require 'luci.model.uci'.cursor()
local config = 'ttnode'
local requests = require('requests')
local BASE_URL = 'http://tiantang.mogencloud.com/web/api/'
local BASE_API = 'http://tiantang.mogencloud.com/api/v1/'
local xformHeaders = {['Content-Type'] = 'application/x-www-form-urlencoded'}
local sckey = uci:get_first(config, 'global', 'serverchan')
local tg_token = uci:get_first(config, 'global', 'tg_token')
local tg_userid = uci:get_first(config, 'global', 'tg_userid')
local token = uci:get_first(config, 'global', 'token')
local auto_cash = uci:get_first(config, 'global', 'auto_cash')
local week = uci:get_first(config, 'global', 'week')
local ttnode = {}
local msg = ''
local total = 0
local msgTitle = '[甜糖星愿]星愿日结详细'
-- BASE Function --
function print_r(t)
local print_r_cache = {}
local function sub_print_r(t, indent)
if (print_r_cache[tostring(t)]) then
print(indent .. '*' .. tostring(t))
else
print_r_cache[tostring(t)] = true
if (type(t) == 'table') then
for pos, val in pairs(t) do
if (type(val) == 'table') then
print(indent .. '[' .. pos .. '] => ' .. tostring(t) .. ' {')
sub_print_r(val, indent .. string.rep(' ', string.len(pos) + 8))
print(indent .. string.rep(' ', string.len(pos) + 6) .. '}')
elseif (type(val) == 'string') then
print(indent .. '[' .. pos .. '] => "' .. val .. '"')
else
print(indent .. '[' .. pos .. '] => ' .. tostring(val))
end
end
else
print(indent .. tostring(t))
end
end
end
if (type(t) == 'table') then
print(tostring(t) .. ' {')
sub_print_r(t, ' ')
print('}')
else
sub_print_r(t, ' ')
end
print()
end
function sleep(n)
os.execute('sleep ' .. n)
end
--APIS--
--发送消息到Server酱 和 Telegram
function ttnode.sendMsg(text, desp)
if sckey:len() > 0 then
local url = 'https://sc.ftqq.com/' .. sckey .. '.send'
local data = 'text=' .. text .. '&desp=' .. desp
response = requests.post {url, data = data, headers = xformHeaders}
end
if tg_token:len() > 0 and tg_userid:len() > 0 then
local tg_url = 'https://api.telegram.org/bot' .. tg_token .. '/sendMessage'
local tg_msg = "<b>"..text.."</b>"..desp
local tg_data = 'chat_id='.. tg_userid ..'&text=' .. tg_msg .. '&parse_mode=html'
response = requests.post {tg_url, data = tg_data, headers = xformHeaders}
end
return 1
end
--获取验证码
function ttnode.getCode(phone)
url = BASE_URL .. 'login/code'
data = 'phone=' .. phone
response = requests.post {url, data = data, headers = xformHeaders}
json_body, error = response.json()
return json_body
end
-- 登录
function ttnode.login(phone, authCode)
url = BASE_URL .. 'login'
data = 'phone=' .. phone .. '&authCode=' .. authCode
response = requests.post {url, data = data, headers = xformHeaders}
json_body, error = response.json()
if json_body.errCode == 0 then
token = json_body.data.token
uci:set('ttnode', '@global[0]', 'token', token)
uci:commit('ttnode')
return true
else
return false
end
end
--甜糖用户初始化信息,可以获取待收取的推广信息数,可以获取账户星星数
function ttnode.getInitInfo()
url = BASE_URL .. 'account/message/loading'
headers = {['Content-Type'] = 'application/json', ['authorization'] = token}
response = requests.post {url, headers = headers}
json_body, error = response.json()
return json_body
end
--获取当前设备列表,可以获取待收的星星数
function ttnode.getDevices()
url = BASE_API .. 'devices?page=1&type=2&per_page=200'
headers = {['Content-Type'] = 'application/json', ['authorization'] = token}
response = requests.get {url, headers = headers}
json_body, error = response.json()
return json_body
end
--收取推广奖励星星
function ttnode.promote_score_logs(score)
if score == 0 then
msg = msg .. '\n ' .. os.date('%Y-%m-%d %H:%M:%S') .. '[推广奖励]0-🌟\n'
return
end
url = BASE_API .. 'promote/score_logs'
headers = {['Content-Type'] = 'application/json', ['authorization'] = token}
data = {score = score}
response = requests.post {url, data = data, headers = headers}
json_body, error = response.json()
if json_body.errCode ~= 0 then
msg = msg .. '\n' .. os.date('%Y-%m-%d %H:%M:%S') .. ' [推广奖励]0-🌟\n'
return
end
msg = msg .. '\n ' .. os.date('%Y-%m-%d %H:%M:%S') .. '[推广奖励]"..score.."-🌟\n'
total = total + score
return
end
--收取设备奖励
function ttnode.score_logs(device_id, score, name)
if score == 0 then
msg = msg .. '\n ' .. os.date('%Y-%m-%d %H:%M:%S') .. '[' .. name .. ']0-🌟\n'
return
end
url = BASE_API .. 'score_logs'
headers = {['Content-Type'] = 'application/json', ['authorization'] = token}
data = {device_id = device_id, score = score}
response = requests.post {url, data = data, headers = headers}
json_body, error = response.json()
if json_body.errCode ~= 0 then
msg = msg .. '\n ' .. os.date('%Y-%m-%d %H:%M:%S') .. '[' .. name .. ']0-🌟\n'
return
end
msg = msg .. '\n ' .. os.date('%Y-%m-%d %H:%M:%S') .. '[' .. name .. ']' .. score .. '-🌟\n'
total = total + tonumber(score)
return
end
--签到功能
function ttnode.sign_in()
url = BASE_URL .. 'account/sign_in'
headers = {['Content-Type'] = 'application/json', ['authorization'] = token}
response = requests.post {url, headers = headers}
json_body, error = response.json()
if json_body.errCode ~= 0 then
msg = msg .. '\n ' .. os.date('%Y-%m-%d %H:%M:%S') .. '[签到奖励]0-🌟(失败:' .. json_body.msg .. ')\n'
return
end
msg = msg .. '\n ' .. os.date('%Y-%m-%d %H:%M:%S') .. '[签到奖励]1-🌟 \n'
total = total + 1
return
end
--支付宝提现
function ttnode.withdraw_logs(bean)
local logStr = ''
url = BASE_API .. 'withdraw_logs'
score = bean.score
score = score - score % 100
real_name = bean.real_name
card_id = bean.card_id
bank_name = '支付宝'
sub_bank_name = ''
ztype = 'zfb'
if score < 1000 then
logStr = '\n' .. os.date('%Y-%m-%d %H:%M:%S') .. '[自动提现]星愿不足1000无法提现\n'
return logStr
end
data = 'score=' .. score .. '&real_name=' .. real_name .. '&card_id=' .. card_id .. '&bank_name=' .. bank_name .. '&sub_bank_name=' .. sub_bank_name .. '&type=' .. ztype
print(data)
headers = {['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8', ['authorization'] = token}
response = requests.post {url, data = data, headers = headers}
json_body, error = response.json()
if json_body.errCode ~= 0 then
print(json_body.msg .. score)
logStr = '\n' .. os.date('%Y-%m-%d %H:%M:%S') .. '[自动提现]提现失败,请关闭自动提现等待更新\n'
return logStr
end
local data = json_body.data
zfbID = data.card_id
pre = string.sub(zfbID, 1, 5)
ends = string.sub(zfbID, -5)
zfbID = pre .. '***' .. ends
logStr = '\n' .. os.date('%Y-%m-%d %H:%M:%S') .. '[自动提现]扣除' .. score .. '-🌟(' .. zfbID .. ')\n'
return logStr
end
--逻辑处理
function ttnode.startProcess()
local resObj = {}
--获取用户信息
local userData = ttnode.getInitInfo()
if userData.errCode ~= 0 then
resObj.code = 1
resObj.msg = os.date('%Y-%m-%d %H:%M:%S') .. ' authorization已经失效,请重新抓包填写!'
ttnode.sendMsg(os.date('%Y-%m-%d %H:%M:%S') .. '[甜糖星愿]-Auth失效通知', resObj.msg)
return resObj
end
local inactivedPromoteScore = userData.data.inactivedPromoteScore
local accountScore = userData.data.score
--获取设备列表信息
local devices = ttnode.getDevices().data.data
msg = msg .. '\n' .. os.date('%Y-%m-%d %H:%M:%S') .. '[收益详细]:\n```lua'
--收取签到收益
ttnode.sign_in()
--收取推广收益
ttnode.promote_score_logs(inactivedPromoteScore)
--收取设备收益
for _, device in pairs(devices) do
ttnode.score_logs(device.hardware_id, device.inactived_score, device.alias)
end
--自动提现
local now_week = os.date('%A')
local withdraw = ''
if week == now_week and auto_cash == '1' then
local userInfo = userData.data
local zfbList = userInfo.zfbList
if next(zfbList) == nil then
withdraw = '\n' .. os.date('%Y-%m-%d %H:%M:%S') .. '[自动提现]提现失败,请绑定支付宝账户\n'
else
local bean = {}
bean.score = userInfo.score
bean.real_name = zfbList[1].name
bean.card_id = zfbList[1].account
withdraw = ttnode.withdraw_logs(bean)
end
end
--收益统计并发送微信消息
local total_str = '\n' .. os.date('%Y-%m-%d %H:%M:%S') .. '[总共收取]' .. total .. '-🌟\n'
local nowdata = ttnode.getInitInfo()
local accountScore = nowdata.data.score
local accountScore_str = '\n' .. os.date('%Y-%m-%d %H:%M:%S') .. '[账户星星]' .. accountScore .. '-🌟\n'
local ends = '\n```\n***\n注意:以上统计仅供参考,一切请以甜糖客户端APP为准'
msg = accountScore_str .. total_str .. withdraw .. msg .. ends
msgRes = ttnode.sendMsg(msgTitle, msg)
resObj.code = 0
resObj.msg = msg
resObj.msgres = msgRes
return resObj
end
return ttnode
|
-- ======= Copyright (c) 2003-2011, Unknown Worlds Entertainment, Inc. All rights reserved. =======
--
-- lua\DamageTypes.lua
--
-- Created by: Andreas Urwalek ([email protected])
--
-- Contains all rules regarding damage types. New types behavior can be defined BuildDamageTypeRules().
--
-- Important callbacks for classes:
--
-- ComputeDamageAttackerOverride(attacker, damage, damageType)
-- ComputeDamageAttackerOverrideMixin(attacker, damage, damageType)
--
-- for target:
-- ComputeDamageOverride(attacker, damage, damageType)
-- ComputeDamageOverrideMixin(attacker, damage, damageType)
-- GetArmorUseFractionOverride(damageType, armorFractionUsed)
-- GetReceivesStructuralDamage(damageType)
-- GetReceivesBiologicalDamage(damageType)
-- GetHealthPerArmorOverride(damageType, healthPerArmor)
--
--
--
-- Damage types
--
-- In NS2 - Keep simple and mostly in regard to armor and non-armor. Can't see armor, but players
-- and structures spawn with an intuitive amount of armor.
-- http://www.unknownworlds.com/ns2/news/2010/6/damage_types_in_ns2
--
-- Normal - Regular damage
-- Light - Reduced vs. armor
-- Heavy - Extra damage vs. armor
-- Puncture - Extra vs. players
-- Structural - Double against structures
-- GrenadeLauncher - Double against structures with 20% reduction in player damage
-- Flamethrower - 5% increase for player damage from structures
-- Gas - Breathing targets only (Spores, Nerve Gas GL). Ignores armor.
-- StructuresOnly - Doesn't damage players or AI units (ARC)
-- Falling - Ignores armor for humans, no damage for some creatures or exosuit
-- Door - Like Structural but also does damage to Doors. Nothing else damages Doors.
-- Flame - Like normal but catches target on fire and plays special flinch animation
-- Corrode - deals normal damage to structures but armor only to non structures
-- ArmorOnly - always affects only armor
-- Biological - only organic, biological targets (non mechanical)
-- StructuresOnlyLight - same as light damage but will not harm players or units which are not valid for structural damage
--
-- ========= For more information, visit us at http://www.unknownworlds.com =====================
--globals for balance-extension tweaking
kAlienVampirismNotHealArmor = false
kDamageMarinesLessScalar = 0.25
-- utility functions
function GetReceivesStructuralDamage(entity)
return entity.GetReceivesStructuralDamage and entity:GetReceivesStructuralDamage()
end
function GetReceivesBiologicalDamage(entity)
return entity.GetReceivesBiologicalDamage and entity:GetReceivesBiologicalDamage()
end
function NS2Gamerules_GetUpgradedDamageScalar( attacker )
if GetHasTech(attacker, kTechId.Weapons3, true) then
return kWeapons3DamageScalar
elseif GetHasTech(attacker, kTechId.Weapons2, true) then
return kWeapons2DamageScalar
elseif GetHasTech(attacker, kTechId.Weapons1, true) then
return kWeapons1DamageScalar
end
return 1.0
end
-- Use this function to change damage according to current upgrades
function NS2Gamerules_GetUpgradedDamage(attacker, doer, damage, damageType, hitPoint)
local damageScalar = 1
if attacker ~= nil then
-- Damage upgrades only affect weapons, not ARCs, Sentries, MACs, Mines, etc.
if doer.GetIsAffectedByWeaponUpgrades and doer:GetIsAffectedByWeaponUpgrades() then
damageScalar = NS2Gamerules_GetUpgradedDamageScalar( attacker )
end
end
return damage * damageScalar
end
--Utility function to apply chamber-upgraded modifications to alien damage
--Note: this should _always_ be called BEFORE damage-type specific modifications are done (i.e. Light vs Normal vs Structural, etc)
function NS2Gamerules_GetUpgradedAlienDamage( target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint, weapon )
if not doer then return damage, armorFractionUsed end
local teamNumber = attacker:GetTeamNumber()
local isAffectedByCrush = doer.GetIsAffectedByCrush and attacker:GetHasUpgrade( kTechId.Crush ) and doer:GetIsAffectedByCrush()
local isAffectedByVampirism = doer.GetVampiricLeechScalar and attacker:GetHasUpgrade( kTechId.Vampirism )
local isAffectedByFocus = doer.GetIsAffectedByFocus and attacker:GetHasUpgrade( kTechId.Focus ) and doer:GetIsAffectedByFocus()
if isAffectedByCrush then --Crush
local crushLevel = attacker:GetSpurLevel()
if crushLevel > 0 then
if target:isa("Exo") or target.GetReceivesStructuralDamage and target:GetReceivesStructuralDamage(damageType) then
damage = damage + ( damage * ( crushLevel * kAlienCrushDamagePercentByLevel ) )
elseif target:isa("Player") then
armorFractionUsed = kBaseArmorUseFraction + ( crushLevel * kAlienCrushDamagePercentByLevel )
end
end
end
if Server then
-- Vampirism
if isAffectedByVampirism then
local vampirismLevel = attacker:GetShellLevel()
if vampirismLevel > 0 then
if attacker:GetIsHealable() and target:isa("Player") then
local scalar = doer:GetVampiricLeechScalar()
if scalar > 0 then
local focusBonus = 1
if isAffectedByFocus then
focusBonus = 1 + doer:GetFocusAttackCooldown()
end
local maxHealth = attacker:GetMaxHealth()
local leechedHealth = maxHealth * vampirismLevel * scalar * focusBonus
attacker:AddHealth( leechedHealth, true, kAlienVampirismNotHealArmor )
end
end
end
end
end
--Focus
if isAffectedByFocus then
local veilLevel = attacker:GetVeilLevel()
local damageBonus = doer:GetMaxFocusBonusDamage()
damage = damage * (1 + (veilLevel/3) * damageBonus) --1.0, 1.333, 1.666, 2
end
--!!!Note: if more than damage and armor fraction modified, be certain the calling-point of this function is updated
return damage, armorFractionUsed
end
-- only certain abilities should work with focus
-- global so mods can easily change this
function InitializeFocusAbilities()
kFocusAbilities = {}
kFocusAbilities[kTechId.Bite] = true
kFocusAbilities[kTechId.Spit] = true
kFocusAbilities[kTechId.LerkBite] = true
kFocusAbilities[kTechId.Swipe] = true
kFocusAbilities[kTechId.Stab] = true
kFocusAbilities[kTechId.Gore] = true
end
function DoesFocusAffectAbility(abilityTech)
if not kFocusAbilities then
InitializeFocusAbilities()
end
if kFocusAbilities[abilityTech] == true then
return true
end
return false
end
function Gamerules_GetDamageMultiplier()
if Server and Shared.GetCheatsEnabled() then
return GetGamerules():GetDamageMultiplier()
end
return 1
end
kDamageType = enum(
{
'Normal', 'Light', 'Heavy', 'Puncture',
'Structural', 'StructuralHeavy', 'Splash',
'Gas', 'NerveGas', 'StructuresOnly',
'Falling', 'Door', 'Flame', 'Flamethrower',
'Corrode', 'ArmorOnly', 'Biological', 'StructuresOnlyLight',
'Spreading', 'GrenadeLauncher', 'MachineGun'
})
-- Describe damage types for tooltips
kDamageTypeDesc = {
"",
"Light: reduced vs. armor",
"Heavy: extra vs. armor",
"Puncture: extra vs. players",
"Structural: Double vs. structures",
"StructuralHeavy: Double vs. structures and double vs. armor",
"Gas damage: affects breathing targets only",
"NerveGas: affects biological units, player will take only armor damage",
"Structures only: Doesn't damage players or AI units",
"Falling: Ignores armor for humans, no damage for aliens",
"Door: Can also affect Doors",
"Flame: Deals 4.5x damage vs. flammable structures and double vs. all other structures",
"Flamethrower: Reduced vs. armor, 4.5x damage vs. flammable structures and double vs. all other structures",
"Corrode damage: Damage structures or armor only for non structures",
"Armor damage: Will never reduce health",
"Biological: Will only damage biological targets.",
"StructuresOnlyLight: reduced vs. structures with armor",
"Spreading: Does less damage against small targets.",
"GrenadeLauncher: Double structure damage, 20% reduction in player damage",
"MachineGun: Deals 1.5x amount of base damage vs. players"
}
kSpreadingDamageScalar = 0.75
kBaseArmorUseFraction = 0.7
kExosuitArmorUseFraction = 1 -- exos have no health
kStructuralDamageScalar = 2
kPuncturePlayerDamageScalar = 2
kGLPlayerDamageReduction = 0.8
kLightHealthPerArmor = 4
kHealthPointsPerArmor = 2
kHeavyHealthPerArmor = 1
kFlameableMultiplier = 2.5
kCorrodeDamagePlayerArmorScalar = 0.12
kCorrodeDamageExoArmorScalar = 0.4
kStructureLightHealthPerArmor = 9
kStructureLightArmorUseFraction = 0.9
-- deal only 33% of damage to friendlies
kFriendlyFireScalar = 0.33
local function ApplyDefaultArmorUseFraction(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return damage, kBaseArmorUseFraction, healthPerArmor
end
local function ApplyHighArmorUseFractionForExos(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target:isa("Exo") then
armorFractionUsed = kExosuitArmorUseFraction
end
return damage, armorFractionUsed, healthPerArmor
end
local function ApplyDefaultHealthPerArmor(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return damage, armorFractionUsed, kHealthPointsPerArmor
end
local function DoubleHealthPerArmor(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return damage, armorFractionUsed, healthPerArmor * (kLightHealthPerArmor / kHealthPointsPerArmor)
end
local function HalfHealthPerArmor(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return damage, armorFractionUsed, healthPerArmor * (kHeavyHealthPerArmor / kHealthPointsPerArmor)
end
local function ApplyAttackerModifiers(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
damage = NS2Gamerules_GetUpgradedDamage(attacker, doer, damage, damageType, hitPoint)
damage = damage * Gamerules_GetDamageMultiplier()
if attacker and attacker.ComputeDamageAttackerOverride then
damage = attacker:ComputeDamageAttackerOverride(attacker, damage, damageType, doer, hitPoint)
end
if doer and doer.ComputeDamageAttackerOverride then
damage = doer:ComputeDamageAttackerOverride(attacker, damage, damageType)
end
if attacker and attacker.ComputeDamageAttackerOverrideMixin then
damage = attacker:ComputeDamageAttackerOverrideMixin(attacker, damage, damageType, doer, hitPoint)
end
if doer and doer.ComputeDamageAttackerOverrideMixin then
damage = doer:ComputeDamageAttackerOverrideMixin(attacker, damage, damageType, doer, hitPoint)
end
return damage, armorFractionUsed, healthPerArmor
end
local function ApplyTeamModifiers(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
-- team vs team type damage multiplier
local attackerType = attacker:GetTeamType()
local targetType = target:GetTeamType()
if kTeamVsTeamDamage[attackerType] then
--Log("Multiplying damage by %s because %s attacked %s (was %s)", (kTeamVsTeamDamage[attackerType][targetType] or 1.0), attackerType, targetType, damage)
damage = damage * (kTeamVsTeamDamage[attackerType][targetType] or 1.0)
end
return damage, armorFractionUsed, healthPerArmor
end
local function ApplyTargetModifiers(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
-- The host can provide an override for this function.
if target.ComputeDamageOverride then
damage = target:ComputeDamageOverride(attacker, damage, damageType, hitPoint)
end
-- Used by mixins.
if target.ComputeDamageOverrideMixin then
damage = target:ComputeDamageOverrideMixin(attacker, damage, damageType, hitPoint)
end
if target.GetArmorUseFractionOverride then
armorFractionUsed = target:GetArmorUseFractionOverride(damageType, armorFractionUsed, hitPoint)
end
if target.GetHealthPerArmorOverride then
healthPerArmor = target:GetHealthPerArmorOverride(damageType, healthPerArmor, hitPoint)
end
local damageTable = {}
damageTable.damage = damage
damageTable.armorFractionUsed = armorFractionUsed
damageTable.healthPerArmor = healthPerArmor
if target.ModifyDamageTaken then
target:ModifyDamageTaken(damageTable, attacker, doer, damageType, hitPoint)
end
return damageTable.damage, damageTable.armorFractionUsed, damageTable.healthPerArmor
end
local function ApplyFriendlyFireModifier(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
-- changed from vanilla: no longer excludes self
if target and attacker and HasMixin(target, "Team") and HasMixin(attacker, "Team") and target:GetTeamNumber() == attacker:GetTeamNumber() then
damage = damage * kFriendlyFireScalar
end
return damage, armorFractionUsed, healthPerArmor
end
local function IgnoreArmor(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return damage, 0, healthPerArmor
end
local function MaximizeArmorUseFraction(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return damage, 1, healthPerArmor
end
local function MultiplyForStructures(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target.GetReceivesStructuralDamage and target:GetReceivesStructuralDamage(damageType) then
damage = damage * kStructuralDamageScalar
end
return damage, armorFractionUsed, healthPerArmor
end
local function ReduceForPlayersDoubleStructure(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target.GetReceivesStructuralDamage and target:GetReceivesStructuralDamage(damageType) then
damage = damage * kStructuralDamageScalar
elseif target:isa("Player") then
damage = damage * kGLPlayerDamageReduction
end
return damage, armorFractionUsed, healthPerArmor
end
local function MultiplyForPlayers(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(target:isa("Player") or target:isa("Exosuit"), damage * kPuncturePlayerDamageScalar, damage), armorFractionUsed, healthPerArmor
end
local function ReducedDamageAgainstSmall(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target.GetIsSmallTarget and target:GetIsSmallTarget() then
damage = damage * kSpreadingDamageScalar
end
return damage, armorFractionUsed, healthPerArmor
end
local function IgnoreHealthForPlayers(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target:isa("Player") then
local maxDamagePossible = healthPerArmor * target.armor
damage = math.min(damage, maxDamagePossible)
armorFractionUsed = 1
end
return damage, armorFractionUsed, healthPerArmor
end
local function IgnoreHealthForPlayersUnlessExo(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target:isa("Player") and not target:isa("Exo") then
local maxDamagePossible = healthPerArmor * target.armor
damage = math.min(damage, maxDamagePossible)
armorFractionUsed = 1
end
return damage, armorFractionUsed, healthPerArmor
end
local function IgnoreHealth(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
local maxDamagePossible = healthPerArmor * target.armor
damage = math.min(damage, maxDamagePossible)
return damage, 1, healthPerArmor
end
local function ReduceGreatlyForPlayers(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target:isa("Exo") or target:isa("Exosuit") or target:isa("Onos") then
damage = damage * kCorrodeDamageExoArmorScalar
elseif target:isa("Player") then
damage = damage * kCorrodeDamagePlayerArmorScalar
end
return damage, armorFractionUsed, healthPerArmor
end
local function IgnorePlayersUnlessExo(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(target:isa("Player") and not target:isa("Exo") , 0, damage), armorFractionUsed, healthPerArmor
end
local function IgnoreARCsAndMACs(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(target:isa("ARC") or target:isa("MAC") , 0, damage), armorFractionUsed, healthPerArmor
end
local function IgnorePowerPoints(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(target:isa("PowerPoint") , 0, damage), armorFractionUsed, healthPerArmor
end
local function DamagePlayersOnly(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(target:isa("Player") or target:isa("Exosuit"), damage, 0), armorFractionUsed, healthPerArmor
end
local function DamageAlienOnly(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(HasMixin(target, "Team") and target:GetTeamType() == kAlienTeamType, damage, 0), armorFractionUsed, healthPerArmor
end
local function DamageMarinesLess(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if HasMixin(target, "Team") and target:GetTeamType() == kMarineTeamType then
damage = kDamageMarinesLessScalar * damage
end
return damage, armorFractionUsed, healthPerArmor
end
local function DamageStructuresOnly(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if not target.GetReceivesStructuralDamage or not target:GetReceivesStructuralDamage(damageType) then
damage = 0
end
return damage, armorFractionUsed, healthPerArmor
end
local function IgnoreDoors(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(target:isa("Door"), 0, damage), armorFractionUsed, healthPerArmor
end
local function DamageBiologicalOnly(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if not target.GetReceivesBiologicalDamage or not target:GetReceivesBiologicalDamage(damageType) then
damage = 0
end
return damage, armorFractionUsed, healthPerArmor
end
local function DamageBreathingOnly(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if not target.GetReceivesVaporousDamage or not target:GetReceivesVaporousDamage(damageType) then
damage = 0
end
return damage, armorFractionUsed, healthPerArmor
end
local function MultiplyFlameAble(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target.GetIsFlameAble and target:GetIsFlameAble(damageType) then
damage = damage * kFlameableMultiplier
end
return damage, armorFractionUsed, healthPerArmor
end
local function DoubleHealthPerArmorForStructures(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target.GetReceivesStructuralDamage and target:GetReceivesStructuralDamage(damageType) then
healthPerArmor = healthPerArmor * (kStructureLightHealthPerArmor / kHealthPointsPerArmor)
armorFractionUsed = kStructureLightArmorUseFraction
end
return damage, armorFractionUsed, healthPerArmor
end
local function DoubleHealthPerArmorForPlayers(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
if target:isa("Player") then
healthPerArmor = healthPerArmor * (kLightHealthPerArmor / kHealthPointsPerArmor)
end
return damage, armorFractionUsed, healthPerArmor
end
local kMachineGunPlayerDamageScalar = 1.5
local function MultiplyForMachineGun(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
return ConditionalValue(target:isa("Player") or target:isa("Exosuit"), damage * kMachineGunPlayerDamageScalar, damage), armorFractionUsed, healthPerArmor
end
kDamageTypeGlobalRules = nil
kDamageTypeRules = nil
--[[
* Define any new damage type behavior in this function
--]]
local function BuildDamageTypeRules()
kDamageTypeGlobalRules = {}
kDamageTypeRules = {}
-- global rules
table.insert(kDamageTypeGlobalRules, ApplyDefaultArmorUseFraction)
table.insert(kDamageTypeGlobalRules, ApplyHighArmorUseFractionForExos)
table.insert(kDamageTypeGlobalRules, ApplyDefaultHealthPerArmor)
table.insert(kDamageTypeGlobalRules, ApplyAttackerModifiers)
table.insert(kDamageTypeGlobalRules, ApplyTargetModifiers)
table.insert(kDamageTypeGlobalRules, ApplyTeamModifiers)
table.insert(kDamageTypeGlobalRules, ApplyFriendlyFireModifier)
-- ------------------------------
-- normal damage rules
kDamageTypeRules[kDamageType.Normal] = {}
-- light damage rules
kDamageTypeRules[kDamageType.Light] = {}
table.insert(kDamageTypeRules[kDamageType.Light], DoubleHealthPerArmor)
-- ------------------------------
-- heavy damage rules
kDamageTypeRules[kDamageType.Heavy] = {}
table.insert(kDamageTypeRules[kDamageType.Heavy], HalfHealthPerArmor)
-- ------------------------------
-- Puncture damage rules
kDamageTypeRules[kDamageType.Puncture] = {}
table.insert(kDamageTypeRules[kDamageType.Puncture], MultiplyForPlayers)
-- ------------------------------
-- Spreading damage rules
kDamageTypeRules[kDamageType.Spreading] = {}
table.insert(kDamageTypeRules[kDamageType.Spreading], ReducedDamageAgainstSmall)
-- ------------------------------
-- structural rules
kDamageTypeRules[kDamageType.Structural] = {}
table.insert(kDamageTypeRules[kDamageType.Structural], MultiplyForStructures)
-- ------------------------------
-- Grenade Launcher rules
kDamageTypeRules[kDamageType.GrenadeLauncher] = {}
table.insert(kDamageTypeRules[kDamageType.GrenadeLauncher], ReduceForPlayersDoubleStructure)
-- ------------------------------
-- Machine Gun rules
kDamageTypeRules[kDamageType.MachineGun] = {}
table.insert(kDamageTypeRules[kDamageType.MachineGun], MultiplyForMachineGun)
-- ------------------------------
-- structural heavy rules
kDamageTypeRules[kDamageType.StructuralHeavy] = {}
table.insert(kDamageTypeRules[kDamageType.StructuralHeavy], HalfHealthPerArmor)
table.insert(kDamageTypeRules[kDamageType.StructuralHeavy], MultiplyForStructures)
-- ------------------------------
-- gas damage rules
kDamageTypeRules[kDamageType.Gas] = {}
table.insert(kDamageTypeRules[kDamageType.Gas], IgnoreArmor)
table.insert(kDamageTypeRules[kDamageType.Gas], DamageBreathingOnly)
-- ------------------------------
-- structures only rules
kDamageTypeRules[kDamageType.StructuresOnly] = {}
table.insert(kDamageTypeRules[kDamageType.StructuresOnly], DamageStructuresOnly)
-- ------------------------------
-- Splash rules
kDamageTypeRules[kDamageType.Splash] = {}
table.insert(kDamageTypeRules[kDamageType.Splash], DamageStructuresOnly)
table.insert(kDamageTypeRules[kDamageType.Splash], IgnoreARCsAndMACs)
table.insert(kDamageTypeRules[kDamageType.Splash], IgnorePowerPoints)
-- ------------------------------
-- fall damage rules
kDamageTypeRules[kDamageType.Falling] = {}
table.insert(kDamageTypeRules[kDamageType.Falling], IgnoreArmor)
-- ------------------------------
-- Door damage rules
kDamageTypeRules[kDamageType.Door] = {}
table.insert(kDamageTypeRules[kDamageType.Door], MultiplyForStructures)
table.insert(kDamageTypeRules[kDamageType.Door], HalfHealthPerArmor)
-- ------------------------------
-- Flame damage rules
kDamageTypeRules[kDamageType.Flame] = {}
table.insert(kDamageTypeRules[kDamageType.Flame], MultiplyFlameAble)
table.insert(kDamageTypeRules[kDamageType.Flame], MultiplyForStructures)
-- ------------------------------
-- Flamethrower damage rules
kDamageTypeRules[kDamageType.Flamethrower] = {}
table.insert(kDamageTypeRules[kDamageType.Flame], MultiplyFlameAble)
table.insert(kDamageTypeRules[kDamageType.Flame], MultiplyForStructures)
table.insert(kDamageTypeRules[kDamageType.Flame], DoubleHealthPerArmorForPlayers)
-- ------------------------------
-- Corrode damage rules
kDamageTypeRules[kDamageType.Corrode] = {}
table.insert(kDamageTypeRules[kDamageType.Corrode], ReduceGreatlyForPlayers)
table.insert(kDamageTypeRules[kDamageType.Corrode], IgnoreHealthForPlayersUnlessExo)
-- ------------------------------
-- nerve gas rules
kDamageTypeRules[kDamageType.NerveGas] = {}
--table.insert(kDamageTypeRules[kDamageType.NerveGas], DamageAlienOnly)
table.insert(kDamageTypeRules[kDamageType.NerveGas], DamageMarinesLess)
table.insert(kDamageTypeRules[kDamageType.NerveGas], IgnoreHealth)
-- ------------------------------
-- StructuresOnlyLight damage rules
kDamageTypeRules[kDamageType.StructuresOnlyLight] = {}
table.insert(kDamageTypeRules[kDamageType.StructuresOnlyLight], DoubleHealthPerArmorForStructures)
-- ------------------------------
-- ArmorOnly damage rules
kDamageTypeRules[kDamageType.ArmorOnly] = {}
table.insert(kDamageTypeRules[kDamageType.ArmorOnly], ReduceGreatlyForPlayers)
table.insert(kDamageTypeRules[kDamageType.ArmorOnly], IgnoreHealth)
-- ------------------------------
-- Biological damage rules
kDamageTypeRules[kDamageType.Biological] = {}
table.insert(kDamageTypeRules[kDamageType.Biological], DamageBiologicalOnly)
-- ------------------------------
end
-- applies all rules and returns damage, armorUsed, healthUsed
function GetDamageByType(target, attacker, doer, damage, damageType, hitPoint, weapon)
assert(target)
if not kDamageTypeGlobalRules or not kDamageTypeRules then
BuildDamageTypeRules()
end
-- at first check if damage is possible, if not we can skip the rest
if not CanEntityDoDamageTo(attacker, target, Shared.GetCheatsEnabled(), Shared.GetDevMode(), GetFriendlyFire(), damageType) then
return 0, 0, 0
end
local armorUsed = 0
local healthUsed = 0
local armorFractionUsed, healthPerArmor = 0
-- apply global rules at first
for _, rule in ipairs(kDamageTypeGlobalRules) do
damage, armorFractionUsed, healthPerArmor = rule(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
end
--Account for Alien Chamber Upgrades damage modifications (must be before damage-type rules)
if attacker:GetTeamType() == kAlienTeamType and attacker:isa("Player") then
damage, armorFractionUsed = NS2Gamerules_GetUpgradedAlienDamage( target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint, weapon )
end
-- apply damage type specific rules
for _, rule in ipairs(kDamageTypeRules[damageType]) do
damage, armorFractionUsed, healthPerArmor = rule(target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint)
end
if damage > 0 and healthPerArmor > 0 then
--Log("healthPerArmor: %s, armorFractionUsed: %s", healthPerArmor, armorFractionUsed)
-- Each point of armor blocks a point of health but is only destroyed at half that rate (like NS1)
-- Thanks Harimau!
local healthPointsBlocked = math.min(healthPerArmor * target.armor, armorFractionUsed * damage)
armorUsed = healthPointsBlocked / healthPerArmor
-- Anything left over comes off of health
healthUsed = damage - healthPointsBlocked
end
--Log("damage: %s, armorUsed: %s, healthUsed: %s", damage, armorUsed, healthUsed)
return damage, armorUsed, healthUsed
end |
local eventMarkers = {}
local blips = {}
local markers = {
{3649.01, -1934.18, 19.76},
{4001.79, -1660.19, 20.27 },
{4071.88, -1548.56, 20.56},
{3811.99, -2538.42, 19.6},
{4204.76, -1785, 20.24},
}
local timers = {}
local crimProgress = 0
local copProgress = 0
local ownedByCrims = false
local ownedByCops = false
local capturedByCrims = false
local capturedByCops = false
local playersInMarker = 0
local cityCol = createColCuboid(3022.98, -2698.86, 19, 1200, 1200, 12.25)
local cityArea = createRadarArea(3022.98, -2698.86, 1200,1200, 255,255,255,180)
function isOwnedByCrims()
return ownedByCrims
end
function onResourceStart ()
executeSQLQuery("CREATE TABLE IF NOT EXISTS eventMarkers (id INT, owner TEXT)")
for k,v in ipairs (markers) do
marker = createMarker(v[1], v[2], v[3], "checkpoint", 2, 255,255,255,150)
blips[marker] = createBlip(v[1], v[2], v[3], 0, 3.5, 255,255,255,255)
eventMarkers[marker] = k
setElementData(marker, "AURcityevent.eventMarker", true)
local query = executeSQLQuery("SELECT * FROM eventMarkers")
if (#query == 0) then
executeSQLQuery("INSERT INTO eventMarkers (id, owner) VALUES (?,?)", 1, "None")
executeSQLQuery("INSERT INTO eventMarkers (id, owner) VALUES (?,?)", 2, "None")
executeSQLQuery("INSERT INTO eventMarkers (id, owner) VALUES (?,?)", 3, "None")
executeSQLQuery("INSERT INTO eventMarkers (id, owner) VALUES (?,?)", 4, "None")
executeSQLQuery("INSERT INTO eventMarkers (id, owner) VALUES (?,?)", 5, "None")
else
executeSQLQuery("UPDATE eventMarkers SET owner=?", "none")
end
setElementData(marker, "id", k)
end
end
addEventHandler("onResourceStart", resourceRoot, onResourceStart)
local timerAntiEco = {}
function provokeMarker (p, team, marker)
if (type(team) ~= "string") then return false end
if (isTimer(timerAntiEco[p])) then return exports.NGCdxmsg:createNewDxMessage("You need to wait some more time to take another marker!",p,255,255,0) end
timerAntiEco[p] = setTimer(function() killTimer(timerAntiEco[p]) end, 1000*40, 1)
if (team == "Criminals") then
local mr, mg, mb, ma = getMarkerColor(marker)
if (mr == 255) and (mg == 0) and (mb == 0) and (ma == 255) then return false end
executeSQLQuery("UPDATE eventMarkers SET owner=? WHERE id=?", "crim",getElementData(marker, "id"))
setMarkerColor(marker, 255, 0, 0, 255)
setBlipColor(blips[marker], 255, 0, 0, 255)
setBlipVisibleDistance(blips[marker], 1200)
--setElementData(marker, "AURcityevent.team", "Criminals")
exports.NGCdxmsg:createNewDxMessage("Criminals have captured a marker in the city!",root,255,0,0)
--if (getElementData(marker, "AURcityevent.team") ~= "Criminals") then
for k,v in ipairs (getPlayersInTeam(getTeamFromName("Criminals"))) do
if (isElementWithinColShape(v, cityCol)) then
exports.csgdrugs:giveDrug(v, "LSD",50)
exports.csgdrugs:giveDrug(v, "Cocaine",50)
exports.csgdrugs:giveDrug(v, "Heroine",50)
exports.csgdrugs:giveDrug(v, "Ritalin",50)
exports.csgdrugs:giveDrug(v, "Ecstasy",50)
exports.csgdrugs:giveDrug(v, "Weed",50)
exports.AURpayments:addMoney(v, 4000,"Custom","CTC",0,"AURcityevent")
exports.server:givePlayerWantedPoints(v,10)
exports.NGCdxmsg:createNewDxMessage("You captured a marker, and recieved $4,000!",v,255,255,0)
exports.NGCdxmsg:createNewDxMessage("You captured a marker, and got 50 hit each drug!",v,255,255,0)
end
--end
end
elseif (team == "Government") or (team == "Military Forces") or (team == "SWAT Team") then
local mr, mg, mb, ma = getMarkerColor(marker)
if (mr == 0) and (mg == 0) and (mb == 255) and (ma == 150) then return false end
executeSQLQuery("UPDATE eventMarkers SET owner=? WHERE id=?", "law", getElementData(marker, "id"))
setMarkerColor(marker, 0, 0, 255, 150)
setBlipColor(blips[marker], 0, 0, 255, 255)
exports.NGCdxmsg:createNewDxMessage("Law forces have captured a marker in the city!",root,255,0,0)
setElementData(marker, "AURcityevent.team", "Law")
--if (getElementData(marker, "AURcityevent.team") ~= "Law") then
for k,v in ipairs (getElementsByType("player")) do
if not (v) then return erro("the bug is from player") end
if getPlayerTeam(v) then
local team = getTeamName(getPlayerTeam(v))
if (team == "Government") or (team == "Military Forces") or (team == "SWAT Team") then
if (isElementWithinColShape(v, cityCol)) then
exports.AURpayments:addMoney(v, 6000,"Custom","CTC",0,"AURcityevent")
setPedArmor(v, tonumber(getPedArmor(v)+10))
exports.NGCdxmsg:createNewDxMessage("You have captured a marker, and recieved $6,000!",v,255,255,0)
exports.NGCdxmsg:createNewDxMessage("You have captured a marker, and got 10% Armor!",v,255,255,0)
end
end
end
--end
end
end
end
function checkerForStates ()
--Updates the color.
local copMarkers = executeSQLQuery("SELECT * FROM eventMarkers WHERE owner=?", "law")
local crimMarkers = executeSQLQuery("SELECT * FROM eventMarkers WHERE owner=?", "crim")
if (#copMarkers > #crimMarkers) and (#crimMarkers ~= 0) or (#copMarkers == 3) or (#copMarkers == 4) then
setRadarAreaColor(cityArea, 0,0,255,180)
setRadarAreaFlashing(cityArea, true)
ownedByCops = false
ownedByCrims = false
elseif (#crimMarkers > #copMarkers) and (#copMarkers ~= 0) or (#crimMarkers == 3) or (#crimMarkers == 4) then
setRadarAreaColor(cityArea, 255,0,0,180)
setRadarAreaFlashing(cityArea, true)
ownedByCops = false
ownedByCrims = false
elseif (#copMarkers == 5) then
setRadarAreaColor(cityArea, 0,0,255,180)
setRadarAreaFlashing(cityArea, false)
ownedByCops = true
ownedByCrims = false
elseif (#crimMarkers == 5) then
setRadarAreaColor(cityArea, 255,0,0,180)
setRadarAreaFlashing(cityArea, false)
ownedByCrims = true
ownedByCops = false
elseif (#crimMarkers == 0) and (#copMarkers == 0) then
setRadarAreaColor(cityArea,255,255,255,180)
setRadarAreaFlashing(cityArea, false)
ownedByCops = false
ownedByCrims = false
end
for k,v in ipairs (getElementsByType"player") do
if (doesPedHaveJetPack(v)) and (isElementWithinColShape(v, cityCol)) then
removePedJetPack(v)
exports.NGCdxmsg:createNewDxMessage("Not allowed to use jetpack in the city!",v,255,255,0)
end
end
end
setTimer(checkerForStates, 500,0)
function isPlayerLaw (player)
if getPlayerTeam(player) then
local team = getTeamName(getPlayerTeam(player))
if (type(team) ~= "string") then return false end
if not (team) then return error("Team error") end
if (team == "Government") or (team == "Military Forces") or (team == "SWAT Team") then
return true
else
return false
end
else
return false
end
end
function onMarkerHit(hitElement, dim)
if hitElement then
if getElementType(hitElement) == "player" then
if (not getPlayerTeam(hitElement)) then return end
if not (dim) then return false end
if not (eventMarkers[source]) then return false end
if getPlayerTeam(hitElement) then
local team = getTeamName(getPlayerTeam(hitElement))
if (type(team) ~= "string") then return false end
if (getElementData(source, "owner") == team) then return false end
playersInMarker = playersInMarker + 1
--if (playersInMarker > 1) then return exports.NGCdxmsg:createNewDxMessage("Only 1 player can capture the marker!", hitElement, 255,0,0) end
timers[hitElement] = setTimer(provokeMarker, 1000*6, 1, hitElement, getTeamName(getPlayerTeam(hitElement)), source)
setElementData(hitElement, "isPlayerCTC", true)
end
end
end
end
addEventHandler("onMarkerHit", root, onMarkerHit)
function checkAFKPlayers()
for index, thePlayer in ipairs(getElementsByType("player"))do
if (getPlayerIdleTime(thePlayer) > 180000) then
if (getElementData(thePlayer, "isPlayerCTC") == true) then
exports.NGCdxmsg:createNewDxMessage(thePlayer, exports.AURlanguage:getTranslate("You have been killed for being Away From Keyboard while capturing the city.", true, thePlayer),255,0,0)
killPed(thePlayer)
end
end
end
end
setTimer(checkAFKPlayers, 10000, 0)
function onMarkerLeave (leftElement, dim)
if hitElement then
if getElementType(hitElement) == "player" then
setElementData(leftElement, "isPlayerCTC", false)
if not (dim) then return false end
if not (eventMarkers[source]) then return false end
playersInMarker = playersInMarker - 1
if (isTimer(timers[leftElement])) then
killTimer(timers[leftElement])
end
end
end
end
addEventHandler("onMarkerLeave", root, onMarkerLeave)
function killAddOns ( ammo, attacker, weapon, bodypart )
if (isElementWithinColShape ( source, cityCol )) and (isElementWithinColShape ( attacker, cityCol )) then
if getPlayerTeam(source) then
if (getTeamName(getPlayerTeam(source)) == "Criminals") and (isPlayerLaw(attacker)) then
exports.AURpayments:addMoney(attacker, 2000,"Custom","CTC",0,"AURcityevent")
exports.NGCdxmsg:createNewDxMessage("You have recieved $1,000 for defending the city!",attacker, 255,255,0)
if (capturedByCrims) then
setTimer(setElementPosition,1000*6,1,source,3531.14, -1944.29, 19.7)
end
elseif (getTeamName(getPlayerTeam(attacker)) == "Criminals") and (isPlayerLaw(source)) then
exports.AURpayments:addMoney(attacker, 2000,"Custom","CTC",0,"AURcityevent")
exports.NGCdxmsg:createNewDxMessage("You have recieved $1,000 for attacking the city!",attacker, 255,255,0)
if (capturedByCops) then
setTimer(setElementPosition,1000*6,1,source,3531.14, -1944.29, 19.7)
end
end
end
end
end
addEventHandler("onPlayerWasted", root, killAddOns)
function payout ()
local playersIngame = getElementsByType"player"
if (#playersIngame > 10) then
if (ownedByCops == true) then
for k,v in ipairs (getPlayersInTeam(getTeamFromName"Government")) do
exports.AURpayments:addMoney(v, 50000,"Custom","CTC",0,"AURcityevent")
exports.NGCdxmsg:createNewDxMessage("You have recieved $50,000 for keeping the city out of threat!",v,255,255,0)
end
for k,v in ipairs (getPlayersInTeam(getTeamFromName"SWAT Team")) do
exports.AURpayments:addMoney(v, 50000,"Custom","CTC",0,"AURcityevent")
exports.NGCdxmsg:createNewDxMessage("You have recieved $50,000 for keeping the city out of threat!",v,255,255,0)
end
for k,v in ipairs (getPlayersInTeam(getTeamFromName"Military Forces")) do
exports.AURpayments:addMoney(v, 50000,"Custom","CTC",0,"AURcityevent")
exports.NGCdxmsg:createNewDxMessage("You have recieved $50,000 for keeping the city out of threat!",v,255,255,0)
end
elseif (ownedByCrims == true) then
for k,v in ipairs (getPlayersInTeam(getTeamFromName"Criminals")) do
exports.AURpayments:addMoney(v, 50000,"Custom","CTC",0,"AURcityevent")
exports.NGCdxmsg:createNewDxMessage("You have recieved $50,000 for keeping the city in threat!",v,255,255,0)
end
end
end
end
setTimer(payout, 1000*60*10,0)
function weaponsRestriction ()
if (getElementType(source) ~= "player") then return false end
local notAllowed = {
[3] = true,
[23] = true,
}
if (isElementWithinColShape(source, cityCol)) then
local currentID = getPedWeapon(source)
if (notAllowed[currentID]) then
cancelEvent()
toggleControl ( source, 'fire', false )
else
toggleControl ( source, 'fire', true )
end
end
end
addEventHandler("onWeaponFire", root, weaponsRestriction)
function setCityForCrims (p, cmd)
if (getPlayerName(p) ~= "[AUR]Nixon-") then return false end
executeSQLQuery("UPDATE eventMarkers SET owner=?", "crim")
ownedByCrims = true
ownedByCops = false
for k,v in ipairs (getElementsByType"marker") do
if (getElementData(v, "AURcityevent.eventMarker") == true) then
setMarkerColor(v, 255,0,0,255)
setBlipColor(blips[v], 255,0,0,255)
end
end
end
addCommandHandler("setforcrims", setCityForCrims)
function setCityForCops (p, cmd)
if (getPlayerName(p) ~= "[AUR]Nixon-") then return false end
executeSQLQuery("UPDATE eventMarkers SET owner=?", "law")
ownedByCrims = false
ownedByCops = true
for k,v in ipairs (getElementsByType"marker") do
if (getElementData(v, "AURcityevent.eventMarker") == true) then
setMarkerColor(v, 0,0,255,255)
setBlipColor(blips[v], 0,0,255,255)
end
end
end
addCommandHandler("setforcops", setCityForCops)
|
-- Function Availability
FileWriteLineFast("test/output.txt", "Function Availability", FM_WRITE);
local fa = dofile("test/common/function_availability.lua");
fa.FunctionSupported(FontInit, "MTR_FontInit", FontFunctionSupported);
fa.FunctionSupported(FontCreate, "MTR_FontCreate", FontFunctionSupported);
fa.FunctionSupported(FontAddAtlas, "MTR_FontAddAtlas", FontFunctionSupported);
fa.FunctionSupported(FontCacheTtf, "MTR_FontCacheTtf", FontFunctionSupported);
fa.FunctionSupported(FontFree, "MTR_FontFree", FontFunctionSupported);
fa.FunctionSupported(FontFree, "MTR_FontDeleteAtlas", FontFunctionSupported);
fa.FunctionSupported(FontFree, "MTR_FontDeleteAllAtlases",
FontFunctionSupported);
fa.FunctionSupported(FontFree, "MTR_FontDetachAtlas", FontFunctionSupported);
fa.FunctionSupported(FontFree, "MTR_FontDetachAllAtlases",
FontFunctionSupported);
fa.FunctionSupported(FontFree, "MTR_FontGetAtlasSprite", FontFunctionSupported);
fa.FunctionSupported(FontFree, "MTR_FontGetAtlasesCount",
FontFunctionSupported);
fa.FunctionSupported(FontDrawString_f, "MTR_FontDrawString_f",
FontFunctionSupported);
fa.FunctionSupported(FontGetHeight, "MTR_FontGetHeight", FontFunctionSupported);
fa.FunctionSupported(FontGetStringWidth, "MTR_FontGetStringWidth",
FontFunctionSupported);
fa.FunctionSupported(FontGetName, "MTR_FontGetName", FontFunctionSupported);
|
local resolver_access = require "kong.resolver.access"
-- Stubs
require "kong.tools.ngx_stub"
local APIS_FIXTURES = {
{name = "mockbin", inbound_dns = "mockbin.com", upstream_url = "http://mockbin.com"},
{name = "mockbin", inbound_dns = "mockbin-auth.com", upstream_url = "http://mockbin.com"},
{name = "mockbin", inbound_dns = "*.wildcard.com", upstream_url = "http://mockbin.com"},
{name = "mockbin", inbound_dns = "wildcard.*", upstream_url = "http://mockbin.com"},
{name = "mockbin", path = "/mockbin", upstream_url = "http://mockbin.com"},
{name = "mockbin", path = "/mockbin-with-dashes", upstream_url = "http://mockbin.com"},
{name = "mockbin", path = "/some/deep/url", upstream_url = "http://mockbin.com"}
}
_G.dao = {
apis = {
find_all = function()
return APIS_FIXTURES
end
}
}
local apis_dics
describe("Resolver Access", function()
describe("load_apis_in_memory()", function()
it("should retrieve all APIs in datastore and return them organized", function()
apis_dics = resolver_access.load_apis_in_memory()
assert.equal("table", type(apis_dics))
assert.truthy(apis_dics.by_dns)
assert.truthy(apis_dics.path_arr)
assert.truthy(apis_dics.wildcard_dns_arr)
end)
it("should return a dictionary of APIs by inbound_dns", function()
assert.equal("table", type(apis_dics.by_dns["mockbin.com"]))
assert.equal("table", type(apis_dics.by_dns["mockbin-auth.com"]))
end)
it("should return an array of APIs by path", function()
assert.equal("table", type(apis_dics.path_arr))
assert.equal(3, #apis_dics.path_arr)
for _, item in ipairs(apis_dics.path_arr) do
assert.truthy(item.strip_path_pattern)
assert.truthy(item.path)
assert.truthy(item.api)
end
assert.equal("/mockbin", apis_dics.path_arr[1].strip_path_pattern)
assert.equal("/mockbin%-with%-dashes", apis_dics.path_arr[2].strip_path_pattern)
end)
it("should return an array of APIs with wildcard inbound_dns", function()
assert.equal("table", type(apis_dics.wildcard_dns_arr))
assert.equal(2, #apis_dics.wildcard_dns_arr)
for _, item in ipairs(apis_dics.wildcard_dns_arr) do
assert.truthy(item.api)
assert.truthy(item.pattern)
end
assert.equal("^.+%.wildcard%.com$", apis_dics.wildcard_dns_arr[1].pattern)
assert.equal("^wildcard%..+$", apis_dics.wildcard_dns_arr[2].pattern)
end)
end)
describe("find_api_by_path()", function()
it("should return nil when no matching API for that URI", function()
local api = resolver_access.find_api_by_path("/", apis_dics.path_arr)
assert.falsy(api)
end)
it("should return the API for a matching URI", function()
local api = resolver_access.find_api_by_path("/mockbin", apis_dics.path_arr)
assert.same(APIS_FIXTURES[5], api)
api = resolver_access.find_api_by_path("/mockbin-with-dashes", apis_dics.path_arr)
assert.same(APIS_FIXTURES[6], api)
api = resolver_access.find_api_by_path("/mockbin-with-dashes/and/some/uri", apis_dics.path_arr)
assert.same(APIS_FIXTURES[6], api)
api = resolver_access.find_api_by_path("/dashes-mockbin", apis_dics.path_arr)
assert.falsy(api)
api = resolver_access.find_api_by_path("/some/deep/url", apis_dics.path_arr)
assert.same(APIS_FIXTURES[7], api)
end)
end)
describe("find_api_by_inbound_dns()", function()
it("should return nil and a list of all the Host headers in the request when no API was found", function()
local api, all_hosts = resolver_access.find_api_by_inbound_dns({
Host = "foo.com",
["X-Host-Override"] = {"bar.com", "hello.com"}
}, apis_dics)
assert.falsy(api)
assert.same({"foo.com", "bar.com", "hello.com"}, all_hosts)
end)
it("should return an API when one of the Host headers matches", function()
local api = resolver_access.find_api_by_inbound_dns({Host = "mockbin.com"}, apis_dics)
assert.same(APIS_FIXTURES[1], api)
api = resolver_access.find_api_by_inbound_dns({Host = "mockbin-auth.com"}, apis_dics)
assert.same(APIS_FIXTURES[2], api)
end)
it("should return an API when one of the Host headers matches a wildcard dns", function()
local api = resolver_access.find_api_by_inbound_dns({Host = "wildcard.com"}, apis_dics)
assert.same(APIS_FIXTURES[4], api)
api = resolver_access.find_api_by_inbound_dns({Host = "wildcard.fr"}, apis_dics)
assert.same(APIS_FIXTURES[4], api)
api = resolver_access.find_api_by_inbound_dns({Host = "foobar.wildcard.com"}, apis_dics)
assert.same(APIS_FIXTURES[3], api)
api = resolver_access.find_api_by_inbound_dns({Host = "barfoo.wildcard.com"}, apis_dics)
assert.same(APIS_FIXTURES[3], api)
end)
end)
describe("strip_path()", function()
it("should strip the api's path from the requested URI", function()
assert.equal("/status/200", resolver_access.strip_path("/mockbin/status/200", apis_dics.path_arr[1].strip_path_pattern))
assert.equal("/status/200", resolver_access.strip_path("/mockbin-with-dashes/status/200", apis_dics.path_arr[2].strip_path_pattern))
assert.equal("/", resolver_access.strip_path("/mockbin", apis_dics.path_arr[1].strip_path_pattern))
assert.equal("/", resolver_access.strip_path("/mockbin/", apis_dics.path_arr[1].strip_path_pattern))
end)
it("should only strip the first pattern", function()
assert.equal("/mockbin/status/200/mockbin", resolver_access.strip_path("/mockbin/mockbin/status/200/mockbin", apis_dics.path_arr[1].strip_path_pattern))
end)
end)
end)
|
local CodeGenerator = require("api.CodeGenerator")
do
local config = require("mod.elona.locale.en.config").config
print(inspect(config))
local menu = config.menu
local gen = CodeGenerator:new {
always_tabify = true
}
local ORDER = {
"game",
"screen",
"net",
"anime",
"input",
"keybindings",
"message",
"language"
}
for _, menu_id in ipairs(ORDER) do
local items = config.menu[menu_id]
if type(items) == "table" then
local menu = {
_type = "base.config_menu",
_id = menu_id,
items = {}
}
local out = {}
for item_id, t in pairs(items) do
if type(t) == "table" then
local option = {
_id = item_id,
type = ""
}
out[#out+1] = option
table.insert(menu.items, "base." .. item_id)
end
end
gen:write_comment("")
gen:write_comment("Menu: " .. menu_id)
gen:write_comment("")
gen:tabify()
gen:write("data:add_multi(\"base.config_option\", ")
gen:write_table(out)
gen:write(")")
gen:tabify()
gen:tabify()
gen:write("data:add ")
gen:write_table(menu)
gen:tabify()
gen:tabify()
end
end
print(gen)
end
for _, lang in ipairs({"en", "jp"}) do
local config = require("mod.elona.locale." .. lang .. ".config").config
local out = { config = { menu = {}, option = {} } }
local ORDER = {
"game",
"screen",
"net",
"anime",
"input",
"keybindings",
"message",
"language"
}
local gen = CodeGenerator:new {
always_tabify = true,
strict = false
}
for _, menu_id in ipairs(ORDER) do
local items = config.menu[menu_id]
if type(items) == "table" then
local t = {
name = items.name
}
gen:write_key(menu_id)
gen:write(" = ")
gen:write_value(t)
gen:write(",")
gen:tabify()
end
end
gen:tabify()
gen:tabify()
for _, menu_id in ipairs(ORDER) do
local items = config.menu[menu_id]
if type(items) == "table" then
gen:tabify()
gen:write_comment("")
gen:write_comment("Menu: " .. menu_id)
gen:write_comment("")
for item_id, t in pairs(items) do
if type(t) == "table" then
gen:tabify()
gen:write_key(item_id)
gen:write(" = ")
gen:write_value(t)
gen:write(",")
gen:tabify()
end
end
end
end
gen:write_table(out)
print(gen)
end
-- Local Variables:
-- open-nefia-always-send-to-repl: t
-- End:
|
function x2c(x) return string.char(tonumber(x, 16)) end
function u(s) return s:gsub("%%(%x%x)", x2c) end
server = net.createServer(net.TCP)
server:listen(80, function(conn)
conn:on("receive", function(conn, p)
q = string.match(p, "GET (.+) HTTP/1.1")
is = false
if q ~= "/favicon.ico" then
if q ~= "/" then
p = {}
for k, v in string.gmatch(q, "([^?=&]+)=(([^&]*))" ) do p[k] = u(v) end
file.open("config.lua", "w+")
file.write("id={"..p['id'].."}:sp={"..p['sp'].."}:u={"..p['u'].."}:p={"..p['p'].."}")
file.close()
h = 'Success!'
is = true
else
h = '<!DOCTYPE html><html><body style="font-family: arial"><form><table>'..
'<tr><td colspan="2"><b>Select Home Wireless</b></td></tr>'..
'<tr><td>SSID </td><td><input type="text" name="id" required></td></tr>'..
'<tr><td>SSID Password </td><td><input type="password" name="sp" required></td></tr>'..
'<tr><td colspan="2"><b>Create Account</b></td></tr>'..
'<tr><td>Email </td><td><input type="email" name="u" required></td></tr>'..
'<tr><td>Create Password </td><td><input type="password" name="p" required></td></tr>'..
'<tr><td> </td><td><input type="submit" value="Save"></td></tr>'..
'</table></form></body></html>'
end
conn:send(h)
if is then
tmr.alarm(1, 2500, 0, function() node.restart() end)
end
end
end)
conn:on("sent", function(conn) conn:close() end)
end) |
local function vmstat(path)
local path = path or "/proc/vmstat"
local tbl = {}
local pattern = "(%g+)%s+(%d+)"
for str in io.lines(path) do
local key, value = str:match(pattern)
if key then
tbl[key] = tonumber(value)
end
end
return tbl;
end
return {
decoder = vmstat;
} |
function love.conf(t)
t.window.title = "Puchi the game"
end
|
--
-- RemDebug 1.0 Beta
-- Copyright Kepler Project 2005 (http://www.keplerproject.org/remdebug)
--
local socket = require"socket"
--local lfs = require"lfs"
local debug = require"debug"
local json = require("json")
module("remdebug.engine", package.seeall)
_COPYRIGHT = "2006 - Kepler Project"
_DESCRIPTION = "Remote Debugger for the Lua programming language"
_VERSION = "1.0"
-- Extracts and returns file name and line number from a "setb" or "delb" command line.
local function get_breakpoint_parameters_from(commandLine)
local expression
local substring
-- Select a pattern matching string used to extract the command line arguments.
-- If it contains quotes, then assume a quoted path containing spaces was given.
if not string.find(commandLine, '"') then
expression = "^([%a]+)%s+([%w%p]+)%s+(%d+)$"
else
expression = '^([%a]+)%s+(["].-["])%s+(%d+)$'
end
-- Extract arguments.
local _, _, _, fileName, lineNumber = string.find(commandLine, expression)
-- Remove double quotes from retrieved file name string.
-- This way the debug_hook() function below can lookup breakpoints by file name only.
_, _, substring = string.find(fileName, '["](.-)["]')
if substring then
fileName = substring
end
--[[
-- Remove path from retrieved file name string.
_, _, substring = string.find(fileName, ".-([^/\\]+)$")
if substring then
fileName = substring
end
--]]
return fileName, lineNumber
end
-- Combines "path2" to the end of "path1" and returns it as a single path.
-- Correctly handles double quotes and trailing slashes in the paths when combining them.
-- Argument "path2" should not be set to an absolute path. It is expected to be sub-directories
-- and maybe a file name under "path1".
-- If "path1" is empty, then "path2" is returned. If "path2" is empty, then "path1" is returned.
local function combine_paths(path1, path2)
local expression
local substring
local pathSeparator
local combinedPath
-- If one of the given paths is empty/nil, then return the other path.
if (path1 == nil) or (path1 == "") then
return path2
end
if (path2 == nil) or (path2 == "") then
return path1
end
-- Guess which path separator to use ('/' or '\') by analyzing the first path.
pathSeparator = "/"
if string.find(path1, "\\") then
pathSeparator = "\\"
end
-- Remove double quotes from paths.
expression = '["](.-)["]'
_, _, substring = string.find(path1, expression)
if substring then
path1 = substring
end
_, _, substring = string.find(path2, expression)
if substring then
path2 = substring
end
-- Remove periods, slashes, and spaces from the end of path1.
-- Note: The "(.-)" part of the expression extracts all chars to the left of the chars to be removed.
_, _, substring = string.find(path1, "(.-)\./\\%s")
if substring then
path1 = substring
end
-- Remove periods, slashes, and spaces from the beginning of path2.
-- Note: The "(.-)" part of the expression extracts all chars to the right of the chars to be removed.
_, _, substring = string.find(path2, "\./\\%s(.-)")
if substring then
path2 = substring
end
-- Combine the two paths. Double quote the result if it contains spaces.
combinedPath = path1 .. pathSeparator .. path2
if string.find(combinedPath, " ") then
combinedPath = "\"" .. combinedPath .. "\""
end
return combinedPath
end
local coro_debugger
local events = { BREAK = 1, WATCH = 2 }
local breakpoints = {}
local watches = {}
local step_into = false
local step_over = false
local step_level = 0
local stack_level = 0
local start_frame_index = 3
local error_event = false
local controller_host = "localhost"
local controller_port = 8171
local function set_breakpoint(file, line)
print( "set_breakpoint("..file..","..line..")" )
if not breakpoints[file] then
breakpoints[file] = {}
end
breakpoints[file][line] = true
end
local function remove_breakpoint(file, line)
if breakpoints[file] then
breakpoints[file][line] = nil
end
end
local function has_breakpoint(file, line)
return breakpoints[file] and breakpoints[file][line]
end
local function restore_vars(frame, vars)
if type(vars) ~= 'table' then return end
local func = debug.getinfo(frame, "f").func
local i = 1
local written_vars = {}
while true do
local name = debug.getlocal(frame, i)
if not name then break end
debug.setlocal(frame, i, vars[name])
written_vars[name] = true
i = i + 1
end
i = 1
while true do
local name = debug.getupvalue(func, i)
if not name then break end
if not written_vars[name] then
debug.setupvalue(func, i, vars[name])
written_vars[name] = true
end
i = i + 1
end
end
local function restore_stack(stack)
local stack = {}
local frameNum = (not error_event) and start_frame_index or start_frame_index + 1
for i,frame in ipairs(stack) do
-- Calling debug.getlocal in a different function frame from this
-- current one screws up the frame number index passed to debug.getlocal
-- restore_vars inlined to avoid screwing up the frame number
local vars = frame.vars
if type(vars) ~= 'table' then return end
local func = debug.getinfo(frameNum, "f").func
local i = 1
local written_vars = {}
while true do
local name = debug.getlocal(frameNum, i)
if not name then break end
debug.setlocal(frameNum, i, vars[name])
written_vars[name] = true
i = i + 1
end
i = 1
while true do
local name = debug.getupvalue(func, i)
if not name then break end
if not written_vars[name] then
debug.setupvalue(func, i, vars[name])
written_vars[name] = true
end
i = i + 1
end
-- restore_vars( frameNum, frame.vars )
frameNum = frameNum + 1
end
end
local function capture_stack()
local stack = {}
local frameNum = (not error_event) and start_frame_index or start_frame_index + 1
while true do
-- local frame = capture_frame(frameNum)
-- if not frame then break end
local info = debug.getinfo(frameNum, "Snlf")
if not info then
break
end
-- Calling debug.getlocal in a different function frame from this
-- current one screws up the frame number index passed to debug.getlocal
--print( "Frame("..frameNum..") of type: "..tostring(info.what) )
-- capture_vars inlined to avoid screwing up the frame number
local vars = {}
local func = info.func
local i = 1
if func then
while true do
local name, value = debug.getupvalue(func, i)
if not name then break end
vars[name] = value
i = i + 1
end
i = 1
end
while true do
local name, value = debug.getlocal(frameNum, i)
if not name then break end
--print( "[" .. frameNum .. "] " .. tostring(name) .. " = " .. tostring(value) )
vars[name] = value
i = i + 1
end
setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) })
-- capture_frame
local frame = {}
frame.vars = vars
frame.what = info.what
frame.name = info.name or "(nil)"
frame.file = info.source -- info.short_src
frame.line = info.currentline
--[[
print( "Frame("..frameNum..")" )
for k,v in pairs(frame) do
print( k .. ":" .. tostring(v) )
end
print( "" )
--]]
table.insert(stack, frame)
frameNum = frameNum + 1
end
return stack
end
local function break_dir(path)
local paths = {}
path = string.gsub(path, "\\", "/")
for w in string.gfind(path, "[^\/]+") do
table.insert(paths, w)
end
return paths
end
local function merge_paths(path1, path2)
local paths1 = break_dir(path1)
local paths2 = break_dir(path2)
for i, path in ipairs(paths2) do
if path == ".." then
table.remove(paths1, table.getn(paths1))
elseif path ~= "." then
table.insert(paths1, path)
end
end
return table.concat(paths1, "/")
end
local function debug_hook(event, line, msg)
--print( "event("..tostring(event)..") line("..tostring(line)..")" )
if event == "call" then
stack_level = stack_level + 1
elseif event == "return" or event == "tail return" then
stack_level = stack_level - 1
else
local level = 2
if event == "error" then
if msg then print( msg ) end
level = level + 1
error_event = true
end
local file = debug.getinfo(level, "S").source
if string.find(file, "@") == 1 then
file = string.sub(file, 2)
end
-- TODO: Find a better solution to the basedir problem
-- For now, strip path info off file.
local _, _, filename = string.find(file, ".-([^/\\]+)$")
-- if filename then file = filename end
-- file = merge_paths(lfs.currentdir(), file)
--print( file .."("..tostring(line)..")")
-- local vars = capture_vars()
--print( "event("..tostring(Event)..") at "..tostring(file) .. ":" ..tostring(line) )
local stack = capture_stack()
local frame = stack[1]
local vars = frame.vars
table.foreach(watches, function (index, value)
setfenv(value, vars)
local status, res = pcall(value)
if status and res then
coroutine.resume(coro_debugger, events.WATCH, stack, file, line, index)
end
end)
if step_into or (step_over and stack_level <= step_level) or has_breakpoint(file, line) or event == "error" then
step_into = false
step_over = false
coroutine.resume(coro_debugger, events.BREAK, stack, file, line)
restore_stack(stack)
end
end
end
local function format_data_for_display(data, pretty_print_json)
local pretty_print_json = pretty_print_json or false
local value = data
local typename = type(data)
if typename == "string" then
-- Enclose strings in double quotes
value = '"' .. value .. '"'
elseif typename == "function" then
local functionInfo = debug.getinfo(data, "S")
if functionInfo.source == "=[C]" then
value = "internal"
else
value = string.format("%s:%d", functionInfo.source, functionInfo.linedefined)
end
elseif typename == "table" then
-- If this is a Corona internal type it'll have these properties
if data._type ~= nil then
typename = data._type
end
if data._properties ~= nil then
value = data._properties
else
-- Format the table as JSON
local pcall_status, pretty_val = pcall(json.encode, data)
if not pcall_status then
-- Something went wrong, emit the unformatted data
value = "[raw] "..tostring(data)
else
-- We'll use "pretty_val", tidy it up
value = pretty_val:gsub("<type '(.-)' is not supported by JSON.>", "<%1>")
end
end
if pretty_print_json then
value = json.prettify(value)
end
end
return tostring(typename), tostring(value)
end
local function debugger_loop(server)
local command
local eval_env = {}
local frameIndex = 1
while true do
local line, status = server:receive()
command = string.sub(line, string.find(line, "^[A-Z]+"))
-- print("remdebug: line: "..tostring(line))
-- print("remdebug: command: "..tostring(command))
if command == "SETB" then
local filename, line = get_breakpoint_parameters_from(line)
if filename and line then
set_breakpoint(filename, tonumber(line))
server:send("200 OK\n")
else
server:send("400 Bad Request\n")
end
elseif command == "DELB" then
local filename, line = get_breakpoint_parameters_from(line)
if filename and line then
remove_breakpoint(filename, tonumber(line))
server:send("200 OK\n")
else
server:send("400 Bad Request\n")
end
elseif command == "EXEC" then
local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$")
if chunk then
local func = loadstring(chunk)
local status, res
if func then
setfenv(func, eval_env[frameIndex].vars)
status, res = xpcall(func, debug.traceback)
end
res = tostring(res)
if status then
server:send("200 OK " .. string.len(res) .. "\n")
server:send(res)
else
server:send("401 Error in Expression " .. string.len(res) .. "\n")
server:send(res)
end
else
server:send("400 Bad Request\n")
end
elseif command == "DUMP" then
local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$")
if chunk then
local func = loadstring(chunk)
local status, res
if func then
setfenv(func, eval_env[frameIndex].vars)
status, res = xpcall(func, debug.traceback)
end
if status then
local _, _, expr = string.find(chunk, "return %((.*)%)")
typename, value = format_data_for_display(res, true)
if expr and typename and value then
response = string.format("%s = (%s) %s", expr, typename, value)
else
response = "Could not evaluate '"..tostring(expr).."' (perhaps it's not defined yet)"
end
server:send("200 OK " .. string.len(response) .. "\n")
server:send(response)
else
res = tostring(res)
server:send("401 Error in Expression " .. string.len(res) .. "\n")
server:send(res)
end
else
server:send("400 Bad Request\n")
end
elseif command == "SETW" then
local _, _, exp = string.find(line, "^[A-Z]+%s+(.+)$")
if exp then
local func = loadstring("return(" .. exp .. ")")
local newidx = table.getn(watches) + 1
watches[newidx] = func
-- table.setn(watches, newidx)
server:send("200 OK " .. newidx .. "\n")
else
server:send("400 Bad Request\n")
end
elseif command == "DELW" then
local _, _, index = string.find(line, "^[A-Z]+%s+(%d+)$")
index = tonumber(index)
if index then
watches[index] = nil
server:send("200 OK\n")
else
server:send("400 Bad Request\n")
end
elseif command == "RUN" then
server:send("200 OK\n")
print("RUN: breakpoints: "..json.encode(breakpoints))
local ev, stack, file, line, idx_watch = coroutine.yield()
eval_env = stack
if ev == events.BREAK then
local label = (not error_event and "Paused " or "Error " )
server:send("202 " .. label .. file .. " " .. line .. "\n")
elseif ev == events.WATCH then
server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n")
else
server:send("401 Error in Execution " .. string.len(file) .. "\n")
server:send(file)
end
elseif command == "STEP" then
server:send("200 OK\n")
step_into = true
local ev, stack, file, line, idx_watch = coroutine.yield()
eval_env = stack
if ev == events.BREAK then
local label = (not error_event and "Paused " or "Error " )
server:send("202 " .. label .. file .. " " .. line .. "\n")
elseif ev == events.WATCH then
server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n")
else
server:send("401 Error in Execution " .. string.len(file) .. "\n")
server:send(file)
end
elseif command == "OVER" then
server:send("200 OK\n")
step_over = true
step_level = stack_level
local ev, stack, file, line, idx_watch = coroutine.yield()
eval_env = stack
if ev == events.BREAK then
local label = (not error_event and "Paused " or "Error " )
server:send("202 " .. label .. file .. " " .. line .. "\n")
elseif ev == events.WATCH then
server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n")
else
server:send("401 Error in Execution " .. string.len(file) .. "\n")
server:send(file)
end
elseif command == "BACKTRACE" then
local stacktrace = {}
for i,frame in ipairs(eval_env) do
local prefix = ( i == frameIndex and "*" ) or " "
local s
-- print("json.version: "..tostring(json.version))
-- Can't use json for frames because they use userdata as array indices
-- print("remdebug: frame.name: "..tostring(frame.name))
-- print(" frame.file: "..tostring(frame.file))
-- print(" frame.line: "..tostring(frame.line))
if frame.what ~= "C" then
s = string.format("%s[%3d] %s at %s:%d", prefix, i, frame.name, frame.file, frame.line )
else
s = string.format("%s[%3d] (Runtime)", prefix, i )
end
table.insert(stacktrace, s)
end
stacktrace = table.concat(stacktrace, "\n")
if not stacktrace then
server:send("200 OK " .. 0 .. "\n")
else
server:send("200 OK " .. string.len(stacktrace) .. "\n")
server:send(stacktrace)
end
elseif command == "FRAME" then
local _, _, _, index = string.find(line, "^([A-Z]+)%s+([%d]+)$")
index = tonumber(index)
if index > #eval_env then
index = #eval_env
end
if eval_env[index].what ~= "C" then
frameIndex = index
server:send("200 OK\n")
else
server:send("402 Invalid frame index number\n")
end
elseif command == "LOCALS" then
local ignore = { __FILE__ = true, __LINE__ = true }
local vars = {}
local frame = eval_env[frameIndex]
if frame then
for k,v in pairs(frame.vars) do
if k == "(*temporary)" or ignore[k] then
-- do nothing
else
typename, value = format_data_for_display(v)
table.insert(vars, string.format("%s = (%s) %s",
tostring(k), typename, value))
end
end
end
local msg = table.concat(vars,"\n")
if msg == nil then
server:send("200 OK " .. 0 .. "\n")
else
server:send("200 OK " .. string.len(msg) .. "\n")
server:send(msg)
end
else
server:send("400 Bad Request\n")
end
end
end
coro_debugger = coroutine.create(debugger_loop)
--
-- remdebug.engine.config(tab)
-- Configures the engine
--
function config(tab)
if tab.host then
controller_host = tab.host
end
if tab.port then
controller_port = tab.port
end
end
--
-- remdebug.engine.start()
-- Tries to start the debug session by connecting with a controller
--
function start()
-- pcall(require, "remdebug.config")
local server = socket.connect(controller_host, controller_port)
if server then
_TRACEBACK = function (message)
local err = debug.traceback(message)
server:send("401 Error in Execution " .. string.len(err) .. "\n")
server:send(err)
server:close()
return err
end
debug.sethook(debug_hook, "lcr")
return coroutine.resume(coro_debugger, server)
end
end
|
--[[
Returns a selection image with rounded corners.
]]
local Settings = script.Parent.Parent
local Constants = require(Settings.Pages.LeaveGameScreen.Constants)
return function()
local RoundedSelectionImage = Instance.new("ImageLabel")
RoundedSelectionImage.Name = "SelectorImage"
RoundedSelectionImage.Image = Constants.Image.BUTTON_SELECTOR
RoundedSelectionImage.Position = UDim2.new(0, -7, 0, -7)
RoundedSelectionImage.Size = UDim2.new(1, 14, 1, 14)
RoundedSelectionImage.BackgroundTransparency = 1
RoundedSelectionImage.ScaleType = Enum.ScaleType.Slice
RoundedSelectionImage.SliceCenter = Rect.new(31, 31, 63, 63)
return RoundedSelectionImage
end
|
require("analytics")
local logger = require("logger")
-- Stuff defined in this file:
-- . the data structures that store the configuration of
-- the stack of panels
-- . the main game routine
-- (rising, timers, falling, cursor movement, swapping, landing)
-- . the matches-checking routine
local min, pairs, deepcpy = math.min, pairs, deepcpy
local max = math.max
local garbage_bounce_time = #garbage_bounce_table
local clone_pool = {}
-- Represents the full panel stack for one player
Stack =
class(
function(s, arguments)
local which = arguments.which or 1
assert(arguments.match ~= nil)
local match = arguments.match
assert(arguments.is_local ~= nil)
local is_local = arguments.is_local
local panels_dir = arguments.panels_dir or config.panels
-- level or difficulty should be set
assert(arguments.level ~= nil or arguments.difficulty ~= nil)
local level = arguments.level
local difficulty = arguments.difficulty
local speed = arguments.speed
local player_number = arguments.player_number or which
local wantsCanvas = arguments.wantsCanvas or 1
local character = arguments.character or config.character
s.match = match
s.character = character
s.max_health = 1
s.panels_dir = panels_dir
s.portraitFade = 0
s.is_local = is_local
s.drawsAnalytics = true
if not panels[panels_dir] then
s.panels_dir = config.panels
end
if s.match.mode == "puzzle" then
s.drawsAnalytics = false
else
s.do_first_row = true
end
if difficulty then
if s.match.mode == "endless" then
s.NCOLORS = difficulty_to_ncolors_endless[difficulty]
elseif s.match.mode == "time" then
s.NCOLORS = difficulty_to_ncolors_1Ptime[difficulty]
end
end
-- frame.png dimensions
if wantsCanvas then
s.canvas = love.graphics.newCanvas(104 * GFX_SCALE, 204 * GFX_SCALE)
s.canvas:setFilter("nearest", "nearest")
end
if level then
s:setLevel(level)
speed = speed or level_to_starting_speed[level]
end
s.health = s.max_health
s.garbage_cols = {
{1, 2, 3, 4, 5, 6, idx = 1},
{1, 3, 5, idx = 1},
{1, 4, idx = 1},
{1, 2, 3, idx = 1},
{1, 2, idx = 1},
{1, idx = 1}
}
s.later_garbage = {} -- Queue of garbage that is done waiting in telegraph, and been popped out, and will be sent to our stack next frame
s.garbage_q = GarbageQueue(s) -- Queue of garbage that is about to be dropped
s:moveForPlayerNumber(which)
s.panel_buffer = ""
s.gpanel_buffer = ""
s.input_buffer = ""
s.confirmedInput = "" -- All inputs the player has input ever
s.panels = {}
s.width = 6
s.height = 12
for i = 0, s.height do
s.panels[i] = {}
for j = 1, s.width do
s.panels[i][j] = Panel()
end
end
s.CLOCK = 0
s.game_stopwatch = 0
s.game_stopwatch_running = false
s.do_countdown = true
s.max_runs_per_frame = 3
s.displacement = 16
-- This variable indicates how far below the top of the play
-- area the top row of panels actually is.
-- This variable being decremented causes the stack to rise.
-- During the automatic rising routine, if this variable is 0,
-- it's reset to 15, all the panels are moved up one row,
-- and a new row is generated at the bottom.
-- Only when the displacement is 0 are all 12 rows "in play."
s.danger_col = {false, false, false, false, false, false}
-- set true if this column is near the top
s.danger_timer = 0 -- decides bounce frame when in danger
s.difficulty = difficulty or 2
s.speed = speed or 1 -- The player's speed level decides the amount of time
-- the stack takes to rise automatically
if s.speed_times == nil then
s.panels_to_speedup = panels_to_next_speed[s.speed]
end
s.rise_timer = 1 -- When this value reaches 0, the stack will rise a pixel
s.rise_lock = false -- If the stack is rise locked, it won't rise until it is
-- unlocked.
s.has_risen = false -- set once the stack rises once during the game
s.stop_time = 0
s.pre_stop_time = 0
s.NCOLORS = s.NCOLORS or 5
s.score = 0 -- der skore
s.chain_counter = 0 -- how high is the current chain
s.panels_in_top_row = false -- boolean, for losing the game
s.danger = s.danger or false -- boolean, panels in the top row (danger)
s.danger_music = s.danger_music or false -- changes music state
s.n_active_panels = 0
s.prev_active_panels = 0
s.n_chain_panels = 0
-- These change depending on the difficulty and speed levels:
s.FRAMECOUNT_HOVER = s.FRAMECOUNT_HOVER or FC_HOVER[s.difficulty]
s.FRAMECOUNT_FLASH = s.FRAMECOUNT_FLASH or FC_FLASH[s.difficulty]
s.FRAMECOUNT_FACE = s.FRAMECOUNT_FACE or FC_FACE[s.difficulty]
s.FRAMECOUNT_POP = s.FRAMECOUNT_POP or FC_POP[s.difficulty]
s.FRAMECOUNT_MATCH = s.FRAMECOUNT_FACE + s.FRAMECOUNT_FLASH
s.FRAMECOUNT_RISE = speed_to_rise_time[s.speed]
s.rise_timer = s.FRAMECOUNT_RISE
-- Player input stuff:
s.manual_raise = false -- set until raising is completed
s.manual_raise_yet = false -- if not set, no actual raising's been done yet
-- since manual raise button was pressed
s.prevent_manual_raise = false
s.swap_1 = false -- attempt to initiate a swap on this frame
s.swap_2 = false
s.taunt_up = nil -- will hold an index
s.taunt_down = nil -- will hold an index
s.taunt_queue = Queue()
s.cur_wait_time = config.input_repeat_delay -- number of ticks to wait before the cursor begins
-- to move quickly... it's based on P1CurSensitivity
s.cur_timer = 0 -- number of ticks for which a new direction's been pressed
s.cur_dir = nil -- the direction pressed
s.cur_row = 7 -- the row the cursor's on
s.cur_col = 3 -- the column the left half of the cursor's on
s.top_cur_row = s.height + (s.match.mode == "puzzle" and 0 or -1)
s.poppedPanelIndex = s.poppedPanelIndex or 1
s.panels_cleared = s.panels_cleared or 0
s.metal_panels_queued = s.metal_panels_queued or 0
s.lastPopLevelPlayed = s.lastPopLevelPlayed or 1
s.lastPopIndexPlayed = s.lastPopIndexPlayed or 1
s.combo_chain_play = nil
s.game_over = false -- only set if this player got a game over
s.game_over_clock = 0 -- only set if game_over is true, the exact clock frame the player lost
s.sfx_land = false
s.sfx_garbage_thud = 0
s.card_q = Queue()
s.pop_q = Queue()
s.which = which
s.player_number = player_number --player number according to the multiplayer server, for game outcome reporting
s.shake_time = 0
s.prev_states = {}
s.analytic = AnalyticsInstance(s.is_local)
if s.match.mode == "vs" then
s.telegraph = Telegraph(s, s) -- Telegraph holds the garbage that hasn't been committed yet and also tracks the attack animations
-- NOTE: this is the telegraph above this stack, so the opponents puts garbage in this stack.
end
s.combos = {} -- Tracks the combos made throughout the whole game. Key is the clock time, value is the combo size
s.chains = {} -- Tracks the chains mades throughout the whole game
--[[
.last_complete - the CLOCK index into the last chain or nil if no chains this game yet
.current - the CLOCK index into the current chain or nil if no chain active
indexes
Key - CLOCK time the chain started
Value -
start - CLOCK time the chain started (same as key)
finish - CLOCK time the chain finished
size - the chain size 2, 3, etc
]]
s.panelGenCount = 0
s.garbageGenCount = 0
s.rollbackCount = 0 -- the number of times total we have done rollback
s.lastRollbackFrame = -1 -- the last frame we had to rollback from
s.framesBehindArray = {}
s.totalFramesBehind = 0
end)
function Stack.setLevel(self, level)
self.level = level
--difficulty = level_to_difficulty[level]
self.speed_times = {15 * 60, idx = 1, delta = 15 * 60}
self.max_health = level_to_hang_time[level]
self.FRAMECOUNT_HOVER = level_to_hover[level]
self.FRAMECOUNT_GPHOVER = level_to_garbage_panel_hover[level]
self.FRAMECOUNT_FLASH = level_to_flash[level]
self.FRAMECOUNT_FACE = level_to_face[level]
self.FRAMECOUNT_POP = level_to_pop[level]
self.combo_constant = level_to_combo_constant[level]
self.combo_coefficient = level_to_combo_coefficient[level]
self.chain_constant = level_to_chain_constant[level]
self.chain_coefficient = level_to_chain_coefficient[level]
if self.match.mode == "2ptime" then
self.NCOLORS = level_to_ncolors_time[level]
else
self.NCOLORS = level_to_ncolors_vs[level]
end
end
-- Positions the stack draw position for the given player
function Stack.moveForPlayerNumber(stack, player_num)
local stack_padding_x_for_legacy_pos = ((canvas_width - legacy_canvas_width) / 2)
if player_num == 1 then
stack.pos_x = 4 + stack_padding_x_for_legacy_pos / GFX_SCALE
stack.score_x = 315 + stack_padding_x_for_legacy_pos
stack.mirror_x = 1
stack.origin_x = stack.pos_x
stack.multiplication = 0
stack.id = "_1P"
stack.VAR_numbers = ""
elseif player_num == 2 then
stack.pos_x = 172 + stack_padding_x_for_legacy_pos / GFX_SCALE
stack.score_x = 410 + stack_padding_x_for_legacy_pos
stack.mirror_x = -1
stack.origin_x = stack.pos_x + (stack.canvas:getWidth() / GFX_SCALE) - 8
stack.multiplication = 1
stack.id = "_2P"
end
stack.pos_y = 4 + (canvas_height - legacy_canvas_height) / GFX_SCALE
stack.score_y = 100 + (canvas_height - legacy_canvas_height)
end
function Stack.divergenceString(stackToTest)
local result = ""
local panels = stackToTest.panels
if panels then
for i=#panels,1,-1 do
for j=1,#panels[i] do
result = result .. (tostring(panels[i][j].color)) .. " "
if panels[i][j].state ~= "normal" then
result = result .. (panels[i][j].state) .. " "
end
end
result = result .. "\n"
end
end
if stackToTest.telegraph then
result = result .. "telegraph.chain count " .. stackToTest.telegraph.garbage_queue.chain_garbage:len() .. "\n"
result = result .. "telegraph.senderCurrentlyChaining " .. tostring(stackToTest.telegraph.senderCurrentlyChaining) .. "\n"
result = result .. "telegraph.attacks " .. table.length(stackToTest.telegraph.attacks) .. "\n"
end
result = result .. "garbage_q " .. stackToTest.garbage_q:len() .. "\n"
result = result .. "later_garbage " .. table.length(stackToTest.later_garbage) .. "\n"
result = result .. "Stop " .. stackToTest.stop_time .. "\n"
result = result .. "Pre Stop " .. stackToTest.pre_stop_time .. "\n"
result = result .. "Shake " .. stackToTest.shake_time .. "\n"
result = result .. "Displacement " .. stackToTest.displacement .. "\n"
result = result .. "Clock " .. stackToTest.CLOCK .. "\n"
result = result .. "Panel Buffer " .. stackToTest.panel_buffer .. "\n"
return result
end
-- Backup important variables into the passed in variable to be restored in rollback. Note this doesn't do a full copy.
function Stack.rollbackCopy(self, source, other)
if other == nil then
if #clone_pool == 0 then
other = {}
else
other = clone_pool[#clone_pool]
clone_pool[#clone_pool] = nil
end
end
other.do_swap = source.do_swap
other.speed = source.speed
other.health = source.health
other.garbage_cols = deepcpy(source.garbage_cols)
--[[if source.garbage_cols then
other.garbage_idxs = other.garbage_idxs or {}
local n_g_cols = #(source.garbage_cols or other.garbage_cols)
for i=1,n_g_cols do
other.garbage_idxs[i]=source.garbage_cols[i].idx
end
else
end--]]
other.later_garbage = deepcpy(source.later_garbage)
other.garbage_q = source.garbage_q:makeCopy()
if source.telegraph then
other.telegraph = source.telegraph:rollbackCopy(source.telegraph, other.telegraph)
end
local width = source.width or other.width
local height_to_cpy = #source.panels
other.panels = other.panels or {}
local startRow = 1
if self.panels[0] then
startRow = 0
end
for i = startRow, height_to_cpy do
if other.panels[i] == nil then
other.panels[i] = {}
for j = 1, width do
other.panels[i][j] = Panel()
end
end
for j = 1, width do
local opanel = other.panels[i][j]
local spanel = source.panels[i][j]
opanel:clear()
for k, v in pairs(spanel) do
opanel[k] = v
end
end
end
for i = height_to_cpy + 1, #other.panels do
other.panels[i] = nil
end
other.countdown_CLOCK = source.countdown_CLOCK
other.starting_cur_row = source.starting_cur_row
other.starting_cur_col = source.starting_cur_col
other.countdown_cursor_state = source.countdown_cursor_state
other.countdown_cur_speed = source.countdown_cur_speed
other.countdown_timer = source.countdown_timer
other.CLOCK = source.CLOCK
other.game_stopwatch = source.game_stopwatch
other.game_stopwatch_running = source.game_stopwatch_running
other.prev_rise_lock = source.prev_rise_lock
other.rise_lock = source.rise_lock
other.top_cur_row = source.top_cur_row
other.cursor_lock = source.cursor_lock
other.displacement = source.displacement
other.speed_times = deepcpy(source.speed_times)
other.panels_to_speedup = source.panels_to_speedup
other.stop_time = source.stop_time
other.pre_stop_time = source.pre_stop_time
other.score = source.score
other.chain_counter = source.chain_counter
other.n_active_panels = source.n_active_panels
other.prev_active_panels = source.prev_active_panels
other.n_chain_panels = source.n_chain_panels
other.FRAMECOUNT_RISE = source.FRAMECOUNT_RISE
other.rise_timer = source.rise_timer
other.manual_raise = source.manual_raise
other.manual_raise_yet = source.manual_raise_yet
other.prevent_manual_raise = source.prevent_manual_raise
other.cur_timer = source.cur_timer
other.cur_dir = source.cur_dir
other.cur_row = source.cur_row
other.cur_col = source.cur_col
other.shake_time = source.shake_time
other.peak_shake_time = source.peak_shake_time
other.do_countdown = source.do_countdown
other.ready_y = source.ready_y
other.combos = deepcpy(source.combos)
other.chains = deepcpy(source.chains)
other.panel_buffer = source.panel_buffer
other.gpanel_buffer = source.gpanel_buffer
other.panelGenCount = source.panelGenCount
other.garbageGenCount = source.garbageGenCount
other.panels_in_top_row = source.panels_in_top_row
other.has_risen = source.has_risen
other.metal_panels_queued = source.metal_panels_queued
other.panels_cleared = source.panels_cleared
other.danger_timer = source.danger_timer
other.analytic = deepcpy(source.analytic)
other.game_over_clock = source.game_over_clock
return other
end
function Stack.restoreFromRollbackCopy(self, other)
self:rollbackCopy(other, self)
if self.telegraph then
self.telegraph.owner = self.garbage_target
self.telegraph.sender = self
end
-- The remaining inputs is the confirmed inputs not processed yet for this clock time
-- We have processed CLOCK time number of inputs when we are at CLOCK, so we only want to process the CLOCK+1 input on
self.input_buffer = string.sub(self.confirmedInput, self.CLOCK+1)
end
function Stack.rollbackToFrame(self, frame)
local currentFrame = self.CLOCK
local difference = currentFrame - frame
local safeToRollback = difference <= MAX_LAG
if not safeToRollback then
if self.garbage_target then
self.garbage_target.tooFarBehindError = true
end
return -- EARLY RETURN
end
if frame < currentFrame then
local prev_states = self.prev_states
logger.debug("Rolling back " .. self.which .. " to " .. frame)
assert(prev_states[frame])
self:restoreFromRollbackCopy(prev_states[frame])
if self.garbage_target and self.garbage_target.later_garbage then
-- The garbage that we send this time might (rarely) not be the same
-- as the garbage we sent before. Wipe out the garbage we sent before...
for k, v in pairs(self.garbage_target.later_garbage) do
if k > frame then
self.garbage_target.later_garbage[k] = nil
end
end
end
self.rollbackCount = self.rollbackCount + 1
self.lastRollbackFrame = currentFrame
end
end
-- Saves state in backups in case its needed for rollback
-- NOTE: the CLOCK time is the save state for simulating right BEFORE that clock time is simulated
function Stack.saveForRollback(self)
local prev_states = self.prev_states
local garbage_target = self.garbage_target
self.garbage_target = nil
self.prev_states = nil
self:remove_extra_rows()
prev_states[self.CLOCK] = self:rollbackCopy(self)
self.prev_states = prev_states
self.garbage_target = garbage_target
local deleteFrame = self.CLOCK - MAX_LAG - 1
if prev_states[deleteFrame] then
Telegraph.saveClone(prev_states[deleteFrame].telegraph)
-- Has a reference to stacks we don't want kept around
prev_states[deleteFrame].telegraph = nil
clone_pool[#clone_pool + 1] = prev_states[deleteFrame]
prev_states[deleteFrame] = nil
end
end
function Stack.set_garbage_target(self, new_target)
self.garbage_target = new_target
if self.telegraph then
self.telegraph.owner = new_target
self.telegraph:updatePosition()
end
end
local MAX_TAUNT_PER_10_SEC = 4
function Stack.can_taunt(self)
return self.taunt_queue:len() < MAX_TAUNT_PER_10_SEC or self.taunt_queue:peek() + 10 < love.timer.getTime()
end
function Stack.taunt(self, taunt_type)
while self.taunt_queue:len() >= MAX_TAUNT_PER_10_SEC do
self.taunt_queue:pop()
end
self.taunt_queue:push(love.timer.getTime())
end
-- Represents an individual panel in the stack
Panel =
class(
function(p)
p:clear()
end
)
function Panel.regularColorsArray()
return {
1, -- hearts
2, -- circles
3, -- triangles
4, -- stars
5, -- diamonds
6, -- inverse triangles
}
-- Note see the methods below for square, shock, and colorless
end
function Panel.extendedRegularColorsArray()
local result = Panel.regularColorsArray()
result[#result+1] = 7 -- squares
return result
end
function Panel.allPossibleColorsArray()
local result = Panel.extendedRegularColorsArray()
result[#result+1] = 8 -- shock
result[#result+1] = 9 -- colorless
return result
end
-- Sets all variables to the default settings
function Panel.clear(self)
-- color 0 is an empty panel.
-- colors 1-7 are normal colors, 8 is [!], 9 is garbage.
self.color = 0
-- A panel's timer indicates for how many more frames it will:
-- . be swapping
-- . sit in the MATCHED state before being set POPPING
-- . sit in the POPPING state before actually being POPPED
-- . sit and be POPPED before disappearing for good
-- . hover before FALLING
-- depending on which one of these states the panel is in.
self.timer = 0
-- is_swapping is set if the panel is swapping.
-- The panel's timer then counts down from 3 to 0,
-- causing the swap to end 3 frames later.
-- The timer is also used to offset the panel's
-- position on the screen.
self.initial_time = nil
self.pop_time = nil
self.pop_index = nil
self.x_offset = nil
self.y_offset = nil
self.width = nil
self.height = nil
self.garbage = nil
self.metal = nil
self.shake_time = nil
self.match_anyway = nil
-- Also flags
self:clear_flags()
end
-- states:
-- swapping, matched, popping, popped, hovering,
-- falling, dimmed, landing, normal
-- flags:
-- from_left
-- dont_swap
-- chaining
do
local exclude_hover_set = {
matched = true,
popping = true,
popped = true,
hovering = true,
falling = true
}
function Panel.exclude_hover(self)
return exclude_hover_set[self.state] or self.garbage
end
local exclude_match_set = {
swapping = true,
matched = true,
popping = true,
popped = true,
dimmed = true,
falling = true
}
function Panel.exclude_match(self)
return exclude_match_set[self.state] or self.color == 0 or self.color == 9 or (self.state == "hovering" and not self.match_anyway)
end
local exclude_swap_set = {
matched = true,
popping = true,
popped = true,
hovering = true,
dimmed = true
}
function Panel.exclude_swap(self)
return exclude_swap_set[self.state] or self.dont_swap or self.garbage
end
function Panel.support_garbage(self)
return self.color ~= 0 or self.hovering
end
-- "Block garbage fall" means
-- "falling-ness should not propogate up through this panel"
-- We need this because garbage doesn't hover, it just falls
-- opportunistically.
local block_garbage_fall_set = {
matched = true,
popping = true,
popped = true,
hovering = true,
swapping = true
}
function Panel.block_garbage_fall(self)
return block_garbage_fall_set[self.state] or self.color == 0
end
function Panel.dangerous(self)
return self.color ~= 0 and not (self.state == "falling" and self.garbage)
end
end
function Panel.has_flags(self)
return (self.state ~= "normal") or self.is_swapping_from_left or self.dont_swap or self.chaining
end
function Panel.clear_flags(self)
self.combo_index = nil
self.combo_size = nil
self.chain_index = nil
self.is_swapping_from_left = nil
self.dont_swap = nil
self.chaining = nil
-- Animation timer for "bounce" after falling from garbage.
self.fell_from_garbage = nil
self.state = "normal"
end
function Stack.set_puzzle_state(self, puzzle)
-- Copy the puzzle into our state
local boardSizeInPanels = self.width * self.height
while string.len(puzzle.stack) < boardSizeInPanels do
puzzle.stack = "0" .. puzzle.stack
end
local puzzleString = puzzle.stack
if puzzle.randomizeColors then
puzzleString = Puzzle.randomizeColorString(puzzleString)
end
self.panels = self:puzzleStringToPanels(puzzleString)
self.do_countdown = puzzle.do_countdown or false
self.puzzleType = puzzle.puzzleType or "moves"
if puzzle.moves ~= 0 then
self.puzzle_moves = puzzle.moves
end
-- transform any cleared garbage into colorless garbage panels
self.gpanel_buffer = "9999999999999999999999999999999999999999999999999999999999999999999999999"
end
function Stack.puzzleStringToPanels(self, puzzleString)
local panels = {}
local garbageStartRow = nil
local garbageStartColumn = nil
local isMetal = false
local connectedGarbagePanels = nil
-- chunk the aprilstack into rows
-- it is necessary to go bottom up because garbage block panels contain the offset relative to their bottom left corner
for row = 1, 12 do
local rowString = string.sub(puzzleString, #puzzleString - 5, #puzzleString)
puzzleString = string.sub(puzzleString, 1, #puzzleString - 6)
-- copy the panels into the row
panels[row] = {}
for column = 6, 1, -1 do
local color = string.sub(rowString, column, column)
if not garbageStartRow and tonumber(color) then
local panel = Panel()
panel.color = tonumber(color)
panels[row][column] = panel
else
-- start of a garbage block
if color == "]" or color == "}" then
garbageStartRow = row
garbageStartColumn = column
connectedGarbagePanels = {}
if color == "}" then
isMetal = true
end
end
local panel = Panel()
panel.garbage = true
panel.color = 9
panel.y_offset = row - garbageStartRow
-- iterating the row right to left to make sure we catch the start of each garbage block
-- but the offset is expected left to right, therefore we can't know the x_offset before reaching the end of the garbage
-- instead save the column index in that field to calculate it later
panel.x_offset = column
panel.metal = isMetal
panels[row][column] = panel
table.insert(connectedGarbagePanels, panel)
-- garbage ends here
if color == "[" or color == "{" then
-- calculate dimensions of the garbage and add it to the relevant width/height properties
local height = connectedGarbagePanels[#connectedGarbagePanels].y_offset + 1
-- this is disregarding the possible existence of irregularly shaped garbage
local width = garbageStartColumn - column + 1
for i = 1, #connectedGarbagePanels do
connectedGarbagePanels[i].x_offset = connectedGarbagePanels[i].x_offset - column
connectedGarbagePanels[i].height = height
connectedGarbagePanels[i].width = width
-- panels are already in the main table and they should already be updated by reference
end
garbageStartRow = nil
garbageStartColumn = nil
connectedGarbagePanels = nil
isMetal = false
end
end
end
end
-- add row 0 because it crashes if there is no row 0 for whatever reason
panels[0] = {}
for column = 6, 1, -1 do
local panel = Panel()
panel.color = 0
panels[0][column] = panel
end
return panels
end
function Stack.puzzle_done(self)
if not self.do_countdown then
-- For now don't require active panels to be 0, we will still animate in game over,
-- and we need to win immediately to avoid the failure below in the chain case.
--if P1.n_active_panels == 0 then
--if self.puzzleType == "chain" or P1.prev_active_panels == 0 then
local panels = self.panels
for row = 1, self.height do
for col = 1, self.width do
local color = panels[row][col].color
if color ~= 0 and color ~= 9 then
return false
end
end
end
return true
--end
--end
end
return false
end
function Stack.puzzle_failed(self)
if not self.do_countdown then
if self.puzzleType == "moves" then
if self.n_active_panels == 0 and self.prev_active_panels == 0 then
return self.puzzle_moves == 0
end
elseif self.puzzleType and self.puzzleType == "chain" then
if self.n_active_panels == 0 and self.prev_active_panels == 0 and #self.analytic.data.reached_chains == 0 and self.analytic.data.destroyed_panels > 0 then
-- We finished matching but never made a chain -> fail
return true
end
if #self.analytic.data.reached_chains > 0 and self.n_chain_panels == 0 then
-- We achieved a chain, finished chaining, but haven't won yet -> fail
return true
end
end
end
return false
end
function Stack.has_falling_garbage(self)
for i = 1, self.height + 3 do --we shouldn't have to check quite 3 rows above height, but just to make sure...
local prow = self.panels[i]
for j = 1, self.width do
if prow and prow[j].garbage and prow[j].state == "falling" then
return true
end
end
end
return false
end
-- Setup the stack at a new starting state
function Stack.starting_state(self, n)
if self.do_first_row then
self.do_first_row = nil
for i = 1, (n or 8) do
self:new_row()
self.cur_row = self.cur_row - 1
end
end
end
function Stack.prep_first_row(self)
if self.do_first_row then
self.do_first_row = nil
self:new_row()
self.cur_row = self.cur_row - 1
end
end
-- Takes the control input from input_state and sets up the engine to start using it.
function Stack.controls(self)
local new_dir = nil
local sdata = self.input_state
local raise, swap, up, down, left, right = unpack(base64decode[sdata])
if (raise) and (not self.prevent_manual_raise) then
self.manual_raise = true
self.manual_raise_yet = false
end
self.swap_1 = swap
self.swap_2 = swap
if up then
new_dir = "up"
elseif down then
new_dir = "down"
elseif left then
new_dir = "left"
elseif right then
new_dir = "right"
end
if new_dir == self.cur_dir then
if self.cur_timer ~= self.cur_wait_time then
self.cur_timer = self.cur_timer + 1
end
else
self.cur_dir = new_dir
self.cur_timer = 0
end
end
function Stack.shouldRun(self, runsSoFar)
-- We want to run after game over to show game over effects.
if self:game_ended() then
return runsSoFar == 0
end
-- Decide how many frames of input we should run.
local buffer_len = string.len(self.input_buffer)
-- If we are local we always want to catch up and run the new input which is already appended
if self.is_local then
return buffer_len > 0
end
if self:behindRollback() then
return true
end
-- In debug mode allow forcing a certain number of frames behind
if config.debug_mode and config.debug_vsFramesBehind and config.debug_vsFramesBehind ~= 0 then
if (config.debug_vsFramesBehind > 0) == (self.which == 2) then
-- Don't fall behind if the game is over for the other player
if self.garbage_target and self.garbage_target:game_ended() == false then
-- If we are at the end of the replay we want to catch up
if network_connected() or string.len(self.garbage_target.input_buffer) > 0 then
local framesBehind = math.abs(config.debug_vsFramesBehind)
if self.CLOCK >= self.garbage_target.CLOCK - framesBehind then
return false
end
end
end
end
end
-- If we are not local, we want to run faster to catch up.
if buffer_len >= 15 - runsSoFar then
-- way behind, run at max speed.
return runsSoFar < self.max_runs_per_frame
elseif buffer_len >= 10 - runsSoFar then
-- When we're closer, run fewer times per frame, so things are less choppy.
-- This might have a side effect of taking a little longer to catch up
-- since we don't always run at top speed.
local maxRuns = math.min(2, self.max_runs_per_frame)
return runsSoFar < maxRuns
elseif buffer_len >= 1 then
return runsSoFar == 0
end
return false
end
-- Runs one step of the stack.
function Stack.run(self)
if GAME.gameIsPaused then
return
end
if self.is_local == false then
if self.play_to_end then
GAME.preventSounds = true
if string.len(self.input_buffer) < 4 then
self.play_to_end = nil
GAME.preventSounds = false
end
end
end
self:setupInput()
self:simulate()
end
-- Grabs input from the buffer of inputs or from the controller and sends out to the network if needed.
function Stack.setupInput(self)
self.input_state = nil
if self:game_ended() == false then
if self.input_buffer and string.len(self.input_buffer) > 0 then
self.input_state = string.sub(self.input_buffer, 1, 1)
self.input_buffer = string.sub(self.input_buffer, 2)
end
else
self.input_state = self:idleInput()
end
self:controls()
end
function Stack.receiveConfirmedInput(self, input)
self.confirmedInput = self.confirmedInput .. input
self.input_buffer = self.input_buffer .. input
--logger.debug("Player " .. self.which .. " got new input. Total length: " .. string.len(self.confirmedInput))
end
-- Enqueue a card animation
function Stack.enqueue_card(self, chain, x, y, n)
if self.canvas == nil then
return
end
card_burstAtlas = nil
card_burstParticle = nil
if config.popfx == true then
card_burstAtlas = characters[self.character].images["burst"]
card_burstFrameDimension = card_burstAtlas:getWidth() / 9
card_burstParticle = love.graphics.newQuad(card_burstFrameDimension, 0, card_burstFrameDimension, card_burstFrameDimension, card_burstAtlas:getDimensions())
end
self.card_q:push({frame = 1, chain = chain, x = x, y = y, n = n, burstAtlas = card_burstAtlas, burstParticle = card_burstParticle})
end
-- Enqueue a pop animation
function Stack.enqueue_popfx(self, x, y, popsize)
if self.canvas == nil then
return
end
if characters[self.character].images["burst"] then
burstAtlas = characters[self.character].images["burst"]
burstFrameDimension = burstAtlas:getWidth() / 9
burstParticle = love.graphics.newQuad(burstFrameDimension, 0, burstFrameDimension, burstFrameDimension, burstAtlas:getDimensions())
bigParticle = love.graphics.newQuad(0, 0, burstFrameDimension, burstFrameDimension, burstAtlas:getDimensions())
end
if characters[self.character].images["fade"] then
fadeAtlas = characters[self.character].images["fade"]
fadeFrameDimension = fadeAtlas:getWidth() / 9
fadeParticle = love.graphics.newQuad(fadeFrameDimension, 0, fadeFrameDimension, fadeFrameDimension, fadeAtlas:getDimensions())
end
poptype = "small"
self.pop_q:push(
{
frame = 1,
burstAtlas = burstAtlas,
burstFrameDimension = burstFrameDimension,
burstParticle = burstParticle,
fadeAtlas = fadeAtlas,
fadeFrameDimension = fadeFrameDimension,
fadeParticle = fadeParticle,
bigParticle = bigParticle,
bigTimer = 0,
popsize = popsize,
x = x,
y = y
}
)
end
local d_col = {up = 0, down = 0, left = -1, right = 1}
local d_row = {up = 1, down = -1, left = 0, right = 0}
-- One run of the engine routine.
function Stack.simulate(self)
-- Don't run the main logic if the player has simulated past one of the game overs or the time attack time
if self:game_ended() == false then
self:prep_first_row()
local panels = self.panels
local width = self.width
local height = self.height
local prow = nil
local panel = nil
local swapped_this_frame = nil
if self.do_countdown then
self.game_stopwatch_running = false
self.rise_lock = true
if not self.countdown_cursor_state then
self.countdown_CLOCK = self.CLOCK
self.starting_cur_row = self.cur_row
self.starting_cur_col = self.cur_col
self.cur_row = self.height
self.cur_col = self.width - 1
self.countdown_cursor_state = "ready_falling"
self.countdown_cur_speed = 4 --one move every this many frames
self.cursor_lock = true
end
if self.countdown_CLOCK == 8 then
self.countdown_cursor_state = "moving_down"
self.countdown_timer = 180 --3 seconds at 60 fps
elseif self.countdown_cursor_state == "moving_down" then
--move down
if self.cur_row == self.starting_cur_row then
self.countdown_cursor_state = "moving_left"
elseif self.CLOCK % self.countdown_cur_speed == 0 then
self.cur_row = self.cur_row - 1
end
elseif self.countdown_cursor_state == "moving_left" then
--move left
if self.cur_col == self.starting_cur_col then
self.countdown_cursor_state = "ready"
self.cursor_lock = nil
elseif self.CLOCK % self.countdown_cur_speed == 0 then
self.cur_col = self.cur_col - 1
end
end
if self.countdown_timer then
if self.countdown_timer == 0 then
--we are done counting down
self.do_countdown = nil
self.countdown_timer = nil
self.starting_cur_row = nil
self.starting_cur_col = nil
self.countdown_CLOCK = nil
self.game_stopwatch_running = true
if self.which == 1 and self:shouldChangeSoundEffects() then
SFX_Go_Play = 1
end
elseif self.countdown_timer and self.countdown_timer % 60 == 0 and self.which == 1 then
--play beep for timer dropping to next second in 3-2-1 countdown
if self.which == 1 and self:shouldChangeSoundEffects() then
SFX_Countdown_Play = 1
end
end
if self.countdown_timer then
self.countdown_timer = self.countdown_timer - 1
end
end
if self.countdown_CLOCK then
self.countdown_CLOCK = self.countdown_CLOCK + 1
end
else
self.game_stopwatch_running = true
end
if self.pre_stop_time ~= 0 then
self.pre_stop_time = self.pre_stop_time - 1
elseif self.stop_time ~= 0 then
self.stop_time = self.stop_time - 1
end
self.panels_in_top_row = false
local top_row = self.height
--self.displacement%16==0 and self.height or self.height-1
prow = panels[top_row]
for idx = 1, width do
if prow[idx]:dangerous() then
self.panels_in_top_row = true
end
end
-- calculate which columns should bounce
self.danger = false
prow = panels[self.height - 1]
for idx = 1, width do
if prow[idx]:dangerous() then
self.danger = true
self.danger_col[idx] = true
else
self.danger_col[idx] = false
end
end
if self.danger then
if self.panels_in_top_row and self.speed ~= 0 and self.match.mode ~= "puzzle" then
-- Player has topped out, panels hold the "flattened" frame
self.danger_timer = 15
elseif self.stop_time == 0 then
self.danger_timer = self.danger_timer - 1
end
if self.danger_timer < 0 then
self.danger_timer = 17
end
end
-- determine whether to play danger music
-- Changed this to play danger when something in top 3 rows
-- and to play casual when nothing in top 3 or 4 rows
if not self.danger_music then
-- currently playing casual
for _, prow in pairs({panels[self.height], panels[self.height - 1], panels[self.height - 2]}) do
for idx = 1, width do
if prow[idx].color ~= 0 and prow[idx].state ~= "falling" or prow[idx]:dangerous() then
self.danger_music = true
break
end
end
end
if self.shake_time > 0 then
self.danger_music = false
end
else
--currently playing danger
local toggle_back = true
-- Normally, change back if nothing is in the top 3 rows
local changeback_rows = {panels[self.height], panels[self.height - 1], panels[self.height - 2]}
-- But optionally, wait until nothing is in the fourth row
if (config.danger_music_changeback_delay) then
table.insert(changeback_rows, panels[self.height - 3])
end
for _, prow in pairs(changeback_rows) do
for idx = 1, width do
if prow[idx].color ~= 0 then
toggle_back = false
break
end
end
end
self.danger_music = not toggle_back
end
if self.displacement == 0 and self.has_risen then
self.top_cur_row = self.height
self:new_row()
end
self.prev_rise_lock = self.rise_lock
self.rise_lock = self.n_active_panels ~= 0 or self.prev_active_panels ~= 0 or self.shake_time ~= 0 or self.do_countdown or self.do_swap
if self.prev_rise_lock and not self.rise_lock then
self.prevent_manual_raise = false
end
-- Increase the speed if applicable
if self.speed_times then
local time = self.speed_times[self.speed_times.idx]
if self.CLOCK == time then
self.speed = min(self.speed + 1, 99)
self.FRAMECOUNT_RISE = speed_to_rise_time[self.speed]
if self.speed_times.idx ~= #self.speed_times then
self.speed_times.idx = self.speed_times.idx + 1
else
self.speed_times[self.speed_times.idx] = time + self.speed_times.delta
end
end
elseif self.panels_to_speedup <= 0 then
self.speed = min(self.speed + 1, 99)
self.panels_to_speedup = self.panels_to_speedup + panels_to_next_speed[self.speed]
self.FRAMECOUNT_RISE = speed_to_rise_time[self.speed]
end
-- Phase 0 //////////////////////////////////////////////////////////////
-- Stack automatic rising
if self.speed ~= 0 and not self.manual_raise and self.stop_time == 0 and not self.rise_lock and self.match.mode ~= "puzzle" then
if self.panels_in_top_row then
self.health = self.health - 1
if self.health < 1 and self.shake_time < 1 then
self:set_game_over()
end
else
self.rise_timer = self.rise_timer - 1
if self.rise_timer <= 0 then -- try to rise
self.displacement = self.displacement - 1
if self.displacement == 0 then
self.prevent_manual_raise = false
self.top_cur_row = self.height
self:new_row()
end
self.rise_timer = self.rise_timer + self.FRAMECOUNT_RISE
end
end
end
if not self.panels_in_top_row and not self:has_falling_garbage() then
self.health = self.max_health
end
if self.displacement % 16 ~= 0 then
self.top_cur_row = self.height - 1
end
-- Begin the swap we input last frame.
if self.do_swap then
self:swap()
swapped_this_frame = true
self.do_swap = nil
end
-- Look for matches.
self:check_matches()
-- Clean up the value we're using to match newly hovering panels
-- This is pretty dirty :(
for row = 1, #panels do
for col = 1, width do
panels[row][col].match_anyway = nil
end
end
-- Phase 2. /////////////////////////////////////////////////////////////
-- Timer-expiring actions + falling
local propogate_fall = {false, false, false, false, false, false}
local skip_col = 0
local fallen_garbage = 0
local shake_time = 0
popsize = "small"
for row = 1, #panels do
for col = 1, width do
local cntinue = false
if skip_col > 0 then
skip_col = skip_col - 1
cntinue = true
end
panel = panels[row][col]
if cntinue then
elseif panel.garbage then
if panel.state == "matched" then
-- try to fall
panel.timer = panel.timer - 1
if panel.timer == panel.pop_time then
if config.popfx == true then
self:enqueue_popfx(col, row, popsize)
end
if self:shouldChangeSoundEffects() then
SFX_Garbage_Pop_Play = panel.pop_index
end
end
if panel.timer == 0 then
if panel.y_offset == -1 then
local color, chaining = panel.color, panel.chaining
panel:clear()
panel.color, panel.chaining = color, chaining
self:set_hoverers(row, col, self.FRAMECOUNT_GPHOVER, true, true)
panel.fell_from_garbage = 12
else
panel.state = "normal"
end
end
elseif (panel.state == "normal" or panel.state == "falling") then
if panel.x_offset == 0 then
local prow = panels[row - 1]
local supported = false
if panel.y_offset == 0 then
for i = col, col + panel.width - 1 do
supported = supported or prow[i]:support_garbage()
end
else
supported = not propogate_fall[col]
end
if supported then
for x = col, col - 1 + panel.width do
panels[row][x].state = "normal"
propogate_fall[x] = false
end
else
skip_col = panel.width - 1
for x = col, col - 1 + panel.width do
panels[row - 1][x]:clear()
propogate_fall[x] = true
panels[row][x].state = "falling"
panels[row - 1][x], panels[row][x] = panels[row][x], panels[row - 1][x]
end
end
end
if panel.shake_time and panel.state == "normal" then
if row <= self.height then
if self:shouldChangeSoundEffects() then
if panel.height > 3 then
self.sfx_garbage_thud = 3
else
self.sfx_garbage_thud = panel.height
end
end
shake_time = max(shake_time, panel.shake_time, self.peak_shake_time or 0)
--a smaller garbage block landing should renew the largest of the previous blocks' shake times since our shake time was last zero.
self.peak_shake_time = max(shake_time, self.peak_shake_time or 0)
panel.shake_time = nil
end
end
end
cntinue = true
end
if propogate_fall[col] and not cntinue then
if panel:block_garbage_fall() then
propogate_fall[col] = false
else
panel.state = "falling"
panel.timer = 0
end
end
if cntinue then
elseif panel.state == "falling" then
-- if it's on the bottom row, it should surely land
if row == 1 then
-- if there's a panel below, this panel's gonna land
-- unless the panel below is falling.
panel.state = "landing"
panel.timer = 12
if self:shouldChangeSoundEffects() then
self.sfx_land = true
end
elseif panels[row - 1][col].color ~= 0 and panels[row - 1][col].state ~= "falling" then
-- if it lands on a hovering panel, it inherits
-- that panel's hover time.
if panels[row - 1][col].state == "hovering" then
panel.state = "normal"
self:set_hoverers(row, col, panels[row - 1][col].timer, false, false)
else
panel.state = "landing"
panel.timer = 12
end
if self:shouldChangeSoundEffects() then
self.sfx_land = true
end
else
panels[row - 1][col], panels[row][col] = panels[row][col], panels[row - 1][col]
panels[row][col]:clear()
end
elseif panel:has_flags() and panel.timer ~= 0 then
panel.timer = panel.timer - 1
if panel.timer == 0 then
if panel.state == "swapping" then
-- a swap has completed here.
panel.state = "normal"
panel.dont_swap = nil
local from_left = panel.is_swapping_from_left
panel.is_swapping_from_left = nil
-- Now there are a few cases where some hovering must
-- be done.
if panel.color ~= 0 then
if row ~= 1 then
if panels[row - 1][col].color == 0 then
self:set_hoverers(row, col, self.FRAMECOUNT_HOVER, false, true, false)
-- if there is no panel beneath this panel
-- it will begin to hover.
-- CRAZY BUG EMULATION:
-- the space it was swapping from hovers too
if from_left then
if panels[row][col - 1].state == "falling" then
self:set_hoverers(row, col - 1, self.FRAMECOUNT_HOVER, false, true)
end
else
if panels[row][col + 1].state == "falling" then
self:set_hoverers(row, col + 1, self.FRAMECOUNT_HOVER + 1, false, false)
end
end
elseif panels[row - 1][col].state == "hovering" then
-- swap may have landed on a hover
self:set_hoverers(row, col, self.FRAMECOUNT_HOVER, false, true, panels[row - 1][col].match_anyway, "inherited")
end
end
else
-- an empty space finished swapping...
-- panels above it hover
self:set_hoverers(row + 1, col, self.FRAMECOUNT_HOVER + 1, false, false, false, "empty")
end
elseif panel.state == "hovering" then
if panels[row - 1][col].state == "hovering" then
-- This panel is no longer hovering.
-- it will now fall without sitting around
-- for any longer!
panel.timer = panels[row - 1][col].timer
elseif panels[row - 1][col].color ~= 0 then
panel.state = "landing"
panel.timer = 12
else
panel.state = "falling"
panels[row][col], panels[row - 1][col] = panels[row - 1][col], panels[row][col]
panel.timer = 0
-- Not sure if needed:
panels[row][col]:clear_flags()
end
elseif panel.state == "landing" then
panel.state = "normal"
elseif panel.state == "matched" then
-- This panel's match just finished the whole
-- flashing and looking distressed thing.
-- It is given a pop time based on its place
-- in the match.
panel.state = "popping"
panel.timer = panel.combo_index * self.FRAMECOUNT_POP
elseif panel.state == "popping" then
--logger.debug("POP")
if (panel.combo_size > 6) or self.chain_counter > 1 then
popsize = "normal"
end
if self.chain_counter > 2 then
popsize = "big"
end
if self.chain_counter > 3 then
popsize = "giant"
end
if config.popfx == true then
self:enqueue_popfx(col, row, popsize)
end
self.score = self.score + 10
-- self.score_render=1;
-- TODO: What is self.score_render?
-- this panel just popped
-- Now it's invisible, but sits and waits
-- for the last panel in the combo to pop
-- before actually being removed.
-- If it is the last panel to pop,
-- it should be removed immediately!
if panel.combo_size == panel.combo_index then
self.panels_cleared = self.panels_cleared + 1
if self.match.mode == "vs" and self.panels_cleared % level_to_metal_panel_frequency[self.level] == 0 then
self.metal_panels_queued = min(self.metal_panels_queued + 1, level_to_metal_panel_cap[self.level])
end
if self:shouldChangeSoundEffects() then
SFX_Pop_Play = 1
end
self.poppedPanelIndex = panel.combo_index
panel.color = 0
if self.panels_to_speedup then
self.panels_to_speedup = self.panels_to_speedup - 1
end
if panel.chaining then
self.n_chain_panels = self.n_chain_panels - 1
end
panel:clear_flags()
self:set_hoverers(row + 1, col, self.FRAMECOUNT_HOVER + 1, true, false, true, "combo")
else
panel.state = "popped"
panel.timer = (panel.combo_size - panel.combo_index) * self.FRAMECOUNT_POP
self.panels_cleared = self.panels_cleared + 1
if self.match.mode == "vs" and self.panels_cleared % level_to_metal_panel_frequency[self.level] == 0 then
self.metal_panels_queued = min(self.metal_panels_queued + 1, level_to_metal_panel_cap[self.level])
end
if self:shouldChangeSoundEffects() then
SFX_Pop_Play = 1
end
self.poppedPanelIndex = panel.combo_index
end
elseif panel.state == "popped" then
-- It's time for this panel
-- to be gone forever :'(
if self.panels_to_speedup then
self.panels_to_speedup = self.panels_to_speedup - 1
end
if panel.chaining then
self.n_chain_panels = self.n_chain_panels - 1
end
panel.color = 0
panel:clear_flags()
-- Any panels sitting on top of it
-- hover and are flagged as CHAINING
self:set_hoverers(row + 1, col, self.FRAMECOUNT_HOVER + 1, true, false, true, "popped")
elseif panel.state == "dead" then
-- Nothing to do here, the player lost.
else
-- what the heck.
-- if a timer runs out and the routine can't
-- figure out what flag it is, tell brandon.
-- No seriously, email him or something.
error("something terrible happened\n" .. "panel.state was " .. tostring(panel.state) .. " when a timer expired?!\n" .. "panel.is_swapping_from_left = " .. tostring(panel.is_swapping_from_left) .. "\n" .. "panel.dont_swap = " .. tostring(panel.dont_swap) .. "\n" .. "panel.chaining = " .. tostring(panel.chaining))
end
-- the timer-expiring action has completed
end
end
-- Advance the fell-from-garbage bounce timer, or clear it and stop animating if the panel isn't hovering or falling.
if cntinue then
elseif panel.fell_from_garbage then
if panel.state ~= "hovering" and panel.state ~= "falling" then
panel.fell_from_garbage = nil
else
panel.fell_from_garbage = panel.fell_from_garbage - 1
end
end
end
end
local prev_shake_time = self.shake_time
self.shake_time = self.shake_time - 1
self.shake_time = max(self.shake_time, shake_time)
if self.shake_time == 0 then
self.peak_shake_time = 0
end
-- Phase 3. /////////////////////////////////////////////////////////////
-- Actions performed according to player input
-- CURSOR MOVEMENT
local playMoveSounds = true -- set this to false to disable move sounds for debugging
if self.cur_dir and (self.cur_timer == 0 or self.cur_timer == self.cur_wait_time) and not self.cursor_lock then
local prev_row = self.cur_row
local prev_col = self.cur_col
self.cur_row = bound(1, self.cur_row + d_row[self.cur_dir], self.top_cur_row)
self.cur_col = bound(1, self.cur_col + d_col[self.cur_dir], width - 1)
if (playMoveSounds and (self.cur_timer == 0 or self.cur_timer == self.cur_wait_time) and (self.cur_row ~= prev_row or self.cur_col ~= prev_col)) then
if self:shouldChangeSoundEffects() then
SFX_Cur_Move_Play = 1
end
if self.cur_timer ~= self.cur_wait_time then
self.analytic:register_move()
end
end
else
self.cur_row = bound(1, self.cur_row, self.top_cur_row)
end
if self.cur_timer ~= self.cur_wait_time then
self.cur_timer = self.cur_timer + 1
end
-- TAUNTING
if self:shouldChangeSoundEffects() then
if self.taunt_up ~= nil then
for _, t in ipairs(characters[self.character].sounds.taunt_ups) do
t:stop()
end
characters[self.character].sounds.taunt_ups[self.taunt_up]:play()
self:taunt("taunt_up")
self.taunt_up = nil
elseif self.taunt_down ~= nil then
for _, t in ipairs(characters[self.character].sounds.taunt_downs) do
t:stop()
end
characters[self.character].sounds.taunt_downs[self.taunt_down]:play()
self:taunt("taunt_down")
self.taunt_down = nil
end
end
-- SWAPPING
if (self.swap_1 or self.swap_2) and not swapped_this_frame then
local do_swap = self:canSwap(self.cur_row, self.cur_col)
if do_swap then
self.do_swap = true
self.analytic:register_swap()
end
self.swap_1 = false
self.swap_2 = false
end
-- MANUAL STACK RAISING
if self.manual_raise and self.match.mode ~= "puzzle" then
if not self.rise_lock then
if self.panels_in_top_row then
self:set_game_over()
end
self.has_risen = true
self.displacement = self.displacement - 1
if self.displacement == 1 then
self.manual_raise = false
self.rise_timer = 1
if not self.prevent_manual_raise then
self.score = self.score + 1
end
self.prevent_manual_raise = true
end
self.manual_raise_yet = true --ehhhh
self.stop_time = 0
elseif not self.manual_raise_yet then
self.manual_raise = false
end
-- if the stack is rise locked when you press the raise button,
-- the raising is cancelled
end
-- if at the end of the routine there are no chain panels, the chain ends.
if self.chain_counter ~= 0 and self.n_chain_panels == 0 then
self.chains[self.chains.current].finish = self.CLOCK
self.chains[self.chains.current].size = self.chain_counter
self.chains.last_complete = self.current
self.chains.current = nil
if self:shouldChangeSoundEffects() then
SFX_Fanfare_Play = self.chain_counter
end
self.analytic:register_chain(self.chain_counter)
self.chain_counter = 0
if self.garbage_target and self.garbage_target.telegraph then
self.telegraph:chainingEnded(self.CLOCK)
end
end
if (self.score > 99999) then
self.score = 99999
-- lol owned
end
self.prev_active_panels = self.n_active_panels
self.n_active_panels = 0
for row = 1, self.height do
for col = 1, self.width do
local panel = panels[row][col]
if (panel.garbage and panel.state ~= "normal") or (panel.color ~= 0 and panel.state ~= "landing" and (panel:exclude_hover() or panel.state == "swapping") and not panel.garbage) or panel.state == "swapping" then
self.n_active_panels = self.n_active_panels + 1
end
end
end
if self.telegraph then
local to_send = self.telegraph:pop_all_ready_garbage(self.CLOCK)
if to_send and to_send[1] then
-- Right now the training attacks are put on the players telegraph,
-- but they really should be a seperate telegraph since the telegraph on the player's stack is for sending outgoing attacks.
local receiver = self.garbage_target or self
receiver:receiveGarbage(self.CLOCK + GARBAGE_DELAY_LAND_TIME, to_send)
end
end
if self.later_garbage[self.CLOCK] then
self.garbage_q:push(self.later_garbage[self.CLOCK])
self.later_garbage[self.CLOCK] = nil
end
self:remove_extra_rows()
--double-check panels_in_top_row
self.panels_in_top_row = false
-- If any dangerous panels are in the top row, garbage should not fall.
for col_idx = 1, width do
if panels[top_row][col_idx]:dangerous() then
self.panels_in_top_row = true
end
end
-- local garbage_fits_in_populated_top_row
-- if self.garbage_q:len() > 0 then
-- --even if there are some panels in the top row,
-- --check if the next block in the garbage_q would fit anyway
-- --ie. 3-wide garbage might fit if there are three empty spaces where it would spawn
-- garbage_fits_in_populated_top_row = true
-- local next_garbage_block_width, next_garbage_block_height, _metal, from_chain = unpack(self.garbage_q:peek())
-- local cols = self.garbage_cols[next_garbage_block_width]
-- local spawn_col = cols[cols.idx]
-- local spawn_row = #self.panels
-- for idx=spawn_col, spawn_col+next_garbage_block_width-1 do
-- if prow[idx]:dangerous() then
-- garbage_fits_in_populated_top_row = nil
-- end
-- end
-- end
-- If any panels (dangerous or not) are in rows above the top row, garbage should not fall.
for row_idx = top_row + 1, #self.panels do
for col_idx = 1, width do
if panels[row_idx][col_idx].color ~= 0 then
self.panels_in_top_row = true
end
end
end
if self.garbage_q:len() > 0 then
local next_garbage_block_width, next_garbage_block_height, _metal, from_chain = unpack(self.garbage_q:peek())
local drop_it = not self.panels_in_top_row and not self:has_falling_garbage() and ((from_chain and next_garbage_block_height > 1) or (self.n_active_panels == 0 and self.prev_active_panels == 0))
if drop_it and self.garbage_q:len() > 0 then
if self:drop_garbage(unpack(self.garbage_q:peek())) then
self.garbage_q:pop()
end
end
end
-- Update Music
if self:shouldChangeMusic() then
if self.do_countdown then
if SFX_Go_Play == 1 then
themes[config.theme].sounds.go:stop()
themes[config.theme].sounds.go:play()
SFX_Go_Play = 0
elseif SFX_Countdown_Play == 1 then
themes[config.theme].sounds.countdown:stop()
themes[config.theme].sounds.countdown:play()
SFX_Go_Play = 0
end
else
local winningPlayer = self
if GAME.battleRoom then
winningPlayer = GAME.battleRoom:winningPlayer(P1, P2)
end
local musics_to_use = nil
local dynamicMusic = false
local stageHasMusic = current_stage and stages[current_stage].musics and stages[current_stage].musics["normal_music"]
local characterHasMusic = winningPlayer.character and characters[winningPlayer.character].musics and characters[winningPlayer.character].musics["normal_music"]
if ((current_use_music_from == "stage") and stageHasMusic) or not characterHasMusic then
if stages[current_stage].music_style == "dynamic" then
dynamicMusic = true
end
musics_to_use = stages[current_stage].musics
elseif characterHasMusic then
if characters[winningPlayer.character].music_style == "dynamic" then
dynamicMusic = true
end
musics_to_use = characters[winningPlayer.character].musics
else
-- no music loaded
end
local wantsDangerMusic = self.danger_music
if self.garbage_target and self.garbage_target.danger_music then
wantsDangerMusic = true
end
if dynamicMusic then
local fadeLength = 60
if not self.fade_music_clock then
self.fade_music_clock = fadeLength -- start fully faded in
self.match.current_music_is_casual = true
end
local normalMusic = {musics_to_use["normal_music"], musics_to_use["normal_music_start"]}
local dangerMusic = {musics_to_use["danger_music"], musics_to_use["danger_music_start"]}
if #currently_playing_tracks == 0 then
find_and_add_music(musics_to_use, "normal_music")
find_and_add_music(musics_to_use, "danger_music")
end
-- Do we need to switch music?
if self.match.current_music_is_casual ~= wantsDangerMusic then
self.match.current_music_is_casual = not self.match.current_music_is_casual
if self.fade_music_clock >= fadeLength then
self.fade_music_clock = 0 -- Do a full fade
else
-- switched music before we fully faded, so start part way through
self.fade_music_clock = fadeLength - self.fade_music_clock
end
end
if self.fade_music_clock < fadeLength then
self.fade_music_clock = self.fade_music_clock + 1
end
local fadePercentage = self.fade_music_clock / fadeLength
if wantsDangerMusic then
setFadePercentageForGivenTracks(1 - fadePercentage, normalMusic)
setFadePercentageForGivenTracks(fadePercentage, dangerMusic)
else
setFadePercentageForGivenTracks(fadePercentage, normalMusic)
setFadePercentageForGivenTracks(1 - fadePercentage, dangerMusic)
end
else -- classic music
if wantsDangerMusic then --may have to rethink this bit if we do more than 2 players
if (self.match.current_music_is_casual or #currently_playing_tracks == 0) and musics_to_use["danger_music"] then -- disabled when danger_music is unspecified
stop_the_music()
find_and_add_music(musics_to_use, "danger_music")
self.match.current_music_is_casual = false
elseif #currently_playing_tracks == 0 and musics_to_use["normal_music"] then
stop_the_music()
find_and_add_music(musics_to_use, "normal_music")
self.match.current_music_is_casual = true
end
else --we should be playing normal_music or normal_music_start
if (not self.match.current_music_is_casual or #currently_playing_tracks == 0) and musics_to_use["normal_music"] then
stop_the_music()
find_and_add_music(musics_to_use, "normal_music")
self.match.current_music_is_casual = true
end
end
end
end
end
-- Update Sound FX
if self:shouldChangeSoundEffects() then
if SFX_Swap_Play == 1 then
themes[config.theme].sounds.swap:stop()
themes[config.theme].sounds.swap:play()
SFX_Swap_Play = 0
end
if SFX_Cur_Move_Play == 1 then
if not (self.match.mode == "vs" and themes[config.theme].sounds.swap:isPlaying()) and not self.do_countdown then
themes[config.theme].sounds.cur_move:stop()
themes[config.theme].sounds.cur_move:play()
end
SFX_Cur_Move_Play = 0
end
if self.sfx_land then
themes[config.theme].sounds.land:stop()
themes[config.theme].sounds.land:play()
self.sfx_land = false
end
if SFX_Countdown_Play == 1 then
if self.which == 1 then
themes[config.theme].sounds.countdown:stop()
themes[config.theme].sounds.countdown:play()
end
SFX_Countdown_Play = 0
end
if SFX_Go_Play == 1 then
if self.which == 1 then
themes[config.theme].sounds.go:stop()
themes[config.theme].sounds.go:play()
end
SFX_Go_Play = 0
end
if self.combo_chain_play then
themes[config.theme].sounds.land:stop()
themes[config.theme].sounds.pops[self.lastPopLevelPlayed][self.lastPopIndexPlayed]:stop()
characters[self.character]:play_combo_chain_sfx(self.combo_chain_play)
self.combo_chain_play = nil
end
if SFX_garbage_match_play then
for _, v in pairs(characters[self.character].sounds.garbage_matches) do
v:stop()
end
if #characters[self.character].sounds.garbage_matches ~= 0 then
characters[self.character].sounds.garbage_matches[math.random(#characters[self.character].sounds.garbage_matches)]:play()
end
SFX_garbage_match_play = nil
end
if SFX_Fanfare_Play == 0 then
--do nothing
elseif SFX_Fanfare_Play >= 6 then
themes[config.theme].sounds.pops[self.lastPopLevelPlayed][self.lastPopIndexPlayed]:stop()
themes[config.theme].sounds.fanfare3:play()
elseif SFX_Fanfare_Play >= 5 then
themes[config.theme].sounds.pops[self.lastPopLevelPlayed][self.lastPopIndexPlayed]:stop()
themes[config.theme].sounds.fanfare2:play()
elseif SFX_Fanfare_Play >= 4 then
themes[config.theme].sounds.pops[self.lastPopLevelPlayed][self.lastPopIndexPlayed]:stop()
themes[config.theme].sounds.fanfare1:play()
end
SFX_Fanfare_Play = 0
if self.sfx_garbage_thud >= 1 and self.sfx_garbage_thud <= 3 then
local interrupted_thud = nil
for i = 1, 3 do
if themes[config.theme].sounds.garbage_thud[i]:isPlaying() and self.shake_time > prev_shake_time then
themes[config.theme].sounds.garbage_thud[i]:stop()
interrupted_thud = i
end
end
if interrupted_thud and interrupted_thud > self.sfx_garbage_thud then
themes[config.theme].sounds.garbage_thud[interrupted_thud]:play()
else
themes[config.theme].sounds.garbage_thud[self.sfx_garbage_thud]:play()
end
if #characters[self.character].sounds.garbage_lands ~= 0 and interrupted_thud == nil then
for _, v in pairs(characters[self.character].sounds.garbage_lands) do
v:stop()
end
characters[self.character].sounds.garbage_lands[math.random(#characters[self.character].sounds.garbage_lands)]:play()
end
self.sfx_garbage_thud = 0
end
if SFX_Pop_Play or SFX_Garbage_Pop_Play then
local popLevel = min(max(self.chain_counter, 1), 4)
local popIndex = 1
if SFX_Garbage_Pop_Play then
popIndex = SFX_Garbage_Pop_Play
else
popIndex = min(self.poppedPanelIndex, 10)
end
--stop the previous pop sound
themes[config.theme].sounds.pops[self.lastPopLevelPlayed][self.lastPopIndexPlayed]:stop()
--play the appropriate pop sound
themes[config.theme].sounds.pops[popLevel][popIndex]:play()
self.lastPopLevelPlayed = popLevel
self.lastPopIndexPlayed = popIndex
SFX_Pop_Play = nil
SFX_Garbage_Pop_Play = nil
end
if self.game_over or (self.garbage_target and self.garbage_target.game_over) then
if self:shouldChangeSoundEffects() then
SFX_GameOver_Play = 1
end
end
end
self.CLOCK = self.CLOCK + 1
if self.garbage_target and self.CLOCK > self.garbage_target.CLOCK + MAX_LAG then
self.garbage_target.tooFarBehindError = true
end
local gameEndedClockTime = self.match:gameEndedClockTime()
if self.game_stopwatch_running and (gameEndedClockTime == 0 or self.CLOCK <= gameEndedClockTime) then
self.game_stopwatch = (self.game_stopwatch or -1) + 1
end
end
self:update_popfxs()
self:update_cards()
end
function Stack:receiveGarbage(frameToReceive, garbageList)
-- If we are past the frame the attack would be processed we need to rollback
if self.CLOCK > frameToReceive then
self:rollbackToFrame(frameToReceive)
end
local garbage = self.later_garbage[frameToReceive] or {}
for i = 1, #garbageList do
garbage[#garbage + 1] = garbageList[i]
end
self.later_garbage[frameToReceive] = garbage
end
function Stack:updateFramesBehind()
if self.garbage_target and self.garbage_target ~= self then
if not self.framesBehindArray[self.CLOCK] then
local framesBehind = math.max(0, self.garbage_target.CLOCK - self.CLOCK)
self.framesBehindArray[self.CLOCK] = framesBehind
self.totalFramesBehind = self.totalFramesBehind + framesBehind
end
end
end
function Stack.behindRollback(self)
if self.lastRollbackFrame > self.CLOCK then
return true
end
return false
end
function Stack.shouldChangeMusic(self)
local result = not GAME.gameIsPaused and not GAME.preventSounds
if result then
if self:game_ended() or self.canvas == nil then
result = false
end
-- If we are still catching up from rollback don't play sounds again
if self:behindRollback() then
result = false
end
if self.play_to_end then
result = false
end
if self.garbage_target and self.garbage_target.play_to_end then
result = false
end
end
return result
end
function Stack.shouldChangeSoundEffects(self)
local result = self:shouldChangeMusic() and not SFX_mute
return result
end
function Stack:averageFramesBehind()
local average = tonumber(string.format("%1.1f", round(self.totalFramesBehind / math.max(self.CLOCK, 1)), 1))
return average
end
-- Returns true if the stack is simulated past the end of the match.
function Stack.game_ended(self)
local gameEndedClockTime = self.match:gameEndedClockTime()
if self.match.mode == "vs" then
-- Note we use "greater" and not "greater than or equal" because our stack may be currently processing this clock frame.
-- At the end of the clock frame it will be incremented and we know we have process the game over clock frame.
if gameEndedClockTime > 0 and self.CLOCK > gameEndedClockTime then
return true
end
elseif self.match.mode == "time" then
if gameEndedClockTime > 0 and self.CLOCK > gameEndedClockTime then
return true
elseif self.game_stopwatch then
if self.game_stopwatch > time_attack_time * 60 then
return true
end
end
elseif self.match.mode == "endless" then
if gameEndedClockTime > 0 and self.CLOCK > gameEndedClockTime then
return true
end
elseif self.match.mode == "puzzle" then
if self:puzzle_done() then
return true
elseif self:puzzle_failed() then
return true
end
end
return false
end
-- Returns 1 if this player won, 0 for draw, and -1 for loss, nil if no result yet
function Stack.gameResult(self)
if self:game_ended() == false then
return nil
end
local gameEndedClockTime = self.match:gameEndedClockTime()
if self.match.mode == "vs" then
local otherPlayer = self.garbage_target
if otherPlayer == self or otherPlayer == nil then
return -1
-- We can't call it until someone has lost and everyone has played up to that point in time.
elseif otherPlayer:game_ended() then
if self.game_over_clock == gameEndedClockTime and otherPlayer.game_over_clock == gameEndedClockTime then
return 0
elseif self.game_over_clock == gameEndedClockTime then
return -1
elseif otherPlayer.game_over_clock == gameEndedClockTime then
return 1
end
end
elseif self.match.mode == "time" then
if gameEndedClockTime > 0 and self.CLOCK > gameEndedClockTime then
return -1
elseif self.game_stopwatch then
if self.game_stopwatch > time_attack_time * 60 then
return 1
end
end
elseif self.match.mode == "endless" then
if gameEndedClockTime > 0 and self.CLOCK > gameEndedClockTime then
return -1
end
elseif self.match.mode == "puzzle" then
if self:puzzle_done() then
return 1
elseif self:puzzle_failed() then
return -1
end
end
return nil
end
-- Sets the current stack as "lost"
-- Also begins drawing game over effects
function Stack.set_game_over(self)
if self.game_over_clock ~= 0 then
error("should not set gameover when it is already set")
end
self.game_over = true
self.game_over_clock = self.CLOCK
if self.canvas then
local popsize = "small"
local panels = self.panels
local width = self.width
for row = 1, #panels do
for col = 1, width do
local panel = panels[row][col]
panel.state = "dead"
if row == #panels then
self:enqueue_popfx(col, row, popsize)
end
end
end
end
end
-- Randomly returns a win sound if the character has one
function Stack.pick_win_sfx(self)
if #characters[self.character].sounds.wins ~= 0 then
return characters[self.character].sounds.wins[math.random(#characters[self.character].sounds.wins)]
else
return themes[config.theme].sounds.fanfare1 -- TODO add a default win sound
end
end
function Stack.canSwap(self, row, column)
local panels = self.panels
local width = self.width
local height = self.height
-- in order for a swap to occur, one of the two panels in
-- the cursor must not be a non-panel.
local do_swap =
(panels[row][column].color ~= 0 or panels[row][column + 1].color ~= 0) and -- also, both spaces must be swappable.
(not panels[row][column]:exclude_swap()) and
(not panels[row][column + 1]:exclude_swap()) and -- also, neither space above us can be hovering.
(row == #panels or (panels[row + 1][column].state ~= "hovering" and panels[row + 1][column + 1].state ~= "hovering")) and --also, we can't swap if the game countdown isn't finished
not self.do_countdown and --also, don't swap on the first frame
not (self.CLOCK and self.CLOCK <= 1)
-- If you have two pieces stacked vertically, you can't move
-- both of them to the right or left by swapping with empty space.
-- TODO: This might be wrong if something lands on a swapping panel?
if panels[row][column].color == 0 or panels[row][column + 1].color == 0 then
do_swap = do_swap and not (row ~= self.height and (panels[row + 1][column].state == "swapping" and panels[row + 1][column + 1].state == "swapping") and (panels[row + 1][column].color == 0 or panels[row + 1][column + 1].color == 0) and (panels[row + 1][column].color ~= 0 or panels[row + 1][column + 1].color ~= 0))
do_swap = do_swap and not (row ~= 1 and (panels[row - 1][column].state == "swapping" and panels[row - 1][column + 1].state == "swapping") and (panels[row - 1][column].color == 0 or panels[row - 1][column + 1].color == 0) and (panels[row - 1][column].color ~= 0 or panels[row - 1][column + 1].color ~= 0))
end
do_swap = do_swap and (self.puzzle_moves == nil or self.puzzle_moves > 0)
return do_swap
end
-- Swaps panels at the current cursor location
function Stack.swap(self)
local panels = self.panels
local row = self.cur_row
local col = self.cur_col
if self.puzzle_moves then
self.puzzle_moves = self.puzzle_moves - 1
end
panels[row][col], panels[row][col + 1] = panels[row][col + 1], panels[row][col]
local tmp_chaining = panels[row][col].chaining
panels[row][col]:clear_flags()
panels[row][col].state = "swapping"
panels[row][col].chaining = tmp_chaining
tmp_chaining = panels[row][col + 1].chaining
panels[row][col + 1]:clear_flags()
panels[row][col + 1].state = "swapping"
panels[row][col + 1].is_swapping_from_left = true
panels[row][col + 1].chaining = tmp_chaining
panels[row][col].timer = 4
panels[row][col + 1].timer = 4
if self:shouldChangeSoundEffects() then
SFX_Swap_Play = 1
end
-- If you're swapping a panel into a position
-- above an empty space or above a falling piece
-- then you can't take it back since it will start falling.
if self.cur_row ~= 1 then
if (panels[row][col].color ~= 0) and (panels[row - 1][col].color == 0 or panels[row - 1][col].state == "falling") then
panels[row][col].dont_swap = true
end
if (panels[row][col + 1].color ~= 0) and (panels[row - 1][col + 1].color == 0 or panels[row - 1][col + 1].state == "falling") then
panels[row][col + 1].dont_swap = true
end
end
-- If you're swapping a blank space under a panel,
-- then you can't swap it back since the panel should
-- start falling.
if self.cur_row ~= self.height then
if panels[row][col].color == 0 and panels[row + 1][col].color ~= 0 then
panels[row][col].dont_swap = true
end
if panels[row][col + 1].color == 0 and panels[row + 1][col + 1].color ~= 0 then
panels[row][col + 1].dont_swap = true
end
end
end
-- Removes unneeded rows
function Stack.remove_extra_rows(self)
local panels = self.panels
local width = self.width
for row = #panels, self.height + 1, -1 do
local nonempty = false
local prow = panels[row]
for col = 1, width do
nonempty = nonempty or (prow[col].color ~= 0)
end
if nonempty then
break
else
panels[row] = nil
end
end
end
-- drops a width x height garbage.
function Stack.drop_garbage(self, width, height, metal)
logger.debug("dropping garbage at frame "..self.CLOCK)
local spawn_row = self.height + 1
-- Do one last check for panels in the way.
for i = spawn_row, #self.panels do
if self.panels[i] then
for j = 1, self.width do
if self.panels[i][j] then
if self.panels[i][j].color ~= 0 then
logger.trace("Aborting garbage drop: panel found at row " .. tostring(i) .. " column " .. tostring(j))
return false
end
end
end
end
end
if self.canvas ~= nil then
logger.trace(string.format("Dropping garbage on player %d - height %d width %d %s", self.player_number, height, width, metal and "Metal" or ""))
end
for i = self.height + 1, spawn_row + height - 1 do
if not self.panels[i] then
self.panels[i] = {}
for j = 1, self.width do
self.panels[i][j] = Panel()
end
end
end
local cols = self.garbage_cols[width]
local spawn_col = cols[cols.idx]
cols.idx = wrap(1, cols.idx + 1, #cols)
local shake_time = garbage_to_shake_time[width * height]
for y = spawn_row, spawn_row + height - 1 do
for x = spawn_col, spawn_col + width - 1 do
local panel = self.panels[y][x]
panel.garbage = true
panel.color = 9
panel.width = width
panel.height = height
panel.y_offset = y - spawn_row
panel.x_offset = x - spawn_col
panel.shake_time = shake_time
panel.state = "falling"
if metal then
panel.metal = metal
end
end
end
return true
end
-- Goes through whole stack checking for matches and updating chains etc based on matches.
function Stack.check_matches(self)
if self.do_countdown then
return
end
local panels = self.panels
for col = 1, self.width do
for row = 1, self.height do
panels[row][col].matching = nil
end
end
local is_chain = false
local combo_size = 0
local floodQueue = Queue()
for row = 1, self.height do
for col = 1, self.width do
if
row ~= 1 and row ~= self.height and --check vertical match centered here.
(not (panels[row - 1][col]:exclude_match() or panels[row][col]:exclude_match() or panels[row + 1][col]:exclude_match())) and
panels[row][col].color == panels[row - 1][col].color and
panels[row][col].color == panels[row + 1][col].color
then
for m_row = row - 1, row + 1 do
local panel = panels[m_row][col]
if not panel.matching then
combo_size = combo_size + 1
panel.matching = true
end
if panel.match_anyway and panel.chaining then
panel.chaining = nil
self.n_chain_panels = self.n_chain_panels - 1
end
is_chain = is_chain or panel.chaining
end
floodQueue:push({row, col, true, true})
end
if
col ~= 1 and col ~= self.width and --check horiz match centered here.
(not (panels[row][col - 1]:exclude_match() or panels[row][col]:exclude_match() or panels[row][col + 1]:exclude_match())) and
panels[row][col].color == panels[row][col - 1].color and
panels[row][col].color == panels[row][col + 1].color
then
for m_col = col - 1, col + 1 do
local panel = panels[row][m_col]
if not panel.matching then
combo_size = combo_size + 1
panel.matching = true
end
if panel.match_anyway and panel.chaining then
panel.chaining = nil
self.n_chain_panels = self.n_chain_panels - 1
end
is_chain = is_chain or panel.chaining
end
floodQueue:push({row, col, true, true})
end
end
end
-- This is basically two flood fills at the same time.
-- One for clearing normal garbage, one for metal.
local garbage = {}
local seen, seenm = {}, {}
local garbage_size = 0
while floodQueue:len() ~= 0 do
local y, x, normal, metal = unpack(floodQueue:pop())
local panel = panels[y][x]
-- We found a new panel we haven't handled yet that we should
if ((panel.garbage and panel.state == "normal") or panel.matching) and ((normal and not seen[panel]) or (metal and not seenm[panel])) then
-- We matched a new garbage
if ((metal and panel.metal) or (normal and not panel.metal)) and panel.garbage and not garbage[panel] then
garbage[panel] = true
if self:shouldChangeSoundEffects() then
SFX_garbage_match_play = true
end
if y <= self.height then
garbage_size = garbage_size + 1
end
end
seen[panel] = seen[panel] or normal
seenm[panel] = seenm[panel] or metal
if panel.garbage then
normal = normal and not panel.metal
metal = metal and panel.metal
end
if normal or metal then
if y ~= 1 then
floodQueue:push({y - 1, x, normal, metal})
end
if y ~= #panels then
floodQueue:push({y + 1, x, normal, metal})
end
if x ~= 1 then
floodQueue:push({y, x - 1, normal, metal})
end
if x ~= self.width then
floodQueue:push({y, x + 1, normal, metal})
end
end
end
end
if is_chain then
if self.chain_counter ~= 0 then
self.chain_counter = self.chain_counter + 1
else
self.chain_counter = 2
end
end
local first_panel_row = 0
local first_panel_col = 0
local metal_count = 0
local pre_stop_time = self.FRAMECOUNT_MATCH + self.FRAMECOUNT_POP * (combo_size + garbage_size)
local garbage_match_time = self.FRAMECOUNT_MATCH + self.FRAMECOUNT_POP * (combo_size + garbage_size)
local garbage_index = garbage_size - 1
local combo_index = combo_size
for row = 1, #panels do
local gpan_row = nil
for col = self.width, 1, -1 do
local panel = panels[row][col]
if garbage[panel] then
panel.state = "matched"
panel.timer = garbage_match_time + 1
panel.initial_time = garbage_match_time
panel.pop_time = self.FRAMECOUNT_POP * garbage_index
panel.pop_index = min(max(garbage_size - garbage_index, 1), 10)
panel.y_offset = panel.y_offset - 1
panel.height = panel.height - 1
if panel.y_offset == -1 then
if gpan_row == nil then
if string.len(self.gpanel_buffer) <= 10 * self.width then
local garbagePanels = PanelGenerator.makeGarbagePanels(self.match.seed + self.garbageGenCount, self.NCOLORS, self.gpanel_buffer, self.match.mode, self.level)
self.gpanel_buffer = self.gpanel_buffer .. garbagePanels
logger.info("Generating garbage with seed: " .. self.match.seed + self.garbageGenCount .. " buffer: " .. self.gpanel_buffer)
self.garbageGenCount = self.garbageGenCount + 1
end
gpan_row = string.sub(self.gpanel_buffer, 1, 6)
self.gpanel_buffer = string.sub(self.gpanel_buffer, 7)
end
panel.color = string.sub(gpan_row, col, col) + 0
if is_chain then
panel.chaining = true
self.n_chain_panels = self.n_chain_panels + 1
end
end
garbage_index = garbage_index - 1
elseif row <= self.height then
if panel.matching then
if panel.color == 8 then
metal_count = metal_count + 1
end
panel.state = "matched"
panel.timer = self.FRAMECOUNT_MATCH + 1
if is_chain and not panel.chaining then
panel.chaining = true
self.n_chain_panels = self.n_chain_panels + 1
end
panel.combo_index = combo_index
panel.combo_size = combo_size
panel.chain_index = self.chain_counter
combo_index = combo_index - 1
if combo_index == 0 then
first_panel_col = col
first_panel_row = row
end
else
-- if a panel wasn't matched but was eligible,
-- we might have to remove its chain flag...!
-- It can't actually chain the first frame it hovers,
-- so it can keep its chaining flag in that case.
if not (panel.match_anyway or panel:exclude_match()) then
if row ~= 1 then
-- a panel landed on the bottom row, so it surely
-- loses its chain flag.
-- no swapping panel below
-- so this panel loses its chain flag
if panels[row - 1][col].state ~= "swapping" and panel.chaining then
--if panel.chaining then
panel.chaining = nil
self.n_chain_panels = self.n_chain_panels - 1
end
elseif (panel.chaining) then
panel.chaining = nil
self.n_chain_panels = self.n_chain_panels - 1
end
end
end
end
end
end
if (combo_size ~= 0) then
self.combos[self.CLOCK] = combo_size
if self.garbage_target and self.telegraph and metal_count == 3 and combo_size >= 3 then
self.telegraph:push({6, 1, true, false}, first_panel_col, first_panel_row, self.CLOCK)
end
self.analytic:register_destroyed_panels(combo_size)
if (combo_size > 3) then
if (score_mode == SCOREMODE_TA) then
if (combo_size > 30) then
combo_size = 30
end
self.score = self.score + score_combo_TA[combo_size]
elseif (score_mode == SCOREMODE_PDP64) then
if (combo_size < 41) then
self.score = self.score + score_combo_PdP64[combo_size]
else
self.score = self.score + 20400 + ((combo_size - 40) * 800)
end
end
self:enqueue_card(false, first_panel_col, first_panel_row, combo_size)
if self.garbage_target and self.telegraph then
if metal_count > 3 then
for i = 3, metal_count do
self.telegraph:push({6, 1, true, false}, first_panel_col, first_panel_row, self.CLOCK)
end
end
if metal_count ~= combo_size then
local combo_pieces = combo_garbage[combo_size]
for i=1,#combo_pieces do
self.telegraph:push({combo_pieces[i], 1, false, false}, first_panel_col, first_panel_row, self.CLOCK)
end
end
end
--EnqueueConfetti(first_panel_col<<4+P1StackPosX+4,
-- first_panel_row<<4+P1StackPosY+self.displacement-9);
--TODO: this stuff ^
first_panel_row = first_panel_row + 1 -- offset chain cards
end
if (is_chain) then
if self.chain_counter == 2 then
self.chains.current = self.CLOCK
self.chains[self.CLOCK] = {start = self.CLOCK} -- a bit redundant, but might come in handy, maybe, probably not. The key is the same as .start.
end
self.chains[self.chains.current].size = self.chain_counter
self:enqueue_card(true, first_panel_col, first_panel_row, self.chain_counter)
--EnqueueConfetti(first_panel_col<<4+P1StackPosX+4,
-- first_panel_row<<4+P1StackPosY+self.displacement-9);
if self.garbage_target and self.telegraph then
self.telegraph:push({6, self.chain_counter - 1, false, true}, first_panel_col, first_panel_row, self.CLOCK)
end
end
local chain_bonus = self.chain_counter
if (score_mode == SCOREMODE_TA) then
if (self.chain_counter > 13) then
chain_bonus = 0
end
self.score = self.score + score_chain_TA[chain_bonus]
end
if ((combo_size > 3) or is_chain) then
local stop_time
if self.panels_in_top_row and is_chain then
if self.level then
local length = (self.chain_counter > 4) and 6 or self.chain_counter
stop_time = -8 * self.level + 168 + (length - 1) * (-2 * self.level + 22)
else
stop_time = stop_time_danger[self.difficulty]
end
elseif self.panels_in_top_row then
if self.level then
local length = (combo_size < 9) and 2 or 3
stop_time = self.chain_coefficient * length + self.chain_constant
else
stop_time = stop_time_danger[self.difficulty]
end
elseif is_chain then
if self.level then
local length = min(self.chain_counter, 13)
stop_time = self.chain_coefficient * length + self.chain_constant
else
stop_time = stop_time_chain[self.difficulty]
end
else
if self.level then
stop_time = self.combo_coefficient * combo_size + self.combo_constant
else
stop_time = stop_time_combo[self.difficulty]
end
end
self.stop_time = max(self.stop_time, stop_time)
self.pre_stop_time = max(self.pre_stop_time, pre_stop_time)
--MrStopState=1;
--MrStopTimer=MrStopAni[self.stop_time];
--TODO: Mr Stop ^
-- @CardsOfTheHeart says there are 4 chain sfx: --x2/x3, --x4, --x5 is x2/x3 with an echo effect, --x6+ is x4 with an echo effect
if self:shouldChangeSoundEffects() then
if is_chain then
self.combo_chain_play = {e_chain_or_combo.chain, self.chain_counter}
elseif combo_size > 3 then
self.combo_chain_play = {e_chain_or_combo.combo, "combos"}
end
end
self.sfx_land = false
end
--if garbage_size > 0 then
self.pre_stop_time = max(self.pre_stop_time, pre_stop_time)
--end
self.manual_raise = false
--self.score_render=1;
--Nope.
if metal_count > 5 then
self.combo_chain_play = {e_chain_or_combo.combo, "combo_echos"}
elseif metal_count > 2 then
self.combo_chain_play = {e_chain_or_combo.combo, "combos"}
end
end
end
-- Sets the hovering state on the appropriate panels
function Stack.set_hoverers(self, row, col, hover_time, add_chaining, extra_tick, match_anyway, debug_tag)
assert(type(match_anyway) ~= "string")
-- the extra_tick flag is for use during Phase 1&2,
-- when panels above the first should be given an extra tick of hover time.
-- This is because their timers will be decremented once on the same tick
-- they are set, as Phase 1&2 iterates backward through the stack.
local not_first = 0 -- if 1, the current panel isn't the first one
local hovers_time = hover_time
local brk = row > #self.panels
local panels = self.panels
while not brk do
local panel = panels[row][col]
if panel.color == 0 or panel:exclude_hover() or panel.state == "hovering" and panel.timer <= hover_time then
brk = true
else
if panel.state == "swapping" then
hovers_time = hovers_time + panels[row][col].timer - 1
else
local chaining = panel.chaining
panel:clear_flags()
panel.state = "hovering"
panel.match_anyway = match_anyway
panel.debug_tag = debug_tag
local adding_chaining = (not chaining) and panel.color ~= 9 and add_chaining
if chaining or adding_chaining then
panel.chaining = true
end
panel.timer = hovers_time
if extra_tick then
panel.timer = panel.timer + not_first
end
if adding_chaining then
self.n_chain_panels = self.n_chain_panels + 1
end
end
not_first = 1
end
row = row + 1
brk = brk or row > #self.panels
end
end
-- Adds a new row to the play field
function Stack.new_row(self)
local panels = self.panels
-- move cursor up
self.cur_row = bound(1, self.cur_row + 1, self.top_cur_row)
-- move panels up
for row = #panels + 1, 1, -1 do
panels[row] = panels[row - 1]
end
panels[0] = {}
-- put bottom row into play
for col = 1, self.width do
panels[1][col].state = "normal"
end
if string.len(self.panel_buffer) <= 10 * self.width then
local opponentLevel = nil
if self.garbage_target then
opponentLevel = self.garbage_target.level
end
self.panel_buffer = PanelGenerator.makePanels(self.match.seed + self.panelGenCount, self.NCOLORS, self.panel_buffer, self.match.mode, self.level, opponentLevel)
logger.info("generating panels with seed: " .. self.match.seed + self.panelGenCount .. " buffer: " .. self.panel_buffer)
self.panelGenCount = self.panelGenCount + 1
end
-- generate a new row
local metal_panels_this_row = 0
if self.metal_panels_queued > 3 then
self.metal_panels_queued = self.metal_panels_queued - 2
metal_panels_this_row = 2
elseif self.metal_panels_queued > 0 then
self.metal_panels_queued = self.metal_panels_queued - 1
metal_panels_this_row = 1
end
for col = 1, self.width do
local panel = Panel()
panels[0][col] = panel
local this_panel_color = string.sub(self.panel_buffer, col, col)
--a capital letter for the place where the first shock block should spawn (if earned), and a lower case letter is where a second should spawn (if earned). (color 8 is metal)
if tonumber(this_panel_color) then
--do nothing special
elseif this_panel_color >= "A" and this_panel_color <= "Z" then
if metal_panels_this_row > 0 then
this_panel_color = 8
else
this_panel_color = panel_color_to_number[this_panel_color]
end
elseif this_panel_color >= "a" and this_panel_color <= "z" then
if metal_panels_this_row > 1 then
this_panel_color = 8
else
this_panel_color = panel_color_to_number[this_panel_color]
end
end
panel.color = this_panel_color + 0
panel.state = "dimmed"
end
self.panel_buffer = string.sub(self.panel_buffer, 7)
self.displacement = 16
end
|
-- Author: Pablo Musa
-- Creation Date: jun 20 2011
-- Last Modification: aug 09 2011
local lmp = require"luamemprofiler"
lmp.start(...)
local t = {}
lmp.stop()
lmp.start(...)
local t = {10}
lmp.stop()
lmp.start(...)
local t = {10, 20, 30}
lmp.stop()
lmp.start(...)
local t = {}
for i=10,200,10 do
table.insert(t, i)
end
lmp.stop()
lmp.start(...)
local t = {}
for i=10,320,10 do
table.insert(t, i)
end
lmp.stop()
lmp.start(...)
local t = {}
for i=10,330,10 do
table.insert(t, i)
end
lmp.stop()
|
local currentPlane
local isClientInPlane = false
local velocityX = 0
local velocityY = 0
local startTime = 0
local startX, startY = 0, 0
addEvent("createPlane", true)
addEventHandler("createPlane", resourceRoot, function (x, y, angle, vx, vy)
if isElement(currentPlane) then
destroyElement(currentPlane)
end
currentPlane = createVehicle(592, x, y, Config.planeZ, 0, 0, angle)
currentPlane.frozen = true
currentPlane.dimension = localPlayer.dimension
currentPlane:setCollisionsEnabled(false)
local ped = createPed(0, currentPlane.position)
ped.dimension = localPlayer.dimension
ped.vehicle = currentPlane
ped.alpha = 0
setTimer(function ()
ped.alpha = 255
ped.vehicle = currentPlane
ped:setControlState("accelerate", true)
end, 1000, 1)
velocityX = vx or 0
velocityY = vy or 0
startX = x
startY = y
startTime = getTickCount()
isClientInPlane = true
startPlaneCamera(currentPlane)
end)
function getFlightDistance()
return ((getTickCount() - startTime) / 1000) * Config.planeSpeed
end
addEventHandler("onClientPreRender", root, function (deltaTime)
if not isElement(currentPlane) then
return
end
updatePlaneCamera(deltaTime / 1000)
local passedTime = (getTickCount() - startTime) / 1000
currentPlane.position = Vector3(startX + velocityX * passedTime, startY + velocityY * passedTime, Config.planeZ - 10)
if isClientInPlane then
setElementPosition(localPlayer, currentPlane.position, false)
end
if math.abs(currentPlane.position.x) > Config.planeDistance + 50 or
math.abs(currentPlane.position.y) > Config.planeDistance + 50
then
destroyElement(currentPlane)
return
end
local flightDistance = getFlightDistance()
if isClientInPlane and flightDistance > 3000 and
(math.abs(currentPlane.position.x) > Config.autoParachuteDistance or
math.abs(currentPlane.position.y) > Config.autoParachuteDistance)
then
jumpFromPlane()
end
end)
function canJumpFromPlane()
if not isClientInPlane then
return false
end
if getFlightDistance() < 800 then
return false
end
return true
end
function jumpFromPlane()
if isClientInPlane then
if localPlayer:getData("dead") then
return
end
if getFlightDistance() < 800 then
return
end
isClientInPlane = false
localPlayer:setData("isInPlane", false, false)
triggerServerEvent("planeJump", resourceRoot)
fadeCamera(false, 0)
end
end
function destroyPlane()
if isElement(currentPlane) then
destroyElement(currentPlane)
end
end
function getPlane()
return currentPlane
end
bindKey("f", "down", function ()
jumpFromPlane()
end)
addEvent("planeJump", true)
addEventHandler("planeJump", resourceRoot, function ()
isClientInPlane = false
stopPlaneCamera()
fadeCamera(true, 1)
end)
|
-- Copyright (c) 2017-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the license found in the LICENSE file in
-- the root directory of this source tree. An additional grant of patent rights
-- can be found in the PATENTS file in the same directory.
--
--[[
--
-- MaxBatchDataset builds batches of up to and including maxbatch tokens.
--
--]]
local tnt = require 'torchnet.env'
local argcheck = require 'argcheck'
local transform = require 'torchnet.transform'
local vector = require 'vector'
local MaxBatchDataset, _ =
torch.class('tnt.MaxBatchDataset', 'tnt.Dataset', tnt)
MaxBatchDataset.__init = argcheck{
doc = [[
<a name="MaxBatchDataset">
#### tnt.MaxBatchDataset(@ARGP)
@ARGT
Given a `dataset`, `tnt.MaxBatchDataset` merges samples from this dataset into
a batch such that the total size of the batch does not exceed maxbatch.
]],
{name='self', type='tnt.MaxBatchDataset'},
{name='dataset', type='tnt.Dataset'},
{name='maxbatch', type='number'},
{name='samplesize', type='function'},
{name='merge', type='function', opt=true},
call =
function(self, dataset, maxbatch, samplesize, merge)
assert(maxbatch > 0 and math.floor(maxbatch) == maxbatch,
'maxbatch should be a positive integer number')
self.dataset = dataset
self.maxbatch = maxbatch
self.samplesize = samplesize
self.makebatch = transform.makebatch{merge=merge}
self:_buildIndex()
end
}
MaxBatchDataset._buildIndex = argcheck{
{name='self', type='tnt.MaxBatchDataset'},
call = function(self)
self.offset = vector.tensor.new_long()
self.offset[1] = 1
local size = self.dataset:size()
local maxssz, maxtsz = 0, 0
local nstok, nttok = 0, 0
for i = 1, size do
local _, ssz, tsz = self.samplesize(self.dataset, i)
if math.max(ssz, tsz) > self.maxbatch then
print("warning: found sample that exceeds maxbatch size")
end
maxtsz = math.max(maxtsz, tsz)
maxssz = math.max(maxssz, ssz)
local nsamples = i - self.offset[#self.offset] + 1
local tottsz = nsamples * maxtsz
local totssz = nsamples * maxssz
nstok = nstok + ssz
nttok = nttok + tsz
if i > 1 and math.max(tottsz, totssz) > self.maxbatch then
self.offset[#self.offset + 1] = i
maxssz = ssz
maxtsz = tsz
nstok = ssz
nttok = tsz
end
end
self.offset = self.offset:getTensor()
end
}
MaxBatchDataset.size = argcheck{
{name='self', type='tnt.MaxBatchDataset'},
call =
function(self)
return self.offset:size(1)
end
}
MaxBatchDataset.get = argcheck{
{name='self', type='tnt.MaxBatchDataset'},
{name='idx', type='number'},
call =
function(self, idx)
assert(idx >= 1 and idx <= self:size(), 'index out of bound')
local samples = {}
local first = self.offset[idx]
local last = idx < self:size() and
self.offset[idx + 1] - 1 or self.dataset:size()
for i = first, last do
local sample = self.dataset:get(i)
table.insert(samples, sample)
end
samples = self.makebatch(samples)
collectgarbage()
collectgarbage()
return samples
end
}
|
local images = {_count = 0, _index = 0}
local waiting_images = false
local send_image = false
set_stream_request_callback(function(request)
if string.sub(request, 1, 1) ~= "?" then return end
if request == "?!" then
if images._count > images._index then
images._index = images._index + 1
send_stream_message("!", images[images._index])
else
send_image = true
toggle_heartbeat_system(true)
end
else
waiting_images = false
images._count = 0
images._index = 0
ui.addTextArea(0, request) -- send the request to the bot
toggle_heartbeat_system(true)
end
end)
set_stream_failure_callback(function()
ui.addTextArea(1, "") -- cancel the request
toggle_heartbeat_system(false)
end)
onEvent("TextAreaCallback", function(id, name, callback)
if waiting_images then
if not send_image then
images._count = images._count + 1
images[images._count] = callback
return
end
else
waiting_images = true
end
send_image = false
toggle_heartbeat_system(false)
send_stream_message("!", callback)
end)
onEvent("NewPlayer", function(player)
tfm.exec.chatMessage("loaded v2", player)
end)
onEvent("Loop", function()
system.loadPlayerData(stream_bot)
end) |
require 'xlua'
require 'optim'
require 'cunn'
dofile './provider.lua'
local c = require 'trepl.colorize'
cmd = torch.CmdLine()
cmd:text()
cmd:text()
cmd:text('compare the Decorelated BatchNormalizaiton method with baselines on vggA architechture')
cmd:text()
cmd:text('Options')
cmd:option('-model','vggA_DBN','the methods')
cmd:option('-max_epoch',100,'maximum number of iterations')
cmd:option('-epoch_step',20000,'epoch step: no lr annealing if it is larger than the maximum')
cmd:option('-save',"../0_experiment_result/0run_NNN/log_Conv_1vggA_1validate" ,'subdirectory to save logs')
cmd:option('-batchSize',256,'the number of examples per batch')
cmd:option('-optimization','simple','the methods: options:simple,rms,adagrad,adam')
cmd:option('-learningRate',1,'initial learning rate')
---for simple (sgd)--------
cmd:option('-lrD_k',1000,'exponential learning rate decay, and each lrD_k iteration the learning rate become half')
cmd:option('-weightDecay',0.0005,'weight Decay for regularization')
cmd:option('-momentum',0.9,'momentum')
------------for rms/ agagrad-------
cmd:option('-rms_alpha',0,'the rate of the rms method')
cmd:option('-m_perGroup',16,'the number of per group')
cmd:option('-seed',1,'')
cmd:text()
-- parse input params
opt = cmd:parse(arg)
-- opt.rundir = cmd:string('../0_experiment_result/0run_NNN/console/exp_Conv_1vggA_1validate/Info', opt, {dir=true})
-- paths.mkdir(opt.rundir)
-- -- create log file
-- cmd:log(opt.rundir .. '/log', opt)
print(c.blue'==>' ..' configuring optimizer')
if opt.optimization == 'simple' then
opt.optimState = {
learningRate =opt.learningRate,
weightDecay = opt.weightDecay,
momentum = opt.momentum,
learningRateDecay = learningRateDecay
}
optimMethod = optim.sgd
elseif opt.optimization == 'adagrad' then
opt.optimState = {
learningRate = opt.learningRate,
}
optimMethod = optim.adagrad
elseif opt.optimization == 'rms' then
opt.optimState = {
learningRate = opt.learningRate,
alpha=opt.rms_alpha
}
optimMethod = optim.rmsprop
elseif opt.optimization == 'adam' then
opt.optimState = {
learningRate = opt.learningRate
}
optimMethod = optim.adam
else
error('Unknown optimizer')
end
print(opt)
torch.manualSeed(opt.seed) -- fix random seed so program runs the same every time
threadNumber=4
torch.setnumthreads(threadNumber)
torch.setdefaulttensortype('torch.FloatTensor')
do -- data augmentation module
local BatchFlip,parent = torch.class('nn.BatchFlip', 'nn.Module')
function BatchFlip:__init()
parent.__init(self)
self.train = true
end
function BatchFlip:updateOutput(input)
if self.train then
local bs = input:size(1)
local flip_mask = torch.randperm(bs):le(bs/2)
for i=1,input:size(1) do
if flip_mask[i] == 1 then image.hflip(input[i], input[i]) end
end
end
self.output = input
return self.output
end
end
print(c.blue '==>' ..' configuring model')
local model = nn.Sequential()
model:add(nn.BatchFlip():float())
model:add(nn.Copy('torch.FloatTensor','torch.CudaTensor'):cuda())
model:add(dofile('models/Conv/'..opt.model..'.lua'):cuda())
model:get(2).updateGradInput = function(input) return end
print(model)
print(c.blue '==>' ..' loading data')
provider = torch.load './dataset/cifar_provider_split_float.t7'
print('train data numbers:'..provider.trainData.data:size(1))
print('validate data numbers:'..provider.validateData.data:size(1))
print('validate data numbers:'..provider.testData.data:size(1))
confusion = optim.ConfusionMatrix(10)
print('Will save at '..opt.save)
paths.mkdir(opt.save)
log_name=opt.model..'_'..opt.optimization..'_lr'..opt.learningRate..'_g'..opt.m_perGroup..'_mm'..opt.momentum..'_'..opt.weightDecay..'_'..opt.lrD_k..'.log'
testLogger = optim.Logger(paths.concat(opt.save, log_name))
testLogger:setNames{'% mean class accuracy (train set)', '% mean class accuracy (test set)'}
testLogger.showPlot = false
parameters,gradParameters = model:getParameters()
print(c.blue'==>' ..' setting criterion')
criterion = nn.CrossEntropyCriterion():cuda()
function train()
model:training()
epoch = epoch or 1
-- drop learning rate every "epoch_step" epochs
if epoch % opt.epoch_step == 0 then opt.optimState.learningRate = opt.optimState.learningRate/2 end
print(c.blue '==>'.." online epoch # " .. epoch .. ' [batchSize = ' .. opt.batchSize .. ']')
local targets = torch.CudaTensor(opt.batchSize)
local indices = torch.randperm(provider.trainData.data:size(1)):long():split(opt.batchSize)
-- remove last element so that all the batches have equal size
indices[#indices] = nil
-- local tic = torch.tic()
for t,v in ipairs(indices) do
xlua.progress(t, #indices)
local inputs = provider.trainData.data:index(1,v)
targets:copy(provider.trainData.labels:index(1,v))
local feval = function(x)
if x ~= parameters then parameters:copy(x) end
gradParameters:zero()
local outputs = model:forward(inputs)
local f = criterion:forward(outputs, targets)
local df_do = criterion:backward(outputs, targets)
model:backward(inputs, df_do)
confusion:batchAdd(outputs, targets)
print(string.format("minibatches processed: %6s, loss = %6.6f", iteration, f))
losses[#losses + 1] = f
timeCosts[#timeCosts+1]=torch.toc(start_time)
print(string.format("time Costs = %6.6f", timeCosts[#timeCosts]))
iteration=iteration+1
return f,gradParameters
end
-----learning rate schedule---------------
local k=torch.log(2)/opt.lrD_k
local lr_scale=torch.exp(-k*iteration)
opt.optimState.learningRate=opt.learningRate* lr_scale
print('learning Rate:'..opt.optimState.learningRate)
optimMethod (feval, parameters, opt.optimState)
end
confusion:updateValids()
print(('Train accuracy: '..c.cyan'%.2f'..' %%\t time: %.2f s'):format(
confusion.totalValid * 100, torch.toc(start_time)))
train_acc = confusion.totalValid * 100
train_accus[#train_accus+1]=train_acc
confusion:zero()
epoch = epoch + 1
end
function validate()
-- disable flips, dropouts and batch normalization
model:evaluate()
print(c.blue '==>'.." validating")
local bs = 125
for i=1,provider.validateData.data:size(1),bs do
local outputs = model:forward(provider.validateData.data:narrow(1,i,bs))
confusion:batchAdd(outputs, provider.validateData.labels:narrow(1,i,bs))
end
confusion:updateValids()
print('Validate accuracy:', confusion.totalValid * 100)
validate_accus[#validate_accus+1]=confusion.totalValid * 100
if testLogger then
paths.mkdir(opt.save)
testLogger:add{train_acc, confusion.totalValid * 100}
testLogger:style{'-','-'}
testLogger:plot()
end
if epoch % 1000 == 0 then
local filename = paths.concat(opt.save, 'model.net')
print('==> saving model to '..filename)
torch.save(filename, model:get(3))
end
confusion:zero()
end
function test()
model:evaluate()
print(c.blue '==>'.." testing")
local bs = 125
for i=1,provider.testData.data:size(1),bs do
local outputs = model:forward(provider.testData.data:narrow(1,i,bs))
confusion:batchAdd(outputs, provider.testData.labels:narrow(1,i,bs))
end
confusion:updateValids()
print('Test accuracy:', confusion.totalValid * 100)
test_accus[#test_accus+1]=confusion.totalValid * 100
if testLogger then
paths.mkdir(opt.save)
testLogger:add{train_acc, confusion.totalValid * 100}
testLogger:style{'-','-'}
testLogger:plot()
end
confusion:zero()
end
iteration=0
losses={}
timeCosts={}
train_accus={}
validate_accus={}
test_accus={}
start_time=torch.tic()
for i=1,opt.max_epoch do
train()
validate()
test()
end
results={}
--results.opt=opt
results.losses=losses
results.train_accus=train_accus
results.validate_accus=validate_accus
results.test_accus=test_accus
results.timeCosts=timeCosts
torch.save('set_result/Conv/result_1vggA_1validate_'..opt.model..'_'..opt.optimization..'_lr'..opt.learningRate..'_g'..opt.m_perGroup..'_mm'..opt.momentum..'_'..opt.weightDecay..'_'..opt.lrD_k..
'_seed'..opt.seed..'.dat',results)
|
-- Copyright 2019 Teverse.com
-- Tool Constants:
local toolName = "Hand"
local toolDesc = ""
local toolIcon = "fa:s-hand-pointer"
local selection = require("tevgit:workshop/controllers/core/selection.lua")
local history = require("tevgit:workshop/controllers/core/history.lua")
local clickEvent = nil
return {
name = toolName,
icon = toolIcon,
desc = toolDesc,
activate = function()
-- Set the event listener to a variable so we can disconnect this handler
-- when the tool is deactivated
clickEvent = engine.input:mouseLeftPressed(function ( inputObj )
if not inputObj.systemHandled then
-- This is not a gui event, let's continue.
local hit = engine.physics:rayTestScreen(engine.input.mousePosition)
if hit and not hit.object.workshopLocked then
-- user has clicked a object in 3d space.
if selection.isSelected(hit.object) then
-- user clicked a selected object,
-- we're gonna turn into drag mode!
-- calculate the 'centre' of the selection
local bounds = aabb()
if #selection.selection > 0 then
bounds.min = selection.selection[1].position
bounds.max = selection.selection[1].position
end
for _,v in pairs(selection.selection) do
bounds:expand(v.position + (v.size/2))
bounds:expand(v.position - (v.size/2))
end
local centre = bounds:getCentre()
-- calculate the mouse's offset from the centre
local mouseOffset = hit.hitPosition - centre
-- calculate every selected item's offset from the centre
local offsets = {}
for _,v in pairs(selection.selection) do
offsets[v] = v.position - centre
end
-- tell history to monitor changes we make to selected items
history.beginAction(selection.selection, "Hand tool drag")
local grid = engine.construct("grid", workspace, {
step = 0.5,
colour = colour(0.1, 0, 0.1),
size = 10,
rotation = quaternion:setEuler(math.rad(90), 0, 0)
})
while engine.input:isMouseButtonDown(enums.mouseButton.left) do
-- fire a ray, exclude selected items.
local hits, didExclude = engine.physics:rayTestScreenAllHits(engine.input.mousePosition, selection.selection)
if (#hits > 0) then
local newCentre = hits[1].hitPosition - mouseOffset
local avgPos = vector3(0,0,0)
for _,v in pairs(selection.selection) do
if offsets[v] then
v.position = newCentre + offsets[v]
avgPos = avgPos + v.position
end
end
grid.position = avgPos / #selection.selection
end
wait()
end
history.endAction()
grid:destroy()
else
-- user clicked an unselected object, let's select it
if engine.input:isKeyDown(enums.key.leftShift) then
-- holding shift, so we append the clicked object to selection
selection.addSelection(hit.object)
else
-- we override the user's selection here
selection.setSelection(hit.object)
end
end
else
selection.setSelection({})
end
end
end)
end,
deactivate = function ()
if clickEvent then
clickEvent:disconnect()
clickEvent = nil
end
end
} |
--[[ * PRINCIPES *
On importe tout le fichier de code, pas simplement une fonction factory
--]]
-- On crée une table qu'on renverra à la fin. En fait, une référence, mais on changera le contenu à chaque appel de new().
local CMaton = {}
-- Cette métatable fera le lien entre la table locale qu'on crée dans le new et la table exportable moduleAliens
local cmaton_mt = { __index = CMaton }
local CSpriteFactory = require("class/CSpriteFactory")
local TYPE_SPRITE = require("enum/ETypeSprite")
local STATE_MATON = require("enum/EStateMaton")
-- On stocke la window dont on a besoin partout pour les largeur et hauteur
local objWindow = nit
-- Returns the angle between two points.
function math.angle(x1,y1, x2,y2) return math.atan2(y2-y1, x2-x1) end
-- Notre méthode Factory qui renvoie une fonction particulière de lua
function CMaton.new()
-- print("CPrisonnier.new() / Création d'un instance de CSprite")
local objMaton = {}
return setmetatable( objMaton, cmaton_mt)
end
function CMaton:addToList(pList)
table.insert(pList, self)
end
function CMaton:setPosition(pX, pY)
self.objSprite:setPosition(pX, pY)
end
function CMaton:createNew(pList, pWindow)
-- On stocke le paramètre
objWindow = pWindow
local objSpriteFactory = CSpriteFactory.new()
local objMaton = CMaton.new()
objMaton.objSprite = objSpriteFactory:createSpriteMaton()
-- On SURCHARGE le sprite des MATONS car pas tous les sprites ont besoin de ces variables
objMaton.objSprite.speed = 0
objMaton.objSprite.angleRad = 0
objMaton.objSprite.vx = 0
objMaton.objSprite.vy = 0
-- Le MATON
objMaton.target = nil
objMaton.rangeDetection = 0
objMaton.state = STATE_MATON.NONE
objMaton:addToList(pList)
-- On le place au hasard DE BASE dans la partie haute de la fenêtre, vitesse au hasard, angle au hasard
objMaton:setPosition(
math.random(10, objWindow.largeur-10),
math.random(10, (objWindow.hauteur/2)-10)
)
objMaton.objSprite.speed = math.random(5,50) / 200
objMaton.objSprite.range = math.random(10, 150) -- détecte entre 10 et 150 pixels
-- Angle au hasard entre le point où est le maton et un point au hasard dans tout l'écran
local xHasard = math.random(0,objWindow.largeur)
local yHasard = math.random(0,objWindow.hauteur)
objMaton.objSprite.angleRad = math.angle(objMaton.objSprite.x, objMaton.objSprite.y, xHasard, yHasard)
-- print(objMaton.objSprite.angleRad * 360 / math.pi)
objMaton.target = nil
return objMaton
end
function CMaton:update(dt)
-- * GESTION du N° de FRAME qu'on incrémente petit à petit
self.objSprite.idFrameAVirguleCourant = self.objSprite.idFrameAVirguleCourant + 7*dt
if self.objSprite.idFrameAVirguleCourant >= #self.objSprite.framesAnimMatrix + 1 then
self.objSprite.idFrameAVirguleCourant = 1
end
if self.state == nil then
print("***** ERROR STATE NIL *****")
end
if self.state == STATE_MATON.NONE then
self.state = STATE_MATON.CHANGEDIR
elseif self.state == STATE_MATON.WALK then
-- COLLISION with BORDERS
local bCollide = false
if self.objSprite.x < 0 then
-- On le colle à la paroie
self.objSprite.x = 0
bCollide = true
end
if self.objSprite.x > objWindow.largeur then
self.objSprite.x = objWindow.largeur
bCollide = true
end
if self.objSprite.y < 0 then
self.objSprite.y = 0
bCollide = true
end
if self.objSprite.y > objWindow.hauteur then
self.objSprite.y = objWindow.hauteur
bCollide = true
end
if bCollide then
self.state = STATE_MATON.CHANGEDIR
end
elseif self.state == STATE_MATON.CHANGEDIR then
-- Angle au hasard entre le point où est le maton et un point au hasard dans tout l'écran
local xHasard = math.random(0,objWindow.largeur)
local yHasard = math.random(0,objWindow.hauteur)
self.objSprite.angleRad = math.angle(self.objSprite.x, self.objSprite.y, xHasard, yHasard)
self.state = STATE_MATON.WALK
end
-- * CALCUL des nouvelles COORDONNEES
-- nouvelle Vx, Vy
self.objSprite.vx = self.objSprite.speed * 2 * 60 * dt * math.cos(self.objSprite.angleRad)
self.objSprite.vy = self.objSprite.speed * 2 * 60 * dt * math.sin(self.objSprite.angleRad)
-- print("vx : "..self.objSprite.vx..", vy : "..self.objSprite.vy)
-- nouvelles coordonées
self.objSprite.x = self.objSprite.x + self.objSprite.vx
self.objSprite.y = self.objSprite.y + self.objSprite.vy
end
function CMaton:draw()
local idFrameEntier = math.floor(self.objSprite.idFrameAVirguleCourant)
-- Affichage du Hero
love.graphics.draw(self.objSprite.image, self.objSprite.framesAnimMatrix[self.objSprite.idAnimCourant][idFrameEntier], self.objSprite.x, self.objSprite.y, 0, 1, 1, self.objSprite.width/2, self.objSprite.height/2)
end
return CMaton |
-------------------------------------------------
---- (Abstract) Class: MusicEditing.Object
-------------------------------------------------
local Object = {
-- ASSUME: __index is always table instead of function, and the table is this class or a class derived from this class
getClass = function (self)
return getmetatable(self).__index
end,
-- ASSUME: __index is always table instead of function
-- CAUTION: this function can be slow when there are lots of classes in the namespace
getClassName = function (self, namespace)
assert(namespace and type(namespace) == "table", "Invalid namespace")
local class = self:getClass()
for k,v in pairs(namespace) do
if (v == class) then
return k
end
end
error("This class does not exist in the namespace")
end,
-- ASSUME: __index is always table instead of function
isDerivedFrom = function (self, class)
local metatable = getmetatable(self)
while(metatable and metatable.__index) do
if (metatable.__index == class) then
return true
end
metatable = getmetatable(metatable.__index)
end
return false
end,
}
return Object
|
require "SvgWriter"
require "vmath"
require "Viewport"
require "SubImage"
require "GridAxis"
require "PixelImage"
require "_utils"
-- Sizing
local imageSize = vmath.vec2(350, 350);
local subImages = SubImage.SubImage(1, 1, imageSize.x, imageSize.y, 0, 50);
local coordSize = 6;
local coordWidth = coordSize * (imageSize.x / imageSize.y);
--image
local image = PixelImage.PixelImage("Parallelogram.txt")
local pixelSize = image:Size();
pixelSize = pixelSize / 2;
pixelSize.y = pixelSize.y;
local vp = Viewport.Viewport(imageSize, pixelSize, image:Size())
local trans2 = Viewport.Transform2D()
vp:SetTransform(trans2);
--styles
local styleLib = SvgWriter.StyleLibrary();
image:Style(styleLib);
styleLib:AddStyle(nil, "grid",
SvgWriter.Style():stroke("#888"):stroke_width("1.5px"):fill("none"));
styleLib:AddStyle(nil, "frag_area",
SvgWriter.Style():stroke("red"):stroke_width("7px"):stroke_opacity(0.7)
:stroke_linejoin("round"):fill("none"));
styleLib:AddStyle(nil, "sample_box",
SvgWriter.Style():stroke("#4B4"):stroke_width("4px"):fill("none"));
styleLib:AddStyle(nil, "sample_pt",
SvgWriter.Style():stroke("none"):fill("goldenrod"));
--Sample point.
local texCoord = vmath.vec2(0.395, 0.385)
local samplePt = texCoord * image:Size();
local lowLeftPt = samplePt - vmath.vec2(5.5, 5.5)
local upRightPt = samplePt + vmath.vec2(5.5, 5.5)
local pts =
{
vmath.vec2(1.2, 1.7),
vmath.vec2(1.8, 4.3),
vmath.vec2(5.3, 4.4),
vmath.vec2(4.3, 1.8),
}
pts = vp:Transform(pts);
local pathSampleArea = SvgWriter:Path();
pathSampleArea
:M(pts[1])
:L(pts[2])
:L(pts[3])
:L(pts[4])
:Z()
samplePt = vp:Transform(samplePt);
local ptRadius = vp:Length(0.25)
local sampleBoxes =
{
{vmath.vec2(1, 5), vmath.vec2(1, 1)},
{vmath.vec2(4, 5), vmath.vec2(1, 1)},
{vmath.vec2(4, 4), vmath.vec2(1, 1)},
{vmath.vec2(2, 4), vmath.vec2(2, 2)},
}
local writer = SvgWriter.SvgWriter(ConstructSVGName(arg[0]), {subImages:Size().x .."px", subImages:Size().y .. "px"});
writer:StyleLibrary(styleLib);
writer:BeginDefinitions();
writer:EndDefinitions();
image:Draw(writer, vmath.vec2(0, 0), subImages:Size(), {"grid"});
for i, box in ipairs(sampleBoxes) do
image:DrawPixelRect(writer, vmath.vec2(0, 0), subImages:Size(),
box[1], box[2],
{"sample_box"})
end
writer:Path(pathSampleArea, {"frag_area"})
writer:Circle(samplePt, ptRadius, {"sample_pt"})
writer:Close();
|
project "glad"
kind "StaticLib"
staticruntime "on"
language "C++"
cppdialect "C++17"
targetdir (TargetDir)
objdir (ObjectDir)
warnings "off"
files
{
"%{prj.location}/**.c" ,
"%{prj.location}/**.h" ,
"%{prj.location}/premake5.lua" ,
}
includedirs
{
"%{prj.location}/"
}
filter "configurations:debug"
optimize "on"
runtime "debug"
filter "configurations:release"
optimize "on"
runtime "release"
filter "configurations:distrubution"
optimize "on"
runtime "release"
|
-- naive basic recursive binpacker,
local function simple_solver(nodes, w, h)
table.sort(nodes, function(a, b) return a.h > b.h end)
local get_node;
get_node = function(n, w, h)
if (n.used) then
local r = get_node(n.r, w, h)
if (r) then
return r;
else
return get_node(n.d, w, h)
end
elseif (w <= n.w and h <= n.h) then
n.used = true
n.d = {x = n.x, y = n.y + h, w = n.w, h = n.h - h}
n.r = {x = n.x + w, y = n.y, w = n.w - w, h = h }
return n
end
end
local root = {x = 0, y = 0, w = w, h = h}
for _, v in ipairs(nodes) do
local n = get_node(root, v.w, v.h)
if (n) then
v.x = n.x; v.y = n.y
v.used = true
end
end
-- did we get a solution or not?
local rest = {}
for _, v in ipairs(nodes) do
-- option here would also be to split the work-set based on the not-used ones,
-- add that to a second plane and offset- / re-order that
if not v.used then
table.insert(rest, v)
end
end
if #rest > 0 then
return false, rest
end
-- some post- processing here to make sure we add space when possible would be nice,
return true
end
local ro_controls =
{
["LEFT"] =
function()
end,
["TAB"] =
function()
end
}
local function simple_ro_input(cell, iotbl, sym, lutsym)
-- input is only used to relayout, and since mouse.lua still does not handle/
-- expose a context based state machine we are stuck with manual controls for
-- adjusting the composition.
if iotbl.digital and not iotbl.active then
return
end
if sym and ro_controls[sym] then
ro_controls[sym](cell)
end
end
local function simple_rw_input(iotbl)
-- allow some kind of typing, the likely path from this isn't in-pipeworld
-- itself as you can just type into the source cell, but from an encoder
-- attached that is connected to an external source where you get 'input'
-- events.
end
local function apply_pad(set)
for _,v in ipairs(set) do
v.x = v.x + v.pad_w
v.y = v.y + v.pad_h
v.w = v.w - v.pad_w - v.pad_w
v.h = v.h - v.pad_h - v.pad_h
end
end
local function expose_bin(set, max_w, max_h)
-- add some padding, a better post processing here would be some kind of
-- graph drawing algorithm e.g. spring or something to space things out after
-- we have a solution
for _,v in ipairs(set) do
v.pad_w = 20
v.pad_h = 20
v.w = v.w + v.pad_w + v.pad_w
v.h = v.h + v.pad_h + v.pad_h
end
if simple_solver(set, max_w, max_h) then
apply_pad(set)
return
end
-- remove down to 1 px border
for _,v in ipairs(set) do
v.w = v.w - v.pad_w - v.pad_w
v.h = v.h - v.pad_h - v.pad_h
v.pad_w = 1
v.pad_h = 1
end
-- and expose-like shrink until we have a solution
while not simple_solver(set, max_w, max_h) do
for _,v in ipairs(set) do
v.w = v.w * 0.9
v.h = v.h * 0.9
end
end
apply_pad(set)
end
local policies = {
ro_bin = {expose_bin, simple_ro_input},
rw_bin = {expose_bin, simple_rw_input},
}
local function apply_solver(cell)
local w = cell.rendertarget_wh[1]
local h = cell.rendertarget_wh[2]
local boxes = {}
-- translate into current set, add some padding
for _,v in ipairs(cell.compose_set) do
local props = image_surface_resolve(v)
table.insert(boxes, {
vid = v,
x = 0,
y = 0,
w = props.width,
h = props.height,
z = 1
})
end
-- policy will reposition/resize/tag
cell.policy[1](boxes, w, h)
for _,v in ipairs(boxes) do
move_image(v.vid, v.x, v.y)
resize_image(v.vid, v.w, v.h)
order_image(v.vid, v.z)
end
end
return
function(row, cfg, opts, ...)
-- arguments are treated as full cells (table), vids that we inherit
-- (caller expected to null_surface+share_storage) or factory functions
-- in order to provide input and react on changes
local cells = {...}
opts = type(opts) == "table" and opts or {}
if not opts.policy then
opts.policy = cfg.compose_policy
end
if not policies[opts.policy] then
warning("unknown composition packing policy")
return
end
-- setup the buffer and quality / format
local w, h = unpack(cfg.compose_default_wh)
if opts.width then
w = opts.width
end
if opts.height then
h = opts.height
end
local fmt = ALLOC_QUALITY_NORMAL
if opts.format and type(opts.format) == "number" then
fmt = opts.format
end
local vid = alloc_surface(w, h, true, fmt)
if not valid_vid(vid) then
warning("could not allocate composition surface")
return
end
image_mask_set(vid, MASK_UNPICKABLE)
-- Create the composition intermediates and bind as rendertarget,
--
-- This is not (yet) clocked off the set of producers but rather updates
-- every frame which is wasteful.
--
-- What should be done is to enable verbose reporting (part of fsrv.lua)
--
local set = {}
local input_map = {}
local clean_set =
function()
for _, v in ipairs(set) do
delete_image(v)
end
end
for _, v in ipairs(cells) do
if type(v) == "table" then
v = v:export_content("video_buffer_handle")
end
if type(v) == "number" and valid_vid(v) then
-- In order to not break the source cell, we need to make a copy, the problem
-- is to pick a suitable scale and trigger on storage modifications. Just go with
-- the native storage size and let the layouting scheme deal with per-surface resizes.
--
-- Arcan does not do this yet, but be able to tag_transform a surface to react on
-- backing store changes is probably the way forward rather than adding more appl-
-- level logic on_resize.
local props = image_storage_properties(v)
local surf = null_surface(props.width, props.height)
-- vid limit might be reached
if not valid_vid(surf) then
warning("couldn't allocate composition-intermediate")
clean_set(set)
return
end
image_sharestorage(v, surf)
table.insert(set, surf)
image_tracetag(surf, "composite_intermediate_" .. tostring(v))
show_image(surf)
-- if we need to retain the input mapping for external clients, track that
-- though we might need to do something more fancy to survive across multiple
-- compose(compose()) (which is kindof insane)
if valid_vid(v, TYPE_FRAMESERVER) then
input_map[surf] = v
end
table.insert(set, surf)
else
warning("bad member in compose-cell source set")
end
end
if #set == 0 then
clean_set(cells)
warning("refusing empty composition-cell source set")
return
end
define_rendertarget(vid,
set, RENDERTARGET_DETACH, RENDERTARGET_NOSCALE, -1)
-- finally tie to the cell itself
local res = pipeworld_cell_template("compose", row, cfg)
res.input_map = input_map
res.compose_set = set
res.policy = policies[opts.policy]
res.rendertarget_wh = {w, h}
res:set_content(vid)
res.types = {
{},
{"video_buffer_handle"}
}
local focus = res.focus
res.focus =
function(cell, ...)
focus(cell, ...)
cell.cfg.input_grab(cell,
function(iotbl, sym, lutsym)
if not iotbl then -- grab release
return
end
cell.policy[2](cell, iotbl, sym, lutsym)
end
)
end
apply_solver(res)
return res
end,
{
-- resize
-- auto_relayout
--
}
|
test2 = {}
function test2.load()
print("Test 2!")
end
function test2.draw()
love.graphics.circle("line",250,450,50,20)
end |
ATTRIBUTE.name = "Chemistry"
ATTRIBUTE.category = "Professions"
ATTRIBUTE.description = "The skill of investigating properties and reactions of some substances." |