content
stringlengths 5
1.05M
|
|---|
function ScryerCavalier_OnEnterCombat(Unit,Event)
Unit:CastSpell(30931)
Unit:registerEvent("ScryerCavalier_Spellbreaker", 24000, 0)
end
function ScryerCavalier_Spellbreaker(Unit,Event)
Unit:FullCastSpellOnTarget(35871,Unit:GetClosestPlayer())
end
function ScryerCavalier_OnLeaveCombat(Unit,Event)
Unit:RemoveEvents()
end
function ScryerCavalier_OnDied(Unit,Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(22967, 1, "ScryerCavalier_OnEnterCombat")
RegisterUnitEvent(22967, 2, "ScryerCavalier_OnLeaveCombat")
RegisterUnitEvent(22967, 4, "ScryerCavalier_OnDied")
|
-- HANDLER KUPOWANIA JAK SKIN = 0 TO NIE DAJ RADY
-- Troche zmiennych
local temp_arr = nil
local order_step = 0 -- na jednym GUI to rozwiążemy
local orderGroupArray = nil
local clothes = false
local dummy = nil
local selected = 1
-- Tablica na ubranka
local clothes = {}
clothes[1] = {2, 100, "Ubranie dziwaka"}
clothes[2] = {7, 200, "Dres"}
clothes[3] = {1, 300, "Przetarte ubrania"}
clothes[4] = {298, 35, "Warszawski cwaniaczek"}
clothes[5] = {9, 150, "Brązowy garnitur"}
clothes[6] = {10, 70, "Babciny 1"}
clothes[7] = {11, 160, "Kelnerka 1"}
clothes[8] = {12, 180, "Czarna sukienka"}
clothes[9] = {13, 85, "Fioletowa koszulka"}
clothes[10] = {14, 90, "Koszula w kwiaty"}
clothes[11] = {15, 75, "Koszula w kratkę"}
clothes[12] = {16, 120, "Kamizelka odblaskowa"}
clothes[13] = {17, 210, "Ciemny garnitur"}
clothes[14] = {18, 140, "Szorty"}
clothes[15] = {19, 50, "Czerwone dresy"}
clothes[16] = {20, 60, "Dresy ortalionowe"}
clothes[17] = {21, 70, "Koszula w paski"}
clothes[18] = {22, 65, "Pomarańczowe dresy"}
clothes[19] = {23, 90, "Beżowe spodenki"}
clothes[20] = {24, 110, "Kurtka LS"}
clothes[21] = {25, 125, "Bejsbolówka"}
clothes[22] = {26, 135, "Komplet podróżniczy"}
clothes[23] = {27, 50, "Komplet budowniczy"}
clothes[24] = {28, 60, "Czarna podkoszulka"}
clothes[25] = {29, 90, "Bluza z kapturem"}
clothes[26] = {30, 60, "Szara podkoszulka"}
clothes[27] = {31, 80, "Komplet Rodeo damski"}
clothes[28] = {32, 40, "Zniszczona koszula"}
clothes[29] = {33, 50, "Bagienny komplet"}
clothes[30] = {34, 80, "Komplet Rodeo męski"}
clothes[31] = {35, 150, "Różowa koszula"}
clothes[32] = {36, 140, "Niebieskie spodenki"}
clothes[33] = {37, 140, "Jasno-niebieska koszula"}
clothes[34] = {38, 70, "Beżowo-biała koszulka"}
clothes[35] = {39, 85, "Brązowy żakiet"}
clothes[36] = {40, 210, "Jasno-czerwona sukienka"}
clothes[37] = {41, 120, "Aqua komplet"}
clothes[38] = {43, 115, "Fioletowa koszula"}
clothes[39] = {44, 95, "Niebieska koszula w kratkę"}
clothes[40] = {45, 120, "Zielone bermudy"}
clothes[41] = {46, 140, "Biała koszula"}
clothes[42] = {47, 75, "Jasno-brązowa koszula"}
clothes[43] = {48, 65, "Koszulka w paski"}
clothes[44] = {49, 140, "Komplet mistrza sztuk walki"}
clothes[45] = {50, 80, "Szary kombinezon"}
clothes[46] = {51, 140, "Komplet sportowy żółty"}
clothes[47] = {52, 140, "Komplet sportowy pasiak"}
clothes[48] = {53, 70, "Koszula w kropki"}
clothes[49] = {54, 85, "Różowa spódnica"}
clothes[50] = {55, 180, "Sukienka w paski"}
clothes[51] = {56, 110, "Koszulka na ramiączkach"}
clothes[52] = {57, 250, "Ciemny garnitur"}
clothes[53] = {58, 50, "Przetarte jeansy"}
clothes[54] = {59, 130, "Elegancka koszula"}
clothes[55] = {60, 100, "Jasno-brązowa koszulka"}
clothes[56] = {61, 300, "Strój pilota"}
clothes[57] = {62, 90, "Pidżama"}
clothes[58] = {63, 100, "Bikini"}
clothes[59] = {64, 110, "Minispódniczka"}
clothes[60] = {66, 140, "Niebiesko-biała bejsbolówka"}
clothes[61] = {67, 80, "Szara bluza"}
clothes[62] = {68, 190, "Czarna sutanna"}
clothes[63] = {69, 95, "Komplet jeanoswy"}
clothes[64] = {70, 250, "Kitel lekarski"}
clothes[65] = {71, 250, "Mundur PD1"}
clothes[66] = {72, 100, "Jeansy dzwony"}
clothes[67] = {73, 100, "Spodnie moro"}
clothes[68] = {75, 70, "Strój jednoczęściowy"}
clothes[69] = {76, 210, "Niebieski żakiet"}
clothes[70] = {77, 15, "Podarta spódnica"}
clothes[71] = {78, 10, "Porwane ubrania"}
clothes[72] = {79, 8, "Podarta kamizelka"}
clothes[73] = {80, 150, "Czerwony strój bokserski"}
clothes[74] = {81, 150, "Niebieski strój bokserski"}
clothes[75] = {82, 250, "Gwiazda Rocka 1"}
clothes[76] = {83, 250, "Gwiazda Rocka 2"}
clothes[77] = {84, 250, "Gwiazda Rocka 3"}
clothes[78] = {85, 100, "Sztuczne futro"}
clothes[79] = {87, 140, "Bikini"}
clothes[80] = {88, 150, "Jasna spódnica"}
clothes[81] = {89, 90, "Niebieska suknia"}
clothes[82] = {90, 160, "Czarna minispódniczka"}
clothes[83] = {91, 230, "Biała sukienka"}
clothes[84] = {92, 160, "Bikini z chustą"}
clothes[85] = {93, 140, "Czarne jeansy"}
clothes[86] = {94, 160, "Kremowa koszula"}
clothes[87] = {95, 65, "Wyblakła koszula"}
clothes[88] = {96, 140, "Komplet sportowy czarny"}
clothes[89] = {97, 120, "Czerwone bermudy"}
clothes[90] = {98, 150, "Koszula z kołnierzykiem"}
clothes[91] = {99, 140, "Komplet sporowy z kaskiem"}
clothes[92] = {100, 135, "Kamizelka skórzana"}
clothes[93] = {101, 110, "Zielona koszula"}
clothes[94] = {102, 80, "Fioletowe szorty"}
clothes[95] = {103, 80, "Fioletowa chusta"}
clothes[96] = {104, 75, "Fioletowy TankTop"}
clothes[97] = {105, 68, "Zielona bluza"}
clothes[98] = {106, 65, "Zielona koszula w kratkę"}
clothes[99] = {107, 80, "Zielony podkoszulek"}
clothes[100] = {108, 60, "Czarne dresy"}
clothes[101] = {109, 60, "Biały podkoszulek"}
clothes[102] = {110, 70, "Spodenki jeansowe"}
clothes[103] = {111, 210, "Czarny garnitur ze swetrem"}
clothes[104] = {112, 110, "Brązowa kurtka"}
clothes[105] = {113, 290, "Szary garnitur"}
clothes[106] = {114, 60, "Koszulka z kołnierzykiem"}
clothes[107] = {115, 90, "Luźne dresy"}
clothes[108] = {116, 80, "Biały TankTop"}
clothes[109] = {117, 160, "Czarna koszula"}
clothes[110] = {118, 160, "Czarna koszula"}
clothes[111] = {120, 275, "Szarawy garnitur"}
clothes[112] = {121, 110, "Koszulka ARMY"}
clothes[113] = {122, 140, "Beżowe luźne spodnie"}
clothes[114] = {123, 120, "Koszula z kwiatami"}
clothes[115] = {124, 110, "Obcisła koszulka"}
clothes[116] = {125, 130, "Skórzana kurtka"}
clothes[117] = {126, 150, "Ciemno-niebieska koszula"}
clothes[118] = {127, 220, "Brązowe futro"}
clothes[119] = {128, 90, "Podwinięte jeansy"}
clothes[120] = {129, 75, "Długa spódnica"}
clothes[121] = {130, 80, "Spódnica XXL"}
clothes[122] = {131, 110, "Slim jeansy"}
clothes[123] = {132, 50, "Stara koszula"}
clothes[124] = {133, 50, "Ubrodzone jeansy"}
clothes[125] = {134, 20, "Zniszczone ubrania"}
clothes[126] = {135, 15, "Rozpięta brudna koszula"}
clothes[127] = {136, 18, "Fioletowe porawne spodnie"}
clothes[128] = {137, 25, "Porwane jeansy"}
clothes[129] = {138, 160, "Białe bikini"}
clothes[130] = {139, 160, "Żółte bikini"}
clothes[131] = {140, 160, "Czerwone bikini"}
clothes[132] = {141, 240, "Żakiet w paski"}
clothes[133] = {142, 110, "Pomarańczowo-niebieska koszulka"}
clothes[134] = {143, 140, "Jasno-niebieska koszula"}
clothes[135] = {144, 135, "Czarno-czerwona koszulka"}
clothes[136] = {145, 140, "Stringi"}
clothes[137] = {146, 150, "Czarne szorty"}
clothes[138] = {147, 220, "Jasno-ciemny garnitur"}
clothes[139] = {148, 240, "Grynszpanowy żakiet"}
clothes[140] = {150, 220, "Atramentowy żakiet"}
clothes[141] = {151, 95, "Jeansowa spódnica"}
clothes[142] = {152, 100, "Czerwona minispódniczka"}
clothes[143] = {153, 210, "Garnitur z kaskiem"}
clothes[144] = {154, 150, "Kobaltowe szorty"}
clothes[145] = {155, 170, "Żółto-czerwona koszulka"}
clothes[146] = {156, 160, "Błękitna koszula"}
clothes[147] = {157, 90, "Jeanoswe szelki"}
clothes[148] = {158, 95, "Jeansowe szelki"}
clothes[149] = {159, 70, "Szelki"}
clothes[150] = {160, 35, "Zniszczona koszula"}
-- Kupowane
local buy_name = nil
local buy_price = nil
local buy_count = nil
local buy_uid = nil
--
-- Część na ubrania
--
-- Init GUI
addEventHandler("onClientResourceStart", resourceRoot, function()
local screenx, screeny = guiGetScreenSize()
----------------------------------------------------------
-- GUI
-- SKLEPOWE
----------------------------------------------------------
cloth_arrow_left = guiCreateStaticImage(screenx * 0.285, screeny * 0.70, screeny * 0.15, screeny * 0.15, "icons/a_left.png", false)
addEventHandler("onClientGUIClick", cloth_arrow_left, function() stepCloth("prev") end, false)
cloth_arrow_right = guiCreateStaticImage ( screenx * 0.625, screeny * 0.70, screeny * 0.15, screeny * 0.15, "icons/a_right.png", false )
addEventHandler("onClientGUIClick", cloth_arrow_right, function() stepCloth("next") end, false)
cloth_btn_buy = guiCreateStaticImage ( screenx * 0.41, screeny * 0.72, screeny * 0.12, screeny * 0.12, "icons/cash.png", false )
addEventHandler("onClientGUIClick", cloth_btn_buy, function() buyCloth() end, false)
cloth_btn_cancel = guiCreateStaticImage ( screenx * 0.52, screeny* 0.72, screeny * 0.12, screeny * 0.12, "icons/cancel.png", false )
addEventHandler("onClientGUIClick", cloth_btn_cancel, function() stopPlayerDummy() end, false)
setShoppingGui(false)
----------------------------------------------------------
-- GUI
-- ZAMAWIANIE
----------------------------------------------------------
wnd_order = guiCreateWindow(0.32, 0.24, 0.35, 0.52, "Zamów produkty", true)
guiWindowSetSizable(wnd_order, false)
grid_order = guiCreateGridList(0.03, 0.07, 0.94, 0.76, true, wnd_order)
guiGridListSetSortingEnabled(grid_order, false)
guiGridListAddColumn(grid_order, "Nr", 0.2)
guiGridListAddColumn(grid_order, "Kategoria", 0.8)
guiGridListAddRow(grid_order)
guiGridListSetItemText(grid_order, 0, 1, "1", false, false)
guiGridListSetItemText(grid_order, 0, 2, "Żarcie", false, false)
btn_order_sel = guiCreateButton(0.09, 0.87, 0.33, 0.08, "Wybierz", true, wnd_order)
addEventHandler("onClientGUIClick", btn_order_sel, function() finishStep() end, false)
guiSetProperty(btn_order_sel, "NormalTextColour", "FFAAAAAA")
btn_order_cancel = guiCreateButton(0.58, 0.87, 0.33, 0.08, "Anuluj", true, wnd_order)
addEventHandler("onClientGUIClick", btn_order_cancel, function() guiSetVisible(wnd_order, false) showCursor(false) guiSetInputEnabled(false) end, false)
guiSetProperty(btn_order_cancel, "NormalTextColour", "FFAAAAAA")
guiSetVisible(wnd_order, false)
----------------------------------------------------------
-- GUI
-- ILOŚĆ
----------------------------------------------------------
wnd_order_count = guiCreateWindow(0.30, 0.38, 0.40, 0.23, "Finalizacja zamówienia", true)
guiWindowSetSizable(wnd_order_count, false)
btn_count_accept = guiCreateButton(0.13, 0.61, 0.29, 0.21, "Gotowe", true, wnd_order_count)
addEventHandler("onClientGUIClick", btn_count_accept, function() checkoutPlayerOrder() end, false)
guiSetProperty(btn_count_accept, "NormalTextColour", "FFAAAAAA")
btn_count_cancel = guiCreateButton(0.57, 0.61, 0.30, 0.22, "Anuluj", true, wnd_order_count)
addEventHandler("onClientGUIClick", btn_count_cancel, function() guiSetVisible(wnd_order_count, false) showCursor(false) guiSetInputEnabled(false) end, false)
guiSetProperty(btn_count_cancel, "NormalTextColour", "FFAAAAAA")
ipt_order_count = guiCreateEdit(0.13, 0.33, 0.74, 0.21, "999", true, wnd_order_count)
guiEditSetMaxLength(ipt_order_count, 4)
lab_order_count = guiCreateLabel(0.13, 0.18, 0.73, 0.09, "Ile sztuk produktu chcesz kupić?", true, wnd_order_count)
guiSetVisible(wnd_order_count, false)
----------------------------------------------------------
-- GUI
-- Koszt
----------------------------------------------------------
wnd_cost = guiCreateWindow(0.30, 0.38, 0.40, 0.23, "Finalizacja zamówienia", true)
guiWindowSetSizable(wnd_cost, false)
btn_cost_accept = guiCreateButton(0.13, 0.61, 0.29, 0.21, "Gotowe", true, wnd_cost)
addEventHandler("onClientGUIClick", btn_cost_accept, function() setProductCost() end, false)
guiSetProperty(btn_cost_accept, "NormalTextColour", "FFAAAAAA")
btn_cost_cancel = guiCreateButton(0.57, 0.61, 0.30, 0.22, "Anuluj", true, wnd_cost)
addEventHandler("onClientGUIClick", btn_cost_cancel, function() guiSetVisible(wnd_cost, false) showCursor(false) guiSetInputEnabled(false) end, false)
guiSetProperty(btn_cost_cancel, "NormalTextColour", "FFAAAAAA")
ipt_order_cost = guiCreateEdit(0.13, 0.33, 0.74, 0.21, "999", true, wnd_cost)
guiEditSetMaxLength(ipt_order_cost, 4)
lab_order_cost = guiCreateLabel(0.13, 0.18, 0.73, 0.09, "Ile ma kosztować każda sztuka tego produktu?", true, wnd_cost)
guiSetVisible(wnd_cost, false)
----------------------------------------------------------
-- GUI
-- Finalizacja, ile kosztuje i czy akcept?
----------------------------------------------------------
wnd_final = guiCreateWindow(0.30, 0.38, 0.40, 0.23, "Finalizacja zamówienia", true)
guiWindowSetSizable(wnd_final, false)
btn_final_accept = guiCreateButton(0.13, 0.61, 0.29, 0.21, "Kup", true, wnd_final)
addEventHandler("onClientGUIClick", btn_final_accept, function() finalPlayerOrder() end, false)
guiSetProperty(btn_final_accept, "NormalTextColour", "FFAAAAAA")
btn_final_cancel = guiCreateButton(0.57, 0.61, 0.30, 0.22, "Anuluj", true, wnd_final)
addEventHandler("onClientGUIClick", btn_final_cancel, function() guiSetVisible(wnd_final, false) showCursor(false) guiSetInputEnabled(false) end, false)
guiSetProperty(btn_final_cancel, "NormalTextColour", "FFAAAAAA")
lab_final = guiCreateLabel(0.13, 0.18, 0.73, 0.09, "Czy jesteś pewien, że chcesz kupić DE x1000?", true, wnd_final)
lab_final_price = guiCreateLabel(0.13, 0.33, 0.74, 0.12, "Całkowity koszt: $1500", true, wnd_final)
guiSetVisible(wnd_final, false)
end)
-- GUI func
function setShoppingGui(state)
guiSetVisible(cloth_arrow_right, state)
guiSetVisible(cloth_arrow_left, state)
guiSetVisible(cloth_btn_cancel, state)
guiSetVisible(cloth_btn_buy, state)
end
function buyCloth()
local p_money = tonumber(getElementData(localPlayer, "player.cash"))
local cost = tonumber(clothes[selected][2])
if cost > p_money then
outputChatBox("Błąd: Nie masz wystarczająco pieniędzy.")
return
end
stopPlayerDummy()
setPlayerMoney(p_money - cost)
setElementData(localPlayer, "player.cash", (p_money - cost))
triggerServerEvent("onPlayerClothBuy", getRootElement(), getLocalPlayer(), tonumber(clothes[selected][1]), clothes[selected][3])
end
function stepCloth(nav)
if nav == "prev" then
if (selected - 1) < 1 then
selected = 1
else
selected = selected - 1
end
else
if (selected + 1) > table.getn(clothes) then
selected = 1
else
selected = selected + 1
end
end
setElementModel(dummy, clothes[selected][1])
end
-- Spawnowanie manekina, freezowanie gracza i w ogóle początek kupowania ciuchów
function spawnPlayerDummy()
local static_x, static_y, static_z = getElementPosition(localPlayer)
local x, y, z = getElementPosition(localPlayer)
local a, b, r = getElementRotation(localPlayer)
x = x - math.sin ( math.rad(r) ) * 4
y = y + math.cos ( math.rad(r) ) * 4
if dummy == nil then
dummy = createPed ( 0, x, y, z )
-- Poprawka z kamerą
local cam = getCamera()
detachElements( cam )
setElementPosition( cam, 0,0,0 )
setCameraTarget(localPlayer)
setElementInterior(dummy, getElementInterior(localPlayer))
setElementDimension(dummy, getElementDimension(localPlayer))
setElementRotation(dummy, 0, 0, r + 180)
addEventHandler("onClientRender",getRootElement(), drawDummyText)
setElementFrozen(localPlayer, true)
setCameraMatrix ( static_x, static_y, static_z, x, y, z )
selected = 1
setShoppingGui(true)
showCursor(true)
guiSetInputEnabled(true)
end
end
-- Koniec kupowania
function stopPlayerDummy()
removeEventHandler("onClientRender", getRootElement(), drawDummyText)
destroyElement(dummy)
setElementFrozen(localPlayer, false)
setCameraTarget ( localPlayer )
dummy = nil
setShoppingGui(false)
showCursor(false)
guiSetInputEnabled(false)
end
function drawDummyText()
if dummy ~= nil then
local px, py, pz = getElementPosition(localPlayer)
local x, y, z = getPedBonePosition( dummy, 8 )
local is_coll = processLineOfSight(px, py, pz, x, y, z, true, false, false, true, false, false)
if is_coll == false then
local distance = getDistanceBetweenPoints3D ( px, py, pz, x, y, z )
if distance < 15.0 then
local sX, sY = getScreenFromWorldPosition( x, y, z + 0.25 );
if sX then
dxDrawText("#006600$"..clothes[selected][2], sX, sY, sX, sY, tocolor(5,150,200,255), 2.0, "pricedown", "center", "bottom", false, false, false, true )
end
else
stopPlayerDummy()
end
end
end
end
-- Pokazywanie asortymentu
function showPlayerBuyMenu( theArray)
if theArray then
temp_arr = theArray
guiGridListClear(grid_shopping)
local item_num = table.getn(theArray)
for i = 0, item_num do
guiGridListAddRow(grid_shopping)
end
for i = 0, item_num do
guiGridListSetItemText(grid_shopping, i, 1, theArray[i]["product_name"], false, false)
guiGridListSetItemText(grid_shopping, i, 2, theArray[i]["product_count"], false, false)
guiGridListSetItemText(grid_shopping, i, 3, "$"..theArray[i]["product_price"], false, false)
end
guiSetVisible(wnd_shopping, true)
guiSetInputEnabled(true)
showCursor(true)
end
end
-- kupowajka
function finishPlayerShopping()
-- pobieranie select grid ID, sprawdzanie czy ma wystarczająco kasiory etc.
local index = guiGridListGetSelectedItem ( grid_shopping )
local p_money = tonumber(getElementData(localPlayer, "player.cash"))
local cost = temp_arr[index]["product_price"]
if temp_arr[index]["product_price"] > p_money then
outputChatBox("Błąd: Nie masz wystarczająco pieniędzy.", 200, 200, 200)
return
end
if temp_arr[index]["product_count"] <= 0 then
outputChatBox("Błąd: Ten produkt już się skończył.", 200, 200, 200)
return
end
-- pobierz kaskę
setElementData(localPlayer, "player.cash", (p_money - cost))
setPlayerMoney(p_money - cost)
-- dodaj itema i odejmij jeden z p_count
if temp_arr[index]["product_count"] > 1 then
triggerServerEvent("onPlayerCreateItemRequest", getRootElement(), getLocalPlayer(), temp_arr[index]["product_name"], temp_arr[index]["product_type"], temp_arr[index]["product_value1"], temp_arr[index]["product_value2"], temp_arr[index]["product_uid"], false)
else
triggerServerEvent("onPlayerCreateItemRequest", getRootElement(), getLocalPlayer(), temp_arr[index]["product_name"], temp_arr[index]["product_type"], temp_arr[index]["product_value1"], temp_arr[index]["product_value2"], temp_arr[index]["product_uid"], true)
end
temp_arr[index]["product_count"] = temp_arr[index]["product_count"] - 1
end
-- Wypełnianie tabelki itemkami
function showOrders(array, type)
-- POKAŻ KATEGORIE
if type == 1 then
orderGroupArray = array
guiGridListClear(grid_order)
order_step = 1
for i = 0, table.getn(array) do
guiGridListAddRow(grid_order)
end
for i=0, table.getn(array) do
guiGridListSetItemText(grid_order, i, 1, array[i]["cat_uid"], false, false) --uid
guiGridListSetItemText(grid_order, i, 2, array[i]["cat_name"], false, false) --nazwa
end
end
-- POKAŻ PRODUKTY
if type == 2 then
order_step = 2
orderGroupArray = array
guiGridListClear(grid_order)
for i = 0, table.getn(array) do
guiGridListAddRow(grid_order)
end
for i=0, table.getn(array) do
guiGridListSetItemText(grid_order, i, 1, array[i]["order_uid"], false, false) --uid
guiGridListSetItemText(grid_order, i, 2, array[i]["order_name"], false, false) --nazwa
end
end
guiSetVisible(wnd_order, true)
showCursor(true)
guiSetInputEnabled(true)
end
addEvent("showOrders", true)
addEventHandler("showOrders", localPlayer, showOrders)
function finishStep()
if order_step == 1 then
local option, _ = guiGridListGetSelectedItem ( grid_order )
local cat_id = orderGroupArray[option]["cat_uid"]
triggerServerEvent( "onPlayerShowAvaiableProducts", getRootElement(), getLocalPlayer(), cat_id )
end
if order_step == 2 then
local option, _ = guiGridListGetSelectedItem ( grid_order )
local name = orderGroupArray[option]["order_name"]
buy_name = name
buy_price = tonumber(orderGroupArray[option]["order_price"])
buy_uid = tonumber(orderGroupArray[option]["order_uid"])
guiSetText(lab_order_count, "Ile sztuk produktu "..buy_name.." chcesz kupić?")
guiSetVisible(wnd_order, false)
guiSetVisible(wnd_order_count, true)
--local message = "Kupujesz "..name..". To kosztuje $"..orderGroupArray[option]["order_price"].." za sztukę"
end
end
function checkoutPlayerOrder()
-- sprawdź kasę, sprawdź czy ilość jest OK
local count = tonumber(guiGetText(ipt_order_count))
if not count then
outputChatBox("Błąd: Podano błędną ilość!")
return
end
if count > 9999 or count < 1 then
outputChatBox("Błąd: Podano błędną ilość!")
return
end
buy_count = count
guiSetText(lab_final, "Czy jesteś pewien, że chcesz kupić "..buy_name.." x"..buy_count.."?")
guiSetText(lab_final_price, "Całkowity koszt zamówienia: $"..tonumber(buy_count * tonumber(buy_price)).." ($".. buy_price .."/sztuka)")
guiSetVisible(wnd_order_count, false)
--guiSetVisible(wnd_final, true)
guiSetText(ipt_order_cost, "")
guiSetVisible(wnd_cost, true)
end
function finalPlayerOrder()
local cash = tonumber(buy_count * tonumber(buy_price))
local pcash = tonumber(getElementData(localPlayer, "player.cash"))
if cash > pcash then
outputChatBox("Błąd: Nie posiadasz tyle pieniędzy!")
return
end
local beforeCash = pcash - cash
triggerServerEvent("onPlayerFinishOrder", getRootElement(), getLocalPlayer(), beforeCash, buy_uid, buy_count, productPrice)
guiSetVisible(wnd_final, false)
guiSetInputEnabled(false)
showCursor(false)
end
function setProductCost()
local cost = tonumber(guiGetText(ipt_order_cost))
if not cost then
outputChatBox("Błąd: Podano błędną cenę!")
return
end
if cost > 9999 or cost < 1 then
outputChatBox("Błąd: Podano błędną cenę!")
return
end
productPrice = cost
guiSetVisible(wnd_cost, false)
guiSetVisible(wnd_final, true)
end
--
-- Eventy
--
addEvent("onPlayerStartShopping", true)
addEventHandler("onPlayerStartShopping", localPlayer, showPlayerBuyMenu)
addEvent("onPlayerStartClothesSelect", true)
addEventHandler("onPlayerStartClothesSelect", localPlayer, spawnPlayerDummy)
|
local Pattern = Pattern
local M_PI = math.pi
local sw, sh = stage:getSize()
stage:addChild(DisplayShape.new(sw, sh)
:setSource(Pattern.image(assets:loadImage("bg.png")):setExtend("repeat"))
:paint())
local a = assets:loadDisplay("planet-earth.png"):setPosition(sw / 2, sh / 2):setScale(0.5):setAnchor(0.5, 0.5)
stage:addChild(a)
local s = nil
local count = 0;
local function onEnterFrame(d, e)
count = count + 0.1
stage:removeChild(s)
s = nil
s = DisplayShape.new(sw / 2, sh / 2)
:setAnchor(0.5, 0.5)
:setPosition(sw / 2, sh / 2)
s:setLineWidth(10)
:moveTo(40 + math.sin(count) * 40, 40 + math.cos(count) * 40)
:lineTo(260 + math.cos(count) * 40, 40 + math.sin(count) * 40)
:lineTo(260 + math.sin(count) * 40, 200 + math.cos(count) * 40)
:lineTo(40 + math.cos(count)* 40, 200 + math.sin(count) * 40)
:lineTo(40 + math.sin(count) * 40, 40 + math.cos(count) * 40)
:closePath()
:setSourceColor(1, 1, 0, 0.5)
:fillPreserve()
:setSourceColor(1, 0, 0, 1)
:stroke()
a:setRotation(a:getRotation() + 1)
s:setRotation(count * 0.02 * 360)
stage:addChild(s)
end
stage:addEventListener("enter-frame", onEnterFrame)
stage:showfps(true)
|
Notification = Widget:subclass("Notification")
function Notification:initialize(name, x, y, width, height, title, body, fg, bg, progresscolor, opacity)
Widget.initialize(self, name, x, y, width, height)
self.title = title
self.body = body
self.fg = fg
self.bg = bg
self.progresscolor = progresscolor
self.opacity = opacity
self.progress = 0
self.bodyparts = {}
end
function Notification:createComponents(bridge)
-- Progress
self.components[1] = bridge.addBox(self.x, self.y, self.width * self.progress, 1, self.progresscolor, self.opacity)
self.components[1].setZ(-1)
-- Background
self.components[2] = bridge.addBox(self.x, self.y, self.width, self.height, self.bg, self.opacity)
self.components[2].setZ(-2)
-- Text
local charlen = textWidthScale(bridge, "M", 0.5)
-- Title
self.components[3] = bridge.addText(self.x + 2, self.y + 3, self.title, self.fg)
self.components[3].setScale(0.57)
-- Body
local wrapped = wrapText(self.body, self.width / charlen)
local ydiff = 9
for i,line in ipairs(wrapped) do
self.components[3+i] = bridge.addText(self.x + 2, self.y + ydiff, line, self.fg)
self.components[3+i].setScale(0.5)
ydiff = ydiff + 5
end
end
function Notification:setProgress(val)
self.progress = val
self.components[1].setWidth(self.width * self.progress)
end
|
--- @param lsp LSP
--- @param params table
--- @return boolean
return function (lsp, params)
local doc = params.textDocument
lsp:close(doc.uri)
return true
end
|
local K = unpack(select(2, ...))
local _G = _G
local print = _G.print
local CreateFrame = _G.CreateFrame
local GetSpellInfo = _G.GetSpellInfo
local IsPlayerSpell = _G.IsPlayerSpell
local function Defaults(priorityOverride)
return {["enable"] = true, ["priority"] = priorityOverride or 0, ["stackThreshold"] = 0}
end
local function SpellName(id)
local name = GetSpellInfo(id)
if not name then
print("|cff3c9bedKkthnxUI:|r SpellID is not valid: " .. id .. ". Please check for an updated version, if none exists report to Kkthnx in Discord.")
return "Impale"
else
return name
end
end
K.DebuffsTracking = {}
K.TicksPenance = SpellName(47540)
K.DebuffsTracking["RaidDebuffs"] = {
["type"] = "Whitelist",
["spells"] = {
-- Mythic+ Dungeons
[209858] = Defaults(), -- Necrotic
[226512] = Defaults(), -- Sanguine
[240559] = Defaults(), -- Grievous
[240443] = Defaults(), -- Bursting
[196376] = Defaults(), -- Grievous Tear
[288388] = Defaults(), -- Reap Soul
[288694] = Defaults(), -- Shadow Smash
--BFA Dungeons
--Freehold
[258323] = Defaults(), -- Infected Wound
[257775] = Defaults(), -- Plague Step
[257908] = Defaults(), -- Oiled Blade
[257436] = Defaults(), -- Poisoning Strike
[274389] = Defaults(), -- Rat Traps
[274555] = Defaults(), -- Scabrous Bites
[258875] = Defaults(), -- Blackout Barrel
[256363] = Defaults(), -- Ripper Punch
--Shrine of the Storm
[264560] = Defaults(), -- Choking Brine
[268233] = Defaults(), -- Electrifying Shock
[268322] = Defaults(), -- Touch of the Drowned
[268896] = Defaults(), -- Mind Rend
[268104] = Defaults(), -- Explosive Void
[267034] = Defaults(), -- Whispers of Power
[276268] = Defaults(), -- Heaving Blow
[264166] = Defaults(), -- Undertow
[264526] = Defaults(), -- Grasp of the Depths
[274633] = Defaults(), -- Sundering Blow
[268214] = Defaults(), -- Carving Flesh
[267818] = Defaults(), -- Slicing Blast
[268309] = Defaults(), -- Unending Darkness
[268317] = Defaults(), -- Rip Mind
[268391] = Defaults(), -- Mental Assault
[274720] = Defaults(), -- Abyssal Strike
--Siege of Boralus
[257168] = Defaults(), -- Cursed Slash
[272588] = Defaults(), -- Rotting Wounds
[272571] = Defaults(), -- Choking Waters
[274991] = Defaults(), -- Putrid Waters
[275835] = Defaults(), -- Stinging Venom Coating
[273930] = Defaults(), -- Hindering Cut
[257292] = Defaults(), -- Heavy Slash
[261428] = Defaults(), -- Hangman's Noose
[256897] = Defaults(), -- Clamping Jaws
[272874] = Defaults(), -- Trample
[273470] = Defaults(), -- Gut Shot
[272834] = Defaults(), -- Viscous Slobber
[257169] = Defaults(), -- Terrifying Roar
[272713] = Defaults(), -- Crushing Slam
-- Tol Dagor
[258128] = Defaults(), -- Debilitating Shout
[265889] = Defaults(), -- Torch Strike
[257791] = Defaults(), -- Howling Fear
[258864] = Defaults(), -- Suppression Fire
[257028] = Defaults(), -- Fuselighter
[258917] = Defaults(), -- Righteous Flames
[257777] = Defaults(), -- Crippling Shiv
[258079] = Defaults(), -- Massive Chomp
[258058] = Defaults(), -- Squeeze
[260016] = Defaults(), -- Itchy Bite
[257119] = Defaults(), -- Sand Trap
[260067] = Defaults(), -- Vicious Mauling
[258313] = Defaults(), -- Handcuff
[259711] = Defaults(), -- Lockdown
[256198] = Defaults(), -- Azerite Rounds: Incendiary
[256101] = Defaults(), -- Explosive Burst (mythic)
[256105] = Defaults(), -- Explosive Burst (mythic+)
[256044] = Defaults(), -- Deadeye
[256474] = Defaults(), -- Heartstopper Venom
--Waycrest Manor
[260703] = Defaults(), -- Unstable Runic Mark
[263905] = Defaults(), -- Marking Cleave
[265880] = Defaults(), -- Dread Mark
[265882] = Defaults(), -- Lingering Dread
[264105] = Defaults(), -- Runic Mark
[264050] = Defaults(), -- Infected Thorn
[261440] = Defaults(), -- Virulent Pathogen
[263891] = Defaults(), -- Grasping Thorns
[264378] = Defaults(), -- Fragment Soul
[266035] = Defaults(), -- Bone Splinter
[266036] = Defaults(), -- Drain Essence
[260907] = Defaults(), -- Soul Manipulation
[260741] = Defaults(), -- Jagged Nettles
[264556] = Defaults(), -- Tearing Strike
[265760] = Defaults(), -- Thorned Barrage
[260551] = Defaults(), -- Soul Thorns
[263943] = Defaults(), -- Etch
[265881] = Defaults(), -- Decaying Touch
[261438] = Defaults(), -- Wasting Strike
[268202] = Defaults(), -- Death Lens
[278456] = Defaults(), -- Infest
-- Atal'Dazar
[252781] = Defaults(), -- Unstable Hex
[250096] = Defaults(), -- Wracking Pain
[250371] = Defaults(), -- Lingering Nausea
[253562] = Defaults(), -- Wildfire
[255582] = Defaults(), -- Molten Gold
[255041] = Defaults(), -- Terrifying Screech
[255371] = Defaults(), -- Terrifying Visage
[252687] = Defaults(), -- Venomfang Strike
[254959] = Defaults(), -- Soulburn
[255814] = Defaults(), -- Rending Maul
[255421] = Defaults(), -- Devour
[255434] = Defaults(), -- Serrated Teeth
[256577] = Defaults(), -- Soulfeast
--King's Rest
[270492] = Defaults(), -- Hex
[267763] = Defaults(), -- Wretched Discharge
[276031] = Defaults(), -- Pit of Despair
[265773] = Defaults(), -- Spit Gold
[270920] = Defaults(), -- Seduction
[270865] = Defaults(), -- Hidden Blade
[271564] = Defaults(), -- Embalming Fluid
[270507] = Defaults(), -- Poison Barrage
[267273] = Defaults(), -- Poison Nova
[270003] = Defaults(), -- Suppression Slam
[270084] = Defaults(), -- Axe Barrage
[267618] = Defaults(), -- Drain Fluids
[267626] = Defaults(), -- Dessication
[270487] = Defaults(), -- Severing Blade
[266238] = Defaults(), -- Shattered Defenses
[266231] = Defaults(), -- Severing Axe
[266191] = Defaults(), -- Whirling Axes
[272388] = Defaults(), -- Shadow Barrage
[271640] = Defaults(), -- Dark Revelation
[268796] = Defaults(), -- Impaling Spear
[268419] = Defaults(), -- Gale Slash
--Motherlode
[263074] = Defaults(), -- Festering Bite
[280605] = Defaults(), -- Brain Freeze
[257337] = Defaults(), -- Shocking Claw
[270882] = Defaults(), -- Blazing Azerite
[268797] = Defaults(), -- Transmute: Enemy to Goo
[259856] = Defaults(), -- Chemical Burn
[269302] = Defaults(), -- Toxic Blades
[280604] = Defaults(), -- Iced Spritzer
[257371] = Defaults(), -- Tear Gas
[257544] = Defaults(), -- Jagged Cut
[268846] = Defaults(), -- Echo Blade
[262794] = Defaults(), -- Energy Lash
[262513] = Defaults(), -- Azerite Heartseeker
[260829] = Defaults(), -- Homing Missle (travelling)
[260838] = Defaults(), -- Homing Missle (exploded)
[263637] = Defaults(), -- Clothesline
--Temple of Sethraliss
[269686] = Defaults(), -- Plague
[268013] = Defaults(), -- Flame Shock
[268008] = Defaults(), -- Snake Charm
[273563] = Defaults(), -- Neurotoxin
[272657] = Defaults(), -- Noxious Breath
[267027] = Defaults(), -- Cytotoxin
[272699] = Defaults(), -- Venomous Spit
[263371] = Defaults(), -- Conduction
[272655] = Defaults(), -- Scouring Sand
[263914] = Defaults(), -- Blinding Sand
[263958] = Defaults(), -- A Knot of Snakes
[266923] = Defaults(), -- Galvanize
[268007] = Defaults(), -- Heart Attack
--Underrot
[265468] = Defaults(), -- Withering Curse
[278961] = Defaults(), -- Decaying Mind
[259714] = Defaults(), -- Decaying Spores
[272180] = Defaults(), -- Death Bolt
[272609] = Defaults(), -- Maddening Gaze
[269301] = Defaults(), -- Putrid Blood
[265533] = Defaults(), -- Blood Maw
[265019] = Defaults(), -- Savage Cleave
[265377] = Defaults(), -- Hooked Snare
[265625] = Defaults(), -- Dark Omen
[260685] = Defaults(), -- Taint of G'huun
[266107] = Defaults(), -- Thirst for Blood
[260455] = Defaults(), -- Serrated Fangs
--Operation: Mechagon
[291928] = Defaults(), -- Giga-Zap
[292267] = Defaults(), -- Giga-Zap
[302274] = Defaults(), -- Fulminating Zap
[298669] = Defaults(), -- Taze
[295445] = Defaults(), -- Wreck
[294929] = Defaults(), -- Blazing Chomp
[297257] = Defaults(), -- Electrical Charge
[294855] = Defaults(), -- Blossom Blast
[291972] = Defaults(), -- Explosive Leap
[285443] = Defaults(), -- "Hidden" Flame Cannon
[291974] = Defaults(), -- Obnoxious Monologue
[296150] = Defaults(), -- Vent Blast
[298602] = Defaults(), -- Smoke Cloud
[296560] = Defaults(), -- Clinging Static
[297283] = Defaults(), -- Cave In
[291914] = Defaults(), -- Cutting Beam
[302384] = Defaults(), -- Static Discharge
-- Uldir
-- MOTHER
[268277] = Defaults(), -- Purifying Flame
[268253] = Defaults(), -- Surgical Beam
[268095] = Defaults(), -- Cleansing Purge
[267787] = Defaults(), -- Sundering Scalpel
[268198] = Defaults(), -- Clinging Corruption
[267821] = Defaults(), -- Defense Grid
-- Vectis
[265127] = Defaults(), -- Lingering Infection
[265178] = Defaults(), -- Mutagenic Pathogen
[265206] = Defaults(), -- Immunosuppression
[265212] = Defaults(), -- Gestate
[265129] = Defaults(), -- Omega Vector
[267160] = Defaults(), -- Omega Vector
[267161] = Defaults(), -- Omega Vector
[267162] = Defaults(), -- Omega Vector
[267163] = Defaults(), -- Omega Vector
[267164] = Defaults(), -- Omega Vector
-- Mythrax
--[272146] = Defaults(), -- Annihilation
[272536] = Defaults(), -- Imminent Ruin
[274693] = Defaults(), -- Essence Shear
[272407] = Defaults(), -- Oblivion Sphere
-- Fetid Devourer
[262313] = Defaults(), -- Malodorous Miasma
[262292] = Defaults(), -- Rotting Regurgitation
[262314] = Defaults(), -- Deadly Disease
-- Taloc
[270290] = Defaults(), -- Blood Storm
[275270] = Defaults(), -- Fixate
[271224] = Defaults(), -- Plasma Discharge
[271225] = Defaults(), -- Plasma Discharge
-- Zul
[273365] = Defaults(), -- Dark Revelation
[273434] = Defaults(), -- Pit of Despair
--[274195] = Defaults(), -- Corrupted Blood
[272018] = Defaults(), -- Absorbed in Darkness
[274358] = Defaults(), -- Rupturing Blood
-- Zek'voz, Herald of N'zoth
[265237] = Defaults(), -- Shatter
[265264] = Defaults(), -- Void Lash
[265360] = Defaults(), -- Roiling Deceit
[265662] = Defaults(), -- Corruptor's Pact
[265646] = Defaults(), -- Will of the Corruptor
-- G'huun
[263436] = Defaults(), -- Imperfect Physiology
[263227] = Defaults(), -- Putrid Blood
[263372] = Defaults(), -- Power Matrix
[272506] = Defaults(), -- Explosive Corruption
[267409] = Defaults(), -- Dark Bargain
[267430] = Defaults(), -- Torment
[263235] = Defaults(), -- Blood Feast
[270287] = Defaults(), -- Blighted Ground
-- Siege of Zuldazar
-- Ra'wani Kanae/Frida Ironbellows
[283573] = Defaults(), -- Sacred Blade
[283617] = Defaults(), -- Wave of Light
[283651] = Defaults(), -- Blinding Faith
[284595] = Defaults(), -- Penance
[283582] = Defaults(), -- Consecration
-- Grong
[285998] = Defaults(), -- Ferocious Roar
[283069] = Defaults(), -- Megatomic Fire
[285671] = Defaults(), -- Crushed
[285875] = Defaults(), -- Rending Bite
--[282010] = Defaults(), -- Shaken
-- Jaina
[285253] = Defaults(), -- Ice Shard
[287993] = Defaults(), -- Chilling Touch
[287365] = Defaults(), -- Searing Pitch
[288038] = Defaults(), -- Marked Target
[285254] = Defaults(), -- Avalanche
[287626] = Defaults(), -- Grasp of Frost
[287490] = Defaults(), -- Frozen Solid
[287199] = Defaults(), -- Ring of Ice
[288392] = Defaults(), -- Vengeful Seas
-- Stormwall Blockade
[284369] = Defaults(), -- Sea Storm
[284410] = Defaults(), -- Tempting Song
[284405] = Defaults(), -- Tempting Song
[284121] = Defaults(), -- Thunderous Boom
[286680] = Defaults(), -- Roiling Tides
-- Opulence
[286501] = Defaults(), -- Creeping Blaze
[283610] = Defaults(), -- Crush
[289383] = Defaults(), -- Chaotic Displacement
[285479] = Defaults(), -- Flame Jet
[283063] = Defaults(), -- Flames of Punishment
[283507] = Defaults(), -- Volatile Charge
-- King Rastakhan
[284995] = Defaults(), -- Zombie Dust
[285349] = Defaults(), -- Plague of Fire
[285044] = Defaults(), -- Toad Toxin
[284831] = Defaults(), -- Scorching Detonation
[289858] = Defaults(), -- Crushed
[284662] = Defaults(), -- Seal of Purification
[284676] = Defaults(), -- Seal of Purification
[285178] = Defaults(), -- Serpent's Breath
[285010] = Defaults(), -- Poison Toad Slime
-- Jadefire Masters
[282037] = Defaults(), -- Rising Flames
[284374] = Defaults(), -- Magma Trap
[285632] = Defaults(), -- Stalking
[288151] = Defaults(), -- Tested
[284089] = Defaults(), -- Successful Defense
[286988] = Defaults(), -- Searing Embers
-- Mekkatorque
[288806] = Defaults(), -- Gigavolt Blast
[289023] = Defaults(), -- Enormous
[286646] = Defaults(), -- Gigavolt Charge
[288939] = Defaults(), -- Gigavolt Radiation
[284168] = Defaults(), -- Shrunk
[286516] = Defaults(), -- Anti-Tampering Shock
[286480] = Defaults(), -- Anti-Tampering Shock
[284214] = Defaults(), -- Trample
-- Conclave of the Chosen
[284663] = Defaults(), -- Bwonsamdi's Wrath
[282444] = Defaults(), -- Lacerating Claws
[282592] = Defaults(), -- Bleeding Wounds
[282209] = Defaults(), -- Mark of Prey
[285879] = Defaults(), -- Mind Wipe
[282135] = Defaults(), -- Crawling Hex
[286060] = Defaults(), -- Cry of the Fallen
[282447] = Defaults(), -- Kimbul's Wrath
[282834] = Defaults(), -- Kimbul's Wrath
[286811] = Defaults(), -- Akunda's Wrath
[286838] = Defaults(), -- Static Orb
--Crucible of Storms
--The Restless Cabal
[282386] = Defaults(), -- Aphotic Blast
[282384] = Defaults(), -- Shear Mind
[282566] = Defaults(), -- Promises of Power
[282561] = Defaults(), -- Dark Herald
[282432] = Defaults(), -- Crushing Doubt
[282589] = Defaults(), -- Mind Scramble
[292826] = Defaults(), -- Mind Scramble
--Fa'thuul the Feared
[284851] = Defaults(), -- Touch of the End
[286459] = Defaults(), -- Feedback: Void
[286457] = Defaults(), -- Feedback: Ocean
[286458] = Defaults(), -- Feedback: Storm
[285367] = Defaults(), -- Piercing Gaze of N'Zoth
[284733] = Defaults(), -- Embrace of the Void
[284722] = Defaults(), -- Umbral Shell
[285345] = Defaults(), -- Maddening Eyes of N'Zoth
[285477] = Defaults(), -- Obscurity
[285652] = Defaults(), -- Insatiable Torment
--Eternal Palace
--Lady Ashvane
[296693] = Defaults(), -- Waterlogged
[296725] = Defaults(), -- Barnacle Bash
[296942] = Defaults(), -- Arcing Azerite
[296938] = Defaults(), -- Arcing Azerite
[296941] = Defaults(), -- Arcing Azerite
[296939] = Defaults(), -- Arcing Azerite
[296943] = Defaults(), -- Arcing Azerite
[296940] = Defaults(), -- Arcing Azerite
[296752] = Defaults(), -- Cutting Coral
[297333] = Defaults(), -- Briny Bubble
[297397] = Defaults(), -- Briny Bubble
--Abyssal Commander Sivara
--[294715] = Defaults(), -- Toxic Brand
--[294711] = Defaults(), -- Frost Mark
[300701] = Defaults(), -- Rimefrost
[300705] = Defaults(), -- Septic Taint
[294847] = Defaults(), -- Unstable Mixture
[295850] = Defaults(), -- Delirious
[295421] = Defaults(), -- Overflowing Venom
[295807] = Defaults(), -- Frozen
[300883] = Defaults(), -- Inversion Sickness
[295705] = Defaults(), -- Toxic Bolt
--The Queen’s Court
[301830] = Defaults(), -- Pashmar's Touch
[296851] = Defaults(), -- Fanatical Verdict
[297836] = Defaults(), -- Potent Spark
[297586] = Defaults(), -- Suffering
[304410] = Defaults(), -- Repeat Performance
[299914] = Defaults(), -- Frenetic Charge
[303306] = Defaults(), -- Sphere of Influence
[300545] = Defaults(), -- Mighty Rupture
--Radiance of Azshara
[296566] = Defaults(), -- Tide Fist
[296737] = Defaults(), -- Arcane Bomb
[296746] = Defaults(), -- Arcane Bomb
[295920] = Defaults(), -- Ancient Tempest
[296462] = Defaults(), -- Squall Trap
[299152] = Defaults(), -- Waterlogged
--Orgozoa
[298156] = Defaults(), -- Desensitizing Sting
[298306] = Defaults(), -- Incubation Fluid
--Blackwater Behemoth
[292127] = Defaults(), -- Darkest Depths
[292138] = Defaults(), -- Radiant Biomass
[292167] = Defaults(), -- Toxic Spine
[301494] = Defaults(), -- Piercing Barb
--Za’qul
[295495] = Defaults(), -- Mind Tether
[295480] = Defaults(), -- Mind Tether
[295249] = Defaults(), -- Delirium Realm
[303819] = Defaults(), -- Nightmare Pool
[293509] = Defaults(), -- Manifest Nightmares
[295327] = Defaults(), -- Shattered Psyche
[294545] = Defaults(), -- Portal of Madness
[298192] = Defaults(), -- Dark Beyond
[292963] = Defaults(), -- Dread
[300133] = Defaults(), -- Snapped
--Queen Azshara
[298781] = Defaults(), -- Arcane Orb
[297907] = Defaults(), -- Cursed Heart
[302999] = Defaults(), -- Arcane Vulnerability
[302141] = Defaults(), -- Beckon
[299276] = Defaults(), -- Sanction
[303657] = Defaults(), -- Arcane Burst
[298756] = Defaults(), -- Serrated Edge
[301078] = Defaults(), -- Charged Spear
[298014] = Defaults(), -- Cold Blast
[298018] = Defaults(), -- Frozen
}
}
-- CC DEBUFFS (TRACKING LIST)
K.DebuffsTracking["CCDebuffs"] = {
["type"] = "Whitelist",
["spells"] = {
--Death Knight
[47476] = Defaults(2), -- Strangulate
[108194] = Defaults(4), -- Asphyxiate UH
[221562] = Defaults(4), -- Asphyxiate Blood
[207171] = Defaults(4), -- Winter is Coming
[206961] = Defaults(3), -- Tremble Before Me
[207167] = Defaults(4), -- Blinding Sleet
[212540] = Defaults(1), -- Flesh Hook (Pet)
[91807] = Defaults(1), -- Shambling Rush (Pet)
[204085] = Defaults(1), -- Deathchill
[233395] = Defaults(1), -- Frozen Center
[212332] = Defaults(4), -- Smash (Pet)
[212337] = Defaults(4), -- Powerful Smash (Pet)
[91800] = Defaults(4), -- Gnaw (Pet)
[91797] = Defaults(4), -- Monstrous Blow (Pet)
-- [?????] = Defaults(), -- Reanimation (missing data)
[210141] = Defaults(3), -- Zombie Explosion
--Demon Hunter
[207685] = Defaults(4), -- Sigil of Misery
[217832] = Defaults(3), -- Imprison
[221527] = Defaults(5), -- Imprison (Banished version)
[204490] = Defaults(2), -- Sigil of Silence
[179057] = Defaults(3), -- Chaos Nova
[211881] = Defaults(4), -- Fel Eruption
[205630] = Defaults(3), -- Illidan's Grasp
[208618] = Defaults(3), -- Illidan's Grasp (Afterward)
[213491] = Defaults(4), -- Demonic Trample (it's this one or the other)
[208645] = Defaults(4), -- Demonic Trample
--Druid
[81261] = Defaults(2), -- Solar Beam
[5211] = Defaults(4), -- Mighty Bash
[163505] = Defaults(4), -- Rake
[203123] = Defaults(4), -- Maim
[202244] = Defaults(4), -- Overrun
[99] = Defaults(4), -- Incapacitating Roar
[33786] = Defaults(5), -- Cyclone
[209753] = Defaults(5), -- Cyclone Balance
[45334] = Defaults(1), -- Immobilized
[102359] = Defaults(1), -- Mass Entanglement
[339] = Defaults(1), -- Entangling Roots
[2637] = Defaults(1), -- Hibernate
--Hunter
[202933] = Defaults(2), -- Spider Sting (it's this one or the other)
[233022] = Defaults(2), -- Spider Sting
[213691] = Defaults(4), -- Scatter Shot
[19386] = Defaults(3), -- Wyvern Sting
[3355] = Defaults(3), -- Freezing Trap
[203337] = Defaults(5), -- Freezing Trap (Survival PvPT)
[209790] = Defaults(3), -- Freezing Arrow
[24394] = Defaults(4), -- Intimidation
[117526] = Defaults(4), -- Binding Shot
[190927] = Defaults(1), -- Harpoon
[201158] = Defaults(1), -- Super Sticky Tar
[162480] = Defaults(1), -- Steel Trap
[212638] = Defaults(1), -- Tracker's Net
[200108] = Defaults(1), -- Ranger's Net
--Mage
[61721] = Defaults(3), -- Rabbit (Poly)
[61305] = Defaults(3), -- Black Cat (Poly)
[28272] = Defaults(3), -- Pig (Poly)
[28271] = Defaults(3), -- Turtle (Poly)
[126819] = Defaults(3), -- Porcupine (Poly)
[161354] = Defaults(3), -- Monkey (Poly)
[161353] = Defaults(3), -- Polar bear (Poly)
[61780] = Defaults(3), -- Turkey (Poly)
[161355] = Defaults(3), -- Penguin (Poly)
[161372] = Defaults(3), -- Peacock (Poly)
[277787] = Defaults(3), -- Direhorn (Poly)
[277792] = Defaults(3), -- Bumblebee (Poly)
[118] = Defaults(3), -- Polymorph
[82691] = Defaults(3), -- Ring of Frost
[31661] = Defaults(3), -- Dragon's Breath
[122] = Defaults(1), -- Frost Nova
[33395] = Defaults(1), -- Freeze
[157997] = Defaults(1), -- Ice Nova
[228600] = Defaults(1), -- Glacial Spike
[198121] = Defaults(1), -- Forstbite
--Monk
[119381] = Defaults(4), -- Leg Sweep
[202346] = Defaults(4), -- Double Barrel
[115078] = Defaults(4), -- Paralysis
[198909] = Defaults(3), -- Song of Chi-Ji
[202274] = Defaults(3), -- Incendiary Brew
[233759] = Defaults(2), -- Grapple Weapon
[123407] = Defaults(1), -- Spinning Fire Blossom
[116706] = Defaults(1), -- Disable
[232055] = Defaults(4), -- Fists of Fury (it's this one or the other)
--Paladin
[853] = Defaults(3), -- Hammer of Justice
[20066] = Defaults(3), -- Repentance
[105421] = Defaults(3), -- Blinding Light
[31935] = Defaults(2), -- Avenger's Shield
[217824] = Defaults(2), -- Shield of Virtue
[205290] = Defaults(3), -- Wake of Ashes
--Priest
[9484] = Defaults(3), -- Shackle Undead
[200196] = Defaults(4), -- Holy Word: Chastise
[200200] = Defaults(4), -- Holy Word: Chastise
[226943] = Defaults(3), -- Mind Bomb
[605] = Defaults(5), -- Mind Control
[8122] = Defaults(3), -- Psychic Scream
[15487] = Defaults(2), -- Silence
[64044] = Defaults(1), -- Psychic Horror
--Rogue
[2094] = Defaults(4), -- Blind
[6770] = Defaults(4), -- Sap
[1776] = Defaults(4), -- Gouge
[1330] = Defaults(2), -- Garrote - Silence
[207777] = Defaults(2), -- Dismantle
[199804] = Defaults(4), -- Between the Eyes
[408] = Defaults(4), -- Kidney Shot
[1833] = Defaults(4), -- Cheap Shot
[207736] = Defaults(5), -- Shadowy Duel (Smoke effect)
[212182] = Defaults(5), -- Smoke Bomb
--Shaman
[51514] = Defaults(3), -- Hex
[211015] = Defaults(3), -- Hex (Cockroach)
[211010] = Defaults(3), -- Hex (Snake)
[211004] = Defaults(3), -- Hex (Spider)
[210873] = Defaults(3), -- Hex (Compy)
[196942] = Defaults(3), -- Hex (Voodoo Totem)
[269352] = Defaults(3), -- Hex (Skeletal Hatchling)
[277778] = Defaults(3), -- Hex (Zandalari Tendonripper)
[277784] = Defaults(3), -- Hex (Wicker Mongrel)
[118905] = Defaults(3), -- Static Charge
[77505] = Defaults(4), -- Earthquake (Knocking down)
[118345] = Defaults(4), -- Pulverize (Pet)
[204399] = Defaults(3), -- Earthfury
[204437] = Defaults(3), -- Lightning Lasso
[157375] = Defaults(4), -- Gale Force
[64695] = Defaults(1), -- Earthgrab
--Warlock
[710] = Defaults(5), -- Banish
[6789] = Defaults(3), -- Mortal Coil
[118699] = Defaults(3), -- Fear
[6358] = Defaults(3), -- Seduction (Succub)
[171017] = Defaults(4), -- Meteor Strike (Infernal)
[22703] = Defaults(4), -- Infernal Awakening (Infernal CD)
[30283] = Defaults(3), -- Shadowfury
[89766] = Defaults(4), -- Axe Toss
[233582] = Defaults(1), -- Entrenched in Flame
--Warrior
[5246] = Defaults(4), -- Intimidating Shout
[7922] = Defaults(4), -- Warbringer
[132169] = Defaults(4), -- Storm Bolt
[132168] = Defaults(4), -- Shockwave
[199085] = Defaults(4), -- Warpath
[105771] = Defaults(1), -- Charge
[199042] = Defaults(1), -- Thunderstruck
[236077] = Defaults(2), -- Disarm
--Racial
[20549] = Defaults(4), -- War Stomp
[107079] = Defaults(4), -- Quaking Palm
}
}
-- Raid Buffs (Squared Aura Tracking List)
K.RaidBuffsTracking = {
PRIEST = {
{194384, "TOPRIGHT", {1, 0, 0.75}}, -- Atonement
{214206, "TOPRIGHT", {1, 0, 0.75}}, -- Atonement PvP
{41635, "BOTTOMRIGHT", {0.2, 0.7, 0.2}}, -- Prayer of Mending
{193065, "BOTTOMRIGHT", {0.54, 0.21, 0.78}}, -- Masochism
{139, "BOTTOMLEFT", {0.4, 0.7, 0.2}}, -- Renew
{6788, "BOTTOMLEFT", {0.89, 0.1, 0.1}}, -- Weakened Soul
{17, "TOPLEFT", {0.81, 0.85, 0.1}, true}, -- Power Word: Shield
{47788, "LEFT", {221 / 255, 117 / 255, 0}, true}, -- Guardian Spirit
{33206, "LEFT", {227 / 255, 23 / 255, 13 / 255}, true} -- Pain Suppression
},
DRUID = {
{774, "TOPRIGHT", {0.8, 0.4, 0.8}}, -- Rejuvenation
{155777, "RIGHT", {0.8, 0.4, 0.8}}, -- Germination
{8936, "BOTTOMLEFT", {0.2, 0.8, 0.2}}, -- Regrowth
{33763, "TOPLEFT", {0.4, 0.8, 0.2}}, -- Lifebloom
{48438, "BOTTOMRIGHT", {0.8, 0.4, 0}}, -- Wild Growth
{207386, "TOP", {0.4, 0.2, 0.8}}, -- Spring Blossoms
{102351, "LEFT", {0.2, 0.8, 0.8}}, -- Cenarion Ward (Initial Buff)
{102352, "LEFT", {0.2, 0.8, 0.8}}, -- Cenarion Ward (HoT)
{200389, "BOTTOM", {1, 1, 0.4}} -- Cultivation
},
PALADIN = {
{53563, "TOPRIGHT", {0.7, 0.3, 0.7}}, -- Beacon of Light
{156910, "TOPRIGHT", {0.7, 0.3, 0.7}}, -- Beacon of Faith
{200025, "TOPRIGHT", {0.7, 0.3, 0.7}}, -- Beacon of Virtue
{287280, "RIGHT", {0.7, 0.3, 0.7}}, -- Glimmer of Light
{1022, "BOTTOMRIGHT", {0.2, 0.2, 1}, true}, -- Hand of Protection
{1044, "BOTTOMRIGHT", {0.89, 0.45, 0}, true}, -- Hand of Freedom
{6940, "BOTTOMRIGHT", {0.89, 0.1, 0.1}, true}, -- Hand of Sacrifice
{223306, "BOTTOMLEFT", {0.7, 0.7, 0.3}, true} -- Bestow Faith
},
SHAMAN = {
{61295, "TOPRIGHT", {0.7, 0.3, 0.7}}, -- Riptide
{974, "BOTTOMRIGHT", {0.2, 0.2, 1}} -- Earth Shield
},
MONK = {
{119611, "TOPLEFT", {0.8, 0.4, 0.8}}, --Renewing Mist
{116849, "TOPRIGHT", {0.2, 0.8, 0.2}}, -- Life Cocoon
{124682, "BOTTOMLEFT", {0.4, 0.8, 0.2}}, -- Enveloping Mist
{124081, "BOTTOMRIGHT", {0.7, 0.4, 0}} -- Zen Sphere
},
ROGUE = {
{57934, "TOPRIGHT", {227 / 255, 23 / 255, 13 / 255}} -- Tricks of the Trade
},
WARRIOR = {
{114030, "TOPLEFT", {0.2, 0.2, 1}}, -- Vigilance
{147833, "TOPRIGHT", {227 / 255, 23 / 255, 13 / 255}} -- Intervene
},
PET = {
-- Warlock Pets
{193396, "TOPRIGHT", {0.6, 0.2, 0.8}, true}, -- Demonic Empowerment
-- Hunter Pets
{19615, "TOPLEFT", {227 / 255, 23 / 255, 13 / 255}, true}, -- Frenzy
{136, "TOPRIGHT", {0.2, 0.8, 0.2}, true} -- Mend Pet
},
HUNTER = {},
DEMONHUNTER = {},
WARLOCK = {},
MAGE = {},
DEATHKNIGHT = {},
}
K.RaidBuffsTrackingPosition = {
TOPLEFT = {6, 1},
TOPRIGHT = {-6, 1},
BOTTOMLEFT = {6, 1},
BOTTOMRIGHT = {-6, 1},
LEFT = {6, 1},
RIGHT = {-6, 1},
TOP = {0, 0},
BOTTOM = {0, 0}
}
K.DebuffHighlightColors = {
[25771] = {
enable = false,
style = "FILL",
color = {r = 0.85, g = 0, b = 0, a = 0.85}
},
}
-- Filter this. Pointless to see.
K.UnimportantBuffs = {
[SpellName(113942)] = true, -- Demonic: Gateway
[SpellName(117870)] = true, -- Touch of The Titans
[SpellName(123981)] = true, -- Perdition
[SpellName(124273)] = true, -- Stagger
[SpellName(124274)] = true, -- Stagger
[SpellName(124275)] = true, -- Stagger
[SpellName(126434)] = true, -- Tushui Champion
[SpellName(126436)] = true, -- Huojin Champion
[SpellName(131493)] = true, -- B.F.F. Friends forever!
[SpellName(143625)] = true, -- Brawling Champion
[SpellName(15007)] = true, -- Ress Sickness
[SpellName(170616)] = true, -- Pet Deserter
[SpellName(182957)] = true, -- Treasures of Stormheim
[SpellName(182958)] = true, -- Treasures of Azsuna
[SpellName(185719)] = true, -- Treasures of Val"sharah
[SpellName(186401)] = true, -- Sign of the Skirmisher
[SpellName(186403)] = true, -- Sign of Battle
[SpellName(186404)] = true, -- Sign of the Emissary
[SpellName(186406)] = true, -- Sign of the Critter
[SpellName(188741)] = true, -- Treasures of Highmountain
[SpellName(199416)] = true, -- Treasures of Suramar
[SpellName(225787)] = true, -- Sign of the Warrior
[SpellName(225788)] = true, -- Sign of the Emissary
[SpellName(227723)] = true, -- Mana Divining Stone
[SpellName(231115)] = true, -- Treasures of Broken Shore
[SpellName(233641)] = true, -- Legionfall Commander
[SpellName(23445)] = true, -- Evil Twin
[SpellName(237137)] = true, -- Knowledgeable
[SpellName(237139)] = true, -- Power Overwhelming
[SpellName(239645)] = true, -- Fel Treasures
[SpellName(239647)] = true, -- Epic Hunter
[SpellName(239648)] = true, -- Forces of the Order
[SpellName(239966)] = true, -- War Effort
[SpellName(239967)] = true, -- Seal Your Fate
[SpellName(239968)] = true, -- Fate Smiles Upon You
[SpellName(239969)] = true, -- Netherstorm
[SpellName(240979)] = true, -- Reputable
[SpellName(240980)] = true, -- Light As a Feather
[SpellName(240985)] = true, -- Reinforced Reins
[SpellName(240986)] = true, -- Worthy Champions
[SpellName(240987)] = true, -- Well Prepared
[SpellName(240989)] = true, -- Heavily Augmented
[SpellName(24755)] = true, -- Tricked or Treated
[SpellName(25163)] = true, -- Oozeling"s Disgusting Aura
[SpellName(26013)] = true, -- Deserter
[SpellName(36032)] = true, -- Arcane Charge
[SpellName(36893)] = true, -- Transporter Malfunction
[SpellName(36900)] = true, -- Soul Split: Evil!
[SpellName(36901)] = true, -- Soul Split: Good
[SpellName(39953)] = true, -- A"dal"s Song of Battle
[SpellName(41425)] = true, -- Hypothermia
[SpellName(44212)] = true, -- Jack-o"-Lanterned!
[SpellName(55711)] = true, -- Weakened Heart
[SpellName(57723)] = true, -- Exhaustion (heroism debuff)
[SpellName(57724)] = true, -- Sated (lust debuff)
[SpellName(57819)] = true, -- Argent Champion
[SpellName(57820)] = true, -- Ebon Champion
[SpellName(57821)] = true, -- Champion of the Kirin Tor
[SpellName(58539)] = true, -- Watcher"s Corpse
[SpellName(71041)] = true, -- Dungeon Deserter
[SpellName(72968)] = true, -- Precious"s Ribbon
[SpellName(80354)] = true, -- Temporal Displacement (timewarp debuff)
[SpellName(8326)] = true, -- Ghost
[SpellName(85612)] = true, -- Fiona"s Lucky Charm
[SpellName(85613)] = true, -- Gidwin"s Weapon Oil
[SpellName(85614)] = true, -- Tarenar"s Talisman
[SpellName(85615)] = true, -- Pamela"s Doll
[SpellName(85616)] = true, -- Vex"tul"s Armbands
[SpellName(85617)] = true, -- Argus" Journal
[SpellName(85618)] = true, -- Rimblat"s Stone
[SpellName(85619)] = true, -- Beezil"s Cog
[SpellName(8733)] = true, -- Blessing of Blackfathom
[SpellName(89140)] = true, -- Demonic Rebirth: Cooldown
[SpellName(93337)] = true, -- Champion of Ramkahen
[SpellName(93339)] = true, -- Champion of the Earthen Ring
[SpellName(93341)] = true, -- Champion of the Guardians of Hyjal
[SpellName(93347)] = true, -- Champion of Therazane
[SpellName(93368)] = true, -- Champion of the Wildhammer Clan
[SpellName(93795)] = true, -- Stormwind Champion
[SpellName(93805)] = true, -- Ironforge Champion
[SpellName(93806)] = true, -- Darnassus Champion
[SpellName(93811)] = true, -- Exodar Champion
[SpellName(93816)] = true, -- Gilneas Champion
[SpellName(93821)] = true, -- Gnomeregan Champion
[SpellName(93825)] = true, -- Orgrimmar Champion
[SpellName(93827)] = true, -- Darkspear Champion
[SpellName(93828)] = true, -- Silvermoon Champion
[SpellName(93830)] = true, -- Bilgewater Champion
[SpellName(94158)] = true, -- Champion of the Dragonmaw Clan
[SpellName(94462)] = true, -- Undercity Champion
[SpellName(94463)] = true, -- Thunder Bluff Champion
[SpellName(95809)] = true, -- Insanity debuff (hunter pet heroism: ancient hysteria)
[SpellName(97340)] = true, -- Guild Champion
[SpellName(97341)] = true, -- Guild Champion
[SpellName(97821)] = true -- Void-Touched
}
K.ChannelingTicks = {
[SpellName(740)] = 4, -- 宁静
[SpellName(755)] = 3, -- 生命通道
[SpellName(5143)] = 5, -- 奥术飞弹
[SpellName(12051)] = 3, -- 唤醒
[SpellName(15407)] = 4, -- 精神鞭笞
[SpellName(47540)] = 3, -- 苦修
[SpellName(64843)] = 4, -- 神圣赞美诗
[SpellName(198590)] = 5, -- 吸取灵魂
[SpellName(205021)] = 5, -- 冰霜射线
[SpellName(205065)] = 6, -- 虚空洪流
[SpellName(234153)] = 5, -- 吸取生命
-- [SpellName(291944)] = 6, -- 再生
}
local updateTicks = CreateFrame("Frame")
updateTicks:RegisterEvent("PLAYER_LOGIN")
updateTicks:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED")
updateTicks:SetScript("OnEvent", function()
if K.Class ~= "PRIEST" then
return
end
local numTicks = 3
if IsPlayerSpell(193134) then -- Enhanced Mind Flay
numTicks = 4
end
K.ChannelingTicks[K.TicksPenance] = numTicks
end)
|
---------------------------------
--! @file OutPortConnectorBase.lua
--! @brief OutPortコネクタ基底クラス定義
---------------------------------
--[[
Copyright (c) 2017 Nobuhiko Miyamoto
]]
local OutPortConnector= {}
--_G["openrtm.OutPortConnector"] = OutPortConnector
local ConnectorBase = require "openrtm.ConnectorBase"
-- OutPortコネクタ基底オブジェクト初期化
-- @param info プロファイル
-- @return InPortコネクタ
OutPortConnector.new = function(info)
local obj = {}
setmetatable(obj, {__index=ConnectorBase.new()})
local Manager = require "openrtm.Manager"
obj._rtcout = Manager:instance():getLogbuf("OutPortConnector")
--print(obj._rtcout)
obj._ReturnCode_t = Manager:instance():getORB().types:lookup("::RTC::ReturnCode_t").labelvalue
obj._profile = info
obj._endian = true
-- プロファイル取得
-- @return プロファイル
function obj:profile()
self._rtcout:RTC_TRACE("profile()")
return self._profile
end
-- コネクタID取得
-- @return コネクタID
function obj:id()
self._rtcout:RTC_TRACE("id() = "..self:profile().id)
return self:profile().id
end
-- コネクタ名取得
-- @return コネクタ名
function obj:name()
self._rtcout:RTC_TRACE("name() = "..self:profile().name)
return self:profile().name
end
-- プロファイル設定
-- @param profile プロファイル
-- @return リターンコード
function obj:setConnectorInfo(profile)
self._profile = profile
return self._ReturnCode_t.RTC_OK
end
return obj
end
return OutPortConnector
|
--------------------------------------------------------------------------------
-- frame.lua
-- a custom window like object
--------------------------------------------------------------------------------
local AddonName, Addon = ...
local Frame = Addon:CreateClass('Frame')
local L = LibStub('AceLocale-3.0'):GetLocale(AddonName)
local FlyPaper = LibStub('LibFlyPaper-1.0')
local active = {}
local unused = {}
local function frame_OnSetAlpha(frame, alpha)
frame:OnSetAlpha(alpha)
end
local function frame_OnSetScale(frame, scale)
frame:OnSetScale(scale)
end
local frame_UpdateShown =
[[
if self:GetAttribute("state-hidden") then
self:Hide()
return
end
local isOverrideUIShown = self:GetAttribute('state-overrideui') and true or false
local isPetBattleUIShown = self:GetAttribute('state-petbattleui') and true or false
if isPetBattleUIShown and not self:GetAttribute('state-showinpetbattleui') then
self:Hide()
return
end
if isOverrideUIShown and not self:GetAttribute('state-showinoverrideui') then
self:Hide()
return
end
local displayState = self:GetAttribute('state-display')
if displayState == 'hide' then
if self:GetAttribute('state-alpha') then
self:SetAttribute('state-alpha', nil)
end
self:Hide()
return
end
local stateAlpha = tonumber(displayState)
if self:GetAttribute('state-alpha') ~= stateAlpha then
self:SetAttribute('state-alpha', stateAlpha)
end
self:Show()
]]
local frame_CallUpdateShown = "self:RunAttribute('UpdateShown')"
-- constructor
function Frame:New(id, tooltipText)
id = tonumber(id) or id
local frame = self:Restore(id) or self:Create(id)
frame:LoadSettings()
frame:SetTooltipText(tooltipText)
Addon.OverrideController:Add(frame)
frame:OnAcquire(id)
active[id] = frame
return frame
end
function Frame:Create(id)
local frameName = ('%sFrame%s'):format(AddonName, id)
local frame = self:Bind(CreateFrame('Frame', frameName, UIParent, 'SecureHandlerStateTemplate'))
frame:SetClampedToScreen(true)
frame:SetMovable(true)
-- compatibility:
-- in old versions of dominos, frames had an extra header frame to control
-- visibility, which pushed things up by one frame level
-- so increase the frame level of frames to account for that
frame:SetFrameLevel(frame:GetFrameLevel() + 1)
frame.id = id
frame:SetAttribute('id', id)
frame:SetAttribute('_onstate-alpha', "self:CallMethod('FadeOut')")
frame:SetAttribute('_onstate-display', frame_CallUpdateShown)
frame:SetAttribute('_onstate-hidden', frame_CallUpdateShown)
frame:SetAttribute('_onstate-overrideui', frame_CallUpdateShown)
frame:SetAttribute('_onstate-petbattleui', frame_CallUpdateShown)
frame:SetAttribute('_onstate-showinoverrideui', frame_CallUpdateShown)
frame:SetAttribute('_onstate-showinpetbattleui', frame_CallUpdateShown)
frame:SetAttribute('UpdateShown', frame_UpdateShown)
hooksecurefunc(frame, 'SetAlpha', frame_OnSetAlpha)
hooksecurefunc(frame, 'SetScale', frame_OnSetScale)
frame:OnCreate(id)
return frame
end
function Frame:Restore(id)
local frame = unused[id]
if frame then
unused[id] = nil
frame:OnRestore(id)
return frame
end
end
-- destructor
function Frame:Free(deleteSettings)
active[self.id] = nil
UnregisterStateDriver(self, 'display', 'show')
Addon.MouseOverWatcher:Remove(self)
Addon.OverrideController:Remove(self)
self.docked = nil
self:ClearAllPoints()
self:SetUserPlaced(nil)
self:Hide()
self:OnRelease(self.id, deleteSettings)
unused[self.id] = self
end
--------------------------------------------------------------------------------
-- Lifecycle Hooks
--------------------------------------------------------------------------------
-- called when a frame is acquired from the pool
function Frame:OnAcquire(id)
if self.OnEnable then
Addon:Printf('Bar %q called deprecated method OnEnable', id)
self:OnEnable()
end
end
-- called when a frame is first created
function Frame:OnCreate(id)
end
-- called when a frame is pulled in from the inactive pool
function Frame:OnRestore(id)
end
-- called when a frame is sent to the inactive pool
function Frame:OnRelease(id, deleteSettings)
if self.OnFree then
Addon:Printf('Bar %q called deprecated method OnFree', id)
self:OnFree()
end
end
function Frame:OnLoadSettings()
end
function Frame:OnSetAlpha(alpha)
end
function Frame:OnSetScale(scale)
end
--------------------------------------------------------------------------------
-- Persistence
--------------------------------------------------------------------------------
function Frame:LoadSettings()
-- get defaults must be provided by anything implementing the Frame type
self.sets = Addon:GetFrameSets(self.id) or Addon:SetFrameSets(self.id, self:GetDefaults())
self:Reposition()
if self.sets.hidden then
self:HideFrame()
else
self:ShowFrame()
end
self:UpdateShowStates()
self:ShowInOverrideUI(self:ShowingInOverrideUI())
self:ShowInPetBattleUI(self:ShowingInPetBattleUI())
self:OnLoadSettings()
end
--------------------------------------------------------------------------------
-- Layout and Sizing
--------------------------------------------------------------------------------
function Frame:SetPadding(width, height)
width = tonumber(width) or 0
height = tonumber(height) or width
self.sets.padW = width ~= 0 and width or nil
self.sets.padH = height ~= 0 and height or nil
self:Layout()
end
function Frame:GetPadding()
local width = self.sets.padW or 0
local height = self.sets.padH or width
return width, height
end
function Frame:Layout()
local width, height = 32, 32
local paddingW, paddingH = self:GetPadding()
self:TrySetSize(width + paddingW * 2, height + paddingH * 2)
end
function Frame:TrySetSize(width, height)
if InCombatLockdown() then
return
end
self:SetSize(width, height)
end
--------------------------------------------------------------------------------
-- Scaling
--------------------------------------------------------------------------------
function Frame:SetFrameScale(newScale, scaleAnchored)
newScale = tonumber(newScale) or 1
local oldScale = self:GetFrameScale()
local ratio = oldScale / newScale
self.sets.scale = newScale
self:Rescale()
if not self:GetAnchor() then
local point, x, y = self:GetSavedFramePosition()
self:SetAndSaveFramePosition(point, x * ratio, y * ratio)
end
if scaleAnchored then
for _, f in self:GetAll() do
if f:GetAnchor() == self then
f:SetFrameScale(newScale, true)
end
end
end
end
function Frame:Rescale()
self:SetScale(self:GetFrameScale())
end
function Frame:GetFrameScale()
return self.sets.scale or 1
end
--------------------------------------------------------------------------------
-- Frame Opacity/Fading
--------------------------------------------------------------------------------
function Frame:SetFrameAlpha(alpha)
if alpha == 1 then
self.sets.alpha = nil
else
self.sets.alpha = alpha
end
self:UpdateAlpha()
end
function Frame:GetFrameAlpha()
return self.sets.alpha or 1
end
--faded opacity (mouse not over the frame)
function Frame:SetFadeMultiplier(alpha)
alpha = tonumber(alpha) or 1
if alpha == 1 then
self.sets.fadeAlpha = nil
else
self.sets.fadeAlpha = alpha
end
self:UpdateWatched()
self:UpdateAlpha()
end
function Frame:GetFadeMultiplier()
return self.sets.fadeAlpha or 1
end
function Frame:SetFadeInDelay(delay)
delay = tonumber(delay) or 0
self.sets.fadeInDelay = delay ~= 0 and delay
self:UpdateWatched()
end
function Frame:GetFadeInDelay()
return self.sets.fadeInDelay or 0
end
function Frame:SetFadeOutDelay(delay)
delay = tonumber(delay) or 0
self.sets.fadeOutDelay = delay ~= 0 and delay
self:UpdateWatched()
end
function Frame:GetFadeOutDelay()
return self.sets.fadeOutDelay or 0
end
function Frame:SetFadeInDuration(duration)
duration = tonumber(duration) or 0.1
self.sets.fadeInDuration = duration ~= 0.1 and duration
self:UpdateWatched()
end
function Frame:GetFadeInDuration()
return self.sets.fadeInDuration or 0.1
end
function Frame:SetFadeOutDuration(duration)
duration = tonumber(duration) or 0.1
self.sets.fadeOutDuration = duration ~= 0.1 and duration
self:UpdateWatched()
end
function Frame:GetFadeOutDuration()
return self.sets.fadeOutDuration or 0.1
end
function Frame:UpdateAlpha()
self:SetAlpha(self:GetExpectedAlpha())
if Addon:IsLinkedOpacityEnabled() then
self:ForDocked('UpdateAlpha')
end
end
-- returns the opacity value we expect the frame to be at in its current state
function Frame:GetExpectedAlpha()
-- if this is a docked frame and linked opacity is enabled
-- then return the expected opacity of the parent frame
if Addon:IsLinkedOpacityEnabled() then
local anchor = (self:GetAnchor())
if anchor and anchor:FrameIsShown() then
return anchor:GetExpectedAlpha()
end
end
-- if there's a statealpha value for the frame, then use it
local stateAlpha = self:GetAttribute('state-alpha')
if stateAlpha then
return stateAlpha / 100
end
-- if the frame is moused over, then return the frame's normal opacity
if self.focused then
return self:GetFrameAlpha()
end
return self:GetFrameAlpha() * self:GetFadeMultiplier()
end
--------------------------------------------------------------------------------
-- Focus Checking
--------------------------------------------------------------------------------
local function isChildFocus(...)
local focus = GetMouseFocus()
for i = 1, select('#', ...) do
if focus == select(i, ...) then
return true
end
end
for i = 1, select('#', ...) do
local f = select(i, ...)
if f:IsShown() and isChildFocus(f:GetChildren()) then
return true
end
end
return false
end
local function isDescendant(frame, ...)
for i = 1, select('#', ...) do
local f = select(i, ...)
if frame == f then
return true
end
end
for i = 1, select('#', ...) do
local f = select(i, ...)
if isDescendant(frame, f:GetChildren()) then
return true
end
end
return false
end
-- returns all frames docked to the given frame
function Frame:IsFocus()
if self:IsMouseOver(1, -1, -1, 1) then
return (GetMouseFocus() == WorldFrame) or isChildFocus(self:GetChildren())
end
if SpellFlyout and SpellFlyout:IsMouseOver(1, -1, -1, 1) and isDescendant(SpellFlyout:GetParent(), self) then
return true
end
return Addon:IsLinkedOpacityEnabled() and self:IsDockedFocus()
end
function Frame:IsDockedFocus()
local docked = self.docked
if docked then
for _, frame in pairs(docked) do
if frame:IsFocus() then
return true
end
end
end
return false
end
--------------------------------------------------------------------------------
-- Fading
--------------------------------------------------------------------------------
function Frame:FadeIn()
self:Fade(self:GetExpectedAlpha(), self:GetFadeInDelay(), self:GetFadeInDuration())
end
function Frame:FadeOut()
self:Fade(self:GetExpectedAlpha(), self:GetFadeOutDelay(), self:GetFadeOutDuration())
end
function Frame:Fade(targetAlpha, delay, duration)
if floor(abs(targetAlpha * 100 - self:GetAlpha() * 100)) == 0 then
return
end
Addon:Fade(self, targetAlpha, delay, duration)
if Addon:IsLinkedOpacityEnabled() then
self:ForDocked('Fade', targetAlpha, delay, duration)
end
end
--------------------------------------------------------------------------------
-- Frame Visibility
--------------------------------------------------------------------------------
function Frame:ShowFrame()
self.sets.hidden = nil
self:SetAttribute('state-hidden', nil)
self:UpdateWatched()
self:UpdateAlpha()
if Addon:IsLinkedOpacityEnabled() then
self:ForDocked('ShowFrame')
end
end
function Frame:HideFrame()
self.sets.hidden = true
self:SetAttribute('state-hidden', true)
self:UpdateWatched()
self:UpdateAlpha()
if Addon:IsLinkedOpacityEnabled() then
self:ForDocked('HideFrame')
end
end
function Frame:ToggleFrame()
if self:FrameIsShown() then
self:HideFrame()
else
self:ShowFrame()
end
end
function Frame:FrameIsShown()
return not self.sets.hidden
end
--------------------------------------------------------------------------------
-- Override UI Visibility
--------------------------------------------------------------------------------
function Frame:ShowInOverrideUI(enable)
self.sets.showInOverrideUI = enable and true or false
self:SetAttribute('state-showinoverrideui', enable)
end
function Frame:ShowingInOverrideUI()
return self.sets.showInOverrideUI
end
--------------------------------------------------------------------------------
-- Pet Battle UI Visibility
--------------------------------------------------------------------------------
function Frame:ShowInPetBattleUI(enable)
self.sets.showInPetBattleUI = enable and true or false
self:SetAttribute('state-showinpetbattleui', enable)
end
function Frame:ShowingInPetBattleUI()
return self.sets.showInPetBattleUI
end
--------------------------------------------------------------------------------
-- Click through bars
--------------------------------------------------------------------------------
function Frame:SetClickThrough(enable)
self.sets.clickThrough = enable and true or false
self:UpdateClickThrough()
end
function Frame:GetClickThrough()
return self.sets.clickThrough
end
function Frame:UpdateClickThrough()
end
--------------------------------------------------------------------------------
-- Showstates
--------------------------------------------------------------------------------
function Frame:SetShowStates(states)
self.sets.showstates = states
self:UpdateShowStates()
end
function Frame:GetShowStates()
local states = self.sets.showstates
-- hack to convert [combat] into [combat]show;hide in case a user is using
-- the old style of showstates
if states then
if states:sub(#states) == ']' then
states = states .. 'show;hide'
self.sets.showstates = states
end
end
return states
end
function Frame:UpdateShowStates()
local showstates = self:GetShowStates()
if showstates and showstates ~= '' then
RegisterStateDriver(self, 'display', showstates)
else
UnregisterStateDriver(self, 'display')
if self:GetAttribute('state-display') then
self:SetAttribute('state-display', nil)
end
end
end
--------------------------------------------------------------------------------
-- Positioning
--------------------------------------------------------------------------------
-- how far away a frame can be from another frame/edge to trigger anchoring
Frame.stickyTolerance = 16
-- edge anchoring
function Frame:StickToEdge()
local point, x, y = self:GetRelativeFramePosition()
local rTolerance = self.stickyTolerance / self:GetFrameScale()
local changed = false
if abs(x) <= rTolerance then
x = 0
changed = true
end
if abs(y) <= rTolerance then
y = 0
changed = true
end
--save this junk if we've done something
if changed then
self:SetAndSaveFramePosition(point, x, y)
end
end
-- bar anchoring
function Frame:Stick()
local rTolerance = self.stickyTolerance / self:GetFrameScale()
self:ClearAnchor()
-- only do sticky code if the alt key is not currently down
if Addon:Sticky() and not IsAltKeyDown() then
-- try to stick to a bar, then try to stick to a screen edge
for _, f in self:GetAll() do
if f ~= self then
local point = FlyPaper.Stick(self, f, rTolerance)
if point then
self:SetAnchor(f, point)
break
end
end
end
if not self:GetAnchor() then
self:StickToEdge()
end
end
self:SaveRelativeFramePosition()
end
function Frame:Reanchor()
local f, point = self:GetAnchor()
if not (f and FlyPaper.StickToPoint(self, f, point)) then
self:ClearAnchor()
self:Reposition()
else
self:SetAnchor(f, point)
end
end
function Frame:SetAnchor(anchor, point)
self:ClearAnchor()
if anchor.docked then
local found = false
for i, f in pairs(anchor.docked) do
if f == self then
found = i
break
end
end
if not found then
tinsert(anchor.docked, self)
end
else
anchor.docked = {self}
end
self.sets.anchor = anchor.id .. point
self:UpdateWatched()
self:UpdateAlpha()
end
function Frame:ClearAnchor()
local anchor = self:GetAnchor()
if anchor and anchor.docked then
for i, f in pairs(anchor.docked) do
if f == self then
tremove(anchor.docked, i)
break
end
end
if not next(anchor.docked) then
anchor.docked = nil
end
end
self.sets.anchor = nil
self:UpdateWatched()
self:UpdateAlpha()
end
function Frame:GetAnchor()
local anchorString = self.sets.anchor
if anchorString then
local pointStart = #anchorString - 1
return self:Get(anchorString:sub(1, pointStart - 1)), anchorString:sub(pointStart)
end
end
-- absolute positioning
function Frame:SetFramePosition(...)
self:ClearAllPoints()
self:SetPoint(...)
end
function Frame:SetAndSaveFramePosition(point, x, y)
self:SetFramePosition(point, x, y)
self:SaveFramePosition(point, x, y)
end
-- relative positioning
function Frame:SaveRelativeFramePosition()
self:SaveFramePosition(self:GetRelativeFramePosition())
end
function Frame:GetRelativeFramePosition()
local scale = self:GetScale() or 1
local left = self:GetLeft() or 0
local top = self:GetTop() or 0
local right = self:GetRight() or 0
local bottom = self:GetBottom() or 0
local parent = self:GetParent() or UIParent
local pwidth = parent:GetWidth() / scale
local pheight = parent:GetHeight() / scale
local x, y, point
if left < (pwidth - right) and left < abs((left + right) / 2 - pwidth / 2) then
x = left
point = 'LEFT'
elseif (pwidth - right) < abs((left + right) / 2 - pwidth / 2) then
x = right - pwidth
point = 'RIGHT'
else
x = (left + right) / 2 - pwidth / 2
point = ''
end
if bottom < (pheight - top) and bottom < abs((bottom + top) / 2 - pheight / 2) then
y = bottom
point = 'BOTTOM' .. point
elseif (pheight - top) < abs((bottom + top) / 2 - pheight / 2) then
y = top - pheight
point = 'TOP' .. point
else
y = (bottom + top) / 2 - pheight / 2
end
if point == '' then
point = 'CENTER'
end
return point, x, y
end
-- loading and positionin
local function roundPoint(point)
point = point or 0
if point > 0 then
point = floor(point + 0.5)
else
point = ceil(point - 0.5)
end
return point
end
function Frame:Reposition()
self:Rescale()
self:SetFramePosition(self:GetSavedFramePosition())
end
function Frame:SaveFramePosition(point, x, y)
point = point or 'CENTER'
x = roundPoint(x)
y = roundPoint(y)
local sets = self.sets
sets.point = point ~= 'CENTER' and point or nil
sets.x = x ~= 0 and x or nil
sets.y = y ~= 0 and y or nil
self:SetUserPlaced(true)
end
function Frame:GetSavedFramePosition()
local sets = self.sets
local point = sets.point or 'CENTER'
local x = sets.x or 0
local y = sets.y or 0
return point, x, y
end
--------------------------------------------------------------------------------
-- Context Menus
--------------------------------------------------------------------------------
function Frame:CreateMenu()
local menu = Addon:NewMenu()
if menu then
self:OnCreateMenu(menu)
return menu
end
end
function Frame:OnCreateMenu(menu)
menu:AddLayoutPanel()
menu:AddAdvancedPanel()
menu:AddFadingPanel()
end
function Frame:ShowMenu()
local menu = self.menu
if not menu then
menu = self:CreateMenu()
self.menu = menu
end
if menu then
menu:Hide()
menu:SetOwner(self)
menu:ShowPanel(LibStub('AceLocale-3.0'):GetLocale('Dominos-Config').Layout)
menu:Show()
end
end
--------------------------------------------------------------------------------
-- Tooltip Text
--------------------------------------------------------------------------------
function Frame:GetDisplayName()
return L.BarDisplayName:format(tostring(self.id):gsub('^%l', string.upper))
end
function Frame:SetTooltipText(text)
self.tooltipText = text
end
function Frame:GetTooltipText()
return self.tooltipText
end
--------------------------------------------------------------------------------
-- Mouseover
--------------------------------------------------------------------------------
function Frame:UpdateWatched()
local shouldWatch =
self:FrameIsShown() and self:GetFadeMultiplier() < 1 and
not (Addon:IsLinkedOpacityEnabled() and self:GetAnchor())
if shouldWatch then
Addon.MouseOverWatcher:Add(self)
else
Addon.MouseOverWatcher:Remove(self)
end
end
--------------------------------------------------------------------------------
-- Metamethods
--------------------------------------------------------------------------------
function Frame:Get(id)
return active[tonumber(id) or id]
end
function Frame:GetAll()
return pairs(active)
end
function Frame:CallMethod(method, ...)
local func = self[method]
if type(func) == 'function' then
return func(self, ...)
else
error(('Frame %s does not have a method named %q'):format(self.id, method), 2)
end
end
function Frame:MaybeCallMethod(method, ...)
local func = self[method]
if type(func) == 'function' then
return func(self, ...)
end
end
function Frame:ForAll(method, ...)
for _, frame in self:GetAll() do
frame:MaybeCallMethod(method, ...)
end
end
function Frame:ForDocked(method, ...)
local docked = self.docked
if docked then
for _, frame in pairs(docked) do
frame:CallMethod(method, ...)
end
end
end
-- takes a frameId, and performs the specified action on that frame
-- this adds two special ids: 'all' for all frames and '<number>-<number>' for
-- a range of IDs
function Frame:ForFrame(id, method, ...)
if id == 'all' then
self:ForAll(method, ...)
else
local startID, endID = tostring(id):match('(%d+)-(%d+)')
startID = tonumber(startID)
endID = tonumber(endID)
if startID and endID then
if startID > endID then
local t = startID
startID = endID
endID = t
end
for i = startID, endID do
local f = self:Get(i)
if f then
f:MaybeCallMethod(method, ...)
end
end
else
local f = self:Get(id)
if f then
f:MaybeCallMethod(method, ...)
end
end
end
end
-- exports
Addon.Frame = Frame
|
-- Copyright 2021 Zach Varberg, SmartThings
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local capabilities = require "st.capabilities"
local zcl_clusters = require "st.zigbee.zcl.clusters"
local OnOff = zcl_clusters.OnOff
local ReportAttribute = require "st.zigbee.zcl.global_commands.report_attribute".ReportAttribute
-- Use a global attribute handler to work around limitation of multiple attribute records from the same
-- attribute being reported in a single message
local report_attribute_handler = function(self, device, zb_rx)
for _, record in ipairs(zb_rx.body.zcl_body.attr_records) do
if record.attr_id.value == OnOff.attributes.OnOff.ID and record.data.value == true then
device:emit_event(capabilities.button.button.pushed({state_change = true}))
end
end
end
local function can_handle(opts, driver, device)
return device:get_model() == "lumi.sensor_switch.aq2"
end
local xiaomi_button_subdriver = {
NAME = "Xiaomi/Aqara Button",
zigbee_handlers = {
global = {
[OnOff.ID] = {
[ReportAttribute.ID] = report_attribute_handler
}
},
cluster = {},
attr = {
[OnOff.ID] = {
-- include no-op handler to override the contact default of the parent
[OnOff.attributes.OnOff.ID] = function(...)end,
}
}
},
can_handle = can_handle
}
return xiaomi_button_subdriver
|
-- _.iter.lua
--
_.iter = function(value)
if _.isString(value) then
local i = 0
return function()
if _.lt(i, #value) then
i = i + 1
local c = value:sub(i, i)
return i, c
end
end
elseif _.isTable(value) then
return iterCollection(value)
else
return function() end
end
end
|
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
RegisterServerEvent("xp_system:server:getPlayerXP")
AddEventHandler("xp_system:server:getPlayerXP", function()
local _source = source
local identifier = GetPlayerIdentifier(source, 0)
getPlayerXP(_source, identifier)
end)
RegisterServerEvent("xp_system:server:addPlayerXP")
AddEventHandler("xp_system:server:addPlayerXP", function()
local _source = source
addPlayerXP(_source)
end)
RegisterServerEvent("xp_system:server:giveItem")
AddEventHandler("xp_system:server:giveItem", function(item)
local _source = source
local identifier = GetPlayerIdentifier(_source, 0)
local xPlayer = ESX.GetPlayerFromId(_source)
for k,v in pairs(Config.Items) do
if (v.name == item) then
if (v.item == "item_standard") then
if xPlayer.canCarryItem(v.name, 1) then
print("works")
end
elseif (v.item == "item_weapon") then
if (Player.PlayerData[_source].xp >= v.price) then
if not xPlayer.hasWeapon(v.name) then
xPlayer.addWeapon(v.name, v.ammo)
Player.PlayerData[_source].xp = Player.PlayerData[_source].xp - v.price
TriggerClientEvent("xp_system:client:updateHUD", _source, Player.PlayerData[_source])
xPlayer.showNotification("You have successfully purchased ~g~" .. v.name .. "~s~", true, false, 140)
break
else
xPlayer.addWeaponAmmo(v.name, v.ammo)
Player.PlayerData[_source].xp = Player.PlayerData[_source].xp - v.price
xPlayer.showNotification("You successfully purchased ammo for ~g~" .. v.name .. "~s~", true, false, 140)
break
end
else
xPlayer.showNotification("You don't have enough XP points", true, false, 140)
break
end
end
end
end
end)
AddEventHandler("playerDropped", function()
local _source = source
local identifier = GetPlayerIdentifier(_source, 0)
MySQL.Async.execute("UPDATE exp_system SET xp = @xp WHERE identifier = @identifier", {
['xp'] = Player.PlayerData[_source].xp,
['identifier'] = identifier
}, function(rows)
if rows then
return
end
end)
end)
RegisterServerEvent("xp_system:server:retrievePlayerXP")
AddEventHandler("xp_system:server:retrievePlayerXP", function()
local _source = source
local player = retrievePlayerXP(_source)
TriggerClientEvent("xp_system:client:retrievePlayerXP", _source, player)
end)
RegisterServerEvent("xp_system:server:getPromo")
AddEventHandler("xp_system:server:getPromo", function(promo)
local _source = source
checkPromo(source, promo)
end)
--[[
Commands
]]
RegisterCommand("createpromo", function(source, args, raw)
local xPlayer = ESX.GetPlayerFromId(source)
local group = xPlayer.getGroup()
if (group == "admin" or group == "superadmin" or group == "moderator" or group == "user") then
if args[1] ~= nil then
if args[2] ~= nil then
local promo = args[1]
local xp = args[2]
createPromo(source, promo, xp)
else
TriggerClientEvent("chatMessage", source, "[Promo Code]", {220, 0, 0}, "Invalid Arguments ( createpromo code xp )")
end
else
TriggerClientEvent("chatMessage", source, "[Promo Code]", {220, 0, 0}, "Invalid Arguments ( createpromo code xp )")
end
else
TriggerClientEvent("chatMessage", source, "[Promo Code]", {220, 0, 0}, "You dont have access for this command")
end
end, false)
AddEventHandler("onResourceStop", function(resource)
for k,v in pairs(Player.PlayerData) do
MySQL.Async.execute("UPDATE exp_system SET xp = @xp WHERE identifier = @identifier", {
['xp'] = v.xp,
['identifier'] = v.identifier
}, function(rows)
if rows then
print("SAVED")
end
end)
end
end)
function printToServer(text)
print("[^1XP-SYSTEM^7] " ..text .. ": ^2true^7")
end
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
|
glyph_0 = {
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
1, 0, 0, 0, 1,
1, 0, 0, 1, 1,
1, 0, 1, 0, 1,
1, 1, 0, 0, 1,
1, 0, 0, 0, 1,
0, 1, 1, 1, 0,
}
glyph_1 = {
0, 0, 0, 0, 0,
0, 0, 1, 0, 0,
0, 1, 1, 0, 0,
0, 0, 1, 0, 0,
0, 0, 1, 0, 0,
0, 0, 1, 0, 0,
0, 0, 1, 0, 0,
0, 1, 1, 1, 0,
}
glyph_2 = {
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
1, 0, 0, 0, 1,
0, 0, 0, 0, 1,
0, 0, 0, 1, 0,
0, 0, 1, 0, 0,
0, 1, 0, 0, 0,
1, 1, 1, 1, 1,
}
glyph_3 = {
0, 0, 0, 0, 0,
1, 1, 1, 1, 1,
0, 0, 0, 1, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1,
1, 0, 0, 0, 1,
0, 1, 1, 1, 0,
}
glyph_4 = {
0, 0, 0, 0, 0,
0, 0, 0, 1, 0,
0, 0, 1, 1, 0,
0, 1, 0, 1, 0,
1, 0, 0, 1, 0,
1, 1, 1, 1, 1,
0, 0, 0, 1, 0,
0, 0, 0, 1, 0,
}
glyph_5 = {
0, 0, 0, 0, 0,
1, 1, 1, 1, 1,
1, 0, 0, 0, 0,
1, 1, 1, 1, 0,
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
1, 0, 0, 0, 1,
0, 1, 1, 1, 0,
};
glyph_6 = {
0, 0, 0, 0, 0,
0, 0, 1, 1, 0,
0, 1, 0, 0, 0,
1, 0, 0, 0, 0,
1, 1, 1, 1, 0,
1, 0, 0, 0, 1,
1, 0, 0, 0, 1,
0, 1, 1, 1, 0,
}
glyph_7 = {
0, 0, 0, 0, 0,
1, 1, 1, 1, 1,
1, 0, 0, 0, 1,
0, 0, 0, 1, 0,
0, 0, 1, 0, 0,
0, 1, 0, 0, 0,
0, 1, 0, 0, 0,
0, 1, 0, 0, 0,
};
glyph_table = {
glyph_0, glyph_1, glyph_2, glyph_3, glyph_4, glyph_5, glyph_6, glyph_7
}
function square(xpos, ypos, w, h, c)
for y = 0, h-1 do
for x = 0, w-1 do
pixku.pt(x + xpos, y + ypos, c)
end
end
end
glyph_width = 5
glyph_height = 8
function glyph(g, xpos, ypos, c)
local pos = 1
for y = 0, glyph_height - 1 do
for x = 0, glyph_width - 1 do
if (g[pos] == 1) then
pixku.pt(xpos + x, ypos + y, c)
end
pos = pos + 1
end
end
end
for x=0,7 do
square(x * 32, 0, 32, 32 * (x + 1), x % 8)
end
local xoff = 16 - (glyph_width - 2)
local yoff = 4
g = glyph_table[1]
for x=0,7 do
glyph(glyph_table[x + 1], xoff + x*32, yoff, 7 - x)
end
pixku.save("out.png")
|
ones = {"two", "three", "four", "five", "six", "seven", "eight", "nine"}
tens = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}
msg_two = "two"
msg_hundred = {"hundred", "hundred"}
msg_thousand = {"thousand", "thousand"}
|
object_tangible_item_entertainer_console_stage_smoke_machine = object_tangible_item_entertainer_console_shared_stage_smoke_machine:new {
}
ObjectTemplates:addTemplate(object_tangible_item_entertainer_console_stage_smoke_machine, "object/tangible/item/entertainer_console/stage_smoke_machine.iff")
|
ID = "Shader"
shaders = {
particle_init = {
cs = { "data/shader/particle.hlsl", "InitializeParticleCS" },
},
particle_copy_moon_vertex_dead = {
cs = { "data/shader/particle.hlsl", "CopyDeadMoonVertexCountCS" },
},
particle_emit_in_sphere = {
cs = { "data/shader/particle.hlsl", "EmitInSphereCS" },
},
particle_emit_in_box = {
cs = { "data/shader/emitter_box.hlsl", "EmitInBoxCS" },
},
particle_emit_moon = {
cs = { "data/shader/particle.hlsl", "MoonEmitterCS" },
},
particle_simulate = {
cs = { "data/shader/particle.hlsl", "SimulateParticleCS" },
},
particle_no_simulate = {
cs = { "data/shader/particle.hlsl", "NoSimulateParticleCS" },
},
particle_simulate_a = {
cs = { "data/shader/particle.hlsl", "SimulateParticleACS" },
},
particle_simulate_color = {
cs = { "data/shader/particle.hlsl", "SimulateParticleColorCS" },
},
particle_simulate_moon = {
cs = { "data/shader/particle.hlsl", "SimulateParticleMoonCS" },
},
particle_sort = {
cs = { "data/shader/particlesort.hlsl", "BitonicSortCS" },
},
particle_sort_transpose = {
cs = { "data/shader/particlesort.hlsl", "MatrixTransposeCS" },
},
particle_render = {
vs = { "data/shader/particle.hlsl", "VS" },
gs = { "data/shader/particle.hlsl", "GS" },
ps = { "data/shader/particle.hlsl", "PS" },
},
particle_moon_render = {
vs = { "data/shader/particle.hlsl", "MoonVS" },
gs = { "data/shader/particle.hlsl", "GS" },
ps = { "data/shader/particle.hlsl", "PS" },
},
particle_shadow = {
vs = { "data/shader/particleShadow.hlsl", "VS" },
gs = { "data/shader/particleShadow.hlsl", "GS" },
},
fluid_advect = {
cs = { "data/shader/fluid3d.hlsl", "AdvectCS" },
},
fluid_advect_backward = {
cs = { "data/shader/fluid3d.hlsl", "AdvectBackwardCS" },
},
fluid_advect_maccormack = {
cs = { "data/shader/fluid3d.hlsl", "AdvectMacCormackCS" },
},
fluid_divergence = {
cs = { "data/shader/fluid3d.hlsl", "DivergenceCS" },
},
fluid_jacobi = {
cs = { "data/shader/fluid3d.hlsl", "JacobiCS" },
},
fluid_project = {
cs = { "data/shader/fluid3d.hlsl", "ProjectCS" },
},
fluid_add_pressure = {
cs = { "data/shader/fluid3d.hlsl", "AddPressureCS" },
},
fluid_reset = {
cs = { "data/shader/fluid3d.hlsl", "ResetCS" },
},
fluid_render_volume = {
vs = { "data/shader/fluid3d.hlsl", "RenderVolumeVS" },
ps = { "data/shader/fluid3d.hlsl", "RenderVolumePS" },
},
fluid_render_grid = {
vs = { "data/shader/fluid3d.hlsl", "RenderVolumeVS" },
ps = { "data/shader/fluid3d.hlsl", "RenderGridPS" },
},
}
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:25' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
local ICON_PER_ROW = 6
local ICON_PADDING = 40
local ICON_SIZE = 64
local ICON_OFFSET_X = 0
local ICON_OFFSET_Y = 0
ZO_ICONSELECTOR_MOVEMENT_TYPES =
{
MOVE_RIGHT = 1,
MOVE_LEFT = 2,
MOVE_UP = 3,
MOVE_DOWN = 4,
-- LAST allows derived classes to start their movement enumerations after the base movements
LAST = 5,
}
function ZO_IconSelectorPlaySound(type)
if type == ZO_ICONSELECTOR_MOVEMENT_TYPES.MOVE_RIGHT then
PlaySound(SOUNDS.HOR_LIST_ITEM_SELECTED)
elseif type == ZO_ICONSELECTOR_MOVEMENT_TYPES.MOVE_LEFT then
PlaySound(SOUNDS.HOR_LIST_ITEM_SELECTED)
elseif type == ZO_ICONSELECTOR_MOVEMENT_TYPES.MOVE_UP then
PlaySound(SOUNDS.GAMEPAD_MENU_UP)
elseif type == ZO_ICONSELECTOR_MOVEMENT_TYPES.MOVE_DOWN then
PlaySound(SOUNDS.GAMEPAD_MENU_DOWN)
end
end
--------------------
-- Util Functions --
--------------------
local function GetGridRowCol(index, itemsPerRow)
local row = zo_floor((index - 1) / itemsPerRow)
local col = (index - 1) % itemsPerRow
return row, col
end
local function GetGridIndex(row, col, itemsPerRow)
local index = (row * itemsPerRow) + col
return index
end
----------------------------
-- ZO_GamepadIconSelector --
----------------------------
ZO_GamepadIconSelector = ZO_Object:Subclass()
function ZO_GamepadIconSelector:New(...)
local object = ZO_Object.New(self)
object:Initialize(...)
return object
end
function ZO_GamepadIconSelector:Initialize(control, settings)
self.control = control
self.control.iconSelectorObject = self
self.iconsPerRow = ICON_PER_ROW
self.iconPadding = ICON_PADDING
self.iconSize = ICON_SIZE
self.iconOffsetX = ICON_OFFSET_X
self.iconOffsetY = ICON_OFFSET_Y
if(settings.iconsPerRow) then
self.iconsPerRow = settings.iconsPerRow
end
if(settings.iconPadding) then
self.iconPadding = settings.iconPadding
end
if(settings.iconSize) then
self.iconSize = settings.iconSize
end
if(settings.iconOffsetX) then
self.iconOffsetX = settings.iconOffsetX
end
if(settings.iconOffsetY) then
self.iconOffsetY = settings.iconOffsetY
end
if(settings.totalIcons > self.iconsPerRow) then
self.vertMovementController = ZO_MovementController:New(MOVEMENT_CONTROLLER_DIRECTION_VERTICAL)
end
self.horzMovementController = ZO_MovementController:New(MOVEMENT_CONTROLLER_DIRECTION_HORIZONTAL)
self.onPlaySoundFunction = ZO_IconSelectorPlaySound
self.iconHighlight = control:GetNamedChild("Highlight")
self.iconHighlight:SetHidden(true)
self.iconHighlightHint = self.iconHighlight:GetNamedChild("Hint")
self.iconSelectorControls = {}
local iconSelectorId = 0
for i = 1, settings.totalIcons do
local iconSelector = CreateControlFromVirtual(settings.uniqueName, control, "ZO_GamepadIconSelectorElementTemplate", iconSelectorId)
iconSelector.iconIndex = i
iconSelector:SetDimensions(self.iconSize, self.iconSize)
local row, col = GetGridRowCol(i, self.iconsPerRow)
iconSelector:SetAnchor(TOPLEFT, nil, TOPLEFT, col * (self.iconSize + self.iconPadding) + self.iconOffsetX, row * (self.iconSize + self.iconPadding) + self.iconOffsetY)
settings.initFunc(iconSelector, i)
iconSelectorId = iconSelectorId + 1
table.insert(self.iconSelectorControls, iconSelector)
end
local defaultHighlightIndex = 1
if(settings.defaultHighlightIndex) then
defaultHighlightIndex = settings.defaultHighlightIndex
end
self:HighlightIconControl(defaultHighlightIndex)
end
function ZO_GamepadIconSelector:ForAllIconControls(func, ...)
for i = 1, #self.iconSelectorControls do
func(self.iconSelectorControls[i], i, ...)
end
end
------------------------
-- Selector Highlight --
------------------------
function ZO_GamepadIconSelector:ModifyHighlightIndex(rowDiff, colDiff)
local oldHighlightIndex = self.highlightIndex
local itemsPerRow = self.iconsPerRow
local totalItems = #self.iconSelectorControls
local minCol = 0
local minRow = 0
local row, col = GetGridRowCol(self.highlightIndex, itemsPerRow)
local maxRow, maxCol = GetGridRowCol(totalItems, itemsPerRow)
col = col + colDiff
if(row ~= maxRow) then
if(col < minCol) then
col = itemsPerRow - 1
elseif(col > itemsPerRow - 1) then
col = minCol
end
else
if(col < minCol) then
col = maxCol
elseif(col > maxCol) then
col = minCol
end
end
row = row + rowDiff
if(row < minRow) then
row = maxRow
elseif (row > maxRow) then
row = 0
end
if(row == maxRow and col > maxCol) then
if(rowDiff > 0) then
row = minRow
else
row = row - 1
end
end
local newHighlightIndex = GetGridIndex(row, col, itemsPerRow) + 1
self:HighlightIconControl(newHighlightIndex)
return newHighlightIndex ~= oldHighlightIndex
end
function ZO_GamepadIconSelector:HighlightIconControl(index)
local control = self.iconSelectorControls[index]
self.highlightIndex = index
self.iconHighlight:ClearAnchors()
self.iconHighlight:SetAnchor(CENTER, control, CENTER, 0, 0)
self.iconHighlight:SetHidden(false)
if(control.highlightHint) then
self.iconHighlightHint:SetText(control.highlightHint)
self.iconHighlightHint:SetHidden(false)
else
self.iconHighlightHint:SetHidden(true)
end
end
function ZO_GamepadIconSelector:GetHighlightIndex()
return self.highlightIndex
end
function ZO_GamepadIconSelector_RefreshIconSelectionIndicator(control, index, selectedIconIndex)
local selectedIndicator = control:GetNamedChild("SelectedIndicator")
selectedIndicator:SetHidden(index ~= selectedIconIndex)
end
-------------------------
-- Movement Controller --
-------------------------
function ZO_GamepadIconSelector:Activate()
self:SetDirectionalInputEnabled(true)
end
function ZO_GamepadIconSelector:Deactivate()
self:SetDirectionalInputEnabled(false)
end
function ZO_GamepadIconSelector:SetDirectionalInputEnabled(enabled)
if(self.directionInputEnabled ~= enabled) then
self.directionInputEnabled = enabled
self.iconHighlight:SetHidden(not enabled)
if enabled then
DIRECTIONAL_INPUT:Activate(self, self.control)
else
DIRECTIONAL_INPUT:Deactivate(self)
end
end
end
function ZO_GamepadIconSelector:UpdateDirectionalInput()
if(self.horzMovementController) then
local result = self.horzMovementController:CheckMovement()
if result == MOVEMENT_CONTROLLER_MOVE_NEXT then
self:MoveRight()
elseif result == MOVEMENT_CONTROLLER_MOVE_PREVIOUS then
self:MoveLeft()
end
end
if(self.vertMovementController) then
local result = self.vertMovementController:CheckMovement()
if result == MOVEMENT_CONTROLLER_MOVE_NEXT then
self:MoveDown()
elseif result == MOVEMENT_CONTROLLER_MOVE_PREVIOUS then
self:MoveUp()
end
end
end
function ZO_GamepadIconSelector:MoveUp()
if self:ModifyHighlightIndex(-1, 0) then
self.onPlaySoundFunction(ZO_ICONSELECTOR_MOVEMENT_TYPES.MOVE_UP)
end
end
function ZO_GamepadIconSelector:MoveDown()
if self:ModifyHighlightIndex(1, 0) then
self.onPlaySoundFunction(ZO_ICONSELECTOR_MOVEMENT_TYPES.MOVE_DOWN)
end
end
function ZO_GamepadIconSelector:MoveLeft()
if self:ModifyHighlightIndex(0, -1) then
self.onPlaySoundFunction(ZO_ICONSELECTOR_MOVEMENT_TYPES.MOVE_LEFT)
end
end
function ZO_GamepadIconSelector:MoveRight()
if self:ModifyHighlightIndex(0, 1) then
self.onPlaySoundFunction(ZO_ICONSELECTOR_MOVEMENT_TYPES.MOVE_RIGHT)
end
end
function ZO_GamepadIconSelector:SetPlaySoundFunction(fn)
self.onPlaySoundFunction = fn
end
|
local SkillFsm = require "gameplay.fsm.skillfsm"
local BaseSkillFsm = Inherit(SkillFsm)
local Damage = require "gameplay.damage"
function BaseSkillFsm:Ctor(Owner, SkillInfo, SkillLevel, Target)
self:Enter("Before")
end
function BaseSkillFsm:CalDamage()
local LevelInfo = self.m_LevelInfo
local DamageAmout = LevelInfo.AttackPower + self.m_Owner:GetBaseAttackPower()*LevelInfo.AttackPowerFactor
return Damage:NewIns(DamageAmout, self.m_Owner)
end
return BaseSkillFsm
|
ITEM.name = "Патроны 12x70"
ITEM.ammo = "12x70"
ITEM.ammoAmount = 60
ITEM.desc = "Коробка с патронами калибра 12x70"
ITEM.category = "Патроны"
ITEM.price = 1200
ITEM.exRender = false
ITEM.model = "models/kek1ch/ammo_12x70_buck.mdl"
ITEM.width = 2
ITEM.height = 1
ITEM.iconCam = {
pos = Vector(81.237319946289, 68.166198730469, 50.932453155518),
ang = Angle(25, 220, 0),
fov = 6.3057324840764
}
|
---@class nil @内建空类型
---@class boolean @内建布尔类型
---@class number @内建浮点类型
---@class int @内建整数类型
---@class function @内建函数类型
---@class userdata @内建C++对象类型
---@class thread @内建协程类型
---@class table @内建表类型
---@class any @内建任意类型
---@class void @内建无类型
---@class string @内建字符串类型
|
object_tangible_collection_rare_melee_strike_assault_lance = object_tangible_collection_shared_rare_melee_strike_assault_lance:new {
}
ObjectTemplates:addTemplate(object_tangible_collection_rare_melee_strike_assault_lance, "object/tangible/collection/rare_melee_strike_assault_lance.iff")
|
-- Button.lua
-- This tab contains the Unit.button class, which is simply a touch-sensitive version of Unit.textPanel.
-- The init method requires a table of touch event functions, and can optionally include a highlight style and children.
-- Don't ask me why there isn't a class for buttons without text. Buttons have got to have SOMETHING on them, right?
Unit.button = class(Unit.textPanel)
function Unit.button:init(params, children)
Unit.textPanel.init(self, params, children)
self.touchEvents = params.touchEvents or Unit.style.touchEvents
self.hold = params.hold
self.isHeld = false
self.defaultStyle = self.style
self.priority = params.priority or self.layer
local h = params.highlight
self.highlightTouchEvent = params.highlightTouchEvent or Unit.style.highlightTouchEvent
if h then
self.highlightStyle = {
asset = h.asset or self.style.asset,
tint = h.tint or self.style.tint,
fill = h.fill or self.style.fill,
stroke = h.stroke or self.style.stroke,
strokeWidth = h.strokeWidth or self.style.strokeWidth,
scale = h.scale or self.style.scale,
rotate = h.rotate or self.style.rotate
}
else self.highlightStyle = self.defaultStyle end
self.toucher = Unit.addToucher(self, self.touchEvents, self.priority, params.share)
--self.styleTween = tween.delay(1)
end
function Unit.button:draw()
Unit.textPanel.draw(self)
if self.hold and self.isHeld then self.hold(self) end
end
function Unit.button:hit(touch)
local bl, tr = self:getCorners()
if touch.x > bl.x and touch.y > bl.y and touch.x < tr.x and touch.y < tr.y then return true end
return false
end
function Unit.button:highlight(bool)
if bool then self.style = self.highlightStyle else self.style = self.defaultStyle end
end
-- This is the uber-spooky screen that appears if you deleted Defaults.lua and still refused to define a screen!! :O
Unit.noScreen = Unit.screen({},{
Unit.textPanel({w=1,text="UI error:\nNo screen defined",textFill=color(255),size=20})
})
|
-- decode quoted-printable text
T=read"*a"
T=gsub(T,"=\n","")
T=gsub(T,"=(%x%x)",function (x) return strchar(tonumber(x,16)) end)
write(T)
|
---@diagnostic disable: unbalanced-assignments
local SWFtRywD='2.1.0'local e,v,l6Sm5=next,type,pcall;local oUA,QFKEzBf=setmetatable,getmetatable
local odpE,p=table.insert,table.sort;local lIpFkbLI,JdUtcU=table.remove,table.concat
local GQLN,toXyq,S9TO=math.randomseed,math.random,math.huge;local pS78Y,BCf7,RlMSrmdD,VCD=math.floor,math.max,math.min,math.ceil
local OV7=coroutine.wrap;local X83a=coroutine.yield;local PizLA9mj=rawget
local hUL=table.unpack or unpack;local l,kyWtqIf0=pairs,ipairs;local zupvsz=error;local Mw=os and os.clock or nil
local S1wg_DG={}local function sf0(cmWo_v,RoXZEsn)return cmWo_v>RoXZEsn end;local function qxZa6ozV(BKLwtAVx,BMZNmf0)
return BKLwtAVx<BMZNmf0 end;local function hgW2H5(qL9C)local Colg=0
for ex2xo17,I in l(qL9C)do Colg=Colg+1 end;return Colg end
local function z5i2i(K66,Tq,jmB,...)
jmB=jmB or S1wg_DG.identity;local bjO;for QoYPziln,Hj in l(K66)do
if not bjO then bjO=jmB(Hj,...)else local KBlIVi=jmB(Hj,...)bjO=
Tq(bjO,KBlIVi)and bjO or KBlIVi end end;return bjO end
local function MGSnnzOI(OR8it1,GAqAsa,Oc_,Qj)
for Ybp8=0,#OR8it1,GAqAsa do
local ZmzyNm=S1wg_DG.slice(OR8it1,Ybp8+1,Ybp8+GAqAsa)
if#ZmzyNm>0 then while(#ZmzyNm<GAqAsa and Qj)do
ZmzyNm[#ZmzyNm+1]=Qj end;Oc_(ZmzyNm)end end end
local function B0o5xpg7(akG0mUnS,iy,gc7SaW,FnbJWd2)
for cpdLk=0,#akG0mUnS,iy-1 do
local FbQX=S1wg_DG.slice(akG0mUnS,cpdLk+1,cpdLk+iy)if#FbQX>0 and cpdLk+1 <#akG0mUnS then while
(#FbQX<iy and FnbJWd2)do FbQX[#FbQX+1]=FnbJWd2 end
gc7SaW(FbQX)end end end
local function VQT(ejMVLYZd,eS0X,XDQS4ASf,IiNU)
for gUfudNUg=0,#ejMVLYZd,1 do
local d3=S1wg_DG.slice(ejMVLYZd,gUfudNUg+1,gUfudNUg+eS0X)
if#d3 >0 and gUfudNUg+eS0X<=#ejMVLYZd then while
(#d3 <eS0X and IiNU)do d3[#d3+1]=IiNU end;XDQS4ASf(d3)end end end
local function Id(gTOcAHv,vY_4HT1n,DzPbzg)if vY_4HT1n==0 then DzPbzg(gTOcAHv)end
for UMD=1,vY_4HT1n do
gTOcAHv[vY_4HT1n],gTOcAHv[UMD]=gTOcAHv[UMD],gTOcAHv[vY_4HT1n]Id(gTOcAHv,vY_4HT1n-1,DzPbzg)
gTOcAHv[vY_4HT1n],gTOcAHv[UMD]=gTOcAHv[UMD],gTOcAHv[vY_4HT1n]end end;local function Ub(K3ZE7Ou)return K3ZE7Ou>=0 and 1 or-1 end
local qJExeUn2=-1;S1wg_DG.operator={}
S1wg_DG.operator.add=function(fBI,wMSY)return fBI+wMSY end
S1wg_DG.operator.sub=function(_nD2rl,aVh8xSly)return _nD2rl-aVh8xSly end
S1wg_DG.operator.mul=function(i,P_NNVDyt)return i*P_NNVDyt end
S1wg_DG.operator.div=function(cVEyN,uj2AiF)return cVEyN/uj2AiF end
S1wg_DG.operator.mod=function(W,lbHN2)return W%lbHN2 end
S1wg_DG.operator.exp=function(PwgW3lfq,z)return PwgW3lfq^z end;S1wg_DG.operator.pow=S1wg_DG.operator.exp;S1wg_DG.operator.unm=function(K)return
-K end
S1wg_DG.operator.neg=S1wg_DG.operator.unm
S1wg_DG.operator.floordiv=function(xx,aYb)return pS78Y(xx/aYb)end
S1wg_DG.operator.intdiv=function(JM2,bmAjLT)return JM2 >=0 and pS78Y(JM2/bmAjLT)or
VCD(JM2/bmAjLT)end
S1wg_DG.operator.eq=function(eExYnwnh,XMBmJyiP)return eExYnwnh==XMBmJyiP end
S1wg_DG.operator.neq=function(nowqEU6m,iKD8V)return nowqEU6m~=iKD8V end
S1wg_DG.operator.lt=function(YtRS,A)return YtRS<A end
S1wg_DG.operator.gt=function(mHJ,Q57BJ)return mHJ>Q57BJ end
S1wg_DG.operator.le=function(vM,JeGCDX)return vM<=JeGCDX end
S1wg_DG.operator.ge=function(A,UFZlp)return A>=UFZlp end
S1wg_DG.operator.land=function(VsrKM,uhIq)return VsrKM and uhIq end
S1wg_DG.operator.lor=function(EEOUzhy,hbrt)return EEOUzhy or hbrt end;S1wg_DG.operator.lnot=function(D)return not D end;S1wg_DG.operator.concat=function(Q,mRqle)return
Q..mRqle end;S1wg_DG.operator.length=function(sBEZ8)return
#sBEZ8 end
S1wg_DG.operator.len=S1wg_DG.operator.length;function S1wg_DG.clear(WhHB0ygh)for rYSD0 in l(WhHB0ygh)do WhHB0ygh[rYSD0]=nil end
return WhHB0ygh end;function S1wg_DG.each(BIL5,GQLlkH)for aN4J2zRQ,eWca in l(BIL5)do
GQLlkH(eWca,aN4J2zRQ)end end
function S1wg_DG.eachi(AGUR2QK,FK)
local _=S1wg_DG.sort(S1wg_DG.select(S1wg_DG.keys(AGUR2QK),S1wg_DG.isInteger))
for YQZ729qQ,rZh2wG in kyWtqIf0(_)do FK(AGUR2QK[rZh2wG],rZh2wG)end end;function S1wg_DG.at(sef4eW6Q,...)local Z={}
for UacO6D,FdnzjW in kyWtqIf0({...})do Z[#Z+1]=sef4eW6Q[FdnzjW]end;return Z end
function S1wg_DG.adjust(o,lMAL,CpQ)
if(
o[lMAL]==nil)then zupvsz("key not existing in table")end;local L=S1wg_DG.clone(o)L[lMAL]=
v(CpQ)=='function'and CpQ(L[lMAL])or CpQ;return L end
function S1wg_DG.count(HnQS_Z,rib)
if rib==nil then return S1wg_DG.size(HnQS_Z)end;local hgW2H5=0;for w,YT6wZ in l(HnQS_Z)do
if S1wg_DG.isEqual(YT6wZ,rib)then hgW2H5=hgW2H5+1 end end;return hgW2H5 end
function S1wg_DG.countf(VYv,gU)local hgW2H5=0;for JzG8W4Ya,dZ54oc in l(VYv)do
if gU(dZ54oc,JzG8W4Ya)then hgW2H5=hgW2H5+1 end end;return hgW2H5 end
function S1wg_DG.allEqual(v_LoR,gRY)local z,ad=e(v_LoR)
for z,Ui0Qa in l(v_LoR)do if gRY then
if not gRY(ad,Ui0Qa)then return false end else
if not S1wg_DG.isEqual(ad,Ui0Qa)then return false end end end;return true end
function S1wg_DG.cycle(g,Itx)Itx=Itx or 1;if Itx<=0 then return S1wg_DG.noop end
local JpoaGH,cyAcCT;local RCA=0
while true do
return
function()JpoaGH=JpoaGH and e(g,JpoaGH)or e(g)cyAcCT=not
cyAcCT and JpoaGH or cyAcCT;if Itx then RCA=
(JpoaGH==cyAcCT)and RCA+1 or RCA
if RCA>Itx then return end end;return g[JpoaGH],JpoaGH end end end
function S1wg_DG.map(L46S,GKTYT)local hXSTz8FJ={}
for C24r7o4G,b_4Q38cU in l(L46S)do local N,JbPw,j=C24r7o4G,GKTYT(b_4Q38cU,C24r7o4G)hXSTz8FJ[
j and JbPw or N]=j or JbPw end;return hXSTz8FJ end
function S1wg_DG.mapi(S,cg4FV7bl)local flf9sWX={}for uNoS,ZWoH9V08 in kyWtqIf0(S)do
local RWo,GWBQL,PCldTUn9=uNoS,cg4FV7bl(ZWoH9V08,uNoS)
flf9sWX[PCldTUn9 and GWBQL or RWo]=PCldTUn9 or GWBQL end;return
flf9sWX end
function S1wg_DG.reduce(sO_,ALbdmINL,b)for DUgF0E,vGxJ6f in l(sO_)do
if b==nil then b=vGxJ6f else b=ALbdmINL(b,vGxJ6f)end end;return b end
function S1wg_DG.best(a4ga2I,syGyB_)local VO,J1r=e(a4ga2I)
for iBcU3_7D,N in l(a4ga2I)do if J1r==nil then J1r=N else
J1r=syGyB_(J1r,N)and J1r or N end end;return J1r end
function S1wg_DG.reduceBy(M4V,_feve,OPz_7bk,H64aD)return
S1wg_DG.reduce(S1wg_DG.select(M4V,OPz_7bk),_feve,H64aD)end
function S1wg_DG.reduceRight(ny7,QDj6GAX,k6pXzd)return
S1wg_DG.reduce(S1wg_DG.reverse(ny7),QDj6GAX,k6pXzd)end
function S1wg_DG.mapReduce(hsLwu,R,JKZ)local yHbsh={}for d4z,i in l(hsLwu)do
yHbsh[d4z]=not JKZ and i or R(JKZ,i)JKZ=yHbsh[d4z]end;return yHbsh end
function S1wg_DG.mapReduceRight(HyEk4lbh,PhU,rWwbNge)return
S1wg_DG.mapReduce(S1wg_DG.reverse(HyEk4lbh),PhU,rWwbNge)end
function S1wg_DG.include(SKxD,o3uQKvJ)local vAZm=(v(o3uQKvJ)=='function')and o3uQKvJ or
S1wg_DG.isEqual;for q,fFuE in l(SKxD)do if
vAZm(fFuE,o3uQKvJ)then return true end end;return false end
function S1wg_DG.detect(KypMW,JJT4nKO)local TFLF=(v(JJT4nKO)=='function')and JJT4nKO or
S1wg_DG.isEqual;for hEoAa,PGN in l(KypMW)do if
TFLF(PGN,JJT4nKO)then return hEoAa end end end
function S1wg_DG.where(K2_kF5,YpimJ)
local Gg7Ttui=S1wg_DG.select(K2_kF5,function(_)for EGeAf in l(YpimJ)do
if _[EGeAf]~=YpimJ[EGeAf]then return false end end;return true end)return#Gg7Ttui>0 and Gg7Ttui or nil end
function S1wg_DG.findWhere(ymP,z5pHKyoa)
local h=S1wg_DG.detect(ymP,function(xwT)for y33ux in l(z5pHKyoa)do if z5pHKyoa[y33ux]~=xwT[y33ux]then
return false end end;return true end)return h and ymP[h]end
function S1wg_DG.select(Ut,GOijBp)local oUi={}for b2a3,xer in l(Ut)do
if GOijBp(xer,b2a3)then oUi[#oUi+1]=xer end end;return oUi end
function S1wg_DG.reject(SQHAAR,qybRcP1)local z={}for N0NaR,FBfW in l(SQHAAR)do
if not qybRcP1(FBfW,N0NaR)then z[#z+1]=FBfW end end;return z end;function S1wg_DG.all(lnM4,_oDmX_)
for t,K in l(lnM4)do if not _oDmX_(K,t)then return false end end;return true end
function S1wg_DG.invoke(ppm021I,ASUXhD)
return
S1wg_DG.map(ppm021I,function(KCm,u)
if(
v(KCm)=='table')then
if KCm[ASUXhD]then
if S1wg_DG.isCallable(KCm[ASUXhD])then return
KCm[ASUXhD](KCm,u)else return KCm[ASUXhD]end else
if S1wg_DG.isCallable(ASUXhD)then return ASUXhD(KCm,u)end end elseif S1wg_DG.isCallable(ASUXhD)then return ASUXhD(KCm,u)end end)end
function S1wg_DG.pluck(fDk,gxYY)local sVMxk={}for SyD,v4 in l(fDk)do
if v4[gxYY]then sVMxk[#sVMxk+1]=v4[gxYY]end end;return sVMxk end;function S1wg_DG.max(j7siW,Hl)return z5i2i(j7siW,sf0,Hl)end;function S1wg_DG.min(AP060rq,DIEKD10)return
z5i2i(AP060rq,qxZa6ozV,DIEKD10)end
function S1wg_DG.same(lLJ,EicsS)
return
S1wg_DG.all(lLJ,function(JubU)return
S1wg_DG.include(EicsS,JubU)end)and
S1wg_DG.all(EicsS,function(L)return S1wg_DG.include(lLJ,L)end)end;function S1wg_DG.sort(JKci,SsBe)p(JKci,SsBe)return JKci end
function S1wg_DG.sortedk(o,ZOmcmO)
local _G19JrRB=S1wg_DG.keys(o)p(_G19JrRB,ZOmcmO)local m0r3_J=0
return function()m0r3_J=m0r3_J+1;return _G19JrRB[m0r3_J],
o[_G19JrRB[m0r3_J]]end end
function S1wg_DG.sortedv(MLrs,hP5)local oqjhEZb0=S1wg_DG.keys(MLrs)hP5=hP5 or qxZa6ozV
p(oqjhEZb0,function(G,MOrzq4)return
hP5(MLrs[G],MLrs[MOrzq4])end)local Pha=0;return
function()Pha=Pha+1;return oqjhEZb0[Pha],MLrs[oqjhEZb0[Pha]]end end
function S1wg_DG.sortBy(bEMp,dd,MOQN)local O=dd or S1wg_DG.identity;if(v(dd)=='string')then O=function(bEMp)return
bEMp[dd]end end;MOQN=
MOQN or qxZa6ozV
p(bEMp,function(FEpet,P)return MOQN(O(FEpet),O(P))end)return bEMp end
function S1wg_DG.groupBy(G,EcLLM)local wo={}for ur,XTX in l(G)do local wc8hjKp1=EcLLM(XTX,ur)
if wo[wc8hjKp1]then wo[wc8hjKp1][#
wo[wc8hjKp1]+1]=XTX else wo[wc8hjKp1]={XTX}end end;return wo end
function S1wg_DG.countBy(f,Hjag)local Yg={}for uc,bw in l(f)do local ad=Hjag(bw,uc)
Yg[ad]=(Yg[ad]or 0)+1 end;return Yg end
function S1wg_DG.size(...)local EG344W={...}local MVlUhPEM=EG344W[1]return
(v(MVlUhPEM)=='table')and hgW2H5(EG344W[1])or hgW2H5(EG344W)end;function S1wg_DG.containsKeys(LT,pfiWYrg)
for smnX9H6 in l(pfiWYrg)do if not LT[smnX9H6]then return false end end;return true end
function S1wg_DG.sameKeys(FzRhHR,mMBxOoQa)
for xYSLIT in
l(FzRhHR)do if not mMBxOoQa[xYSLIT]then return false end end
for Eae7ILmk in l(mMBxOoQa)do if not FzRhHR[Eae7ILmk]then return false end end;return true end
function S1wg_DG.sample(Jy23ZRAA,V8IWw,uyYdf)V8IWw=V8IWw or 1;if V8IWw==0 then return{}end;if V8IWw==1 then if uyYdf then
GQLN(uyYdf)end
return{Jy23ZRAA[toXyq(1,#Jy23ZRAA)]}end;return
S1wg_DG.slice(S1wg_DG.shuffle(Jy23ZRAA,uyYdf),1,V8IWw)end
function S1wg_DG.sampleProb(K,ZX,tbdC)if tbdC then GQLN(tbdC)end;local VaY3={}
for HK7Mbgze,VXPfx in kyWtqIf0(K)do if toXyq()<ZX then VaY3[
#VaY3+1]=VXPfx end end;return VaY3 end
function S1wg_DG.nsorted(j3Qk,X1,GpruB)GpruB=GpruB or qxZa6ozV;X1=X1 or 1;local r,hgW2H5={},0
for V7YqV,JbvH7 in
S1wg_DG.sortedv(j3Qk,GpruB)do if hgW2H5 <X1 then hgW2H5=hgW2H5+1;r[hgW2H5]=JbvH7 end end;return r end
function S1wg_DG.shuffle(Cqk9Luq,PeAP9X)if PeAP9X then GQLN(PeAP9X)end;local vN5AF9={}for j,EOgmP in kyWtqIf0(Cqk9Luq)do local jmJof=pS78Y(
toXyq()*j)+1;vN5AF9[j]=vN5AF9[jmJof]
vN5AF9[jmJof]=EOgmP end;return vN5AF9 end;function S1wg_DG.pack(...)return{...}end;function S1wg_DG.find(yz1Kuwby,KVE6TG,YY)
for r9=YY or 1,#yz1Kuwby do if
S1wg_DG.isEqual(yz1Kuwby[r9],KVE6TG)then return r9 end end end;function S1wg_DG.reverse(mtUG)
local PFRuf={}
for KhK1gRj9=#mtUG,1,-1 do PFRuf[#PFRuf+1]=mtUG[KhK1gRj9]end;return PFRuf end;function S1wg_DG.fill(Xgj,Ko,A,IU6Om)IU6Om=
IU6Om or S1wg_DG.size(Xgj)
for A=A or 1,IU6Om do Xgj[A]=Ko end;return Xgj end;function S1wg_DG.zeros(sKIIqz)return
S1wg_DG.fill({},0,1,sKIIqz)end;function S1wg_DG.ones(wmhARqEa)return
S1wg_DG.fill({},1,1,wmhARqEa)end;function S1wg_DG.vector(_RT3,V)return
S1wg_DG.fill({},_RT3,1,V)end
function S1wg_DG.selectWhile(BTA,QVEYENaX)local gxqa={}
for q4,QyKi in
kyWtqIf0(BTA)do if QVEYENaX(QyKi,q4)then gxqa[q4]=QyKi else break end end;return gxqa end
function S1wg_DG.dropWhile(_o3FE,n)local WM;for zb8b,YBqeh in kyWtqIf0(_o3FE)do
if not n(YBqeh,zb8b)then WM=zb8b;break end end;if(WM==nil)then return{}end;return
S1wg_DG.rest(_o3FE,WM)end
function S1wg_DG.sortedIndex(WRkIg,RH_vLUg,aEH,g20N7)local puZN=aEH or qxZa6ozV
if(g20N7 ==true)then p(WRkIg,puZN)end;for _Dy=1,#WRkIg do
if not puZN(WRkIg[_Dy],RH_vLUg)then return _Dy end end;return#WRkIg+1 end;function S1wg_DG.indexOf(MC,WOBSVeqF)
for A=1,#MC do if MC[A]==WOBSVeqF then return A end end end
function S1wg_DG.lastIndexOf(vqW6,R4oRlgh)
local rBRXA=S1wg_DG.indexOf(S1wg_DG.reverse(vqW6),R4oRlgh)if rBRXA then return#vqW6-rBRXA+1 end end
function S1wg_DG.findIndex(qfFSJN,Va8fT08T)for d778=1,#qfFSJN do
if Va8fT08T(qfFSJN[d778],d778)then return d778 end end end
function S1wg_DG.findLastIndex(aZT,ni9je9bJ)
local uwwNE=S1wg_DG.findIndex(S1wg_DG.reverse(aZT),ni9je9bJ)if uwwNE then return#aZT-uwwNE+1 end end;function S1wg_DG.addTop(X40cF,...)
for EW,asgq in kyWtqIf0({...})do odpE(X40cF,1,asgq)end;return X40cF end;function S1wg_DG.prepend(IQybL1,...)return
S1wg_DG.append({...},IQybL1)end;function S1wg_DG.push(hYKT45,...)
local Rq7={...}
for LQ_EIcl,uaL in kyWtqIf0({...})do hYKT45[#hYKT45+1]=uaL end;return hYKT45 end
function S1wg_DG.shift(gujcrFp,ph06vXj)ph06vXj=RlMSrmdD(
ph06vXj or 1,#gujcrFp)local nH0LB4c={}
for ALwJ9=1,ph06vXj do
local _X=gujcrFp[1]nH0LB4c[#nH0LB4c+1]=_X;lIpFkbLI(gujcrFp,1)end;return hUL(nH0LB4c)end
function S1wg_DG.unshift(ruXMob,E)E=RlMSrmdD(E or 1,#ruXMob)local jcgjAE={}
for BZmaGN=1,E do
local HSav=ruXMob[#ruXMob]jcgjAE[#jcgjAE+1]=HSav;lIpFkbLI(ruXMob)end;return hUL(jcgjAE)end
function S1wg_DG.pull(sDjMr,...)local biQX3Ut={...}
for BLEXN_=#sDjMr,1,-1 do local Ljc=false
for fpN7T,FNSk_ in kyWtqIf0(biQX3Ut)do if(Ljc==false)then
if
S1wg_DG.isEqual(sDjMr[BLEXN_],FNSk_)then lIpFkbLI(sDjMr,BLEXN_)Ljc=true end end end end;return sDjMr end
function S1wg_DG.removeRange(LmE,pZTFVP,XL)pZTFVP=pZTFVP or 1;XL=XL or#LmE;if pZTFVP>XL then
zupvsz("start cannot be greater than finish.")end
for L5vC0Jx=XL,pZTFVP,-1 do lIpFkbLI(LmE,L5vC0Jx)end;return LmE end
function S1wg_DG.chunk(vpONJ,A)local LN,dA14qP,JcQc,hDih6_D={},0;A=A or S1wg_DG.identity
for QKbZ464i,F1TsZ in
kyWtqIf0(vpONJ)do hDih6_D=A(F1TsZ,QKbZ464i)dA14qP=(
(hDih6_D~=JcQc)and(dA14qP+1)or dA14qP)JcQc=
(JcQc==nil)and hDih6_D or JcQc;if not LN[dA14qP]then
LN[dA14qP]={vpONJ[QKbZ464i]}else
LN[dA14qP][#LN[dA14qP]+1]=vpONJ[QKbZ464i]end;JcQc=hDih6_D end;return LN end;function S1wg_DG.slice(uF2,T,pC_)local ju={}
for deu1=T or 1,pC_ or#uF2 do ju[#ju+1]=uF2[deu1]end;return ju end;function S1wg_DG.first(IgZ6,kVRiv3F)kVRiv3F=
kVRiv3F or 1;local kWMf={}
for DawC=1,kVRiv3F do kWMf[DawC]=IgZ6[DawC]end;return kWMf end
function S1wg_DG.initial(cP,w)local UZ=
#cP
w=w and UZ- (RlMSrmdD(w,UZ))or UZ-1;local tdH={}for ymt=1,w do tdH[ymt]=cP[ymt]end;return tdH end
function S1wg_DG.last(WxGA,jBuHkH)local E3=#WxGA;jBuHkH=
jBuHkH and E3-RlMSrmdD(jBuHkH-1,E3-1)or 2;local CZi_zK={}for _6KCMph=jBuHkH,E3 do
CZi_zK[#CZi_zK+1]=WxGA[_6KCMph]end;return CZi_zK end;function S1wg_DG.rest(PY3VqYZ8,V)local y={}
for QF=V or 1,#PY3VqYZ8 do y[#y+1]=PY3VqYZ8[QF]end;return y end;function S1wg_DG.nth(hN,hVflx4kh)return
hN[hVflx4kh]end
function S1wg_DG.compact(GP)local oCZYv2dT={}
for RLaqM3,PoH in l(GP)do if PoH then oCZYv2dT[
#oCZYv2dT+1]=PoH end end;return oCZYv2dT end
function S1wg_DG.flatten(xM709D,z50)z50=z50 or false;local sAPD;local AVFi={}
for GGKI,gWaGu in kyWtqIf0(xM709D)do
if
v(gWaGu)=='table'then
sAPD=z50 and gWaGu or S1wg_DG.flatten(gWaGu)
for SFKM,j6jQmlbr in kyWtqIf0(sAPD)do AVFi[#AVFi+1]=j6jQmlbr end else AVFi[#AVFi+1]=gWaGu end end;return AVFi end
function S1wg_DG.difference(m403CY,dL)
if not dL then return S1wg_DG.clone(m403CY)end
return S1wg_DG.select(m403CY,function(PrTsHeT)
return not S1wg_DG.include(dL,PrTsHeT)end)end;function S1wg_DG.union(...)
return S1wg_DG.unique(S1wg_DG.flatten({...}))end
function S1wg_DG.intersection(...)local eNI3MT7={...}
local Rfoo=eNI3MT7[1]lIpFkbLI(eNI3MT7,1)local eUJhGD={}
for wot8,j9vJ in kyWtqIf0(Rfoo)do
if
S1wg_DG.all(eNI3MT7,function(J6Qr27Mh)return
S1wg_DG.include(J6Qr27Mh,j9vJ)end)then eUJhGD[#eUJhGD+1]=j9vJ end end;return eUJhGD end;function S1wg_DG.disjoint(...)return
(#S1wg_DG.intersection(...)==0)end
function S1wg_DG.symmetricDifference(AwxW8Do,_u)return
S1wg_DG.difference(S1wg_DG.union(AwxW8Do,_u),S1wg_DG.intersection(AwxW8Do,_u))end
function S1wg_DG.unique(B)local cdxFVpZw={}
for Y=1,#B do if not S1wg_DG.find(cdxFVpZw,B[Y])then cdxFVpZw[#
cdxFVpZw+1]=B[Y]end end;return cdxFVpZw end;function S1wg_DG.isunique(o9Uh)return
#o9Uh==# (S1wg_DG.unique(o9Uh))end
function S1wg_DG.duplicates(BuX1r)
local Wyf83f2=S1wg_DG.invert(BuX1r)local P0olj={}for z,EHCCkt in kyWtqIf0(BuX1r)do
if Wyf83f2[EHCCkt]~=z and
not S1wg_DG.find(P0olj,EHCCkt)then P0olj[#P0olj+1]=EHCCkt end end;return P0olj end
function S1wg_DG.zip(...)local x={...}
local xNWVmS=S1wg_DG.max(x,function(Pkis6H28)return#Pkis6H28 end)local kGWnkgDu={}
for tSE=1,xNWVmS do
if not kGWnkgDu[tSE]then kGWnkgDu[tSE]={}end
for abKH,LDp in kyWtqIf0(x)do if(LDp[tSE]~=nil)then
kGWnkgDu[tSE][#kGWnkgDu[tSE]+1]=LDp[tSE]end end end;return kGWnkgDu end
function S1wg_DG.zipWith(GWouUlzZ,...)local MqJhIr={...}
local Q9=S1wg_DG.max(MqJhIr,function(qnZ81I)return#qnZ81I end)local c={}for N9uN=1,Q9 do
c[N9uN]=GWouUlzZ(hUL(S1wg_DG.pluck(MqJhIr,N9uN)))end;return c end
function S1wg_DG.append(QGC,K8iFU)local gbU={}for h,hS7 in kyWtqIf0(QGC)do gbU[h]=hS7 end;for KQjMKhN,R6PYgHHE in
kyWtqIf0(K8iFU)do gbU[#gbU+1]=R6PYgHHE end;return gbU end
function S1wg_DG.interleave(...)local ZwCXrLO={...}
local lI=S1wg_DG.max(ZwCXrLO,S1wg_DG.size)local iMSMP5Lp={}
for WoARZdZ3=1,lI do for n,Uj in kyWtqIf0(ZwCXrLO)do if Uj[WoARZdZ3]then
iMSMP5Lp[#iMSMP5Lp+1]=Uj[WoARZdZ3]end end end;return iMSMP5Lp end;function S1wg_DG.interpose(HpN_N,yP3QEJ)for pwi=#HpN_N,2,-1 do odpE(HpN_N,pwi,yP3QEJ)end;return
HpN_N end
function S1wg_DG.range(QP,Iy,O9P0mj)
if
(QP==nil)and(Iy==nil)and(O9P0mj==nil)then return{}elseif(QP~=nil)and
(Iy==nil)and(O9P0mj==nil)then
QP,Iy,O9P0mj=Ub(QP),QP,Ub(QP)elseif(QP~=nil)and(Iy~=nil)and(O9P0mj==nil)then
O9P0mj=Ub(Iy-QP)end;local eFGwPxi={QP}
local m4x8ZsD4=BCf7(pS78Y((Iy-QP)/O9P0mj),0)
for _witc0Pe=1,m4x8ZsD4 do eFGwPxi[#eFGwPxi+1]=QP+O9P0mj*_witc0Pe end;return eFGwPxi end
function S1wg_DG.rep(Y8E,h)local EnMMG={}for HzO7UpZ=1,h do EnMMG[HzO7UpZ]=Y8E end;return EnMMG end
function S1wg_DG.powerset(B)local RNTu=#B;local Q_={}
for S8GB,W7yjGm in kyWtqIf0(B)do for X=1,#Q_ do local Y=Q_[X]
odpE(Q_,S1wg_DG.push(S1wg_DG.slice(Y),W7yjGm))end;odpE(Q_,{W7yjGm})end;odpE(Q_,{})return Q_ end;function S1wg_DG.partition(qqvEf3,Wriu,I0Pxr5F)if Wriu<=0 then return end
return OV7(function()
MGSnnzOI(qqvEf3,Wriu or 1,X83a,I0Pxr5F)end)end
function S1wg_DG.overlapping(ukGf_,uZpt01P,hJk0n8bR)if
uZpt01P<=1 then return end
return OV7(function()
B0o5xpg7(ukGf_,uZpt01P or 2,X83a,hJk0n8bR)end)end
function S1wg_DG.aperture(o9DTTJig,v4)if v4 <=1 then return end;return
OV7(function()VQT(o9DTTJig,v4 or 2,X83a)end)end
function S1wg_DG.pairwise(Uaq2_Xzk)return S1wg_DG.aperture(Uaq2_Xzk,2)end;function S1wg_DG.permutation(S0DM)return
OV7(function()Id(S0DM,#S0DM,X83a)end)end
function S1wg_DG.concat(GHasi5,QeX_U9tm,Dp9m,sJjNM)return
JdUtcU(S1wg_DG.map(GHasi5,tostring),QeX_U9tm,Dp9m,sJjNM)end
function S1wg_DG.xprod(GnSs,XP)local Sj={}for yKj1,F9WZ in kyWtqIf0(GnSs)do
for A5,nY_O in kyWtqIf0(XP)do Sj[#Sj+1]={F9WZ,nY_O}end end;return Sj end;function S1wg_DG.xpairs(QAJAyj5,EZ)local n={}
for M,AADiL1 in kyWtqIf0(EZ)do n[M]={QAJAyj5,AADiL1}end;return n end
function S1wg_DG.xpairsRight(Arw,b)
local _ZM1Yj3={}
for rmSU,L2RHrI in kyWtqIf0(b)do _ZM1Yj3[rmSU]={L2RHrI,Arw}end;return _ZM1Yj3 end
function S1wg_DG.sum(XW7Y5Rz)local C=0;for NhwEkTd,XGz in kyWtqIf0(XW7Y5Rz)do C=C+XGz end;return C end;function S1wg_DG.product(Tf4P2eIf)local TF3Htu=1
for K5yUw1t,Mi in kyWtqIf0(Tf4P2eIf)do TF3Htu=TF3Htu*Mi end;return TF3Htu end
function S1wg_DG.mean(WWyrqnSL)return
S1wg_DG.sum(WWyrqnSL)/ (#WWyrqnSL)end
function S1wg_DG.median(gVTyP)
local Ck=S1wg_DG.sort(S1wg_DG.clone(gVTyP))local CRG=#Ck;if CRG==0 then return elseif CRG==1 then return Ck[1]end
local dkz=VCD(CRG/2)return CRG%2 ==0 and(Ck[dkz]+Ck[dkz+1])/2 or
Ck[dkz]end;function S1wg_DG.noop()return end;function S1wg_DG.identity(zrCq)return zrCq end;function S1wg_DG.call(azXMvVdM,...)return
azXMvVdM(...)end;function S1wg_DG.constant(CBgxHfbq)return
function()return CBgxHfbq end end
function S1wg_DG.applySpec(WO)return
function(...)local H={}for C28NuJ3,sz in
l(WO)do H[C28NuJ3]=sz(...)end;return H end end
function S1wg_DG.thread(qH,...)local u=qH;local uJ1Vn4uYP={...}
for Z,pJ in kyWtqIf0(uJ1Vn4uYP)do if v(pJ)=='function'then u=pJ(u)elseif
v(pJ)=='table'then local NAjg=pJ[1]lIpFkbLI(pJ,1)
u=S1wg_DG.reduce(pJ,NAjg,u)end end;return u end
function S1wg_DG.threadRight(con,...)local I=con;local TxmZR6UE={...}
for I1b4o,nAt in kyWtqIf0(TxmZR6UE)do if v(nAt)=='function'then
I=nAt(I)elseif v(nAt)=='table'then local pNJ=nAt[1]lIpFkbLI(nAt,1)odpE(nAt,I)
I=S1wg_DG.reduce(nAt,pNJ)end end;return I end
function S1wg_DG.dispatch(...)local RQ={...}return
function(...)for wnZcHKf,Lv_8 in kyWtqIf0(RQ)do local UQ={Lv_8(...)}if#UQ>0 then
return hUL(UQ)end end end end
function S1wg_DG.memoize(FG)local vLzqjJw=oUA({},{__mode='kv'})
return function(v2dsC21)if
(vLzqjJw[v2dsC21]==nil)then vLzqjJw[v2dsC21]=FG(v2dsC21)end;return
vLzqjJw[v2dsC21]end end
function S1wg_DG.unfold(O,wx)local u,V_84V={}while true do V_84V,wx=O(wx)
if V_84V~=nil then u[#u+1]=V_84V else break end end;return u end
function S1wg_DG.once(qF)local IZbOX7TW=0;local Dd6ZLpU={}return
function(...)IZbOX7TW=IZbOX7TW+1
if IZbOX7TW<=1 then Dd6ZLpU={...}end;return qF(hUL(Dd6ZLpU))end end;function S1wg_DG.before(MP,hgW2H5)local w4c=0;local C58={}
return function(...)w4c=w4c+1;if w4c<=hgW2H5 then C58={...}end;return
MP(hUL(C58))end end
function S1wg_DG.after(Jk6Nh,hgW2H5)
local s1Ws,desLYv=hgW2H5,0;return
function(...)desLYv=desLYv+1;if desLYv>=s1Ws then return Jk6Nh(...)end end end
function S1wg_DG.compose(...)local COq2NY9I=S1wg_DG.reverse{...}
return
function(...)local aoBEg65S,x6=true
for t3cNa2l,Ik in
kyWtqIf0(COq2NY9I)do if aoBEg65S then aoBEg65S=false;x6=Ik(...)else x6=Ik(x6)end end;return x6 end end
function S1wg_DG.pipe(SeHOs,...)return S1wg_DG.compose(...)(SeHOs)end;function S1wg_DG.complement(P2rGsUx)
return function(...)return not P2rGsUx(...)end end;function S1wg_DG.juxtapose(c,...)local v12AhMm={}for F2uxGC,Xs0 in
kyWtqIf0({...})do v12AhMm[F2uxGC]=Xs0(c)end
return hUL(v12AhMm)end
function S1wg_DG.wrap(QK8ibF,TEio7k0z)return function(...)return
TEio7k0z(QK8ibF,...)end end;function S1wg_DG.times(u,N)local O2YgxDc={}
for VLsC67=1,(N or 1)do O2YgxDc[VLsC67]=u(VLsC67)end;return O2YgxDc end
function S1wg_DG.bind(OHw4,FKZ)return function(...)return
OHw4(FKZ,...)end end;function S1wg_DG.bind2(Fl,QhS8FvKI)
return function(FaZIJL,...)return Fl(FaZIJL,QhS8FvKI,...)end end;function S1wg_DG.bindn(sOT2O5,...)local x={...}
return function(...)return
sOT2O5(hUL(S1wg_DG.append(x,{...})))end end
function S1wg_DG.bindall(Wswd_OC,...)
local E={...}
for A0Un,nRHrI in kyWtqIf0(E)do local k=Wswd_OC[nRHrI]if k then
Wswd_OC[nRHrI]=S1wg_DG.bind(k,Wswd_OC)end end;return Wswd_OC end;function S1wg_DG.cond(Zp)
return function(...)
for A,_L_ in kyWtqIf0(Zp)do if _L_[1](...)then return _L_[2](...)end end end end
function S1wg_DG.both(...)
local WHpm={...}
return function(...)
for g,HiR3yiw in kyWtqIf0(WHpm)do if not HiR3yiw(...)then return false end end;return true end end
function S1wg_DG.either(...)local KeKbiDqN={...}return
function(...)for WfrZqHH8,YX9s9O in kyWtqIf0(KeKbiDqN)do
if YX9s9O(...)then return true end end;return false end end
function S1wg_DG.neither(...)local y64dF={...}
return function(...)
for sNSsH,K in kyWtqIf0(y64dF)do if K(...)then return false end end;return true end end
function S1wg_DG.uniqueId(o8T)qJExeUn2=qJExeUn2+1;if o8T then
if v(o8T)=='string'then
return o8T:format(qJExeUn2)elseif v(o8T)=='function'then return o8T(qJExeUn2)end end;return qJExeUn2 end
function S1wg_DG.iterator(xeP,Tv_3VlmX,BT)local _y3z=0
return function()_y3z=_y3z+1;if BT and _y3z>BT then return end
Tv_3VlmX=xeP(Tv_3VlmX)return Tv_3VlmX end end;function S1wg_DG.skip(rdl,NAP_5jYs)
for BZnlpW=1,(NAP_5jYs or 1)do if rdl()==nil then return end end;return rdl end
function S1wg_DG.tabulate(...)
local isN={}for yRADzw1v in...do isN[#isN+1]=yRADzw1v end;return isN end
function S1wg_DG.iterlen(...)local Jafp=0;for XWh8Ee in...do Jafp=Jafp+1 end;return Jafp end;function S1wg_DG.castArray(kpezL1e)return
(v(kpezL1e)~='table')and{kpezL1e}or kpezL1e end
function S1wg_DG.flip(h)return function(...)return
h(hUL(S1wg_DG.reverse({...})))end end
function S1wg_DG.nthArg(R7yfz_l9)return
function(...)local D35PFLu={...}return
D35PFLu[(R7yfz_l9 <0)and
(#D35PFLu+R7yfz_l9+1)or R7yfz_l9]end end;function S1wg_DG.unary(wK)
return function(...)local qeEwE={...}return wK(qeEwE[1])end end
function S1wg_DG.ary(cbtvFnSa,fYKH_)fYKH_=fYKH_ or 1
return function(...)
local W={...}local o={}for Mm99M=1,fYKH_ do o[Mm99M]=W[Mm99M]end
return cbtvFnSa(hUL(o))end end
function S1wg_DG.noarg(l6YH)return function()return l6YH()end end
function S1wg_DG.rearg(gf2,F744Ew)return
function(...)local zgxKF4={...}local UlvVvSBR={}for i2i,uRGAL in kyWtqIf0(F744Ew)do
UlvVvSBR[i2i]=zgxKF4[uRGAL]end;return gf2(hUL(UlvVvSBR))end end
function S1wg_DG.over(...)local UUlqXyb6={...}return
function(...)local fOR92g8={}for jU26,WIPTsAPz in kyWtqIf0(UUlqXyb6)do
fOR92g8[#fOR92g8+1]=WIPTsAPz(...)end;return fOR92g8 end end
function S1wg_DG.overEvery(...)local DgUx8=S1wg_DG.over(...)
return function(...)
return S1wg_DG.reduce(DgUx8(...),function(imac,xX)
return imac and xX end)end end
function S1wg_DG.overSome(...)local Mfb6Kb=S1wg_DG.over(...)
return function(...)
return S1wg_DG.reduce(Mfb6Kb(...),function(RRjV,TDOaFo)return
RRjV or TDOaFo end)end end
function S1wg_DG.overArgs(tLo4,...)local m72l={...}
return
function(...)local npM3DSU={...}for HGp4e1=1,#m72l do local uzJt7E=m72l[HGp4e1]
if
npM3DSU[HGp4e1]then npM3DSU[HGp4e1]=uzJt7E(npM3DSU[HGp4e1])end end;return
tLo4(hUL(npM3DSU))end end
function S1wg_DG.converge(sRe5S32N,Bp,rg)return
function(...)return sRe5S32N(Bp(...),rg(...))end end
function S1wg_DG.partial(S,...)local Fem={...}
return
function(...)local cHmVGY={...}local g29sXR={}for Vat,sfnkWAy8 in kyWtqIf0(Fem)do
g29sXR[Vat]=
(sfnkWAy8 =='_')and S1wg_DG.shift(cHmVGY)or sfnkWAy8 end;return
S(hUL(S1wg_DG.append(g29sXR,cHmVGY)))end end
function S1wg_DG.partialRight(hbJSGe9,...)local pI={...}
return
function(...)local B7jhm={...}local hj3={}for FKxU4=1,#pI do
hj3[FKxU4]=
(pI[FKxU4]=='_')and S1wg_DG.shift(B7jhm)or pI[FKxU4]end;return
hbJSGe9(hUL(S1wg_DG.append(B7jhm,hj3)))end end
function S1wg_DG.curry(UW,tReY)tReY=tReY or 2;local lex={}
local function h79Pm(vksQpy4)
if tReY==1 then return UW(vksQpy4)end;if vksQpy4 ~=nil then lex[#lex+1]=vksQpy4 end
if#lex<tReY then
return h79Pm else local gPCIWPt={UW(hUL(lex))}lex={}return hUL(gPCIWPt)end end;return h79Pm end;function S1wg_DG.time(l4Byxa7,...)local Fn8OR=Mw()local X1Z0van={l4Byxa7(...)}
return Mw()-Fn8OR,hUL(X1Z0van)end
function S1wg_DG.keys(C_ACFsd)local GC={}for SC7gSvMB in
l(C_ACFsd)do GC[#GC+1]=SC7gSvMB end;return GC end;function S1wg_DG.values(Ei)local GFuK1ut={}
for SXmRY3i,b in l(Ei)do GFuK1ut[#GFuK1ut+1]=b end;return GFuK1ut end
function S1wg_DG.path(KApFr,...)
local jE,yVVmXC=KApFr,{...}
for MkxwoCeK,AT in kyWtqIf0(yVVmXC)do if(jE[AT]==nil)then return end;jE=jE[AT]end;return jE end
function S1wg_DG.spreadPath(_8KO,...)local NI={...}for PE,a in kyWtqIf0(NI)do
if _8KO[a]then for GhVWeuQs,kQlY in l(_8KO[a])do
_8KO[GhVWeuQs]=kQlY;_8KO[a][GhVWeuQs]=nil end end end;return _8KO end
function S1wg_DG.flattenPath(xIl1shq,...)local qv={...}for pbEt6T,MBdHQ in kyWtqIf0(qv)do
if xIl1shq[MBdHQ]then for STXAhhM,assFn in l(xIl1shq[MBdHQ])do
xIl1shq[STXAhhM]=assFn end end end
return xIl1shq end;function S1wg_DG.kvpairs(EXpWzv)local kq={}
for up,wlI_l in l(EXpWzv)do kq[#kq+1]={up,wlI_l}end;return kq end;function S1wg_DG.toObj(nK7J)
local xv={}
for IWG,XVipkEh in kyWtqIf0(nK7J)do xv[XVipkEh[1]]=XVipkEh[2]end;return xv end
function S1wg_DG.invert(Y_xg20)
local lOn={}for Mn29lGrm,y in l(Y_xg20)do lOn[y]=Mn29lGrm end;return lOn end;function S1wg_DG.property(ye3DyN)
return function(XoIfNq)return XoIfNq[ye3DyN]end end
function S1wg_DG.propertyOf(zCZ)return function(KOblE1BH)
return zCZ[KOblE1BH]end end;function S1wg_DG.toBoolean(YPFM2F)return not not YPFM2F end
function S1wg_DG.extend(iA,...)
local f={...}for W,_ in kyWtqIf0(f)do
if v(_)=='table'then for _TPK9KUS,CcTDi in l(_)do iA[_TPK9KUS]=CcTDi end end end;return iA end
function S1wg_DG.functions(HNz,_T9Gn3b2)HNz=HNz or S1wg_DG;local mx={}for X,j in l(HNz)do if v(j)=='function'then
mx[#mx+1]=X end end
if _T9Gn3b2 then
local hwLm=QFKEzBf(HNz)
if hwLm and hwLm.__index then
local Jf1lygU=S1wg_DG.functions(hwLm.__index,_T9Gn3b2)for uCC,VoL in kyWtqIf0(Jf1lygU)do mx[#mx+1]=VoL end end end;return mx end
function S1wg_DG.clone(J1Qkmucu,uy8VNDqE)if v(J1Qkmucu)~='table'then return J1Qkmucu end
local LCuIIfa={}
for SUcXQMl,lyRouGA3 in l(J1Qkmucu)do
if v(lyRouGA3)=='table'then
if not uy8VNDqE then
LCuIIfa[SUcXQMl]=S1wg_DG.clone(lyRouGA3,uy8VNDqE)else LCuIIfa[SUcXQMl]=lyRouGA3 end else LCuIIfa[SUcXQMl]=lyRouGA3 end end;return LCuIIfa end;function S1wg_DG.tap(Q3y7y2,xPOK4sH)xPOK4sH(Q3y7y2)return Q3y7y2 end;function S1wg_DG.has(Px1,SUg)return
Px1[SUg]~=nil end
function S1wg_DG.pick(Wf0F6,...)
local G3=S1wg_DG.flatten{...}local D={}for Yghyekk,axo in l(G3)do
if(Wf0F6[axo])~=nil then D[axo]=Wf0F6[axo]end end;return D end
function S1wg_DG.omit(Sv,...)local aKiYWdc=S1wg_DG.flatten{...}local tSTVAx={}
for E4dT34,L0 in l(Sv)do if not
S1wg_DG.include(aKiYWdc,E4dT34)then tSTVAx[E4dT34]=L0 end end;return tSTVAx end
function S1wg_DG.template(wY,ilY2)if not ilY2 then return wY end;for oe1We,jQLYx1y in l(ilY2)do if not wY[oe1We]then
wY[oe1We]=jQLYx1y end end;return wY end
function S1wg_DG.isEqual(m_zjn,TyjL,JVvqdW4)local kDuC=v(m_zjn)local AUw=v(TyjL)
if kDuC~=AUw then return false end;if kDuC~='table'then return(m_zjn==TyjL)end
local vCkLg=QFKEzBf(m_zjn)local A3mjn=QFKEzBf(TyjL)
if JVvqdW4 then if(vCkLg or A3mjn)and
(vCkLg.__eq or A3mjn.__eq)then
return
vCkLg.__eq(m_zjn,TyjL)or A3mjn.__eq(TyjL,m_zjn)or(m_zjn==TyjL)end end
if S1wg_DG.size(m_zjn)~=S1wg_DG.size(TyjL)then return false end;local Wt5k;for fv5Y2j,bSgv in l(m_zjn)do Wt5k=TyjL[fv5Y2j]
if Wt5k==nil or not
S1wg_DG.isEqual(bSgv,Wt5k,JVvqdW4)then return false end end;for Wa5 in l(TyjL)do if
m_zjn[Wa5]==nil then return false end end
return true end
function S1wg_DG.result(JyrC7,QP)
if JyrC7[QP]then if S1wg_DG.isCallable(JyrC7[QP])then
return JyrC7[QP](JyrC7)else return JyrC7[QP]end end;if S1wg_DG.isCallable(QP)then return QP(JyrC7)end end;function S1wg_DG.isTable(_N)return v(_N)=='table'end
function S1wg_DG.isCallable(U)return
(
(
v(U)=='function')or((v(U)=='table')and QFKEzBf(U)and
QFKEzBf(U).__call~=nil)or false)end
function S1wg_DG.isArray(e5qv6Q)
if not(v(e5qv6Q)=='table')then return false end;local S6XO=0;for p7ogY in l(e5qv6Q)do S6XO=S6XO+1
if e5qv6Q[S6XO]==nil then return false end end;return true end;function S1wg_DG.isIterable(ZDP5SDwL)
return S1wg_DG.toBoolean((l6Sm5(l,ZDP5SDwL)))end
function S1wg_DG.type(T7H)local cdPmXFla=v(T7H)if cdPmXFla==
'userdata'then local gOp2cWZ=QFKEzBf(T7H)
local A1=io and io.stdout or nil
if A1 ~=nil and gOp2cWZ==QFKEzBf(A1)then return'file'end end;return
cdPmXFla end
function S1wg_DG.isEmpty(t51v)if(t51v==nil)then return true end;if v(t51v)=='string'then return
#t51v==0 end
if v(t51v)=='table'then return e(t51v)==nil end;return true end;function S1wg_DG.isString(Hp)return v(Hp)=='string'end;function S1wg_DG.isFunction(Tee9V)return
v(Tee9V)=='function'end;function S1wg_DG.isNil(znHly)return
znHly==nil end
function S1wg_DG.isNumber(cD)return v(cD)=='number'end
function S1wg_DG.isNaN(I)return v(I)=='number'and I~=I end
function S1wg_DG.isFinite(AN9)if v(AN9)~='number'then return false end;return AN9 >-S9TO and
AN9 <S9TO end;function S1wg_DG.isBoolean(CCI)return v(CCI)=='boolean'end;function S1wg_DG.isInteger(Ax_b)
return
v(Ax_b)=='number'and pS78Y(Ax_b)==Ax_b end
do
S1wg_DG.forEach=S1wg_DG.each;S1wg_DG.forEachi=S1wg_DG.eachi;S1wg_DG.update=S1wg_DG.adjust
S1wg_DG.alleq=S1wg_DG.allEqual;S1wg_DG.loop=S1wg_DG.cycle;S1wg_DG.collect=S1wg_DG.map
S1wg_DG.inject=S1wg_DG.reduce;S1wg_DG.foldl=S1wg_DG.reduce
S1wg_DG.injectr=S1wg_DG.reduceRight;S1wg_DG.foldr=S1wg_DG.reduceRight
S1wg_DG.mapr=S1wg_DG.mapReduce;S1wg_DG.maprr=S1wg_DG.mapReduceRight
S1wg_DG.any=S1wg_DG.include;S1wg_DG.some=S1wg_DG.include;S1wg_DG.contains=S1wg_DG.include
S1wg_DG.filter=S1wg_DG.select;S1wg_DG.discard=S1wg_DG.reject;S1wg_DG.every=S1wg_DG.all
S1wg_DG.takeWhile=S1wg_DG.selectWhile;S1wg_DG.rejectWhile=S1wg_DG.dropWhile;S1wg_DG.pop=S1wg_DG.shift
S1wg_DG.remove=S1wg_DG.pull;S1wg_DG.rmRange=S1wg_DG.removeRange
S1wg_DG.chop=S1wg_DG.removeRange;S1wg_DG.sub=S1wg_DG.slice;S1wg_DG.head=S1wg_DG.first
S1wg_DG.take=S1wg_DG.first;S1wg_DG.tail=S1wg_DG.rest;S1wg_DG.without=S1wg_DG.difference
S1wg_DG.diff=S1wg_DG.difference;S1wg_DG.symdiff=S1wg_DG.symmetricDifference
S1wg_DG.xor=S1wg_DG.symmetricDifference;S1wg_DG.uniq=S1wg_DG.unique;S1wg_DG.isuniq=S1wg_DG.isunique
S1wg_DG.transpose=S1wg_DG.zip;S1wg_DG.part=S1wg_DG.partition;S1wg_DG.perm=S1wg_DG.permutation
S1wg_DG.transposeWith=S1wg_DG.zipWith;S1wg_DG.intersperse=S1wg_DG.interpose
S1wg_DG.sliding=S1wg_DG.aperture;S1wg_DG.mirror=S1wg_DG.invert;S1wg_DG.join=S1wg_DG.concat
S1wg_DG.average=S1wg_DG.mean;S1wg_DG.always=S1wg_DG.constant;S1wg_DG.cache=S1wg_DG.memoize
S1wg_DG.juxt=S1wg_DG.juxtapose;S1wg_DG.uid=S1wg_DG.uniqueId;S1wg_DG.iter=S1wg_DG.iterator
S1wg_DG.nAry=S1wg_DG.ary;S1wg_DG.methods=S1wg_DG.functions;S1wg_DG.choose=S1wg_DG.pick
S1wg_DG.drop=S1wg_DG.omit;S1wg_DG.defaults=S1wg_DG.template
S1wg_DG.compare=S1wg_DG.isEqual;S1wg_DG.matches=S1wg_DG.isEqual end
do local Hgc1S={}local gszf={}gszf.__index=Hgc1S;local function GnYt(L7g)
return oUA({_value=L7g,_wrapped=true},gszf)end
oUA(gszf,{__call=function(_IO9,zcnTZ6pI)return GnYt(zcnTZ6pI)end,__index=function(sIPPW,jrXq,...)return
Hgc1S[jrXq]end})function gszf.chain(T5V8Jm3h)return GnYt(T5V8Jm3h)end;function gszf:value()
return self._value end;Hgc1S.chain,Hgc1S.value=gszf.chain,gszf.value
for yYkU,n0 in
l(S1wg_DG)do
if yYkU~='operator'then
Hgc1S[yYkU]=function(nOa2,...)local r=
v(nOa2)=='table'and PizLA9mj(nOa2,'_wrapped')or false
if r then
local zx=nOa2._value;local crsA2=n0(zx,...)return GnYt(crsA2)else return n0(nOa2,...)end end end end;Hgc1S.operator=S1wg_DG.operator;Hgc1S.op=S1wg_DG.operator
Hgc1S.import=function(uIdK8yDV,e7iD7y21)uIdK8yDV=
uIdK8yDV or _ENV or _G;local ec=S1wg_DG.functions()
for x,Ca in
kyWtqIf0(ec)do if PizLA9mj(uIdK8yDV,Ca)~=nil then if not e7iD7y21 then
rawset(uIdK8yDV,Ca,S1wg_DG[Ca])end else
rawset(uIdK8yDV,Ca,S1wg_DG[Ca])end end;return uIdK8yDV end;gszf._VERSION='Moses v'..SWFtRywD
gszf._URL='http://github.com/Yonaba/Moses'
gszf._LICENSE='MIT <http://raw.githubusercontent.com/Yonaba/Moses/master/LICENSE>'
gszf._DESCRIPTION='utility-belt library for functional programming in Lua'return gszf end
|
local Weapons = ACF.Classes.Weapons
function EFFECT:Init(Data)
local Gun = Data:GetEntity()
if not IsValid(Gun) then return end
local Propellant = Data:GetScale()
local ReloadTime = Data:GetMagnitude()
local Sound = Gun:GetNWString("Sound")
local Class = Gun:GetNWString("Class")
local ClassData = Weapons[Class]
local Attachment = "muzzle"
local LongBarrel = ClassData.LongBarrel
if LongBarrel and Gun:GetBodygroup(LongBarrel.Index) == LongBarrel.Submodel then
Attachment = LongBarrel.NewPos
end
if not ACF.IsValidSound(Sound) then
Sound = ClassData.Sound
end
if Propellant > 0 then
local GunPos = Gun:GetPos()
if Sound ~= "" then
local SoundPressure = (Propellant * 1000) ^ 0.5
-- NOTE: Wiki documents level tops out at 180, but seems to fall off past 127
sound.Play(Sound, GunPos, math.Clamp(SoundPressure, 75, 127), 100, ACF.Volume)
if not (Class == "MG" or Class == "RAC") then
sound.Play(Sound, GunPos, math.Clamp(SoundPressure, 75, 127), 100, ACF.Volume)
if SoundPressure > 127 then
sound.Play(Sound, GunPos, math.Clamp(SoundPressure - 127, 1, 127), 100, ACF.Volume)
end
end
end
local Effect = ClassData.MuzzleFlash
local AttachID = Gun:LookupAttachment(Attachment)
if AttachID > 0 then
ParticleEffectAttach(Effect, PATTACH_POINT_FOLLOW, Gun, AttachID)
else
ParticleEffect(Effect, GunPos, Gun:GetAngles(), Gun)
end
Gun:Animate(ReloadTime, false)
else
Gun:Animate(ReloadTime, true)
end
end
function EFFECT:Think()
return false
end
function EFFECT:Render()
end
|
local utils = require('nvim-autopairs.utils')
local log = require('nvim-autopairs._log')
local api = vim.api
local helpers = {}
function helpers.feed(text, feed_opts)
feed_opts = feed_opts or 'n'
local to_feed = vim.api.nvim_replace_termcodes(text, true, false, true)
vim.api.nvim_feedkeys(to_feed, feed_opts, true)
end
function helpers.insert(text)
helpers.feed('i' .. text, 'x')
end
utils.insert_char = function(text)
api.nvim_put({text}, "c", true, true)
end
utils.feed = function(text,num)
local result = ''
for _ = 1, num, 1 do
result = result .. text
end
api.nvim_feedkeys (api.nvim_replace_termcodes(
result, true, false, true),
"x", true)
end
_G.eq = assert.are.same
_G.Test_filter = function (data)
local run_data = {}
for _, value in pairs(data) do
if value.only == true then
table.insert(run_data, value)
break
end
end
if #run_data == 0 then run_data = data end
return run_data
end
_G.Test_withfile = function(test_data, cb)
for _, value in pairs(test_data) do
it("test "..value.name, function()
local text_before = {}
local pos_before = {
linenr = value.linenr,
colnr = 0
}
if not vim.tbl_islist(value.before) then
value.before = {value.before}
end
local numlnr = 0
for _, text in pairs(value.before) do
local txt = string.gsub(text, '%|' , "")
table.insert(text_before, txt )
if string.match( text, "%|") then
pos_before.colnr = string.find(text, '%|')
pos_before.linenr = pos_before.linenr + numlnr
end
numlnr = numlnr + 1
end
local after = string.gsub(value.after, '%|' , "")
local p_after = string.find(value.after , '%|')
vim.bo.filetype = value.filetype
if vim.fn.filereadable(vim.fn.expand(value.filepath)) == 1 then
vim.cmd(":bd!")
if cb.before then cb.before(value) end
vim.cmd(":e " .. value.filepath)
if value.filetype then
vim.bo.filetype = value.filetype
vim.cmd(":e")
end
vim.api.nvim_buf_set_lines(0, pos_before.linenr -1, pos_before.linenr +#text_before, false, text_before)
vim.fn.cursor(pos_before.linenr, pos_before.colnr)
log.debug("insert:"..value.key)
helpers.insert(value.key)
vim.wait(10)
helpers.feed("<esc>")
if value.key == '<cr>' then
local result = vim.fn.getline(pos_before.linenr + 2)
local pos = vim.fn.getpos('.')
eq(pos_before.linenr + 1, pos[2], '\n\n breakline error:' .. value.name .. "\n")
eq(after, result , "\n\n text error: " .. value.name .. "\n")
else
local result = vim.fn.getline(pos_before.linenr)
local pos = vim.fn.getpos('.')
eq(after, result , "\n\n text error: " .. value.name .. "\n")
eq(p_after, pos[3] + 1, "\n\n pos error: " .. value.name .. "\n")
end
if cb.after then cb.after(value) end
else
eq(false, true, "\n\n file not exist " .. value.filepath .. "\n")
end
end)
end
end
|
local site = {}
function site.doc(page)
return page:redirect('docs')
end
return site
|
local c;
local player = Var "Player";
local ShowComboAt = THEME:GetMetric("Combo", "ShowComboAt");
local Pulse = THEME:GetMetric("Combo", "2ndPulseCommand");
local PulseLabel = THEME:GetMetric("Combo", "2ndPulseLabelCommand");
local NumberMinZoom = THEME:GetMetric("Combo", "NumberMinZoom");
local NumberMaxZoom = THEME:GetMetric("Combo", "NumberMaxZoom");
local NumberMaxZoomAt = THEME:GetMetric("Combo", "NumberMaxZoomAt");
local LabelMinZoom = THEME:GetMetric("Combo", "LabelMinZoom");
local LabelMaxZoom = THEME:GetMetric("Combo", "LabelMaxZoom");
local t = Def.ActorFrame {
LoadFont( "combo", "2ndMIX" ) .. {
Name="Number";
OnCommand=THEME:GetMetric("Combo", "Number2ndOnCommand");
};
LoadActor("_2ndMIX") .. {
Name="Label";
OnCommand=THEME:GetMetric("Combo", "Label2ndOnCommand");
};
InitCommand = function(self)
c = self:GetChildren();
c.Number:visible(false);
c.Label:visible(false);
end;
ComboCommand=function(self, param)
local iCombo = param.Combo;
if not iCombo or iCombo < ShowComboAt then
c.Number:visible(false);
c.Label:visible(false);
return;
end
c.Label:visible(false);
param.Zoom = scale( iCombo, 0, NumberMaxZoomAt, NumberMinZoom, NumberMaxZoom );
param.Zoom = clamp( param.Zoom, NumberMinZoom, NumberMaxZoom );
param.LabelZoom = scale( iCombo, 0, NumberMaxZoomAt, LabelMinZoom, LabelMaxZoom );
param.LabelZoom = clamp( param.LabelZoom, LabelMinZoom, LabelMaxZoom );
c.Number:visible(true);
c.Label:visible(true);
c.Number:settext( string.format("%i", iCombo) );
-- Pulse
Pulse( c.Number, param );
PulseLabel( c.Label, param );
end;
};
return t;
|
local typedefs = require "kong.db.schema.typedefs"
return {
name = "graphql-operation-whitelist",
fields = {
{ consumer = typedefs.no_consumer },
{ run_on = typedefs.run_on_first },
{ protocols = typedefs.protocols_http },
{ config = {
type = "record",
fields = {
{ block_introspection_queries = { type = "boolean", default = false}, },
}, }, },
},
}
|
local debug = require('cmp.utils.debug')
local autocmd = {}
autocmd.events = {}
---Subscribe autocmd
---@param event string
---@param callback function
---@return function
autocmd.subscribe = function(event, callback)
autocmd.events[event] = autocmd.events[event] or {}
table.insert(autocmd.events[event], callback)
return function()
for i, callback_ in ipairs(autocmd.events[event]) do
if callback_ == callback then
table.remove(autocmd.events[event], i)
break
end
end
end
end
---Emit autocmd
---@param event string
autocmd.emit = function(event)
debug.log(' ')
debug.log(string.format('>>> %s', event))
autocmd.events[event] = autocmd.events[event] or {}
for _, callback in ipairs(autocmd.events[event]) do
callback()
end
end
return autocmd
|
---@meta
---@class cc.EaseCircleActionOut :cc.ActionEase
local EaseCircleActionOut={ }
cc.EaseCircleActionOut=EaseCircleActionOut
---*
---@param action cc.ActionInterval
---@return self
function EaseCircleActionOut:create (action) end
---*
---@return self
function EaseCircleActionOut:clone () end
---*
---@param time float
---@return self
function EaseCircleActionOut:update (time) end
---*
---@return cc.ActionEase
function EaseCircleActionOut:reverse () end
---*
---@return self
function EaseCircleActionOut:EaseCircleActionOut () end
|
--[[
-- added by wsh @ 2017-12-11
-- Lua侧带有可复用功能的管理组,配合Unity原生组件UIScrollRect使用,负责管理和调度组下的可复用组件刷新
-- 可根据需要带有按钮组---注意:按钮组中按钮的bind_data会被占用,不要再绑定数据
-- 注意:
-- 1、添加的组件必须是UIWrapComponent的子类、或者实现了它的接口的任何其它类
-- 2、如果组件逻辑功能足够简单,不想再另行创建UIWrapComponent子类,可以直接设置本脚本回调
-- 3、Unity侧在ScrollContent节点挂GridLayoutGroup脚本执行配置,对配置要求如下:
-- A)ScrollRect的父节点锚点和中心点都在中间,配置可滑动区域大小和位置
-- B)ScrollRect节点设置为向4个方向的Stretch
-- C)RectTansform锚点、中心点设置到左上角,保证初始化位置的localPosition必须为(0, 0, 0)
-- D)使用GridLayoutGroup组件padding中的Top、Left来设置ScrollContent在可滑动区域的偏移
-- E)使用GridLayoutGroup组件cellSize来配置Item的尺寸(宽度、高度)
-- F)使用GridLayoutGroup组件spacing来配置Item间隙
-- G)GridLayoutGroup组件startConer、childAlignment设置为UpperLeft
-- H)ScrollRect水平滑动时,StartAxis设置为Vertical,Constraint设置为FixedRowCount,ConstraintCount指定每列Item的个数
-- I)ScrollRect竖直滑动时,StartAxis设置为Horizontal,Constraint设置为FixedColumnCount,ConstraintCount指定每行Item的个数
-- J)Item锚点会自动设置到左上角、中心点设置到重点,Item拼预设的时候按这个配置来拼
-- 4、GridLayoutGroup脚本只是用来执行配置,以及Prefab效果预览,配置读取后将禁用,Item排布全部由本脚本托管,另行计算
-- 5、初始Item数量要保证在最大可能分辨率下能布满整个可滑动区域,再额外多3个行(竖直滑动)/列(水平滑动),否则Item不能复用
-- 使用方式:
-- self.xxx_wrapgroup = self:AddComponent(UIWrapGroup, scroll_content_path, UIWrapComponentTypeClass)--初始化
-- self.xxx_wrapgroup:SetLength(100)--数据长度
-- self.xxx_wrapgroup:ResetToBeginning()--复位
-- TODO:
-- 1、由官方最佳实践得知,带重复项的Item最好只加载一个再执行instantiate:https://unity3d.com/cn/learn/tutorials/temas/best-practices/assets-objects-and-serialization
--]]
local UIWrapGroup = BaseClass("UIWrapGroup", UIBaseContainer)
local base = UIBaseContainer
-- 创建
local function OnCreate(self, wrap_class, ...)
assert(type(wrap_class) == "table" and wrap_class.__ctype == ClassType.class, "wrap_class err : "..tostring(wrap_class))
base.OnCreate(self)
-- Unity侧原生组件
self.unity_scrollrect = self.transform:GetComponentInParent(typeof(CS.UnityEngine.UI.ScrollRect))
self.unity_grid = self.transform:GetComponent(typeof(CS.UnityEngine.UI.GridLayoutGroup))
self.unity_sizefitter = self.transform:GetComponent(typeof(CS.UnityEngine.UI.ContentSizeFitter))
assert(not IsNull(self.unity_scrollrect), "No found UnityEngine.UI.ScrollRect!")
assert(not IsNull(self.unity_grid), "No found UnityEngine.UI.GridLayoutGroup!")
self.unity_grid.enabled = false
if not IsNull(self.unity_sizefitter) then
self.unity_sizefitter.enabled = false
end
-- 由原生组件配置初始化数据
-- 尺寸、间隔、边框--->左上角顶点偏移,粘合边框的Item尺寸
local cell_size = self.unity_grid.cellSize
local spacing = self.unity_grid.spacing
local padding = self.unity_grid.padding
self.item_size = cell_size
self.item_spacing = spacing
self.cell_size = Vector2.New(cell_size.x + spacing.x, cell_size.y + spacing.y)
self.topleft_offset = Vector3.New(padding.left - spacing.x / 2, padding.top - spacing.y / 2, 0)
-- 行/列数限制
self.constraint_count = self.unity_grid.constraintCount
-- 是否为水平拖动
self.horizontal = self.unity_scrollrect.horizontal
-- 通过四角坐标(左下、左上、右上、右下)计算scroll_rect中心点在局部坐标系中的坐标
self.rectTransform.anchoredPosition = Vector2.zero
local scroll_rect_trans = self.unity_scrollrect.transform:GetComponent(typeof(CS.UnityEngine.RectTransform))
local scroll_world_corners = { Vector3.zero, Vector3.zero, Vector3.zero, Vector3.zero}
scroll_rect_trans:GetWorldCorners(scroll_world_corners)
local bottom_left = self.transform:InverseTransformPoint(scroll_world_corners[1])
local top_right = self.transform:InverseTransformPoint(scroll_world_corners[3])
self.center = Vector2.zero
self.center_original = Vector2.zero
self.center_original.x = (bottom_left.x + top_right.x) / 2
self.center_original.y = (bottom_left.y + top_right.y) / 2
-- 其它成员数据
-- 最小索引
self.min_index = 0
-- 最大索引
self.max_index = 0
-- 缓存用
self.tmp_vec3 = Vector3.zero
-- 按钮组
self.__btngroup = nil
-- 当前选中虚拟索引
self.__cur_check_index = nil
-- 自动添加当前挂载节点下的所有孩子
local child_count = self.transform.childCount
for i = 0, child_count - 1 do
self:AddComponent(wrap_class, i, ...)
end
-- 计算孩子布局宽度/高度
local count = math.floor(((self:GetComponentsCount() - 1) / self.constraint_count) + 1)
if self.horizontal then
self.extents = self.cell_size.x * count
else
self.extents = self.cell_size.y * count
end
self.half_extents = self.extents / 2
-- 回调
-- 注册scroll拖动回调
self.__onmove = function(vec2)
self:WrapContent(false)
end
self.unity_scrollrect.onValueChanged:AddListener(self.__onmove)
-- 刷新回调:void __onrefresh(wrap_component, real_index, check)
self.__onrefresh = nil
-- 点击回调:void __onclick(wrap_component, toggle_btn, virtual_index, check)
self.__onclick = nil
end
-- 设置刷新回调
local function SetOnRefresh(self, ...)
self.__onrefresh = BindCallback(...)
end
-- 设置点击回调
local function SetOnClick(self, ...)
self.__onclick = BindCallback(...)
end
-- 获取索引对应位置
local function GetLocalPosition(self, real_index, local_position)
if self.horizontal then
local_position.x = math.floor(real_index / self.constraint_count) * self.cell_size.x
local_position.x = local_position.x + self.cell_size.x / 2
local_position.y = -math.floor(real_index % self.constraint_count) * self.cell_size.y
local_position.y = local_position.y - self.cell_size.y / 2
local_position.z = 0
local_position = local_position + self.topleft_offset
else
local_position.x = math.floor(real_index % self.constraint_count) * self.cell_size.x
local_position.x = local_position.x + self.cell_size.x / 2
local_position.y = -math.floor(real_index / self.constraint_count) * self.cell_size.y
local_position.y = local_position.y - self.cell_size.y / 2
local_position.z = 0
local_position = local_position + self.topleft_offset
end
end
-- 获取真实索引
local function GetRealIndex(self, local_position)
local offset = local_position - self.topleft_offset
local raw_index = math.floor(-offset.y / self.cell_size.y)
local column_index = math.floor(offset.x / self.cell_size.x)
if self.horizontal then
return column_index * self.constraint_count + raw_index
else
return raw_index * self.constraint_count + column_index
end
end
-- 设置长度:多余的孩子会被隐藏
local function SetLength(self, length)
assert(length >= 0)
self.min_index = 0
self.max_index = length - 1
local index = 0
self:Walk(function(component)
component:SetActive(index <= self.max_index)
index = index + 1
end)
-- 设置滑动范围
local scroll_size = Vector2.New(0, 0)
local alignment_index = math.floor((length + self.constraint_count - 1)/ self.constraint_count) * self.constraint_count - 1
GetLocalPosition(self, alignment_index, self.tmp_vec3)
scroll_size.x = math.abs(self.tmp_vec3.x) + self.cell_size.x / 2
scroll_size.y = math.abs(self.tmp_vec3.y) + self.cell_size.y / 2
self.rectTransform.sizeDelta = scroll_size
end
-- 添加UIWrapComponent:必须保证一个名字只对应一个组件
local function AddComponent(self, component_target, var_arg, ...)
local cmp = base.AddComponent(self, component_target, var_arg, ...)
-- 调试模式下强行检测,避免手误
if Config.Debug then
local lookup_table = {}
self:Walk(function(componet)
local cmp_name = componet:GetName()
assert(lookup_table[cmp_name] == nil, "Aready exists component named : "..cmp_name)
lookup_table[cmp_name] = true
end)
end
-- 设置锚点到左上角、中心点到中点
cmp.rectTransform.anchorMin = Vector2.New(0, 1)
cmp.rectTransform.anchorMax = Vector2.New(0, 1)
cmp.rectTransform.pivot = Vector2.New(0.5, 0.5)
-- 设置Item宽、高
cmp.rectTransform.sizeDelta = self.item_size
return cmp
end
-- 按钮点击统一回调
local function ButtonGroupOnClick(self, toggle_btn, check)
local virtual_index = toggle_btn:GetBindData()
if virtual_index == nil then
return
end
-- 选中时记录选中索引
if check then
self.__cur_check_index = virtual_index
end
-- 上层回调
local wrap_component = nil
if virtual_index >= 0 then
wrap_component = self:GetComponent(toggle_btn:GetName())
wrap_component:OnClick(toggle_btn, virtual_index, check)
end
if self.__onclick ~= nil then
self.__onclick(wrap_component, toggle_btn, virtual_index, check)
end
end
-- 添加按钮组
-- @togglebtn_class:按钮组中的按钮类
-- 注意:
-- 1、按钮的bind_data被占用,用于保存该按钮对于的real_index
local function AddButtonGroup(self, togglebtn_class, ...)
local btngroup = UIButtonGroup.New(self, "")
btngroup:OnCreate(togglebtn_class)
btngroup.__name = "__btngroup"
btngroup:SetOnClick(ButtonGroupOnClick, self)
self.__btngroup = btngroup
return btngroup
end
-- 检测虚拟索引是否已经存在
local function CheckVirtualIndexExists(self, virtual_index)
local found_cmp = nil
self.__btngroup:Walk(function(btn_cmp)
if btn_cmp:GetBindData() == virtual_index then
found_cmp = btn_cmp
end
end)
return found_cmp
end
-- 往按钮组中添加其它按钮
-- 多种重载方式
-- 注意:
-- 1、按钮的bind_data被占用,由于列表中的项都有real_index做索引,所以这里要加个虚拟索引到bind_data
-- 2、所有外部回调、交互都需要这个虚拟索引来标识是哪个按钮
-- 3、虚拟索引一定要是负数,避免与列表中的按钮冲突
-- 4、虚拟索引要保证唯一性
local function AddButton(self, togglebtn_class, var_arg, virtual_index, ...)
assert(self.__btngroup ~= nil, "You should add button group first!")
assert(type(virtual_index) == "number" and virtual_index < 0, "Virtual index must be negative number!")
local togglebtn = self.__btngroup:AddComponent(togglebtn_class, var_arg, ...)
-- 调试模式下检测virtual_index是否存在,避免手误
local found_cmp = CheckVirtualIndexExists(self, virtual_index)
if Config.Debug and found_cmp then
error("Aready exists virtual index : "..tostring(virtual_index))
end
togglebtn:SetBindData(virtual_index)
return togglebtn
end
-- 设置按钮初始选中索引
local function SetOriginal(self, original_index)
assert(self.__btngroup ~= nil, "You should add button group first!")
assert(original_index == nil or type(original_index) == "number", "Original index must be nil or number!")
-- 只有在初始选中外部按钮时,才需要在这里设置初始按钮,列表中的按钮在复用检测中会自定虚拟点击
if original_index ~= nil and original_index < 0 then
local found_cmp = nil
found_cmp = CheckVirtualIndexExists(self, original_index)
self.__btngroup:SetOriginal(found_cmp and found_cmp:GetName())
else
self.__btngroup:SetOriginal(nil)
end
self.__cur_check_index = original_index
end
-- 子节点复位
local function ResetChildPositions(self)
local index = 0
self:Walk(function(component)
GetLocalPosition(self, index, self.tmp_vec3)
component.rectTransform.localPosition = self.tmp_vec3
index = index + 1
end)
end
-- 如有必要,清空列表绑定数据
local function ResetChildBindData(self)
if self.__btngroup == nil then
return
end
self:Walk(function(component)
component:SetBindData(nil)
end)
end
-- 如果有按钮组,复位
local function ResetButtonGroup(self)
if self.__btngroup ~= nil then
self.__btngroup:ResetToBeginning()
end
end
-- 复位
local function ResetToBeginning(self)
self.rectTransform.anchoredPosition = Vector2.zero
ResetChildPositions(self)
ResetChildBindData(self)
-- 如果初始按钮为外部按钮,这里会选中,如果不是,则全部切换到非选中(包括列表按钮)
ResetButtonGroup(self)
-- 这里强制刷新时,如果初始按钮为列表按钮,会执行一次虚拟点击
self:WrapContent(true)
end
-- 检测,必要时刷新Item
local function CheckAndUpdateItemIfNeeded(self, component, local_position)
local real_index = GetRealIndex(self, local_position)
if self.min_index <= real_index and real_index <= self.max_index then
-- 调试用
if Config.Debug then
component.gameObject.name = tostring(real_index)
end
-- 重置位置
component.transform.localPosition = local_position
local check = real_index == self.__cur_check_index
-- 如果有按钮组则更新
if self.__btngroup ~= nil then
local current = self.__btngroup:GetCurrent()
local toggle_btn = self.__btngroup:GetComponent(component:GetName())
local bind_data = toggle_btn:GetBindData()
-- 如果被复用的是选中按钮,则允许交互
if bind_data ~= nil and bind_data == self.__cur_check_index then
toggle_btn.unity_uibutton.interactable = true
end
-- 更新绑定数据
toggle_btn:SetBindData(real_index)
-- 如果要更新的是选中按钮,则关闭交互;首次刷新时执行虚拟点击
if check then
toggle_btn.unity_uibutton.interactable = false
if not current then
self.__btngroup:ClickOn(component:GetName())
end
end
end
-- 刷新回调
component:OnRefresh(real_index, check)
if self.__onrefresh ~= nil then
self.__onrefresh(component, real_index, check)
end
end
end
-- 检测复用
local function WrapContent(self, force_reset)
if self:GetComponentsCount() > self.max_index and not force_reset then
return
end
-- 更新scroll_rect中心点在局部坐标系中的坐标
local anchored_position = self.rectTransform.anchoredPosition
self.center.x = self.center_original.x - anchored_position.x
self.center.y = self.center_original.y - anchored_position.y
self:Walk(function(component)
local unity_position = component.transform.localPosition
self.tmp_vec3:Set(unity_position.x, unity_position.y, 0)
local distance = self.horizontal and (self.tmp_vec3.x - self.center.x) or (self.tmp_vec3.y - self.center.y)
if force_reset then
-- update all
CheckAndUpdateItemIfNeeded(self, component, self.tmp_vec3)
elseif math.abs(distance) > self.half_extents then
-- if out of panel, update
if self.horizontal then
self.tmp_vec3.x = distance < 0 and (self.tmp_vec3.x + self.extents) or (self.tmp_vec3.x - self.extents)
else
self.tmp_vec3.y = distance < 0 and (self.tmp_vec3.y + self.extents) or (self.tmp_vec3.y - self.extents)
end
CheckAndUpdateItemIfNeeded(self, component, self.tmp_vec3)
end
end)
end
-- 销毁
local function OnDestroy(self)
if self.__onmove ~= nil then
self.unity_scrollrect.onValueChanged:RemoveListener(self.__onmove)
end
if self.__btngroup ~= nil then
self.__btngroup:Delete()
end
self.unity_scrollrect = nil
self.unity_grid = nil
self.unity_sizefitter = nil
self.__btngroup = nil
self.__onmove = nil
self.__onrefresh = nil
self.__onclick = nil
base.OnDestroy(self)
end
UIWrapGroup.OnCreate = OnCreate
UIWrapGroup.SetOnRefresh = SetOnRefresh
UIWrapGroup.SetOnClick = SetOnClick
UIWrapGroup.SetLength = SetLength
UIWrapGroup.AddComponent = AddComponent
UIWrapGroup.AddButtonGroup = AddButtonGroup
UIWrapGroup.AddButton = AddButton
UIWrapGroup.SetOriginal = SetOriginal
UIWrapGroup.ResetToBeginning = ResetToBeginning
UIWrapGroup.WrapContent = WrapContent
UIWrapGroup.OnDestroy = OnDestroy
return UIWrapGroup
|
--[[-------------------------------------------------------------------]]--[[
Copyright wiltOS Technologies LLC, 2020
Contact: www.wiltostech.com
----------------------------------------]]--
wOS = wOS or {}
wOS.ALCS = wOS.ALCS or {}
wOS.ALCS.Config = wOS.ALCS.Config or {}
wOS.ALCS.Config.GTN = wOS.ALCS.Config.GTN or {}
/*
What amount of money should we take from the poster when they make a listing?
If you want no tax, set it to 0!
*/
wOS.ALCS.Config.GTN.PostingTax = 5000
/*
What amount of money should we take from the poster when they want to remove a listing?
If you want no tax, set it to 0!
*/
wOS.ALCS.Config.GTN.CancelTax = 500
/*
How many days should a listing be made available for bidding?
CAN HAVE DECIMALS! EX: 6.5 ( Six and a half days )
CAN EVEN BE A DECIMAL! EX: 0.5 ( half a day )
*/
wOS.ALCS.Config.GTN.PostingDays = 2
/*
What is the minimum amount of credits that can be placed as the starting bid when making an auction?
This will also be the minimum for BUY IT NOW prices
*/
wOS.ALCS.Config.GTN.MinimumStart = 1
/*
What is the minimum amount of credits that can be placed as the starting bid when making an auction?
*/
wOS.ALCS.Config.GTN.MaximumStart = false
/*
What is the maximum amount of credits that can be placed as the BUY IT NOW price when making an auction?
*/
wOS.ALCS.Config.GTN.MaximumBuyNow = false
|
local rcon = {
id = 0,
PACKET_TYPES = {
AUTH = 3,
AUTH_RESPONSE = 2,
EXECCOMMAND = 2,
RESPONSE_VALUE = 0,
},
PACKET_FULL_SIZE_INCREMENT = 4, -- size width (i32) is not included in 'size' part of packets
PACKET_MIN_BYTES_AFTER_SIZE = 10, -- i32, i32, \0, \0
ID_MAX = math.pow(2, 31) - 1,
}
rcon.PACKET_MIN_SIZE = rcon.PACKET_MIN_BYTES_AFTER_SIZE + rcon.PACKET_FULL_SIZE_INCREMENT
-- packer and unpacker adapted from https://github.com/iryont/lua-struct
local packer = {
i32 = function(stream, val)
local bytes = {}
for _ = 1, 4 do
table.insert(bytes, string.char(val % (2 ^ 8)))
val = math.floor(val / (2 ^ 8))
end
table.insert(stream, table.concat(bytes))
end,
str = function(stream, val)
table.insert(stream, val)
table.insert(stream, string.char(0))
end,
chain = function(fns, ...)
local stream = {}
local vals = {...}
for i, fn in ipairs(fns) do
fn(stream, vals[i])
end
return table.concat(stream)
end,
}
packer.rcon = function(...)
return packer.chain({packer.i32, packer.i32, packer.i32, packer.str, packer.str}, ...)
end
local unpacker = {
i32 = function(stream, i)
if i == nil then i = 1 end
local width = 4
local val = 0
for j = 1, width do
local byte = string.byte(stream:sub(i, i))
val = val + byte * (2 ^ ((j - 1) * 8))
i = i + 1
end
-- signedness
if val >= 2 ^ (width * 8 - 1) then
val = val - 2 ^ (width * 8)
end
return math.floor(val), i
end,
str = function(stream, i)
if i == nil then i = 1 end
local bytes = {}
for j = i, stream:len() do
if stream:sub(j, j) == string.char(0) then
break
end
table.insert(bytes, stream:sub(j, j))
end
return table.concat(bytes), i + #bytes + 1
end,
strlen = function(stream, i, len)
if len == 0 then return "", i end
return stream:sub(i, i+(len-1)), i+len
end,
chain = function(fns, stream)
local vals = {}
local i, val
for _, fn in ipairs(fns) do
val, i = fn(stream, i)
table.insert(vals, val)
end
return unpack(vals)
end,
}
unpacker.rcon = function(stream)
local size, id, packetType, body, empty, i
size, i = unpacker.i32(stream)
id, i = unpacker.i32(stream, i)
packetType, i = unpacker.i32(stream, i)
local expectedBodySize = size - rcon.PACKET_MIN_BYTES_AFTER_SIZE
body, i = unpacker.strlen(stream, i, expectedBodySize)
empty = unpacker.str(stream, i)
return size, id, packetType, body, empty
end
function rcon.pack(packetType, body)
body = body or ""
local size = #body + rcon.PACKET_MIN_BYTES_AFTER_SIZE
local id = rcon.id
local packed = packer.rcon(size, id, packetType, body, "")
rcon.id = (rcon.id + 1) % (rcon.ID_MAX + 1)
return packed, id
end
function rcon.pack_cmd(cmd)
return rcon.pack(rcon.PACKET_TYPES.EXECCOMMAND, cmd)
end
function rcon.pack_auth(password)
return rcon.pack(rcon.PACKET_TYPES.AUTH, password)
end
function rcon.unpack(packet)
local size, id, packetType, body, empty = unpacker.rcon(packet)
local expectedBodySize = size - rcon.PACKET_MIN_BYTES_AFTER_SIZE
if #body ~= expectedBodySize then return nil, "expected body of size "..expectedBodySize..", got "..#body end
if empty ~= "" then return nil, "expected empty string after body, got '"..tostring(empty).."'" end
return {
id = id,
type = packetType,
body = body,
size = size + rcon.PACKET_FULL_SIZE_INCREMENT,
}
end
function rcon.check_auth(packet)
assert(packet.type == rcon.PACKET_TYPES.AUTH_RESPONSE)
return packet.id ~= -1
end
-- Decoder for use with coro-wrapper.lua
function rcon.decoder(data, index)
if not data or index > #data then return end
local packet = rcon.unpack(data:sub(index))
if packet then
local nextIndex = nil
if index+packet.size < #data then
nextIndex = index+packet.size
end
return packet, nextIndex
end
end
return rcon
|
-- Validate either gear sets or inventory.
-- gs validate [inv|set] [filterlist]
-- Where inv == i or inv or inventory
-- Where set == s or set or sets
-- Where filterlist can use - to negate a value (eg: -charis for everything except charis, instead of only charis)
function validate(options)
local validateType = 'sets'
if options and #options > 0 then
if S{'sets','set','s'}:contains(options[1]:lower()) then
table.remove(options,1)
elseif S{'inventory','inv','i'}:contains(options[1]:lower()) then
validateType = 'inv'
table.remove(options,1)
end
end
if validateType == 'inv' then
validate_inventory(options)
else
validate_sets(options)
end
end
-- Function specifically for seeing what of a player's inventory is not in their gear sets
function validate_inventory(filter)
local extraitems = L{}
local alreadyChecked = S{}
windower.add_to_chat(123,'GearSwap: Checking for items in inventory that are not used in your gear sets.')
for k,v in pairs(player.inventory) do
if v.id then
if not alreadyChecked[v.id] and not find_in_sets(v, sets) and tryfilter(v.longname or v.shortname, filter) then
extraitems:append(v.longname or v.shortname)
end
alreadyChecked:add(v.id)
end
end
extraitems = extraitems:sort()
extraitems:map(function(item) windower.add_to_chat(120, item) end)
windower.add_to_chat(123,'GearSwap: Final count = '..tostring(extraitems:length()))
end
-- Utility support for validate_inventory.
function find_in_sets(item, tab, stack)
if stack and stack:contains(tab) then
return false
end
for _,v in pairs(tab) do
nam = v.name or v
if type(nam) == 'string' then
nam = nam:lower()
if item.shortname == nam then
return true
elseif item.longname and item.longname == nam then
return true
end
else
if not stack then stack = S{} end
stack:add(tab)
local try = find_in_sets(item, v, stack)
stack:remove(tab)
if try then
return true
end
end
end
return false
end
-- Function specifically for seeing what of a player's gear sets is not in their inventory
function validate_sets(filter)
local missingitems = S{}
windower.add_to_chat(123,'GearSwap: Checking for items in gear sets that are not in your inventory.')
windower.add_to_chat(123,' (does not detect multiple identical items or look at augments)')
recurse_sets(sets, missingitems, filter)
missingitems = missingitems:sort()
missingitems:map(function(item) windower.add_to_chat(120, item) end)
windower.add_to_chat(123,'GearSwap: Final count = '..tostring(missingitems:length()))
end
-- Utility support for validate_sets.
function recurse_sets(tab, accum, filter, stack)
if stack and stack:contains(tab) then return end
if type(tab) ~= 'table' then return end
for i,v in pairs(tab) do
nam = v.name or v
if type(nam) == 'string' and nam ~= 'empty' then
if type(i) == 'string' and not slot_map[i:lower()] then
windower.add_to_chat(123,'GearSwap: '..tostring(i)..' contains a "name" element but is not a valid slot.')
elseif not player.inventory[nam] and tryfilter(nam:lower(), filter) and type(i)=='string' and slot_map[i:lower()] then
accum:add(nam)
end
elseif type(nam) == 'table' and nam ~= empty then
if not stack then stack = S{} end
stack:add(tab)
recurse_sets(v, accum, filter, stack)
stack:remove(tab)
end
end
end
-- Utility support function for filtering results.
function tryfilter(name, filter)
if not filter or #filter == 0 then
return true
end
local pass = true
for _,v in pairs(filter) do
if v[1] == '-' then
pass = false
v = v:sub(2)
end
if not v or type(v) ~= 'string' then
print_set(filter,'filter with bad v')
end
if name:contains(v:lower()) then
return pass
end
end
return not pass
end
|
-- creates sphere object and makes it as a gaze target
b = BinooAPI;
b:CreateSphere("sphere",1,3,0,0);
b:AddGazeTarget("sphere");
|
ELEMENT_ALL = -2
ELEMENT_NONE = -1
ELEMENT_FIRE = 0
ELEMENT_ICE = 1
ELEMENT_ELECTRICITY = 2
-- Combat actions
COMBAT_WAITING = 0
COMBAT_DECIDING = 1
COMBAT_DEAD = 2
COMBAT_ATTACKING = 3
COMBAT_USING = 4
COMBAT_CASTING = 5
COMBAT_RUNNING = 6
COMBAT_DEFENDING = 7
COMBAT_BUSY = 8
COMBAT_SKIP = 9
-- Which side of the screen
LOCATION_LEFT = 0
LOCATION_RIGHT = 1
COMBATENTITY_TYPE_PLAYER = 0
COMBATENTITY_TYPE_ENEMY = 1
COMBATENTITY_TYPE_FRILL = 2
|
local plr = game:GetService('Players').LocalPlayer;
local char = plr.Character;
local Torso = char.Torso
pplr = game.Workspace.TycoonKing1981
game.Workspace.TycoonKing1981.Head.face:Remove()
torso = pplr.Torso
head = pplr.Head
leftarm = pplr["Left Arm"]
rightarm = pplr["Right Arm"]
leftleg = pplr["Left Leg"]
rightleg = pplr["Right Leg"]
head.Transparency = 1
rightarm.Transparency = 1
leftarm.Transparency = 1
rightleg.Transparency = 1
leftleg.Transparency = 1
torso.Transparency = 1
function cycle(num)
local section=num % 1 * 3;
local secondary=0.5 * math.pi * (section % 1);
if section < 1 then
return 1,1 - math.cos(secondary),1 - math.sin(secondary);
elseif section < 2 then
return 1 - math.sin(secondary),1,1 - math.cos(secondary);
else
return 1 - math.cos(secondary),1 - math.sin(secondary),1;
end
end
--weld------
local weld = function(p0,p1,x,y,z,ax,ay,az)
p0.Position=p1.Position
local w = Instance.new("Motor",p0)
w.Part0=p0
w.Part1=p1
w.C0=CFrame.new(x,y,z)*CFrame.Angles(ax,ay,az)
end
wait(1)
local play = false
local Pause = false
--function chat end--
local Songs = {
{SongName = 'Trigger', SongDesc = 'Nil', Creator = 'Ayeekillerpro', ID = 301999080};
{SongName = 'Lindsey Sterling - Crystallize', SongDesc = 'Nil', Creator = 'Nil', ID = 165000427};
{SongName = 'Charli XCX - Boom clap', SongDesc = 'Nil', Creator = 'brightnikki', ID = 160594536};
{SongName = 'Elle King - Exs & Ohs', SongDesc = 'Nil', Creator = 'Nil', ID = 270207539};
{SongName = 'Burnt Rice - Shawn Wasabi', SongDesc = 'Nil', Creator = 'Nil', ID = 327095350};
{SongName = 'KSI', SongDesc = 'Nil', Creator = 'Violisse', ID = 455542293};
{SongName = 'Desiigner - Timmy Turner (Official Sound)', SongDesc = 'Nil', Creator = 'Nil', ID = 469009274};
{SongName = 'Fall Out Boy - Centuries', SongDesc = 'Nil', Creator = 'Nil', ID = 181547615};
{SongName = 'Black Beatles', SongDesc = 'Nil', Creator = 'Nil', ID = 492272696};
{SongName = 'Nil', SongDesc = 'Nil', Creator = 'Nil', ID = 492272696};
{SongName = 'Nil', SongDesc = 'Nil', Creator = 'Nil', ID = 181086214};
{SongName = 'Nil', SongDesc = 'Nil', Creator = 'Nil', ID = 435358295};
{SongName = 'Nil', SongDesc = 'Nil', Creator = 'Nil', ID = 462185312};
{SongName = 'Nil', SongDesc = 'Nil', Creator = 'Nil', ID = 462185312};
{SongName = 'Nil', SongDesc = 'Nil', Creator = 'Nil', ID = 320597966};
{SongName = 'Nil', SongDesc = 'Nil', Creator = 'Nil', ID = 142319852};
{SongName = 'Nil', SongDesc = 'Nil', Creator = 'Nil', ID = 467369212};
{SongName = 'Nil', SongDesc = 'Nil', Creator = 'Nil', ID = 325360758};
{SongName = 'Nil', SongDesc = 'Nil', Creator = 'Nil', ID = 166667250};
{SongName = 'Nil ', SongDesc = 'Nil', Creator = 'Nil', ID = 320597966};
{SongName = 'Nil', SongDesc = 'Nil', Creator = 'Nil', ID = 411577574};
}
local Sound = Instance.new("Sound",Torso)
function PlayList()
local sng = Songs[math.random(1,#Songs)]
Sound.SoundId = 'rbxassetid://'..sng.ID
Sound:Play()
repeat wait() until Sound.IsPaused == true
if play == false then return end
if Pause == true then return end
PlayList()
end
local Loop = false
local Locked
p = game:GetService('Players').LocalPlayer
p.Chatted:connect(function(msg)
if msg:sub(1,5):lower()=='play ' then
play = true
local val = Instance.new("NumberValue", p.Character)
val.Name = "SongID"
val.Value = tonumber(msg:sub(6))
local id = val.Value
Sound:Stop()
Sound.SoundId='rbxassetid://'..id
Sound:Play()
wait(1)
val:Remove()
elseif msg:sub(1,4):lower()=='vol/' then
local val = Instance.new("NumberValue", p.Character)
val.Name = "VolID"
val.Value = tonumber(msg:sub(5))
if val.Value > 10 then val.Value = 10
end
local id = val.Value
Sound.Volume = id
val:Remove()
elseif msg:sub(1,6) == 'start' then
play = true
PlayList()
elseif msg:sub(1,6) == 'change' then
play = false
Sound:Stop()
play = true
PlayList()
elseif msg:sub(1,5) == 'end' then
play = false
Sound:Stop()
end
end)
--156332473
--222095512
--394260844
--301999080
--181086214
--435358295
--462185312
--Chest
local q = Instance.new("Part")
q.CanCollide=false
q.FormFactor="Custom"
q.Material="SmoothPlastic"
q.BrickColor=BrickColor.new("Black")
q.Size = Vector3.new(2.01,2.01,1.01)
weld(q,char['Torso'],0,0,0,0,0,0)
--local w = Instance.new("Part")
--w.CanCollide=false
--w.FormFactor="Custom"
--w.Material="SmoothPlastic"
--w.BrickColor=BrickColor.new("Grey")
--w.Size = Vector3.new(2.001,.1,.1)
--weld(w,char['Torso'],0,.89,.411,0,0,0)
--Visulisers
local Feedback = Instance.new("Part",char)
Feedback.Anchored = true
Feedback.CanCollide=false
Feedback.TopSurface='Smooth'
Feedback.BrickColor=BrickColor.new("Bright red")
Feedback.Material = Enum.Material.Neon
local Feedback2 = Instance.new("Part",char)
Feedback2.Anchored = true
Feedback2.CanCollide=false
Feedback2.TopSurface='Smooth'
Feedback2.BrickColor=BrickColor.new("Bright red")
Feedback2.Material = Enum.Material.Neon
local Feedback3 = Instance.new("Part",char)
Feedback3.Anchored = true
Feedback3.CanCollide=false
Feedback3.TopSurface='Smooth'
Feedback3.BrickColor=BrickColor.new("Bright red")
Feedback3.Material = Enum.Material.Neon
local Feedback4 = Instance.new("Part",char)
Feedback4.Anchored = true
Feedback4.CanCollide=false
Feedback4.TopSurface='Smooth'
Feedback4.BrickColor=BrickColor.new("Bright red")
Feedback4.Material = Enum.Material.Neon
local Feedback5 = Instance.new("Part",char)
Feedback5.Anchored = true
Feedback5.CanCollide=false
Feedback5.TopSurface='Smooth'
Feedback5.BrickColor=BrickColor.new("Bright red")
Feedback5.Material = Enum.Material.Neon
local Feedback6 = Instance.new("Part",char)
Feedback6.Anchored = true
Feedback6.CanCollide=false
Feedback6.TopSurface='Smooth'
Feedback6.BrickColor=BrickColor.new("Bright red")
Feedback6.Material = Enum.Material.Neon
local Feedback7 = Instance.new("Part",char)
Feedback7.Anchored = true
Feedback7.CanCollide=false
Feedback7.TopSurface='Smooth'
Feedback7.BrickColor=BrickColor.new("Bright red")
Feedback7.Material = Enum.Material.Neon
local Feedback8 = Instance.new("Part",char)
Feedback8.Anchored = true
Feedback8.CanCollide=false
Feedback8.TopSurface='Smooth'
Feedback8.BrickColor=BrickColor.new("Bright red")
Feedback8.Material = Enum.Material.Neon
------------------------------Parent to workspace---------------
Sound.Parent = char
Feedback.Parent = char
Feedback2.Parent = char
Feedback3.Parent = char
Feedback4.Parent = char
Feedback5.Parent = char
Feedback6.Parent = char
Feedback7.Parent = char
Feedback8.Parent = char
q.Parent = char
--w.Parent = game.Workspace
local MaxHeight = .2
game:GetService('RunService').Stepped:connect(function()
for _,v in pairs(char:GetChildren()) do
Feedback.BrickColor = BrickColor.new(Color3.new(cycle(tick())));
Feedback2.BrickColor = BrickColor.new(Color3.new(cycle(tick())));
Feedback3.BrickColor = BrickColor.new(Color3.new(cycle(tick())));
Feedback4.BrickColor = BrickColor.new(Color3.new(cycle(tick())));
Feedback5.BrickColor = BrickColor.new(Color3.new(cycle(tick())));
Feedback6.BrickColor = BrickColor.new(Color3.new(cycle(tick())));
Feedback7.BrickColor = BrickColor.new(Color3.new(cycle(tick())));
Feedback8.BrickColor = BrickColor.new(Color3.new(cycle(tick())));
local Height = Sound.PlaybackLoudness/100 * MaxHeight
local Height2 = Sound.PlaybackLoudness/150 * MaxHeight
local Height3 = Sound.PlaybackLoudness/200 * MaxHeight
local Height4 = Sound.PlaybackLoudness/250 * MaxHeight
local Height5 = Sound.PlaybackLoudness/250 * MaxHeight
local Height6 = Sound.PlaybackLoudness/200 * MaxHeight
local Height7 = Sound.PlaybackLoudness/150 * MaxHeight
local Height8 = Sound.PlaybackLoudness/100 * MaxHeight
Feedback.Size = Vector3.new(.01, (Height ~= 0 and Height or .01), .01)
Feedback.CFrame = plr.Character.Torso.CFrame * CFrame.new(.7,-.8,-.41) +Vector3.new(0,(Height == 0 and 0 or Height/2),0)
Feedback2.Size = Vector3.new(.01, (Height2 ~= 0 and Height2 or .01), .01)
Feedback2.CFrame = plr.Character.Torso.CFrame * CFrame.new(.5,-.8,-.41) +Vector3.new(0,(Height2 == 0 and 0 or Height2/2),0)
Feedback3.Size = Vector3.new(.01, (Height3 ~= 0 and Height3 or .01), .01)
Feedback3.CFrame = plr.Character.Torso.CFrame * CFrame.new(.3,-.8,-.41) +Vector3.new(0,(Height3 == 0 and 0 or Height3/2),0)
Feedback4.Size = Vector3.new(.01, (Height4 ~= 0 and Height4 or .01), .01)
Feedback4.CFrame = plr.Character.Torso.CFrame * CFrame.new(.1,-.8,-.41) +Vector3.new(0,(Height4 == 0 and 0 or Height4/2),0)
Feedback5.Size = Vector3.new(.01, (Height5 ~= 0 and Height5 or .01), .01)
Feedback5.CFrame = plr.Character.Torso.CFrame * CFrame.new(-.1,-.8,-.41) +Vector3.new(0,(Height5 == 0 and 0 or Height5/2),0)
Feedback6.Size = Vector3.new(.01, (Height6 ~= 0 and Height6 or .01), .01)
Feedback6.CFrame = plr.Character.Torso.CFrame * CFrame.new(-.3,-.8,-.41) +Vector3.new(0,(Height6 == 0 and 0 or Height6/2),0)
Feedback7.Size = Vector3.new(.01, (Height7 ~= 0 and Height7 or .01), .01)
Feedback7.CFrame = plr.Character.Torso.CFrame * CFrame.new(-.5,-.8,-.41) +Vector3.new(0,(Height7 == 0 and 0 or Height7/2),0)
Feedback8.Size = Vector3.new(.01, (Height8 ~= 0 and Height8 or .01), .01)
Feedback8.CFrame = plr.Character.Torso.CFrame * CFrame.new(-.7,-.8,-.41) +Vector3.new(0,(Height8 == 0 and 0 or Height8/2),0)
end
end)
|
local component = require("component")
local cassette = component.getPrimary("tape_drive")
function demo_mesa()
while true do
cassette.play()
os.sleep(93)
cassette.stop()
cassette.seek(-math.huge)
end
end
demo_mesa()
|
local libs = {}
local SEARCH_PATH = PS2_SCRIPT_PATH .. "?.lua"
--[[
local myreq = function(name)
print("require " .. name)
local l = libs[name]
if l ~= nil then
return l
else
l = dofile(SEARCH_PATH .. name .. ".lua")
libs[name] = l
return l
end
end
require = myreq
function loadFnl(name)
local f = myreq("fennel")
print("loaded fennel")
local l = libs[name]
if l ~= nil then
return l
else
l = f.dofile(SEARCH_PATH .. "foo" .. ".fnl")
libs[name] = l
return l
end
end
]]
print("setting up package searchers")
--table.insert(package.serchers or package.loaders, function
package.path = SEARCH_PATH
local fennel = require ("fennel")
--fennel.path = "host:script/?.fnl"
fennel.path = PS2_SCRIPT_PATH .. "?.fnl"
print("seting fennel path = " .. fennel.path)
table.insert(package.loaders or package.searchers, fennel.searcher)
return function() end
|
AddCSLuaFile()
DEFINE_BASECLASS("sd_turret_base")
ENT.Base = "sd_turret_base"
ENT.PrintName = "Small Turret"
ENT.Category = "Squirrel Defense"
ENT.Spawnable = true
ENT.SpawnRotation = 180
ENT.Model = false
ENT.UseCustomPhys = true
ENT.PhysMin = Vector(-10, -10, -12)
ENT.PhysMax = Vector(10, 10, 24)
ENT.TurretClass = "sd_gun_small"
ENT.TurretOffset = Vector(0, 0, 15)
if CLIENT then
function ENT:SetupParts()
BaseClass.SetupParts(self)
local part
part = TankLib.Part:Create(TankLib.Part.Model, self)
part:SetModel("models/maxofs2d/button_05.mdl")
part:SetCentered(true)
part:SetPos(Vector(0, 0, 7))
part:SetAngles(Angle(0, 0, 0))
for i = 1, 4 do
local pos = Vector(9, 0, -5)
pos:Rotate(Angle(0, i * 90 + 45, 0))
part = TankLib.Part:Create(TankLib.Part.Model, self)
part:SetModel("models/props_c17/utilityconnecter005.mdl")
part:SetCentered(true)
part:SetPos(pos)
part:SetAngles(Angle(-20, i * 90 + 45, 90))
end
end
function ENT:Draw()
TankLib.Part:Draw(self)
end
end
|
--[[
--MIT License
--
--Copyright (c) 2019 PapyElGringo
--Copyright (c) 2019 Tom Meyers
--
--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.
]]
local filesystem = require('gears.filesystem')
local mat_colors = require('theme.mat-colors')
local theme_dir = filesystem.get_configuration_dir() .. '/theme'
local dpi = require('beautiful').xresources.apply_dpi
local theme = {}
theme.icons = theme_dir .. '/icons/'
theme.font = 'Roboto medium 10'
--HERE
theme.titlebars_enabled = true
theme.titlebar_size = dpi(54)
-- Colors Pallets
-- Primary
theme.primary = mat_colors.indigo
theme.primary.hue_500 = '#8AB4F8' --#003f6b
-- Accent
theme.accent = mat_colors.pink
-- Background
theme.background = mat_colors.blue_grey
theme.background.hue_800 = '#000000' .. '66' --99
theme.background.hue_900 = '#000000' .. '66' -- 121e25
local awesome_overrides = function(theme)
--
end
return {
theme = theme,
awesome_overrides = awesome_overrides
}
|
-- @docclass
UIScrollBar = extends(UIWidget, "UIScrollBar")
-- private functions
local function calcValues(self)
local slider = self:getChildById('sliderButton')
local decrementButton = self:getChildById('decrementButton')
local incrementButton = self:getChildById('incrementButton')
local pxrange, center
if self.orientation == 'vertical' then
pxrange = (self:getHeight() - decrementButton:getHeight() - decrementButton:getMarginTop() - decrementButton:getMarginBottom()
- incrementButton:getHeight() - incrementButton:getMarginTop() - incrementButton:getMarginBottom())
center = self:getY() + math.floor(self:getHeight() / 2)
else -- horizontal
pxrange = (self:getWidth() - decrementButton:getWidth() - decrementButton:getMarginLeft() - decrementButton:getMarginRight()
- incrementButton:getWidth() - incrementButton:getMarginLeft() - incrementButton:getMarginRight())
center = self:getX() + math.floor(self:getWidth() / 2)
end
local range = self.maximum - self.minimum + 1
local proportion
if self.pixelsScroll then
proportion = pxrange/(range+pxrange)
else
proportion = math.min(math.max(self.step, 1), range)/range
end
local px = math.max(proportion * pxrange, 10)
px = px - px % 2 + 1
local offset = 0
if range == 0 or self.value == self.minimum then
if self.orientation == 'vertical' then
offset = -math.floor((self:getHeight() - px) / 2) + decrementButton:getMarginRect().height
else
offset = -math.floor((self:getWidth() - px) / 2) + decrementButton:getMarginRect().width
end
elseif range > 1 and self.value == self.maximum then
if self.orientation == 'vertical' then
offset = math.ceil((self:getHeight() - px) / 2) - incrementButton:getMarginRect().height
else
offset = math.ceil((self:getWidth() - px) / 2) - incrementButton:getMarginRect().width
end
elseif range > 1 then
offset = (((self.value - self.minimum) / (range - 1)) - 0.5) * (pxrange - px)
end
return range, pxrange, px, offset, center
end
local function updateValueDisplay(widget)
if widget == nil then return end
if widget:getShowValue() then
widget:setText(widget:getValue() .. (widget:getSymbol() or ''))
end
end
local function updateSlider(self)
local slider = self:getChildById('sliderButton')
if slider == nil then return end
local range, pxrange, px, offset, center = calcValues(self)
if self.orientation == 'vertical' then
slider:setHeight(px)
slider:setMarginTop(offset)
else -- horizontal
slider:setWidth(px)
slider:setMarginLeft(offset)
end
updateValueDisplay(self)
local status = (self.maximum ~= self.minimum)
self:setOn(status)
for _i,child in pairs(self:getChildren()) do
child:setEnabled(status)
end
end
local function parseSliderPos(self, slider, pos, move)
local delta, hotDistance
if self.orientation == 'vertical' then
delta = move.y
hotDistance = pos.y - slider:getY()
else
delta = move.x
hotDistance = pos.x - slider:getX()
end
if (delta > 0 and hotDistance + delta > self.hotDistance) or
(delta < 0 and hotDistance + delta < self.hotDistance) then
local range, pxrange, px, offset, center = calcValues(self)
local newvalue = self.value + delta * (range / (pxrange - px))
self:setValue(newvalue)
end
end
local function parseSliderPress(self, slider, pos, button)
if self.orientation == 'vertical' then
self.hotDistance = pos.y - slider:getY()
else
self.hotDistance = pos.x - slider:getX()
end
end
-- public functions
function UIScrollBar.create()
local scrollbar = UIScrollBar.internalCreate()
scrollbar:setFocusable(false)
scrollbar.value = 0
scrollbar.minimum = -999999
scrollbar.maximum = 999999
scrollbar.step = 1
scrollbar.orientation = 'vertical'
scrollbar.pixelsScroll = false
scrollbar.showValue = false
scrollbar.symbol = nil
scrollbar.mouseScroll = true
return scrollbar
end
function UIScrollBar:onSetup()
self.setupDone = true
local sliderButton = self:getChildById('sliderButton')
g_mouse.bindAutoPress(self:getChildById('decrementButton'), function() self:decrement() end, 300)
g_mouse.bindAutoPress(self:getChildById('incrementButton'), function() self:increment() end, 300)
g_mouse.bindPressMove(sliderButton, function(mousePos, mouseMoved) parseSliderPos(self, sliderButton, mousePos, mouseMoved) end)
g_mouse.bindPress(sliderButton, function(mousePos, mouseButton) parseSliderPress(self, sliderButton, mousePos, mouseButton) end)
updateSlider(self)
end
function UIScrollBar:onStyleApply(styleName, styleNode)
for name,value in pairs(styleNode) do
if name == 'maximum' then
self:setMaximum(tonumber(value))
elseif name == 'minimum' then
self:setMinimum(tonumber(value))
elseif name == 'step' then
self:setStep(tonumber(value))
elseif name == 'orientation' then
self:setOrientation(value)
elseif name == 'value' then
self:setValue(value)
elseif name == 'pixels-scroll' then
self.pixelsScroll = true
elseif name == 'show-value' then
self.showValue = true
elseif name == 'symbol' then
self.symbol = value
elseif name == 'mouse-scroll' then
self.mouseScroll = value
end
end
end
function UIScrollBar:decrement(count)
count = count or self.step
self:setValue(self.value - count)
end
function UIScrollBar:increment(count)
count = count or self.step
self:setValue(self.value + count)
end
function UIScrollBar:setMaximum(maximum)
if maximum == self.maximum then return end
self.maximum = maximum
if self.minimum > maximum then
self:setMinimum(maximum)
end
if self.value > maximum then
self:setValue(maximum)
else
updateSlider(self)
end
end
function UIScrollBar:setMinimum(minimum)
if minimum == self.minimum then return end
self.minimum = minimum
if self.maximum < minimum then
self:setMaximum(minimum)
end
if self.value < minimum then
self:setValue(minimum)
else
updateSlider(self)
end
end
function UIScrollBar:setRange(minimum, maximum)
self:setMinimum(minimum)
self:setMaximum(maximum)
end
function UIScrollBar:setValue(value)
value = math.max(math.min(value, self.maximum), self.minimum)
if self.value == value then return end
local delta = value - self.value
self.value = value
updateSlider(self)
if self.setupDone then
signalcall(self.onValueChange, self, math.round(value), delta)
end
end
function UIScrollBar:setMouseScroll(scroll)
self.mouseScroll = scroll
end
function UIScrollBar:setStep(step)
self.step = step
end
function UIScrollBar:setOrientation(orientation)
self.orientation = orientation
end
function UIScrollBar:setText(text)
local valueLabel = self:getChildById('valueLabel')
if valueLabel then
valueLabel:setText(text)
end
end
function UIScrollBar:onGeometryChange()
updateSlider(self)
end
function UIScrollBar:onMouseWheel(mousePos, mouseWheel)
if not self.mouseScroll then
return false
end
if mouseWheel == MouseWheelUp then
if self.orientation == 'vertical' then
self:decrement()
else
self:increment()
end
else
if self.orientation == 'vertical' then
self:increment()
else
self:decrement()
end
end
return true
end
function UIScrollBar:getMaximum() return self.maximum end
function UIScrollBar:getMinimum() return self.minimum end
function UIScrollBar:getValue() return math.round(self.value) end
function UIScrollBar:getStep() return self.step end
function UIScrollBar:getOrientation() return self.orientation end
function UIScrollBar:getShowValue() return self.showValue end
function UIScrollBar:getSymbol() return self.symbol end
function UIScrollBar:getMouseScroll() return self.mouseScroll end
|
local BUILDER, PART = pac.PartTemplate("base")
PART.ClassName = "bodygroup"
PART.Group = "legacy"
PART.Icon = 'icon16/user.png'
BUILDER:StartStorableVars()
BUILDER:GetSet("BodyGroupName", "", {
enums = function()
return pace.current_part:GetBodyGroupNameList()
end
})
BUILDER:GetSet("ModelIndex", 0)
BUILDER:EndStorableVars()
function PART:OnShow()
self:SetBodyGroupName(self:GetBodyGroupName())
end
function PART:GetNiceName()
return self.BodyGroupName ~= "" and self.BodyGroupName or "no bodygroup"
end
function PART:SetBodyGroupName(str)
local owner = self:GetOwner()
if owner:IsValid() and not self.markedFailed and self.bodygroup_index and self.oldBodygroup then
owner:SetBodygroup(self.bodygroup_index, self.oldBodygroup)
if owner:IsPlayer() then
owner.pac_bodygroups_torender = owner.pac_bodygroups_torender or {}
owner.pac_bodygroups_torender[self.bodygroup_index] = self.oldBodygroup
end
self.oldBodygroup = nil
end
self.BodyGroupName = str
self.markedFailed = false
self:UpdateBodygroupData()
end
function PART:SetModelIndex(i)
self.ModelIndex = math.floor(tonumber(i) or 0)
self.markedFailed = false
self:UpdateBodygroupData()
end
function PART:UpdateBodygroupData()
self.bodygroup_index = nil
self.minIndex = 0
self.maxIndex = 0
local ent = self:GetOwner()
if not IsValid(ent) or not ent:GetBodyGroups() then return end
local fName = self.BodyGroupName:lower():Trim()
if fName == '' then
return
end
for i, info in ipairs(ent:GetBodyGroups()) do
if info.name:lower():Trim() == fName then
self.bodygroup_index = info.id
self.maxIndex = info.num - 1
self.markedFailed = false
self.oldBodygroup = ent:GetBodygroup(info.id)
return
end
end
if not self.markedFailed then
pac.Message(self, ' - Unable to find bodygroup ' .. fName .. ' on ', ent)
self.markedFailed = true
end
end
function PART:OnBuildBonePositions()
if self.markedFailed then return end
local owner = self:GetOwner()
if not owner:IsValid() then return end
if not self.bodygroup_index then
self:UpdateBodygroupData()
return
end
owner:SetBodygroup(self.bodygroup_index, self.ModelIndex)
if owner:IsPlayer() then
owner.pac_bodygroups_torender = owner.pac_bodygroups_torender or {}
owner.pac_bodygroups_torender[self.bodygroup_index] = self.ModelIndex
end
end
-- for the editor
function PART:GetModelIndexList()
local out = {}
local ent = self:GetOwner()
if ent:IsValid() then
for _, info in pairs(ent:GetBodyGroups()) do
if info.id == self.bodygroup_info.id then
for _, model in pairs(info.submodels) do
table.insert(out, model)
end
break
end
end
end
return out
end
function PART:GetBodyGroupNameList()
local out = {}
local ent = self:GetOwner()
if ent:IsValid() then
for _, info in pairs(ent:GetBodyGroups()) do
out[info.name] = info.name
end
end
return out
end
BUILDER:Register()
|
CAMERA_FOLLOW_AVERAGE = false
--Create Camera
local xscale = t_world.size.x * t_world.tile_size.x * t_world.tile_scale[1]
local yscale = t_world.size.y * t_world.tile_size.y * t_world.tile_scale[2]
Camera = Gamera.new(64, 64, xscale, yscale)
--Set Window size
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
love.window.setMode(WINDOW_WIDTH, WINDOW_HEIGHT)
function updateCamera()
if CAMERA_FOLLOW_AVERAGE then
updateCamerAv()
else
updateCameraTr()
end
end
function updateCameraTr()
--which car?
local car = car1
--where is it?
local x, y = car:getScreenPos()
--leave room in front of car (cool visual effect)
local offdist = 64
local xoff = math.cos(car.angle) * offdist
local yoff = math.sin(car.angle) * offdist
--set Cam position
Camera:setPosition(x + xoff, y + yoff)
end
function updateCameraAv()
--get p1 pos
local p1x, p1y = car1:getScreenPos()
local p2x, p2y = car2:getScreenPos()
--set pos to average
Camera:setPosition((p1x+p2x) / 2, (p1y+p2y) / 2)
--difference in x
local dx = math.abs(p2x - p1x)
local dy = math.abs(p2y - p1y)
--get bigger difference
local dd
if dx > dy then dd = dx else dd = dy end
--get in terms of screen size ( plus padding )
dd = (dd + 64) / (WINDOW_WIDTH - 128)
--clamp it
dd = math.max(dd, 1)
--set zoom
Camera:setScale((1 / dd), (1 / dd))
end
|
local saga = require('lspsaga')
-- add your config value here
-- default value
-- use_saga_diagnostic_sign = true
-- error_sign = '',
-- warn_sign = '',
-- hint_sign = '',
-- infor_sign = '',
-- dianostic_header_icon = ' ',
-- code_action_icon = ' ',
-- code_action_prompt = {
-- enable = true,
-- sign = true,
-- sign_priority = 20,
-- virtual_text = true,
-- },
-- finder_definition_icon = ' ',
-- finder_reference_icon = ' ',
-- max_preview_lines = 10, -- preview lines of lsp_finder and definition preview
-- finder_action_keys = {
-- open = 'o', vsplit = 's',split = 'i',quit = 'q',scroll_down = '<C-f>', scroll_up = '<C-b>' -- quit can be a table
-- },
-- code_action_keys = {
-- quit = 'q',exec = '<CR>'
-- },
-- rename_action_keys = {
-- quit = '<C-c>',exec = '<CR>' -- quit can be a table
-- },
-- definition_preview_icon = ' '
-- "single" "double" "round" "plus"
-- border_style = "single"
-- rename_prompt_prefix = '➤',
-- if you don't use nvim-lspconfig you must pass your server name and
-- the related filetypes into this table
-- like server_filetype_map = {metals = {'sbt', 'scala'}}
-- server_filetype_map = {}
saga.init_lsp_saga {
error_sign = '',
warn_sign = '',
hint_sign = '',
infor_sign = '',
dianostic_header_icon = ' ',
code_action_icon = ' ',
code_action_prompt = {
enable = true,
sign = true,
sign_priority = 20,
virtual_text = true,
},
finder_definition_icon = ' ',
finder_reference_icon = ' ',
max_preview_lines = 10, -- preview lines of lsp_finder and definition preview
finder_action_keys = {
open = 'o',
vsplit = 's',
split = 'i',
quit = 'q',
scroll_down = '<C-f>',
scroll_up = '<C-b>'
},
code_action_keys = {
quit = 'q',
exec = '<CR>'
},
rename_action_keys = {
quit = '<C-c>',
exec = '<CR>' -- quit can be a table
},
definition_preview_icon = ' ',
-- "single" "double" "round" "plus"
border_style = "single",
rename_prompt_prefix = '➤',
-- if you don't use nvim-lspconfig you must pass your server name and
-- the related filetypes into this table
-- like server_filetype_map = {metals = {'sbt', 'scala'}}
server_filetype_map = {}
}
vim.cmd([[
" Finder
nnoremap <silent> gh <Cmd>Lspsaga lsp_finder<CR>
" code action
nnoremap <silent> <leader>ca <cmd>lua require('lspsaga.codeaction').code_action()<CR>
vnoremap <silent> <leader>ca :<C-U>lua require('lspsaga.codeaction').range_code_action()<CR>
" show hover doc
nnoremap <silent>K :Lspsaga hover_doc<CR>
" scroll down hover doc or scroll in definition preview
nnoremap <C-f> <cmd>lua require('lspsaga.action').smart_scroll_with_saga(1)<CR>
" scroll up hover doc
nnoremap <C-b> <cmd>lua require('lspsaga.action').smart_scroll_with_saga(-1)<CR>
" Signature Help
nnoremap <silent> gs :Lspsaga signature_help<CR>
" Rename
nnoremap <silent> gr :Lspsaga rename<CR>
" Preview Defination
nnoremap <silent> pd :Lspsaga preview_definition<CR>
" Show diagnostic
nnoremap <silent> <leader>cd <cmd>lua require('lspsaga.diagnostic').show_line_diagnostics()<CR>
nnoremap <silent> <leader>cd :Lspsaga show_line_diagnostics<CR>
" only show diagnostic if cursor is over the area
nnoremap <silent> <leader>cc <cmd>lua require('lspsaga.diagnostic').show_cursor_diagnostics()<CR>
" jump diagnostic
nnoremap <silent> [e :Lspsaga diagnostic_jump_next<CR>
nnoremap <silent> ]e :Lspsaga diagnostic_jump_prev<CR>
" float terminal also you can pass the cli command in open_float_terminal function
nnoremap <leader>ft :Lspsaga open_floaterm<CR>
tnoremap <leader>ft <C-\><C-n>:Lspsaga close_floaterm<CR>
]])
|
--
-- Created by IntelliJ IDEA.
-- User: alexandre
-- Date: 29/10/2019
-- Time: 14:45
-- To change this template use File | Settings | File Templates.
--
return {
title = 'Store',
party = {'warrior', 'druid', 'archer', 'priest'},
encounters = {
{'unguentoPW', 'unguentoRE', 'unguentoVE'},
}
}
|
loadstring(exports.utils:load('require'))();
require 'general';
local rockets = {};
local camEnabled = false;
local targetable = "player";
local targetSeekDist = 250;
function Rocket(x, y, z, force, target, lifespan, creator)
local self = {};
self.index = nil;
self.pos = Vector3(x, y, z);
self.vel = force or Vector3();
self.target = target;
self.creator = creator;
self.isDead = false;
local life = getTickCount();
self.lifespan = lifespan or 10000;
self.groundCheckDist = 0.06;
local targetHit = false;
self.fall = true;
self.gravity = 0.008;
local deflected = getTickCount();
self.deflectCount = 0;
self.maxDeflections = 4;
self.deflectMinDelay = 200;
local trail = {};
local trailUpdated = getTickCount();
self.trailColor = {math.random(255), math.random(255), math.random(255)};
self.trailUpdateRate = 50;
self.trailLength = 120;
self.trailThickness = 5;
self.marker = Marker(self.pos, "corona", 0.5, self.trailColor[1], 100, 255);
self.light = Light(0, self.pos, 5, self.trailColor[1], 100, 255, _,_,_, true);
--self.obj = Object(3003, self.pos);
--self.obj.mass = 10;
--self.obj:setCollisionsEnabled(false);
function self.update(dt)
if (type(self.target) == "userdata") then
self.vel = self.vel * 0.99;
end
self.pos = self.pos + self.vel * (dt/25);
local gp = getGroundPosition(self.pos.x, self.pos.y, self.pos.z) + self.groundCheckDist;
if (self.pos.z <= gp) then
self.vel.x = self.vel.x * 0.98;
self.vel.y = self.vel.y * 0.98;
self.vel.z = 0;
self.pos.z = gp;
else
if (not self.target) then
if (self.fall) then
self.addVel(0, 0, -self.gravity);
end
end
end
end
function self.addVel(x, y, z)
self.vel = self.vel + Vector3(x, y, z);
end
function self.show()
local vel = (-self.vel);
dxDrawLine3D(self.pos, self.pos+self.vel, tocolor(255,0,0), 5);
Effect.addBulletImpact(self.pos, vel*5, 6, 0, .5);
Effect.addSparks(self.pos, vel, 30, 10, 0,0,0, true, .05, .2);
self.marker.position = self.pos;
self.light.position = self.pos;
--self.obj.position = self.pos;
--self.obj.velocity = self.vel;
local x,y = sfw(self.pos);
if (x) then
local t = isElement(self.target) and self.target.name;
if (t) then
local d = getDistanceBetweenPoints3D(self.pos, Camera.matrix.position);
dxDrawText(t, x, y, x, y, tocolor(255,255,255), 35/d);
end
end
end
function self.expired(ls)
return getTickCount() > life + (ls or self.lifespan);
end
function self.destroy()
--self.obj:destroy();
self.light:destroy();
self.marker:destroy();
table.remove(rockets, self.index);
end
function self.explode()
createExplosion(self.pos, 12);
self.destroy();
end
function self.deflect()
local col = self.colliding();
if (col) then
if (getTickCount() < deflected + self.deflectMinDelay) then
self.deflectCount = self.deflectCount + 1;
if (self.deflectCount == self.maxDeflections) then
self.isDead = true;
end
else
if (self.deflectCount > 0) then
self.deflectCount = self.deflectCount - 1;
end
end
deflected = getTickCount();
self.vel.x = self.vel.x * 0.65;
self.vel.y = self.vel.y * 0.65;
if (self.deflectCount > 0) then
self.vel.z = self.vel.z * 0.3;
else
self.vel.z = self.vel.z * 0.62;
end
self.vel = self.vel - (col.normal * self.vel:dot(col.normal) * 2);
end
end
function self.colliding(target)
local targetPos = self.pos + self.vel * 1.5;
local hit = process(self.pos, targetPos, {
vehicles = true,
ignoredElement = self.obj,
includeWorldModelInfo= true
});
if (hit and hit.element) then
if (hit.element == self.target) then
targetHit = true;
end
self.onhit(hit.element, hit.piece);
end
return hit;
end
function self.onhit(elem, piece)
if (elem.type == "player") then
fxAddBlood(self.pos, self.vel, 3, 1 );
playSFX3D("genrl", 20, 9, self.pos, false);
playSFX3D("pain_a", 0, math.random(25,33), elem.position, false);
elem.health = elem.health - 4;
setPedLookAt(elem, self.pos);
if (math.random(4) == 1) then
local p = elem.position;
p.z = p.z + 0.015;
elem.position = p;
elem.velocity = elem.velocity + self.vel * 1.5;
end
--[[if (math.random(4) == 1) then
setPedAnimation(elem, "ped", "floor_hit", 1000, false, true, false);
end]]
if (piece == 9) then
setPedHeadless(elem, true);
setTimer(function(elem) setPedHeadless(elem, false); end, 9000, 1, elem);
end
end
end
function self.follow()
self.target = isElement(self.target) and self.target or nil;
local target = isElement(self.target) and self.target.position or nil;
if (type(target) == "userdata") then
local force = (target - self.pos):getNormalized();
self.vel = self.vel + force * 0.02;
local d = (self.pos-target).length;
if (targetHit) then
self.isDead = true;
end
end
end
function self.trail()
if (#trail == self.trailLength) then
table.remove(trail, 1);
end
if (getTickCount() > self.trailUpdateRate + trailUpdated) then
trailUpdated = getTickCount();
table.insert(trail, Vector3(self.pos.x, self.pos.y, self.pos.z));
end
for i=#trail, 1, -1 do
local alpha = (255 / #trail) * i;
local color = tocolor(self.trailColor[1], self.trailColor[2], self.trailColor[3], alpha);
if (trail[i+1]) then
dxDrawLine3D(trail[i], trail[i+1], color, self.trailThickness);
end
end
end
table.insert(rockets, self);
return self;
end
addEventHandler("onClientPreRender", root, function(dt)
for i=#rockets, 1, -1 do
local r = rockets[i];
r.index = i;
r.follow();
r.deflect();
r.update(dt);
r.show();
r.trail();
if (r.expired() or r.isDead) then
if (i == #rockets and camEnabled) then
if (#rockets == 1) then
resetCamera();
end
end
r.destroy();
end
end
if (camEnabled) then
local r = rockets[#rockets];
if (r and r.creator == localPlayer) then
Camera.setMatrix(r.pos, r.pos+r.vel, 0, 100);
end
end
localPlayer:setData("rocket_target", false);
if (getControlState("aim_weapon")) then
getTargetOnScreen(targetable);
end
dxDrawText("Rockets: "..#rockets,0,0);
end);
function getTargetOnScreen(targetType)
local plrs = getElementsByType(targetType, root, true);
for i=1, #plrs do
if (plrs[i].onScreen and plrs[i] ~= localPlayer) then
local aimStart = Vector2(sfw(plrs[i].position));
local aimEnd = Vector2(sfw(getPedTargetEnd(localPlayer)));
local d = (aimStart-aimEnd).length;
if (d < targetSeekDist) then
localPlayer:setData("rocket_target", plrs[i]);
dxDrawLine(aimStart,aimEnd);
break;
end
end
end
end
addCommandHandler("cam", function()
camEnabled = not camEnabled;
if (not camEnabled) then
resetCamera();
else
localPlayer.frozen = true;
end
end)
function resetCamera()
localPlayer.frozen = false;
setCameraTarget(localPlayer);
end
|
require("src.misc.keybindings.default")
require("src.misc.keybindings.global")
|
class = require 'hump.class'
VectorLight = require 'hump/vector-light'
local scale = 0.001
local font = love.graphics.newFont(10)
DebugVector = Class {
init = function(self, label, x0 , y0, dx, dy)
self.x0 = x0;
self.y0 = y0;
self.dx = dx;
self.dy = dy;
self.label = label;
end;
draw = function(self, labelDistance)
love.graphics.setColor(255, 0, 0)
love.graphics.line(self.x0, self.y0, self.x0 + self.dx * scale, self.y0 + self.dy * scale);
if self.label then
love.graphics.setColor(0,0,0)
love.graphics.setFont(font)
local unit_x, unit_y = VectorLight.div(VectorLight.len(self.dx, self.dy), self.dx, self.dy)
local dist_x, dist_y = self.dx * scale, self.dy * scale
local distance = math.min(labelDistance, VectorLight.len(dist_x, dist_y))
dist_x, dist_y = VectorLight.mul(distance, unit_x, unit_y)
love.graphics.printf(string.format("%s %f", self.label, VectorLight.len(self.dx, self.dy)), self.x0 + dist_x, self.y0 + dist_y, 100, "left")
end
end;
}
DebugCircle = Class {
init = function(self, label, x0 , y0)
self.x0 = x0;
self.y0 = y0;
self.label = label;
end;
draw = function(self, distance)
love.graphics.setColor(255, 0, 0)
love.graphics.circle("fill", self.x0, self.y0, 5, 20);
-- if self.label then
-- love.graphics.setColor(0,0,0)
-- love.graphics.setFont(font)
-- local unit_x, unit_y = VectorLight.div(VectorLight.len(self.dx, self.dy), self.dx, self.dy)
-- local dist_x, dist_y = self.dx * scale, self.dy * scale
-- local distance = math.min(100, VectorLight.len(dist_x, dist_y))
-- dist_x, dist_y = VectorLight.mul(distance, unit_x, unit_y)
-- love.graphics.printf(string.format("%s %f", self.label, VectorLight.len(self.dx, self.dy)), self.x0 + dist_x, self.y0 + dist_y, 100, "left")
-- end
end;
}
debugEnabled = false
drawDebug = function(debugVectors)
if debugEnabled and debugVectors then
local labelDistance = 100
for key, debugVector in pairs(debugVectors) do
debugVector:draw(labelDistance);
labelDistance = labelDistance + 50
end
end
end;
|
local function printTable(t,offset)
offset = offset or ''
for i,v in pairs(t) do
if(type(v)=='table') then
print(offset ..i ..' :')
printTable(v,offset..'\t')
else
print(offset ..i ..' : '..tostring(v))
end
end
end
local tableToBeSaved = {
i_am_boolean = true,
name = 'myTable',
randomNumbers = {},
point = {
x=0, y=0, z=0, label = 'originPoint'
}
}
for i=1,10 do
table.insert(tableToBeSaved.randomNumbers,math.random(50))
end
local tableIO = require('tableIO')
--Saving table to .lua file
tableIO.save(tableToBeSaved,'savedTable.lua')
local p = io.open('savedTable.txt','w')
--Getting string selrialization and writing it
p:write(tableIO.tableToString(tableToBeSaved))
p:close()
--Getting back the string serialization
p = io.open('savedTable.txt','r')
local str = p:read('*all')
p:close()
--Getting .lua table with require
local tableRead = require 'savedTable'
--Geting table from deserialization
local tableRead2 = tableIO.stringToTable(str)
print('\nTable from .lua')
printTable(tableRead)
print('\nTable from .txt')
printTable(tableRead2)
|
-- status line
vim.cmd([[
hi PrimaryBlock ctermfg=white ctermbg=grey guifg=white guibg=grey
hi SecondaryBlock ctermfg=white ctermbg=grey guifg=white guibg=grey
hi Blanks ctermfg=white ctermbg=grey guifg=white guibg=grey
]])
local mode_map = {
['n'] = 'NORMAL ',
['no'] = 'NORMAL·OPERATOR PENDING ',
['v'] = 'VISUAL ',
['V'] = 'V·LINE ',
[''] = 'V·BLOCK ',
['s'] = 'SELECT ',
['S'] = 'S·LINE ',
[''] = 'S·BLOCK ',
['i'] = 'INSERT ',
['R'] = 'REPLACE ',
['Rv'] = 'V·REPLACE ',
['c'] = 'COMMAND ',
['cv'] = 'VIM EX ',
['ce'] = 'EX ',
['r'] = 'PROMPT ',
['rm'] = 'MORE ',
['r?'] = 'CONFIRM ',
['!'] = 'SHELL ',
['t'] = 'TERMINAL ',
}
function mode()
local m = vim.api.nvim_get_mode().mode
if mode_map[m] == nil then return m end
return mode_map[m]
end
function status_line()
local stl = {
'%#PrimaryBlock#',
mode(),
'%3n ',
'%#SecondaryBlock#',
'%#Blanks#',
'%f ',
'%h%m%r%w ',
'%=',
'%{&fileformat} ',
'| %{&fenc} ',
'| %{&filetype} ',
'%#SecondaryBlock#',
' %<%p%% ',
'%-4.(%l:%c%)',
'%#PrimaryBlock#',
}
return table.concat(stl)
end
vim.opt.statusline = "%{%v:lua.status_line()%}"
|
local L
---------------
-- Hellfire Assault --
---------------
L= DBM:GetModLocalization(1426)
L:SetTimerLocalization({
timerSiegeVehicleCD = "Next Vehicle %s",
})
L:SetOptionLocalization({
timerSiegeVehicleCD = "Show timer for when new siege vehicles spawn"
})
L:SetMiscLocalization({
AddsSpawn1 = "Comin' in hot!",--Blizzard seems to have disabled these
AddsSpawn2 = "Fire in the hole!",--Blizzard seems to have disabled these
BossLeaving = "I'll be back..."
})
---------------------------
-- Iron Reaver --
---------------------------
L= DBM:GetModLocalization(1425)
---------------------------
-- Hellfire High Council --
---------------------------
L= DBM:GetModLocalization(1432)
L:SetWarningLocalization({
reapDelayed = "Reap after Visage ends"
})
L:SetOptionLocalization({
reapDelayed = DBM_CORE_AUTO_ANNOUNCE_OPTIONS.soon:format(184476)
})
------------------
-- Kormrok --
------------------
L= DBM:GetModLocalization(1392)
L:SetMiscLocalization({
ExRTNotice = "%s sent ExRT position assignents. Your positions: Orange:%s, Green:%s, Purple:%s"
})
--------------
-- Kilrogg Deadeye --
--------------
L= DBM:GetModLocalization(1396)
L:SetMiscLocalization({
BloodthirstersSoon = "Come brothers! Seize your destiny!"
})
--------------------
--Gorefiend --
--------------------
L= DBM:GetModLocalization(1372)
L:SetTimerLocalization({
SoDDPS2 = "Next Shadows (%s)",
SoDTank2 = "Next Shadows (%s)",
SoDHealer2 = "Next Shadows (%s)"
})
L:SetOptionLocalization({
SoDDPS2 = "Show timer for next $spell:179864 affecting Damagers",
SoDTank2 = "Show timer for next $spell:179864 affecting Tanks",
SoDHealer2 = "Show timer for next $spell:179864 affecting Healers",
ShowOnlyPlayer = "Only show HudMap for $spell:179909 if you are a participant"
})
--------------------------
-- Shadow-Lord Iskar --
--------------------------
L= DBM:GetModLocalization(1433)
L:SetWarningLocalization({
specWarnThrowAnzu = "Throw Eye of Anzu to %s!"
})
L:SetOptionLocalization({
specWarnThrowAnzu = "Show special warning when you need to throw $spell:179202"
})
--------------------------
-- Fel Lord Zakuun --
--------------------------
L= DBM:GetModLocalization(1391)
L:SetOptionLocalization({
SeedsBehavior = "Set seeds yell behavior for raid (Requires raid leader)",
Iconed = "Star, Circle, Diamond, Triangle, Moon. Usuable for any strat using flare positions",--Default
Numbered = "1, 2, 3, 4, 5. Usable for any strat using numbered positions.",
DirectionLine = "Left, Middle Left, Middle, Middle Right, Right. Typical for straight line strat",
FreeForAll = "Free for all. Assign no positions, just use basic yell"
})
L:SetMiscLocalization({
DBMConfigMsg = "Seed configuration set to %s to match raid leaders configuration.",
BWConfigMsg = "Raid leader is using Bigwigs, DBM automatically configured to use Numbered."
})
--------------------------
-- Xhul'horac --
--------------------------
L= DBM:GetModLocalization(1447)
L:SetOptionLocalization({
ChainsBehavior = "Set Fel Chains warning behavior",
Cast = "Only give original target on cast start. Timer syncs to cast start.",
Applied = "Only give targets affected on cast end. Timer syncs to cast end.",
Both = "Give original target on cast start and targets affected on cast end."
})
--------------------------
-- Socrethar the Eternal --
--------------------------
L= DBM:GetModLocalization(1427)
L:SetOptionLocalization({
InterruptBehavior = "Set interrupt behavior for raid (Requires raid leader)",
Count3Resume = "3 person rotation that resumes where left off when barrier drops",--Default
Count3Reset = "3 person rotation that resets to 1 when barrier drops",
Count4Resume = "4 person rotation that resumes where left off when barrier drops",
Count4Reset = "4 person rotation that resets to 1 when barrier drops"
})
--------------------------
-- Tyrant Velhari --
--------------------------
L= DBM:GetModLocalization(1394)
--------------------------
-- Mannoroth --
--------------------------
L= DBM:GetModLocalization(1395)
L:SetOptionLocalization({
CustomAssignWrath = "Set $spell:186348 icons based on player roles (Must be enabled by raid leader. May conflict with BW or out of date DBM versions)"
})
L:SetMiscLocalization({
felSpire = "begins to empower the Fel Spire!"
})
--------------------------
-- Archimonde --
--------------------------
L= DBM:GetModLocalization(1438)
L:SetWarningLocalization({
specWarnBreakShackle = "Shackled Torment: Break %s!"
})
L:SetOptionLocalization({
specWarnBreakShackle = "Show special warning when affected by $spell:184964. This warning auto assigns break order to minimize similtanious damage.",
ExtendWroughtHud3 = "Extend the HUD lines beyond the $spell:185014 target (May diminish line accuracy)",
AlternateHudLine = "Use alternate line texture for HUD lines between $spell:185014 targets",
NamesWroughtHud = "Show player names HUD for $spell:185014 targets",
FilterOtherPhase = "Filter out warnings for events not in same phase as you",
MarkBehavior = "Set Mark of Legion yell behavior for raid (Requires raid leader)",
Numbered = "Star, Circle, Diamond, Triangle. Usable for any strat using flare positions.",--Default
LocSmallFront = "Melee L/R(Star,Circle), Ranged L/R(Diamond,Triangle). Short debuffs in melee.",
LocSmallBack = "Melee L/R(Star,Circle), Ranged L/R(Diamond,Triangle). Short debuffs at ranged.",
NoAssignment = "Disable all position yells/messages, icons, and HUD for entire raid.",
overrideMarkOfLegion = "Do not allow raid leader to override Mark of Legion behavior (Recommended only for experts that are confident their own settings do not conflict with raid leaders intent)"
})
L:SetMiscLocalization({
phase2point5 = "Look upon the endless forces of the Burning Legion and know the folly of your resistance.",--3 seconds faster than CLEU, used as primary, slower CLEU secondary
First = "First",
Second = "Second",
Third = "Third"
})
-------------
-- Trash --
-------------
L = DBM:GetModLocalization("HellfireCitadelTrash")
L:SetGeneralLocalization({
name = "Hellfire Citadel Trash"
})
|
object_draft_schematic_furniture_must_furniture_throw_pillow_02 = object_draft_schematic_furniture_shared_must_furniture_throw_pillow_02:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_furniture_must_furniture_throw_pillow_02, "object/draft_schematic/furniture/must_furniture_throw_pillow_02.iff")
|
meta.name = "Vlad's cape multi-jump"
meta.version = "WIP"
meta.description = "Unlimited jumping with Vlad's cape"
meta.author = "Zappatic"
-- give unlimited jumps to all vlad's capes
-- note that this disables floating!
set_callback(function()
vladscapes = get_entities_by_type(ENT_TYPE.ITEM_VLADS_CAPE)
for i, cape_uid in ipairs(vladscapes) do
get_entity(cape_uid).can_double_jump = true
end
end, ON.GAMEFRAME)
|
local _test = TEST or require "u-test"
local _ok, _elios = pcall(require, "eli.os")
if not _ok then
_test["eli.os available"] = function()
_test.assert(false, "eli.os not available")
end
if not TEST then
_test.summary()
os.exit()
else
return
end
end
_test["eli.os available"] = function()
_test.assert(true)
end
if not _elios.EOS then
if not TEST then
_test.summary()
print "EOS not detected, only basic tests executed..."
os.exit()
else
print "EOS not detected, only basic tests executed..."
return
end
end
_test["sleep"] = function()
local _referencePoint = os.date("%S")
_elios.sleep(10)
local _afterSleep = os.date("%S")
local _diff = _afterSleep - _referencePoint
if _diff < 0 then _diff = _diff + 60 end
_test.assert(_diff > 8 and _diff < 12)
end
_test["chdir & cwd"] = function()
local _cwd = _elios.cwd()
_elios.chdir("tmp")
local _newCwd = _elios.cwd()
_test.assert(_cwd ~= _newCwd)
_elios.chdir(_cwd)
_newCwd = _elios.cwd()
_test.assert(_cwd == _newCwd)
end
if not TEST then
_test.summary()
end
|
local playsession = {
{"Arusu", {2770}},
{"Krono", {22776}},
{"PogomanD", {152316}},
{"teomarx", {738}},
{"Lithidoria", {1507}},
{"neuronich", {3033}}
}
return playsession
|
-- ===================================================================
-- Initialization
-- ===================================================================
local awful = require("awful")
local gears = require("gears")
local naughty = require("naughty")
local beautiful = require("beautiful")
-- local dpi = beautiful.xresources.apply_dpi
local hotkeys_popup = require("awful.hotkeys_popup")
-- Alt-tab library
-- local cyclefocus = require('cyclefocus')
-- Import logger
local logger = require("utils.log")
-- Default Applications
local apps = require("config.apps").default
-- Icons
local icon_paths = require("themes.icons").icon_paths
-- Screens
local screens = require("config.screens")
-- Define mod keys
local modkey = "Mod4"
local altkey = "Mod1"
local ctrlkey = "Control"
local shiftkey = "Shift"
-- Define mouse buttons
local leftclick = 1
local rightclick = 3
local scrollup = 4
local scrolldown = 5
local XF86Binds = {
-- Brightness (laptop)
brightnessUp = "XF86MonBrightnessUp",
brightnessDown = "XF86MonBrightnessDown",
-- Audio Control
audioRaiseVolume = "XF86AudioRaiseVolume",
audioLowerVolume = "XF86AudioLowerVolume",
audioMute = "XF86AudioMute",
audioNext = "XF86AudioNext",
audioPrev = "XF86AudioPrev",
audioPlay = "XF86AudioPlay",
-- Macro keypad (bind spare XF86 keys to functions)
macro1 = "XF86Launch1",
macro2 = "XF86Launch2",
macro3 = "XF86Launch3",
macro4 = "XF86Launch4",
}
-- define module table
local keys = {}
local spotlight_source_screen = nil
local spotlight_source_tag = nil
local spotlight_client = nil
-- Get home dir
local home_dir = os.getenv("HOME")
local getScreenshotBaseDir = function (subdir)
if(subdir) then
return home_dir .. "/Content/Screenshots/" .. subdir .. "/"
end
return home_dir .. "/Content/Screenshots/"
end
local generateScreenshotFileName = function (client_name)
local prefix = "Screenshot-"
if client_name then
-- remove spaces and /slashes/
prefix = string.gsub(client_name, "(%s+)", "")
prefix = string.gsub(prefix, "(/+)", "") .. "-"
end
return prefix .. os.date("%Y-%m-%d_%Hh%Mm%Ss") .. ".png"
end
-- ===================================================================
-- Movement Functions (Called by some keybinds)
-- ===================================================================
-- ===================================================================
-- Mouse bindings
-- ===================================================================
keys.clientbuttons = gears.table.join(
-- Enable click to focus
awful.button({ }, leftclick, function (c)
-- c:emit_signal("request::activate", "mouse_click", {raise = true})
client.focus = c
c:raise()
end),
-- Enable mod + click to move
awful.button({ modkey }, leftclick, function (c)
-- c:emit_signal("request::activate", "mouse_click", {raise = true})
awful.mouse.client.move(c)
end),
-- Enable mod + click to resize
awful.button({ modkey }, rightclick, function (c)
-- c:emit_signal("request::activate", "mouse_click", {raise = true})
awful.mouse.client.resize(c)
end)
)
-- TODO: Figure out how to bind these to the titlebar only (scroll to change tags)
-- awful.button({ }, 3, function () mymainmenu:toggle() end),
-- awful.button({ }, scrollup, awful.tag.viewnext),
-- awful.button({ }, scrolldown, awful.tag.viewprev)
-- ===================================================================
-- Desktop Key bindings
-- ===================================================================
keys.globalkeys = gears.table.join(
-- =========================================
-- SPAWN APPLICATION KEY BINDINGS
-- =========================================
-- Spawn terminal
awful.key({ modkey }, "Return",
function()
awful.spawn(apps.terminal)
end,
{description = "open a terminal", group = "launcher"}
),
-- Spawn launcher
awful.key({ modkey }, "r",
function()
awful.spawn(apps.launcher)
end,
{description = "application launcher", group = "launcher"}
),
-- Spawn task manager
awful.key({ ctrlkey, shiftkey }, "Escape",
function()
awful.spawn(apps.task_manager)
end,
{description = "task manager", group = "launcher"}
),
-- Spawn file explorer
awful.key({ modkey }, "e",
function()
awful.spawn(apps.filebrowser)
end,
{description = "file explorer", group = "launcher"}
),
-- Spawn web browser
awful.key({ modkey }, "w",
function()
awful.spawn(apps.webbrowser)
end,
{description = "web browser", group = "launcher"}
),
-- Spawn web browser private window
awful.key({ modkey, shiftkey }, "w",
function()
awful.spawn(apps.webbrowser .. " --private-window")
end,
{description = "web browser, private window", group = "launcher"}
),
-- Spawn brave browser
awful.key({ modkey }, "d",
function()
awful.spawn(apps.bravebrowser)
end,
{description = "web browser", group = "launcher"}
),
-- Spawn brave browser private window
awful.key({ modkey, shiftkey }, "d",
function()
awful.spawn(apps.bravebrowser .. " --incognito")
end,
{description = "web browser, private window", group = "launcher"}
),
-- Show help popup
awful.key({ modkey }, "s",
hotkeys_popup.show_help,
{description="show help", group="awesome"}),
-- Lock screen
awful.key({ modkey }, "l",
function()
awful.spawn(apps.lock)
end,
{description="lock screen", group="awesome"}),
-- =========================================
-- FUNCTION KEYS
-- =========================================
-- Brightness
awful.key({}, XF86Binds.brightnessUp,
function()
awful.spawn("xbacklight -inc 10", false)
end,
{description = "+10%", group = "hotkeys"}
),
awful.key({}, XF86Binds.brightnessDown,
function()
awful.spawn("xbacklight -dec 10", false)
end,
{description = "-10%", group = "hotkeys"}
),
-- ALSA volume control
awful.key({}, XF86Binds.audioRaiseVolume,
function()
awful.spawn("amixer -D pulse sset Master 5%+", false)
awesome.emit_signal("volume_change")
end,
{description = "volume up", group = "hotkeys"}
),
awful.key({}, XF86Binds.audioLowerVolume,
function()
awful.spawn("amixer -D pulse sset Master 5%-", false)
awesome.emit_signal("volume_change")
end,
{description = "volume down", group = "hotkeys"}
),
awful.key({}, XF86Binds.audioMute,
function()
awful.spawn("amixer -D pulse set Master 1+ toggle", false)
awesome.emit_signal("volume_change")
end,
{description = "toggle mute", group = "hotkeys"}
),
-- https://wiki.archlinux.org/index.php/MPRIS
awful.key({}, XF86Binds.audioNext,
function()
awful.spawn(apps.mediaKeys .. " next", false)
end,
{description = "next music", group = "hotkeys"}
),
awful.key({}, XF86Binds.audioPrev,
function()
awful.spawn(apps.mediaKeys .. " previous", false)
end,
{description = "previous music", group = "hotkeys"}
),
awful.key({}, XF86Binds.audioPlay,
function()
awful.spawn(apps.mediaKeys .. " play-pause", false)
end,
{description = "play/pause music", group = "hotkeys"}
),
-- Screenshot current active client
awful.key({}, "Print",
function()
-- Get class of window to make a directory for it
local class = client.focus.class
class = string.gsub(client.focus.class, "%s+", "-")
if class == "" then
class = "Unknown"
end
local screenshotDir = getScreenshotBaseDir(class)
-- Do getactivewindow first, incase we're tabbing out or other shenanigans
awful.spawn.easy_async_with_shell(apps.x_helpers.xdotool .. " getactivewindow > /tmp/awesome-active-client.txt", function()
awful.spawn.easy_async_with_shell("mkdir -p " .. screenshotDir, function()
awful.spawn.easy_async_with_shell("cat /tmp/awesome-active-client.txt", function(client_id_string)
if(client_id_string) then
local client_id = string.gsub(client_id_string, "\n", "")
local file_name = screenshotDir .. generateScreenshotFileName(client.focus.name)
local command = (apps.screenshot .. " -i " .. client_id .. " " .. file_name)
logger.log("Screenshot: " .. command)
awful.spawn.easy_async_with_shell(command, function() end)
end
end)
end)
end)
end,
{description = "screenshot current client", group = "hotkeys"}
),
-- Screenshot area
awful.key({modkey, shiftkey}, "s",
-- for snipping tool screenshot in windows:
-- windows key + shift + s
function()
local screenshotDir = getScreenshotBaseDir("SnippingTool")
awful.spawn.easy_async_with_shell("mkdir -p " .. screenshotDir, function()
local file_name = screenshotDir .. generateScreenshotFileName()
local command = (apps.screenshot .. " -s " .. file_name)
logger.log("Screenshot area snip: " .. command)
awful.spawn.easy_async_with_shell(command, function()
-- copy to clipboard
awful.spawn.easy_async_with_shell(apps.x_helpers.xclip .. " -selection clipboard -t image/png -i " .. file_name)
end)
end)
end,
{description = "screenshot selection area", group = "hotkeys"}
),
-- Screenshot whole desktop
awful.key({altkey}, "Print",
function()
local screenshotDir = getScreenshotBaseDir("Desktop")
awful.spawn.easy_async_with_shell("mkdir -p " .. screenshotDir, function()
local file_name = screenshotDir .. generateScreenshotFileName()
local command = (apps.screenshot .. " " .. file_name)
logger.log("Screenshot: " .. command)
awful.spawn.easy_async_with_shell(command, function() end)
end)
end,
{description = "screenshot whole desktop", group = "hotkeys"}
),
-- =========================================
-- PROGRAM LAUNCHERS
-- =========================================
awful.key({modkey}, "#90", -- num pad 0
function ()
awful.spawn.easy_async_with_shell(apps.calculator, function() end)
end,
{description = "calculator", group = "launcher"}
),
awful.key({modkey}, "t",
function ()
awful.spawn.easy_async_with_shell(apps.rofiTimer, function() end)
end,
{description = "timer", group = "launcher"}
),
awful.key({modkey, shiftkey}, "p",
function ()
awful.spawn.easy_async_with_shell(apps.password_prompt, function() end)
end,
{description = "timer", group = "launcher"}
),
awful.key({modkey}, "y",
function ()
awful.spawn.easy_async_with_shell(apps.youtube_dl_rofi_prompt, function() end)
end,
{description = "timer", group = "launcher"}
),
-- =========================================
-- MACRO KEYPAD SHORTCUTS
-- =========================================
awful.key({}, XF86Binds.macro1,
function ()
awful.spawn.easy_async_with_shell(apps.infographics.weather, function() end)
end,
{description = "macro key 1 - weather", group = "launcher"}
),
awful.key({}, XF86Binds.macro2,
function ()
-- Error log:
-- Spotlight tag exists, not focused, no client inside. Can't send any new clients to spotlight from any screen.
-- Can focus and unfocus the spotlight tag but it doesn't close itself.
-- had to move a client onto the tag, and remove it so the spotlight tag closed itself. Then things worked as normal again.
-- Get the main screen
local main_screen = screens.getScreenByOutput(screens.screen_center_primary.output)
-- bail for laptop etc
if main_screen == nil then -- TODO: Just check for ML_DEVICE?
return
end
local spotlight_tag = awful.tag.find_by_name(main_screen, "Spotlight")
local addSpotlightTag = function()
awful.tag.add("Spotlight", {
layout = awful.layout.suit.tile,
screen = main_screen,
selected = true,
volatile = true,
gap_single_client = false
})
spotlight_tag = awful.tag.find_by_name(main_screen, "Spotlight")
end
local addClientToSpotlight = function(c)
-- save info before moving client
spotlight_client = c
spotlight_source_screen = spotlight_client.screen
spotlight_source_tag = spotlight_source_screen.selected_tag
-- move client to spotlight tag
spotlight_client:move_to_tag(main_screen.tags[spotlight_tag.index])
spotlight_client.fullscreen = true
-- focus spotlight
spotlight_client:raise()
spotlight_tag:view_only()
end
local restoreClient = function()
-- TODO use clients previous fullscreen value rather than just false
spotlight_client.fullscreen = false
spotlight_client:move_to_tag(spotlight_source_screen.tags[spotlight_source_tag.index])
-- Apply rules (for spotify etc, not sure if this will break other stuff)
awful.rules.apply(spotlight_client)
end
-- if no spotlight tag exists
if spotlight_tag == nil then
addSpotlightTag()
addClientToSpotlight(client.focus)
-- spotlight tag exists, restore client to where it came from, swap focused client in
-- bit ugly to use name rather than ID, but was the closest thing
elseif spotlight_client.name ~= client.focus.name then
-- get new spotlight client
local next_spotlight_client = client.focus
-- return existing client back to where it came from
restoreClient()
-- Spotlight tag is probably destroyed at this point as it is volatile
addSpotlightTag()
-- move new client into spotlight
addClientToSpotlight(next_spotlight_client)
-- spotlight tag exists and we have triggered this on the spotlight client, return client to where it came from
elseif spotlight_client ~= nil then
-- return spotlight client back to where it came from
restoreClient()
-- focus it
spotlight_client:raise()
-- cleanup
spotlight_client = nil
spotlight_source_screen = nil
spotlight_source_tag = nil
else
-- incase of weirdness. Should not happen
awful.spawn.easy_async_with_shell("notify-send 'spotlight bug'", function() end)
logger.log("SPOTLIGHT - DELETE EDGE CASE")
logger.log("client.focus.name: " .. client.focus.name)
end
end,
{description = "macro key 2 - spotlight", group = "launcher"}
),
awful.key({}, XF86Binds.macro3,
function ()
awful.spawn.easy_async_with_shell(apps.scripts.keyboardToggle, function(state)
local side_screen = screens.getScreenByOutput(screens.screen_right_secondary.output)
for line in state:gmatch("[^\r\n]+") do
if line == "guest" then
naughty.notify({
title = "Attaching devices to guest",
screen = side_screen,
icon = icon_paths.windows10,
timeout = 1,
position = "top_left"
})
awesome.emit_signal("kb_state_change", line)
elseif line == "host" then
naughty.notify({
title = "Attaching devices to host",
screen = side_screen,
icon = icon_paths.linux,
timeout = 1,
position = "top_left"
})
awesome.emit_signal("kb_state_change", line)
end
end
end)
end,
{description = "macro key 3 - keyboard toggle", group = "launcher"}
),
awful.key({}, XF86Binds.macro4,
function ()
-- Teamspeak Mute
local old_coords = mouse.coords()
mouse.coords {
x = 812,
y = 1340
}
awful.spawn.easy_async_with_shell(apps.x_helpers.xdotool .. " click 1", function()
mouse.coords {
x = old_coords.x,
y = old_coords.y
}
end)
end,
{description = "macro key 4", group = "launcher"}
),
-- =========================================
-- RELOAD / QUIT AWESOME
-- =========================================
-- Reload Awesome
awful.key({modkey, ctrlkey}, "r",
awesome.restart,
{description = "reload awesome", group = "awesome"}
),
-- Quit Awesome
awful.key({modkey, shiftkey}, "Escape",
awesome.quit,
{description = "toggle exit screen", group = "awesome"}
),
-- awful.key({}, "XF86PowerOff",
-- function()
-- -- emit signal to show the exit screen
-- awesome.emit_signal("show_exit_screen")
-- end,
-- {description = "toggle exit screen", group = "hotkeys"}
-- ),
-- =========================================
-- CLIENT FOCUSING
-- =========================================
awful.key({ modkey }, "u",
awful.client.urgent.jumpto,
{description = "jump to urgent client", group = "client"}),
awful.key({altkey}, "Tab",
-- Holding ALT when pressing tab repeatedly will just keep
-- opening the same rofi dialog,
-- rather than cycling the list of items in rofi
-- FIX: do not spawn the command if the rofi dialog box is open
function ()
awful.spawn.easy_async_with_shell(apps.altTab, function() end)
end,
{description = "Open alt-tab prompt", group = "client"}),
-- =========================================
-- CLIENT RESIZING
-- =========================================
-- =========================================
-- NUMBER OF MASTER / COLUMN CLIENTS
-- =========================================
-- =========================================
-- GAP CONTROL
-- =========================================
awful.key({modkey}, "-",
function()
awful.tag.incgap(5, nil)
end,
{description = "increment gaps size for the current tag", group = "gaps"}
),
awful.key({modkey, shiftkey}, "=",
function()
awful.tag.incgap(-5, nil)
end,
{description = "decrement gap size for the current tag", group = "gaps"}
),
-- =========================================
-- LAYOUT SELECTION
-- =========================================
-- select next layout
awful.key({modkey}, "space",
function()
awful.layout.inc(1)
end,
{description = "select next", group = "layout"}
),
-- select previous layout
awful.key({modkey, shiftkey}, "space",
function()
awful.layout.inc(-1)
end,
{description = "select previous", group = "layout"}
),
-- =========================================
-- CLIENT MINIMIZATION
-- =========================================
-- restore minimized client
awful.key({modkey, shiftkey}, "n",
function()
local c = awful.client.restore()
-- Focus restored client
if c then
client.focus = c
c:raise()
end
end,
{description = "restore minimized", group = "client"}
)
)
-- ===================================================================
-- Client Key bindings
-- ===================================================================
-- Move given client to given direction
local function move_client(c, direction)
-- If client is floating, move to edge
if c.floating or (awful.layout.get(mouse.screen) == awful.layout.suit.floating) then
local workarea = awful.screen.focused().workarea
if direction == "up" then
c:geometry({nil, y = workarea.y + beautiful.useless_gap * 4, nil, nil})
elseif direction == "down" then
c:geometry({nil, y = workarea.height + workarea.y - c:geometry().height - beautiful.useless_gap * 4 - beautiful.border_width * 2, nil, nil})
elseif direction == "left" then
c:geometry({x = workarea.x + beautiful.useless_gap * 4, nil, nil, nil})
elseif direction == "right" then
c:geometry({x = workarea.width + workarea.x - c:geometry().width - beautiful.useless_gap * 4 - beautiful.border_width * 2, nil, nil, nil})
end
-- Otherwise swap the client in the tiled layout
elseif awful.layout.get(mouse.screen) == awful.layout.suit.max then
if direction == "up" or direction == "left" then
awful.client.swap.byidx(-1, c)
elseif direction == "down" or direction == "right" then
awful.client.swap.byidx(1, c)
end
else
awful.client.swap.bydirection(direction, c, nil)
end
end
keys.clientkeys = gears.table.join(
-- Move to edge or swap by direction
awful.key({modkey, shiftkey}, "Down",
function(c)
move_client(c, "down")
end
),
awful.key({modkey, shiftkey}, "Up",
function(c)
move_client(c, "up")
end
),
awful.key({modkey, shiftkey}, "Left",
function(c)
move_client(c, "left")
end
),
awful.key({modkey, shiftkey}, "Right",
function(c)
move_client(c, "right")
end
),
awful.key({modkey, shiftkey}, "j",
function(c)
move_client(c, "down")
end
),
awful.key({modkey, shiftkey}, "k",
function(c)
move_client(c, "up")
end
),
awful.key({modkey, shiftkey}, "h",
function(c)
move_client(c, "left")
end
),
awful.key({modkey, shiftkey}, "l",
function(c)
move_client(c, "right")
end
),
-- toggle fullscreen
awful.key({modkey}, "f",
function(c)
c.fullscreen = not c.fullscreen
end,
{description = "toggle fullscreen", group = "client"}
),
-- toggle pinned
awful.key({modkey}, "p",
function (c)
c.ontop = not c.ontop
end,
{description = "toggle keep on top", group = "client"}
),
-- toggle floating
awful.key({ modkey, ctrlkey }, "space",
awful.client.floating.toggle,
{description = "toggle floating", group = "client"}),
-- close client
awful.key({modkey, shiftkey}, "c",
function(c)
c:kill()
end,
{description = "close", group = "client"}
),
-- close client 2
awful.key({modkey}, "q",
function(c)
c:kill()
end,
{description = "close", group = "client"}
),
-- Minimize
awful.key({modkey}, "n",
function(c)
c.minimized = true
end,
{description = "minimize", group = "client"}
),
-- Maximize
awful.key({modkey}, "m",
function(c)
c.maximized = not c.maximized
c:raise()
end,
{description = "(un)maximize", group = "client"}
)
)
-- =========================================
-- TASK BINDINGS
-- =========================================
keys.tasklist_buttons = gears.table.join(
awful.button({ }, leftclick, function (c)
if c == client.focus then
c.minimized = true
else
c:emit_signal(
"request::activate",
"tasklist",
{raise = true}
)
end
end),
awful.button({ }, rightclick, function()
awful.menu.client_list({ theme = { width = 250 } })
end),
awful.button({ }, scrollup, function ()
awful.client.focus.byidx(1)
end),
awful.button({ }, scrolldown, function ()
awful.client.focus.byidx(-1)
end
)
)
-- =========================================
-- TAG KEYBOARD BINDINGS
-- =========================================
-- Keyboard mod + 1-9
for i = 1, 9 do
keys.globalkeys = gears.table.join(keys.globalkeys,
-- Switch to tag
awful.key({modkey}, "#" .. i + 9,
function()
local screen = awful.screen.focused()
local tag = screen.tags[i]
if tag then
tag:view_only()
end
end,
{description = "view tag #"..i, group = "tag"}
),
-- Move client to tag
awful.key({modkey, shiftkey}, "#" .. i + 9,
function()
if client.focus then
local tag = client.focus.screen.tags[i]
if tag then
client.focus:move_to_tag(tag)
end
end
end,
{description = "move focused client to tag #"..i, group = "tag"}
),
-- Toggle tag on focused client.
awful.key({ modkey, ctrlkey, shiftkey }, "#" .. i + 9,
function ()
if client.focus then
local tag = client.focus.screen.tags[i]
if tag then
client.focus:toggle_tag(tag)
end
end
end,
{description = "toggle focused client on tag #" .. i, group = "tag"})
)
end
-- =========================================
-- TAG MOUSE BINDINGS
-- =========================================
keys.taglist_buttons = gears.table.join(
-- View tag
awful.button({ }, leftclick, function(t) t:view_only() end),
-- View tag & send current client to the tag with you
awful.button({ modkey }, leftclick, function(t)
if client.focus then
client.focus:move_to_tag(t)
end
end),
-- Focus this tag also (merges clients)
awful.button({ }, rightclick, awful.tag.viewtoggle),
-- Also show client on the tag you clicked
awful.button({ modkey }, rightclick, function(t)
if client.focus then
client.focus:toggle_tag(t)
end
end),
-- Scroll next tag
awful.button({ }, scrollup, function(t) awful.tag.viewnext(t.screen) end),
-- Scroll previous tag
awful.button({ }, scrolldown, function(t) awful.tag.viewprev(t.screen) end)
)
return keys
|
object_tangible_storyteller_prop_pr_gravestone_03 = object_tangible_storyteller_prop_shared_pr_gravestone_03:new {
}
ObjectTemplates:addTemplate(object_tangible_storyteller_prop_pr_gravestone_03, "object/tangible/storyteller/prop/pr_gravestone_03.iff")
|
-- test_nativewindow.lua
local WindowKind = require("WindowKind");
local NativeWindow = require("NativeWindow");
local Application = require("Application");
local windowkind, err = WindowKind:create("test_windowkind");
if not windowkind then
print("Window kind not created, ERROR: ", err);
return false, err;
end
local function main()
local win = windowkind:createWindow(640, 480, "Window Title");
win:Show();
--win:Maximize();
sleep(5000);
end
run(main)
|
--[[*
@authors Centauri Soldier
@copyright Public Domain
@description
<h2>pot</h2>
<p>A logical potentiometer object. The client can set minimum and maximum values for the object, as well as rate of increase/decrease.
Note: 'increase' and 'decrease' are logical terms referring to motion along a line based on the current direction. E.g., If a pot is
alternating and descening, 'increase' would cause the positional value to be absolutely reduced, while 'decrease' would have the opposite
affect.
By default, values are clamped at min and max; however, if the object is set to be revolving (or alternating), any values which exceed the minimum or maximum
boundaries, are carried over. For example, imagine a pot is set to have a min value of 0 and a max of 100. Then, imagine its position is set to 120.
If revolving, it would have a final positional value of 19; if alternating it would have a final positional value of 80 and, if neither, its final positional
value would be 100.</p>
@license <p>The Unlicense<br>
<br>
@moduleid pot
@version 1.2
@versionhistory
<ul>
<li>
<b>1.3</b>
<br>
<p>Added serialization and deserialization methods.</p>
</li>
<li>
<b>1.2</b>
<br>
<p>Fixed a bug in the revolution mechanism.</p>
<p>Added the ability which allows the potentiometer to be continuous in a revolving or alternating manner.</p>
</li>
<li>
<b>1.1</b>
<br>
<p>Added the option for the potentiometer to be continuous in a revolving manner.</p>
</li>
<li>
<b>1.0</b>
<br>
<p>Created the module.</p>
</li>
</ul>
@website https://github.com/CentauriSoldier
*]]
local tPots = {};
local pot;
--make these publicy available
constant("POT_CONTINUITY_NONE", 0);
constant("POT_CONTINUITY_REVOLVE", 1);
constant("POT_CONTINUITY_ALT", 2);
--now localize them
local POT_CONTINUITY_NONE = POT_CONTINUITY_NONE;
local POT_CONTINUITY_REVOLVE = POT_CONTINUITY_REVOLVE;
local POT_CONTINUITY_ALT = POT_CONTINUITY_ALT;
local class = class;
local serialize = serialize;
local deserialize = deserialize;
local math = math;
local function continuityIsValid(nVal)
print("printing the local value of POT_CONTINUITY_NONE: "..POT_CONTINUITY_NONE)
return rawtype(nVal) == "number" and
(nVal == POT_CONTINUITY_NONE or
nVal == POT_CONTINUITY_REVOLVE or
nVal == POT_CONTINUITY_ALT);
end
local function clampMin(oPot)
if (oPot.min >= oPot.max) then
oPot.min = oPot.max - 1;
end
end
local function clampMax(oPot)
if (oPot.max <= oPot.min) then
oPot.max = oPot.min + 1;
end
end
--this is a placeholder so clampPosMin can call clampPosMax
local function clampPosMax()end
local function clampPosMin(oPot)
if (oPot.pos < oPot.min) then
if (oPot.continuity == POT_CONTINUITY_REVOLVE) then
oPot.pos = oPot.min + math.abs(oPot.max - math.abs(-oPot.pos + 1));
clampPosMin(oPot);
elseif (oPot.continuity == POT_CONTINUITY_ALT) then
oPot.pos = oPot.min + (oPot.min - oPot.pos);
oPot.toggleAlternator = true;
clampPosMax(oPot);
else
oPot.pos = oPot.min;
end
else
--check if the alternator needs toggled
if (oPot.toggleAlternator) then
oPot.alternator = oPot.alternator * -1;
oPot.toggleAlternator = false;
end
end
end
local function clampPosMax(oPot)
if (oPot.pos > oPot.max) then
if (oPot.continuity == POT_CONTINUITY_REVOLVE) then
oPot.pos = oPot.pos - math.abs(oPot.max - oPot.min + 1);
clampPosMax(oPot);
elseif (oPot.continuity == POT_CONTINUITY_ALT) then
oPot.pos = oPot.max - (oPot.pos - oPot.max);
oPot.toggleAlternator = true;
clampPosMin(oPot);
else
oPot.pos = oPot.max;
end
else
--check if the alternator needs toggled
if (oPot.toggleAlternator) then
oPot.alternator = oPot.alternator * -1;
oPot.toggleAlternator = false;
end
end
end
local function clampRate(oPot)
local nVariance = oPot.max - oPot.min;
if (math.abs(oPot.rate) > math.abs(nVariance)) then
oPot.rate = nVariance;
end
end
pot = class "pot" {
__construct = function(this, nMin, nMax, nPos, nRate, nContinuity)
tPots[this] = {
alternator = 1,
continuity = continuityIsValid(nContinuity) and nContinuity or POT_CONTINUITY_NONE,
min = 0,
max = 100,
pos = 0,
toggleAlternator = false,
rate = 1,
};
local oPot = tPots[this];
--set the min
if (rawtype(nMin) == "number") then
oPot.min = nMin;
end
--set the max
if (rawtype(nMax) == "number") then
oPot.max = nMax;
clampMax(oPot);
end
--set the position
if (rawtype(nPos) == "number") then
oPot.pos = nPos;
clampPosMin(oPot);
clampPosMax(oPot);
end
--set the rate
if (rawtype(nRate) == "number") then
oPot.rate = nRate;
clampRate(oPot);
end
end,
adjust = function(this, nValue)
local oPot = tPots[this];
local nAmount = oPot.rate;
--allow correct input
if (rawtype(nValue) == "number") then
nAmount = nValue;
end
--set the value
oPot.pos = oPot.pos + nAmount;
--clamp it
clampPosMin(oPot);
clampPosMax(oPot);
return this;
end,
decrease = function(this, nTimes)
local oPot = tPots[this];
local nCount = 1;
if (rawtype(nTimes) == "number") then
nCount = nTimes;
end
--set the value
oPot.pos = oPot.pos - oPot.rate * nCount * oPot.alternator;
--clamp it
if (oPot.continuity == POT_CONTINUITY_ALT) then
clampPosMax(oPot);
end
clampPosMin(oPot);
return this;
end,
deserialize = function(this, sData)
local oPot = tPots[this];
local tData = deserialize.table(sData);
oPot.alternator = tData.alternator;
oPot.continuity = tData.continuity;
oPot.min = tData.min;
oPot.max = tData.max;
oPot.pos = tData.pos;
oPot.toggleAlternator = tData.toggleAlternator;
oPot.rate = tData.rate;
return this;
end,
destroy = function(this)
table.remove(tPots, this);
this = nil;
end,
getMax = function(this)
return tPots[this].max;
end,
getMin = function(this)
return tPots[this].min;
end,
getPos = function(this)
return tPots[this].pos;
end,
getRate = function(this)
return tPots[this].rate;
end,
getContinuity = function(this)
return tPots[this].continuity;
end,
increase = function(this, nTimes)
local oPot = tPots[this];
local nCount = 1;
if (rawtype(nTimes) == "number") then
nCount = nTimes;
end
--set the value
oPot.pos = oPot.pos + oPot.rate * nCount * oPot.alternator;
--clamp it
if (oPot.continuity == POT_CONTINUITY_ALT) then
clampPosMin(oPot);
end
clampPosMax(oPot);
return this;
end,
isAlternating = function(this)
return tPots[this].continuity == POT_CONTINUITY_ALT;
end,
isAscending = function(this)
return (
(tPots[this].continuity == POT_CONTINUITY_REVOLVE or
tPots[this].continuity == POT_CONTINUITY_ALT) and
tPots[this].alternator == 1
);
end,
isDescending = function(this)
return (
(tPots[this].continuity == POT_CONTINUITY_REVOLVE or
tPots[this].continuity == POT_CONTINUITY_ALT) and
tPots[this].alternator == -1
);
end,
isRevolving = function(this)
return tPots[this].revolving == POT_CONTINUITY_REVOLVE;
end,
--[[!
@desc Serializes the object's data.
@func pot.serialize
@module pot
@param bDefer boolean Whether or not to return a table of data to be serialized instead of a serialize string (if deferring serializtion to another object).
@ret sData StringOrTable The data returned as a serialized table (string) or a table is the defer option is set to true.
!]]
serialize = function(this, bDefer)
local oPot = tPots[this];
local tData = {
alternator = oPot.alternator,
continuity = oPot.continuity,
min = oPot.min,
max = oPot.max,
pos = oPot.pos,
toggleAlternator = oPot.toggleAlternator,
rate = oPot.rate,
};
if (not bDefer) then
tData = serialize.table(tData);
end
return tData;
end,
setMax = function(this, nValue)
local oPot = tPots[this];
if (rawtype(nValue) == "number") then
oPot.max = nValue;
clampMax(oPot);
clampPosMax(oPot)
end
return this;
end,
setMin = function(this, nValue)
local oPot = tPots[this];
if (rawtype(nValue) == "number") then
oPot.min = nValue;
clampMin(oPot);
clampPosMin(oPot)
end
return this;
end,
setPos = function(this, nValue)
local oPot = tPots[this];
if (rawtype(nValue) == "number") then
oPot.pos = nValue;
clampPosMin(oPot);
clampPosMax(oPot);
end
return this;
end,
setRate = function(this, nValue)
local oPot = tPots[this];
if (rawtype(nValue) == "number") then
oPot.rate = math.abs(nValue);
clampRate(oPot);
end
return this;
end,
setContinuity = function(this, nContinuity)
local oPot = tPots[this];
oPot.continuity = continuityIsValid(nContinuity) and nContinuity or oPot.continuity;
print("Continuity Set to :"..oPot.continuity.." from input value of: "..nContinuity);
return this;
end,
};
return pot;
|
workspace "Infinite"
architecture "x64"
configurations
{
"Debug",
"Release",
"Dist"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
project "Infinite"
location "Infinite"
kind "SharedLib"
language "C++"
targetdir("bin/" .. outputdir .. "/%{prj.name}")
objdir("bin-int/" .. outputdir .. "/%{prj.name}")
pchheader "infpch.h"
pchsource "Infinite/src/infpch.cpp"
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
"%{prj.name}/src",
"%{prj.name}/vendor/spdlog/include"
}
filter "system:windows"
cppdialect "C++17"
staticruntime "On"
systemversion "latest"
defines
{
"INF_PLATFORM_WINDOWS",
"INF_BUILD_DLL"
}
postbuildcommands
{
("{COPY} %{cfg.buildtarget.relpath} ../bin/" .. outputdir .. "/Sandbox")
}
filter "configurations:Debug"
defines "INF_DEBUG"
symbols "On"
filter "configurations:Release"
defines "INF_RELEASE"
optimize "On"
filter "configurations:Dist"
defines "INF_DIST"
optimize "On"
project "Sandbox"
location "Sandbox"
kind "ConsoleApp"
language "C++"
targetdir("bin/" .. outputdir .. "/%{prj.name}")
objdir("bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
"Infinite/vendor/spdlog/include",
"Infinite/src"
}
links
{
"Infinite"
}
filter "system:windows"
cppdialect "C++17"
staticruntime "On"
systemversion "latest"
defines
{
"INF_PLATFORM_WINDOWS",
}
filter "configurations:Debug"
defines "INF_DEBUG"
symbols "On"
filter "configurations:Release"
defines "iNF_RELEASE"
optimize "On"
filter "configurations:Dist"
defines "INF_DIST"
optimize "On"
|
return function (data)
if data.group == 261037783 then
CQApi:SetGroupMemberVisitingCard(data.group,data.qq,"可能是单推")
return
end
CQApi:SetGroupMemberVisitingCard(data.group,data.qq,"没有名字的笨蛋")
end
|
local test = "test"
|
streets.workshop = {}
streets.workshop.register_sign = function(nodename, desc, img, rrecipe, rtime)
minetest.register_node(nodename, {
description = desc,
tiles = {img},
inventory_image = img,
wield_image = img,
groups = {snappy = 1,attached_node = 1},
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("infotext", desc)
end,
drawtype = "nodebox",
node_box = {
type = "wallmounted",
fixed = {
{-0.4,-0.5,-0.4,0.4,-0.4,0.4}
}
},
paramtype = "light",
paramtype2 = "wallmounted",
walkable = false,
sunlight_propagates = true,
selection_box = {
type = "wallmounted"
},
streets = {
signworkshop = {
recipe = rrecipe,
time = rtime
}
}
})
end
local forms = {
inactive = {
"size[12,10]",
"label[3.5,0;"..streets.S("Sign workshop - Create signs for your roads!").."]",
"label[0,0.5;"..streets.S("Available signs:").."]",
"list[context;streets:signworkshop_list;0,1;5,4]",
"label[9,0.5;"..streets.S("Needed stuff:").."]",
"list[context;streets:signworkshop_recipe;8,1;4,1]",
"label[9,2;"..streets.S("Put it here:").."]",
"list[context;streets:signworkshop_input;8,3;4,1]",
"button[8,4;2,1;streets:signworkshop_send;"..streets.S("Start!").."]",
"label[5.8,0.5;"..streets.S("Selected:").."]",
"list[context;streets:signworkshop_select;6,1;1,1]",
"label[5.8,2.5;"..streets.S("Output:").."]",
"list[context;streets:signworkshop_output;6,3;1,1]",
"list[current_player;main;2,6;8,1]",
"list[current_player;main;2,7.25;8,3;8]",
default.gui_bg,
default.gui_bg_img,
default.gui_slots,
default.get_hotbar_bg(2, 6)
},
active = {
"size[12,10]",
"label[3.5,0;"..streets.S("Sign workshop - Create signs for your roads!").."]",
"label[0,0.5;"..streets.S("Available signs:").."]",
"list[context;streets:signworkshop_list;0,1;5,4]",
"label[9,0.5;"..streets.S("Needed stuff:").."]",
"list[context;streets:signworkshop_recipe;8,1;4,1]",
"label[9,2;"..streets.S("Put it here:").."]",
"list[context;streets:signworkshop_input;8,3;4,1]",
"label[5.8,0.5;"..streets.S("Selected:").."]",
"list[context;streets:signworkshop_select;6,1;1,1]",
"label[5.8,2.5;"..streets.S("Output:").."]",
"list[context;streets:signworkshop_output;6,3;1,1]",
"list[current_player;main;2,6;8,1]",
"list[current_player;main;2,7.25;8,3;8]",
default.gui_bg,
default.gui_bg_img,
default.gui_slots,
default.get_hotbar_bg(2, 6),
}
}
streets.workshop.signs = {}
minetest.after(0, function()
for k, v in pairs(minetest.registered_nodes) do
if v.streets and v.streets.signworkshop then
table.insert(streets.workshop.signs, k)
end
end
end)
minetest.register_node("streets:signworkshop",{
description = streets.S("Sign workshop"),
tiles = {"streets_signworkshop_top.png","streets_signworkshop_bottom.png","streets_signworkshop_side.png","streets_signworkshop_side.png","streets_signworkshop_side.png","streets_signworkshop_front.png"},
groups = {cracky = 1, level = 2},
paramtype2 = "facedir",
after_place_node = function(pos)
minetest.get_meta(pos):set_string("formspec",table.concat(forms.inactive))
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
inv:set_size("streets:signworkshop_list",5*4)
inv:set_size("streets:signworkshop_recipe",3*2)
inv:set_size("streets:signworkshop_input",4*1)
inv:set_size("streets:signworkshop_select",1*1)
inv:set_size("streets:signworkshop_output",1*1)
-- Fill
for k, v in pairs(streets.workshop.signs) do
inv:add_item("streets:signworkshop_list", v)
end
-- Meta
meta:set_string("infotext",streets.S("Sign workshop idle"))
meta:set_string("idle","y")
end,
allow_metadata_inventory_put = function(pos, listname, index, stack, player)
if listname ~= "streets:signworkshop_input" then
return 0
else
return 1
end
end,
allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
-- Move items inside input slots
if to_list == "streets:signworkshop_input" and from_list == "streets:signworkshop_input" then
return 1
-- List -> selection
elseif from_list == "streets:signworkshop_list" and to_list == "streets:signworkshop_select" then
local inv = minetest.get_meta(pos):get_inventory()
local selected = inv:get_stack("streets:signworkshop_list",from_index):to_table()
local need = minetest.registered_nodes[selected.name].streets.signworkshop.recipe
inv:set_list("streets:signworkshop_recipe",{need[1],need[2],need[3],need[4]})
return 1
-- selection -> list
elseif from_list == "streets:signworkshop_select" and to_list == "streets:signworkshop_list" then
local inv = minetest.get_meta(pos):get_inventory()
inv:set_list("streets:signworkshop_recipe",{"","","",""})
return 1
-- Every other case
else
return 0
end
end,
allow_metadata_inventory_take = function(pos, listname, index, stack, player)
if listname == "streets:signworkshop_input" or listname == "streets:signworkshop_output" then
return 99
else
return 0
end
end,
on_receive_fields = function(pos, formname, fields, sender)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
--
if inv:is_empty("streets:signworkshop_input") ~= true and inv:is_empty("streets:signworkshop_select") ~= true and meta:get_string("idle") == "y" then
local selection = inv:get_stack("streets:signworkshop_select",1):get_name()
local def = minetest.registered_nodes[selection].streets.signworkshop
local need = inv:get_list("streets:signworkshop_recipe")
local has = inv:get_list("streets:signworkshop_input")
for k, v in pairs(need) do
need[k] = need[k]:to_table()
if need[k] == nil then need[k] = { name = "" } end
end
for k, v in pairs(has) do
has[k] = has[k]:to_table()
if has[k] == nil then has[k] = { name = "" } end
end
if need[1].name == has[1].name and need[2].name == has[2].name and need[3].name == has[3].name and need[4].name == has[4].name then
meta:set_string("infotext",streets.S("Sign workshop working"))
meta:set_string("idle","n")
meta:set_string("formspec",table.concat(forms.active) .. "label[8,4;"..streets.S("Please wait %s seconds..."):format(def.time).."]")
-- Clear input
inv:set_list("streets:signworkshop_input",{"","","",""})
minetest.after(def.time,function()
-- Reset infotext and meta
meta:set_string("infotext",streets.S("Sign workshop idle"))
meta:set_string("idle","y")
meta:set_string("formspec",table.concat(forms.inactive))
-- Fill output
inv:add_item("streets:signworkshop_output",selection)
end)
end
end
end
})
minetest.register_craft({
output = "streets:signworkshop",
recipe = {
{"default:steel_ingot","default:glass","default:steel_ingot"},
{"default:steel_ingot","default:diamond","default:steel_ingot"},
{"default:cobble","default:cobble","default:cobble"}
}
})
streets.workshop.register_sign("streets:sign_blank", streets.S("Empty sign"), "streets_sign_back.png", {"default:steel_ingot","","",""}, 3)
streets.workshop.register_sign("streets:sign_lava", streets.S("Warning sign (lava)"), "streets_sign_lava.png", {"streets:sign_blank","bucket:bucket_lava","",""}, 5)
streets.workshop.register_sign("streets:sign_water", streets.S("Warning sign (water)"), "streets_sign_water.png", {"streets:sign_blank","bucket:bucket_water","",""}, 5)
streets.workshop.register_sign("streets:sign_construction", streets.S("Warning sign (Construction area)"), "streets_sign_construction.png", {"streets:sign_blank","default:dirt","",""}, 5)
streets.workshop.register_sign("streets:sign_mine", streets.S("Notice sign (Public Mine Ahead)"), "streets_sign_mine.png", {"streets:sign_blank","default:dirt","",""}, 5)
streets.workshop.register_sign("streets:sign_shop", streets.S("Notice sign (Shop/Mall Ahead)"), "streets_sign_construction.png", {"streets:sign_blank","default:dirt","",""}, 5)
streets.workshop.register_sign("streets:sign_workshop", streets.S("Notice sign (Public Workshop Ahead)"), "streets_sign_workshop.png", {"streets:sign_blank","default:dirt","",""}, 5)
streets.workshop.register_sign("streets:sign_grasswalk", streets.S("Warning sign (No walking on the grass)"), "streets_sign_grasswalk.png", {"streets:sign_blank","default:dirt","",""}, 5)
|
function getSignBit(a)
if (a > 0) then
return 1
else
return -1
end
end
local Pos = {}
local T = {}
function GETAXIS_Trace_Calculate(time_s,Pos,T)
local n --后期根据time_s判断 第n条贝塞尔曲线
local as,bs,cs
local at,bt,ct,dt
local trace
local A,B,C,Y1,Y2,t1,t2,t3,Temp,sita,t
local deta
local Sptr = {}
local Tptr = {}
if(time_s <= T[3]) then
n = 0
elseif(time_s <= T[6]) then
n = 1
elseif(time_s <= T[9]) then
n = 2
elseif(time_s <= T[12]) then
n = 3
elseif(time_s <= T[15]) then
n = 4
elseif(time_s <= T[18]) then
n = 5
elseif(time_s <= T[21]) then
n = 6
elseif(time_s <= T[24]) then
n = 7
elseif(time_s <= T[27]) then
n = 8
elseif(time_s <= T[30]) then
n = 9
else
n = 10
end
Sptr = Pos
Tptr = T
cs = 3*(Sptr[2] - Sptr[1])
bs = 3*(Sptr[3] - Sptr[2]) - cs
as = Sptr[4] - Sptr[1] - cs - bs
ct = 3*(Tptr[2] - Tptr[1])
bt = 3*(Tptr[3] - Tptr[2]) - ct
at = Tptr[4] - Tptr[1] - ct - bt
dt = Tptr[1] - time_s
A=bt*bt-3*at*ct
B=bt*ct-9*at*dt
C=ct*ct-3*bt*dt
deta=B*B-4*A*C
if(A==0 and B==0) then
t=-ct/bt
elseif(deta>0) then
Y1=A*bt+3*at*( -B+math.sqrt(deta) )/2
Y2=A*bt+3*at*( -B-math.sqrt(deta) )/2
t1 = getSignBit(Y1)
t2 = getSignBit(Y2)
t=( -bt-( t1* math.abs(Y1) ^ (1.0 / 3.0) +t2* math.abs(Y2)^(1.0/3)))/at/3.0
print(type(math.abs))
elseif(deta==0) then
t1=-bt/at+B/A
t2=-B/A/2.0
if(t1>=0 and t1<=1) then
t=t1
else
t=t2
end
else
Temp=(2*A*bt-3*at*B)/A/2.0/math.sqrt(A)
sita = math.acos(Temp)
t1=( -bt-2* math.sqrt(A)* math.cos(sita/3) ) / at /3
t2=( -bt+math.sqrt(A)*( math.cos(sita/3)+math.sin(sita/3)*math.sqrt(3.0) ) ) / at /3
t3=( -bt+math.sqrt(A)*( math.cos(sita/3)-math.sin(sita/3)*math.sqrt(3.0) ) ) / at /3
t=t3
if(t1 >= 0.0000 and t1 <= 1.00000) then
t = t1
end
if(t2 >= 0.0000 and t2 <= 1.00000) then
t = t2
end
if(t3 >= 0.0000 and t3 <= 1.00000) then
t = t3
end
end
print()
trace =as*t*t*t+bs*t*t+cs*t+Sptr[1];
if(time_s <= T[1]) then
trace = Pos[1]
end
return trace
end
-- + (NSArray *)recursionGetsubLevelPointsWithSuperPoints:(NSArray *)points progress:(CGFloat)progress{
-- if (points.count == 1) return points;
--
-- NSMutableArray *tempArr = [[NSMutableArray alloc] init];
-- for (int i = 0; i < points.count-1; i++) {
-- NSValue *preValue = [points objectAtIndex:i];
-- CGPoint prePoint = preValue.CGPointValue;
--
-- NSValue *lastValue = [points objectAtIndex:i+1];
-- CGPoint lastPoint = lastValue.CGPointValue;
-- CGFloat diffX = lastPoint.x-prePoint.x;
-- CGFloat diffY = lastPoint.y-prePoint.y;
--
-- CGPoint currentPoint = CGPointMake(prePoint.x+diffX*progress, prePoint.y+diffY*progress);
-- [tempArr addObject:[NSValue valueWithCGPoint:currentPoint]];
-- }
-- return [self recursionGetsubLevelPointsWithSuperPoints:tempArr progress:progress];
-- }
local points = {}
function GetArray(points, progress)
a = points[1]
print("get:",a[1])
return tempArr
end
-- local c = {{1,2},{2,3}}
-- GetArray(c)
|
local old_ptd000001_init = PlayerTweakData.init
function PlayerTweakData:init(tweak_data)
old_ptd000001_init(self, tweak_data)
self.movement_state.standard.movement.speed.STANDARD_MAX = 700
self.movement_state.standard.movement.speed.RUNNING_MAX = 1150
self.movement_state.standard.movement.speed.CROUCHING_MAX = 450
self.movement_state.standard.movement.speed.STEELSIGHT_MAX = 1150
self.movement_state.standard.movement.speed.INAIR_MAX = 700
self.movement_state.standard.movement.speed.CLIMBING_MAX = 1150
end
|
local Menu = script.Parent
local App = Menu.Parent
local UIBlox = App.Parent
local Packages = UIBlox.Parent
local Roact = require(Packages.Roact)
local t = require(Packages.t)
local withStyle = require(UIBlox.Core.Style.withStyle)
local ImageSetComponent = require(Packages.UIBlox.Core.ImageSet.ImageSetComponent)
local Images = require(Packages.UIBlox.App.ImageSet.Images)
local GenericTextLabel = require(UIBlox.Core.Text.GenericTextLabel.GenericTextLabel)
local divideTransparency = require(UIBlox.Utility.divideTransparency)
local Controllable = require(Packages.UIBlox.Core.Control.Controllable)
local ControlState = require(Packages.UIBlox.Core.Control.Enum.ControlState)
local KeyLabel = require(script.Parent.KeyLabel)
local TEXT_ONLY_PADDING = 24 --Text only padding at the start and end of cells
local ELEMENT_PADDING = 12 --Padding between elements
local SELECTED_ICON_PADDING = 24 --Padding for selected icons at the end of cells
local KEYLABEL_PADDING = 16 --Padding for key labels at the end of cells
local ICON_SIZE = 36
local SELECTED_ICON_SIZE = 16
local CELL_BACKGROUND_ASSET = Images["component_assets/circle_17"]
local function makeCell(backgroundThemeKey)
local cellComponent = Roact.PureComponent:extend("CellFor" ..backgroundThemeKey)
cellComponent.validateProps = t.strictInterface({
-- Icon can either be an Image in a ImageSet or a regular image asset
icon = t.optional(t.union(t.table, t.string)),
text = t.string,
onActivated = t.callback,
-- A KeyCode to display a keycode hint for, the display string based on the users keyboard is displayed.
keyCodeLabel = t.optional(t.enum(Enum.KeyCode)),
selected = t.optional(t.boolean),
iconColorOverride = t.optional(t.Color3),
textColorOverride = t.optional(t.Color3),
elementHeight = t.integer,
hasRoundTop = t.boolean,
hasRoundBottom = t.boolean,
hasDivider = t.boolean,
disabled = t.optional(t.boolean),
layoutOrder = t.integer,
setButtonRef = t.optional(t.union(t.callback, t.table)),
})
cellComponent.defaultProps = {
selected = false,
disabled = false,
}
function cellComponent:init()
self.state = {
controlState = ControlState.Default,
keyLabelWidth = 0,
}
self.keyLabelSizeChanged = function(rbx)
self:setState({
keyLabelWidth = rbx.AbsoluteSize.X,
})
end
self.setControlState = function(controlState)
self:setState({
controlState = controlState,
})
end
end
function cellComponent:getImageProperties()
local imageSize = CELL_BACKGROUND_ASSET.ImageRectSize
local imageOffset = CELL_BACKGROUND_ASSET.ImageRectOffset
local xOffset = 8 * Images.ImagesResolutionScale
local yOffset = 8 * Images.ImagesResolutionScale
local imageCenter = Rect.new(xOffset, yOffset, imageSize.x - xOffset, imageSize.y - yOffset)
local imageWidth = imageSize.X
local halfImageWidth = math.floor(imageWidth / 2)
local imageRectSize, imageRectOffset, sliceCenter
if self.props.hasRoundTop and self.props.hasRoundBottom then
imageRectSize = imageSize
imageRectOffset = imageOffset
sliceCenter = imageCenter
elseif self.props.hasRoundTop then
imageRectSize = Vector2.new(imageWidth, halfImageWidth)
imageRectOffset = imageOffset
sliceCenter = Rect.new(halfImageWidth - 1, halfImageWidth - 1, halfImageWidth +1, halfImageWidth)
elseif self.props.hasRoundBottom then
imageRectSize = Vector2.new(imageWidth, halfImageWidth)
imageRectOffset = imageOffset + Vector2.new(0, halfImageWidth)
sliceCenter = Rect.new(halfImageWidth - 1, 0, halfImageWidth + 1, 1)
else
imageRectSize = Vector2.new(1, 1)
imageRectOffset = imageOffset + Vector2.new(halfImageWidth, halfImageWidth)
sliceCenter = Rect.new(0, 0, 0, 0)
end
return imageRectSize, imageRectOffset, sliceCenter
end
function cellComponent:render()
return withStyle(function(stylePalette)
local theme = stylePalette.Theme
local font = stylePalette.Font
local leftPadding = TEXT_ONLY_PADDING
if self.props.icon then
leftPadding = ELEMENT_PADDING
end
local rightPadding = 0
if self.props.keyCodeLabel then
rightPadding = KEYLABEL_PADDING
elseif self.props.selected then
rightPadding = SELECTED_ICON_PADDING
end
local overlayTheme = {
Color = Color3.new(1, 1, 1),
Transparency = 1,
}
if self.state.controlState == ControlState.Pressed then
overlayTheme = theme.BackgroundOnPress
elseif self.state.controlState == ControlState.Hover then
overlayTheme = theme.BackgroundOnHover
end
local imageRectSize, imageRectOffset, sliceCenter = self:getImageProperties()
local textLengthOffset = 0
local textOnly = true
if self.props.icon then
textOnly = false
leftPadding = ELEMENT_PADDING
textLengthOffset = ELEMENT_PADDING + ICON_SIZE
end
if self.props.selected then
textOnly = false
textLengthOffset = textLengthOffset + SELECTED_ICON_SIZE + SELECTED_ICON_PADDING
end
if self.props.keyCodeLabel then
textOnly = false
textLengthOffset = textLengthOffset + KEYLABEL_PADDING + self.state.keyLabelWidth
end
-- Add start and end padding for text.
if textOnly then
textLengthOffset = textLengthOffset + TEXT_ONLY_PADDING * 2
else
textLengthOffset = textLengthOffset + ELEMENT_PADDING * 2
end
local textTheme = theme.TextEmphasis
if self.props.textColorOverride then
textTheme = {
Color = self.props.textColorOverride,
Transparency = theme.TextEmphasis.Transparency
}
end
if self.state.controlState == ControlState.Pressed or self.props.disabled then
textTheme = {
Color = textTheme.Color,
Transparency = divideTransparency(theme.TextEmphasis.Transparency, 2)
}
end
local cellStyle = theme[backgroundThemeKey]
return Roact.createElement(Controllable, {
controlComponent = {
component = "ImageButton",
props = {
Size = UDim2.new(1, 0, 0, self.props.elementHeight),
BackgroundTransparency = 1,
Image = CELL_BACKGROUND_ASSET.Image,
ScaleType = Enum.ScaleType.Slice,
SliceCenter = sliceCenter,
ImageRectSize = imageRectSize,
ImageRectOffset = imageRectOffset,
SliceScale = 1 / Images.ImagesResolutionScale,
ImageTransparency = cellStyle.Transparency,
ImageColor3 = cellStyle.Color,
AutoButtonColor = false,
LayoutOrder = self.props.layoutOrder,
BorderSizePixel = 0,
[Roact.Ref] = self.props.setButtonRef,
[Roact.Event.Activated] = self.props.onActivated,
},
children = {
Divider = Roact.createElement("Frame", {
BackgroundColor3 = theme.Divider.Color,
BackgroundTransparency = theme.Divider.Transparency,
BorderSizePixel = 0,
Size = UDim2.new(1, 0, 0, 1),
Position = UDim2.fromScale(0, 1),
AnchorPoint = Vector2.new(0, 1),
Visible = self.props.hasDivider,
}),
StateOverlay = Roact.createElement("ImageLabel", {
BackgroundTransparency = 1,
Image = CELL_BACKGROUND_ASSET.Image,
ScaleType = Enum.ScaleType.Slice,
SliceCenter = sliceCenter,
ImageRectSize = imageRectSize,
ImageRectOffset = imageRectOffset,
SliceScale = 1 / Images.ImagesResolutionScale,
ImageColor3 = overlayTheme.Color,
ImageTransparency = overlayTheme.Transparency,
BorderSizePixel = 0,
Size = UDim2.fromScale(1, 1),
ZIndex = 2,
}),
LeftAlignedContent = Roact.createElement("Frame", {
BackgroundTransparency = 1,
Size = UDim2.fromScale(1, 1),
}, {
Layout = Roact.createElement("UIListLayout", {
HorizontalAlignment = Enum.HorizontalAlignment.Left,
VerticalAlignment = Enum.VerticalAlignment.Center,
FillDirection = Enum.FillDirection.Horizontal,
SortOrder = Enum.SortOrder.LayoutOrder,
Padding = UDim.new(0, ELEMENT_PADDING),
}),
LeftPadding = Roact.createElement("UIPadding", {
PaddingLeft = UDim.new(0, leftPadding)
}),
Icon = self.props.icon and Roact.createElement(ImageSetComponent.Label, {
Image = self.props.icon,
Size = UDim2.fromOffset(ICON_SIZE, ICON_SIZE),
BackgroundTransparency = 1,
ImageColor3 = self.props.iconColorOverride or theme.IconEmphasis.Color,
ImageTransparency = divideTransparency(
theme.IconEmphasis.Transparency,
self.props.disabled and 2 or 1
),
LayoutOrder = 1,
}),
Text = Roact.createElement(GenericTextLabel, {
fontStyle = font.Header2,
colorStyle = textTheme,
BackgroundTransparency = 1,
Size = UDim2.new(1, -textLengthOffset, 1, 0),
Text = self.props.text,
TextTruncate = Enum.TextTruncate.AtEnd,
TextXAlignment = Enum.TextXAlignment.Left,
LayoutOrder = 2,
}),
}),
RightAlignedContent = Roact.createElement("Frame", {
BackgroundTransparency = 1,
Size = UDim2.fromScale(1, 1),
}, {
Layout = Roact.createElement("UIListLayout", {
HorizontalAlignment = Enum.HorizontalAlignment.Right,
VerticalAlignment = Enum.VerticalAlignment.Center,
FillDirection = Enum.FillDirection.Horizontal,
SortOrder = Enum.SortOrder.LayoutOrder,
Padding = UDim.new(0, ELEMENT_PADDING),
}),
RightPadding = Roact.createElement("UIPadding", {
PaddingRight = UDim.new(0, rightPadding)
}),
KeyLabel = self.props.keyCodeLabel and Roact.createElement(KeyLabel, {
keyCode = self.props.keyCodeLabel,
layoutOrder = 2,
[Roact.Change.AbsoluteSize] = self.keyLabelSizeChanged
}),
SelectedIcon = Roact.createElement(ImageSetComponent.Label, {
Image = Images["icons/status/success_small"],
Size = UDim2.fromOffset(SELECTED_ICON_SIZE, SELECTED_ICON_SIZE),
LayoutOrder = 1,
BackgroundTransparency = 1,
ImageColor3 = theme.IconEmphasis.Color,
ImageTransparency = theme.IconEmphasis.Transparency,
Visible = self.props.selected
}),
}),
},
},
onStateChanged = function(_, newState)
self.setControlState(newState)
end,
isDisabled = self.props.disabled,
})
end)
end
return cellComponent
end
return makeCell
|
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
local InventorySlots = {}
local settings = {
cache = {},
cache_used = {},
timer = {
[1] = 0,
[2] = 0,
[3] = 0,
[4] = 0,
[5] = 0,
},
weapons = {
'pistol',
}
}
LoadSlots = function(source)
local xPlayer = ESX.GetPlayerFromId(source)
local PreSlots = {}
MySQL.Async.fetchAll("SELECT identifier, slots FROM users WHERE identifier = @identifier", {
["@identifier"] = xPlayer.getIdentifier()
}, function(result)
if result[1].slots ~= nil then
local data = json.decode(result[1].slots)
table.insert(PreSlots , {
identifier = tostring(result[1].identifier),
first = tostring(data.first),
second = tostring(data.second),
third = tostring(data.third),
fourth = tostring(data.fourth),
fifth = tostring(data.fifth),
})
table.insert(InventorySlots , {
identifier = tostring(result[1].identifier),
first = tostring(data.first),
second = tostring(data.second),
third = tostring(data.third),
fourth = tostring(data.fourth),
fifth = tostring(data.fifth),
})
else
table.insert(PreSlots , {
identifier = tostring(result[1].identifier),
first = tostring("Brak"),
second = tostring("Brak"),
third = tostring("Brak"),
fourth = tostring("Brak"),
fifth = tostring("Brak"),
})
table.insert(InventorySlots , {
identifier = tostring(result[1].identifier),
first = tostring("Brak"),
second = tostring("Brak"),
third = tostring("Brak"),
fourth = tostring("Brak"),
fifth = tostring("Brak"),
})
end
end)
return PreSlots
end
RegisterNetEvent("definitelynotPK:LoadSlots")
AddEventHandler("definitelynotPK:LoadSlots", function()
local _source = source
local slots = LoadSlots(_source)
Wait(2000)
TriggerClientEvent("szymczakovv:updatebinds", _source, slots)
end)
SelectSlot = function(identifier)
local toreturn
for i=1, #InventorySlots, 1 do
local slot = InventorySlots[i]
if (tostring(slot.identifier) == tostring(identifier)) then
toreturn = slot
end
end
return toreturn
end
CheckWeapons = function(item)
local send = false
for i=1, #settings.weapons, 1 do
if (string.lower(item) == string.lower(settings.weapons[i])) then
send = true
end
end
return send
end
CanUse = function(source, identifier, itemName, data)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
if (itemName == tostring('Brak') or itemName == nil) then
xPlayer.showNotification('Brak przypisanego klawisza')
else
if CheckWeapons(itemName) == true then
local count = xPlayer.getInventoryItem(itemName).count
if count > 0 then
TriggerClientEvent('szymczakovv:IsWeapon', _source, itemName)
else
xPlayer.showNotification("You don't have assigned item - deleted from database item")
DeleteFromSlot(source, identifier, data)
end
else
local count = xPlayer.getInventoryItem(itemName).count
if count > 0 then
return true
else
xPlayer.showNotification("You don't have assigned item - deleted from database item")
DeleteFromSlot(source, identifier, data)
end
end
end
end
UseSlot = function(source, identifier, slot_out)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
for i=1, #InventorySlots, 1 do
if ((tostring(InventorySlots[i].identifier)) == tostring(identifier)) then
local sloty = InventorySlots[i]
local data = slot_out
if data == 'first' then
to_use = sloty.first
elseif data == 'second' then
to_use = sloty.second
elseif data == 'third' then
to_use = sloty.third
elseif data == 'fourth' then
to_use = sloty.fourth
elseif data == 'fifth' then
to_use = sloty.fifth
end
if CanUse(_source, identifier, to_use, data) == true then
TriggerClientEvent('szymczakovv:useItem', _source, to_use)
end
end
end
end
RegisterItemToSlot = function(source, slot_out, item)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
for i=1, #InventorySlots, 1 do
local sloty = InventorySlots[i]
if ((tostring(sloty.identifier)) == tostring(xPlayer.getIdentifier())) then
local data = slot_out
if data == 'first' then
sloty.first = item
elseif data == 'second' then
sloty.second = item
elseif data == 'third' then
sloty.third = item
elseif data == 'fourth' then
sloty.fourth = item
elseif data == 'fifth' then
sloty.fifth = item
end
UpdateSlotsDB(sloty, item, xPlayer.getIdentifier(), _source)
end
end
end
DeleteFromSlot = function(source, identifier, slot_out)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
for i=1, #InventorySlots, 1 do
local sloty = InventorySlots[i]
if ((tostring(sloty.identifier)) == tostring(identifier)) then
local data = slot_out
if data == 'first' then
sloty.first = "Brak"
elseif data == 'second' then
sloty.second = "Brak"
elseif data == 'third' then
sloty.third = "Brak"
elseif data == 'fourth' then
sloty.fourth = "Brak"
elseif data == 'fifth' then
sloty.fifth = "Brak"
end
UpdateSlotsDB(sloty, item, xPlayer.getIdentifier(), _source)
end
end
end
UpdateSlotsDB = function(sloty, item, identifier, source)
local _source = source
TriggerClientEvent("szymczakovv:updatebinds", _source, sloty)
MySQL.Async.execute('UPDATE users SET slots = @sloty WHERE identifier = @license',
{
['@sloty'] = json.encode(sloty),
['@license'] = identifier
})
end
RegisterServerEvent('szymczakovv:RegisterItemToSlot')
AddEventHandler('szymczakovv:RegisterItemToSlot', function(itemnum, item)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
RegisterItemToSlot(_source, itemnum, item)
end)
RegisterServerEvent('szymczakovv:UseItemFromBind')
AddEventHandler('szymczakovv:UseItemFromBind', function(num)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
UseSlot(_source, xPlayer.getIdentifier(), num)
end)
RegisterServerEvent('szymczakovv:deleteBind')
AddEventHandler('szymczakovv:deleteBind', function(num)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
DeleteFromSlot(_source, xPlayer.getIdentifier(), num)
end)
ESX.RegisterServerCallback('szymczakovv:getBinds', function(source, cb)
local xPlayer = ESX.GetPlayerFromId(source)
local data = SelectSlot(xPlayer.getIdentifier())
if data ~= nil then
cb(data.first, data.second, data.third, data.fourth, data.fifth)
else
cb("Brak","Brak","Brak","Brak","Brak")
end
end)
|
local oldMarineInit = Marine.OnInitialized
function Marine:OnInitialized()
oldMarineInit(self)
InitMixin(self, WalkMixin)
end
local networkVars = { }
AddMixinNetworkVars(WalkMixin, networkVars)
Shared.LinkClassToMap("Marine", Marine.kMapName, networkVars, true)
if Client then
local oldTriggerFootstep = Player.TriggerFootstep
function Player:TriggerFootstep()
if HasMixin(self, "Walk") and self:GetWalking() then
return
end
return oldTriggerFootstep(self)
end
end
local oldGetPlayFootsteps = Player.GetPlayFootsteps
function Player:GetPlayFootsteps()
if not Client then
return false
end
return oldGetPlayFootsteps(self) and not (HasMixin(self, "Walk") and self:GetWalking())
end
|
local BasePlugin = require "kong.plugins.base_plugin"
local basic_serializer = require "kong.plugins.log-serializers.basic"
local producers = require "kong.plugins.verifi-kafka-log.producers"
local cjson = require "cjson"
local cjson_encode = cjson.encode
local cjson_decode = cjson.decode
local utils = require "kong.tools.utils"
local concat = table.concat
local ngx = ngx
local kong = kong
local gsub = string.gsub
local res_get_headers = ngx.resp.get_headers
local table_concat = table.concat
local KafkaLogHandler = BasePlugin:extend()
KafkaLogHandler.PRIORITY = 5
KafkaLogHandler.VERSION = "0.0.1"
local mt_cache = { __mode = "k" }
local producers_cache = setmetatable({}, mt_cache)
local plugin_uuid = utils.uuid()
--- Computes a cache key for a given configuration.
local function cache_key(conf)
-- here we rely on validation logic in schema that automatically assigns a unique id
-- on every configuartion update
-- return conf.uuid
return plugin_uuid
end
function KafkaLogHandler:new()
KafkaLogHandler.super.new(self, "verifi-kafka-log")
end
function KafkaLogHandler:access(conf)
KafkaLogHandler.super.access(self)
ngx.ctx.rt_body_chunks = {}
ngx.ctx.rt_body_chunk_number = 1
end
function KafkaLogHandler:body_filter(conf)
KafkaLogHandler.super.body_filter(self)
if conf.log_response_body then
local cache_key = cache_key(conf)
if not cache_key then
ngx.log(ngx.ERR, "[verifi-kafka-log] cannot log a given request because configuration has no uuid")
return
end
local producer = producers_cache[cache_key]
if not producer then
kong.log.notice("creating a new Kafka Producer for cache key: ", cache_key)
local err
producer, err = producers.new(conf)
if not producer then
ngx.log(ngx.ERR, "[verifi-kafka-log] failed to create a Kafka Producer for a given configuration: ", err)
return
end
producers_cache[cache_key] = producer
end
local chunk, eof = ngx.arg[1], ngx.arg[2]
if not eof then
ngx.ctx.rt_body_chunks[ngx.ctx.rt_body_chunk_number] = chunk
ngx.ctx.rt_body_chunk_number = ngx.ctx.rt_body_chunk_number + 1
-- ngx.arg[1] = nil
else
local body = table_concat(ngx.ctx.rt_body_chunks)
local ok, err = producer:send(conf.topic, nil, cjson_encode(body))
-- ngx.arg[1] = body
end
end
end
--- Publishes a message to Kafka.
-- Must run in the context of `ngx.timer.at`.
local function log(premature, conf, message)
if premature then
return
end
local cache_key = cache_key(conf)
if not cache_key then
ngx.log(ngx.ERR, "[verifi-kafka-log] cannot log a given request because configuration has no uuid")
return
end
local producer = producers_cache[cache_key]
if not producer then
kong.log.notice("creating a new Kafka Producer for cache key: ", cache_key)
local err
producer, err = producers.new(conf)
if not producer then
ngx.log(ngx.ERR, "[verifi-kafka-log] failed to create a Kafka Producer for a given configuration: ", err)
return
end
producers_cache[cache_key] = producer
end
local ok, err = producer:send(conf.topic, nil, cjson_encode(message))
if not ok then
ngx.log(ngx.ERR, "[verifi-kafka-log] failed to send a message on topic ", conf.topic, ": ", err)
return
end
end
function KafkaLogHandler:log(conf, other)
KafkaLogHandler.super.log(self)
local message = basic_serializer.serialize(ngx)
local ok, err = ngx.timer.at(0, log, conf, message)
if not ok then
ngx.log(ngx.ERR, "[verifi-kafka-log] failed to create timer: ", err)
end
end
return KafkaLogHandler
|
--[[
__________ __ ___.
Open \______ \ ____ ____ | | _\_ |__ _______ ___
Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
\/ \/ \/ \/ \/
$Id$
Port of test_viewports.c to Lua
Copyright (C) 2009 by Maurus Cuelenaere
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
KIND, either express or implied.
]]--
-- TODO: outsource this
rb.DRMODE_SOLID = 3
rb.LCD_BLACK = rb.lcd_rgbpack(0, 0, 0)
rb.LCD_WHITE = rb.lcd_rgbpack(255, 255, 255)
rb.LCD_DEFAULT_FG = rb.LCD_WHITE
rb.LCD_DEFAULT_BG = rb.LCD_BLACK
BGCOLOR_1 = rb.lcd_rgbpack(255,255,0)
BGCOLOR_2 = rb.lcd_rgbpack(0,255,0)
FGCOLOR_1 = rb.lcd_rgbpack(0,0,255)
local vp0 =
{
x = 0,
y = 0,
width = rb.LCD_WIDTH,
height = 20,
font = rb.FONT_UI,
drawmode = rb.DRMODE_SOLID,
fg_pattern = rb.LCD_DEFAULT_FG,
bg_pattern = BGCOLOR_1
}
local vp1 =
{
x = rb.LCD_WIDTH / 10,
y = 20,
width = rb.LCD_WIDTH / 3,
height = rb.LCD_HEIGHT / 2,
font = rb.FONT_SYSFIXED,
drawmode = rb.DRMODE_SOLID,
fg_pattern = rb.LCD_DEFAULT_FG,
bg_pattern = rb.LCD_DEFAULT_BG
};
local vp2 =
{
x = rb.LCD_WIDTH / 2,
y = 40,
width = rb.LCD_WIDTH / 3,
height = (rb.LCD_HEIGHT / 2),
font = rb.FONT_UI,
drawmode = rb.DRMODE_SOLID,
fg_pattern = FGCOLOR_1,
bg_pattern = BGCOLOR_2
};
local vp3 =
{
x = rb.LCD_WIDTH / 4,
y = (5 * rb.LCD_HEIGHT) / 8,
width = rb.LCD_WIDTH / 2,
height = (rb.LCD_HEIGHT / 4),
font = rb.FONT_SYSFIXED,
drawmode = rb.DRMODE_SOLID,
fg_pattern = rb.LCD_BLACK,
bg_pattern = rb.LCD_WHITE
};
rb.set_viewport(vp0)
rb.clear_viewport()
rb.lcd_puts_scroll(0,0,"Viewport testing plugin - this is a scrolling title")
rb.set_viewport(vp1);
rb.clear_viewport();
for i = 0, 3 do
rb.lcd_puts_scroll(0,i,string.format("Left text, scrolling_line %d",i));
end
rb.set_viewport(vp2);
rb.clear_viewport();
for i = 0, 3 do
rb.lcd_puts_scroll(1,i,string.format("Right text, scrolling line %d",i));
end
local y = -10
for i = -10, vp2.width + 10, 5 do
rb.lcd_drawline(i, y, i, vp2.height - y);
end
rb.set_viewport(vp3);
rb.clear_viewport();
for i = 1, 2 do
rb.lcd_puts_scroll(2,i,string.format("Bottom text, a scrolling line %d",i));
end
rb.lcd_puts_scroll(4,3,"Short line")
rb.lcd_update()
rb.button_get(true)
rb.set_viewport(nil)
|
local CEmitter = require 'nelua.cemitter'
local iters = require 'nelua.utils.iterators'
local traits = require 'nelua.utils.traits'
local errorer = require 'nelua.utils.errorer'
local stringer = require 'nelua.utils.stringer'
local bn = require 'nelua.utils.bn'
local cdefs = require 'nelua.cdefs'
local cbuiltins = require 'nelua.cbuiltins'
local typedefs = require 'nelua.typedefs'
local CContext = require 'nelua.ccontext'
local types = require 'nelua.types'
local primtypes = typedefs.primtypes
local function izipargnodes(vars, argnodes)
local iter, ts, i = iters.izip2(vars, argnodes)
local lastargindex = #argnodes
local lastargnode = argnodes[#argnodes]
local calleetype = lastargnode and lastargnode.attr.calleetype
if lastargnode and lastargnode.tag:sub(1,4) == 'Call' and (not calleetype or not calleetype.is_type) then
-- last arg is a runtime call
assert(calleetype)
-- we know the callee type
return function()
local var, argnode
i, var, argnode = iter(ts, i)
if not i then return nil end
if i >= lastargindex and lastargnode.attr.multirets then
-- argnode does not exists, fill with multiple returns type
-- in case it doest not exists, the argtype will be false
local callretindex = i - lastargindex + 1
local argtype = calleetype:get_return_type(callretindex)
return i, var, argnode, argtype, callretindex, calleetype
else
local argtype = argnode and argnode.attr.type
return i, var, argnode, argtype, nil
end
end
else
-- no calls from last argument
return function()
local var, argnode
i, var, argnode = iter(ts, i)
if not i then return end
-- we are sure this argument have no type, set argtype to false
local argtype = argnode and argnode.attr.type
return i, var, argnode, argtype
end
end
end
local function destroy_variable(context, emitter, vartype, varname)
if not vartype:has_destroyable() then return end
local destroymt = vartype.metafields.__destroy
if destroymt then
emitter:add_indent_ln(context:declname(destroymt), '(&', varname, ');')
end
for _,field in ipairs(vartype.fields) do
if field.type:has_destroyable() then
destroy_variable(context, emitter, field.type, varname..'.'..field.name)
end
end
end
local function destroy_callee_returns(context, emitter, retvalname, calleetype, ignoreindexes)
for i,returntype in ipairs(calleetype.rettypes) do
if returntype:has_destroyable() and not ignoreindexes[i] then
local retargname
if calleetype:has_multiple_returns() then
retargname = string.format('%s.r%d', retvalname, i)
else
retargname = retvalname
end
destroy_variable(context, emitter, returntype, retargname)
end
end
end
local function destroy_scope_variables(context, emitter, scope)
for i=#scope.symbols,1,-1 do
local symbol = scope.symbols[i]
if not symbol.moved then
local symtype = scope.symbols[i].type
if symbol.scopedestroy then
destroy_variable(context, emitter, symtype, context:declname(symbol))
end
end
end
if scope.deferblocks then
for i=#scope.deferblocks,1,-1 do
local deferblock = scope.deferblocks[i]
emitter:add_indent_ln('{')
context:push_scope(deferblock.scope.parent)
emitter:add(deferblock)
context:pop_scope()
emitter:add_indent_ln('}')
end
end
end
local function destroy_upscopes_variables(context, emitter, kind)
local scope = context.scope
repeat
destroy_scope_variables(context, emitter, scope)
scope = scope.parent
until (scope[kind] or scope == context.rootscope)
destroy_scope_variables(context, emitter, scope)
end
local function copy_variable(context, emitter, vartype, varname, srcvarname)
local copymt = vartype.metafields.__copy
if copymt then
emitter:add_indent_ln(context:declname(copymt), '(&', varname, ', &', srcvarname, ');')
end
for _,field in ipairs(vartype.fields) do
if field.type:has_copyable() then
copy_variable(context, emitter, field.type, varname..'.'..field.name, srcvarname..'.'..field.name)
end
end
end
local function create_variable(context, emitter, type, val, valtype)
if not valtype and traits.is_astnode(val) then
valtype = val.attr.type
end
local copying = false
if type == valtype and traits.is_astnode(val) and val.attr.lvalue and type:has_copyable() then
if not val.attr.maymove or val.attr.moved then
copying = true
else
val.attr.moved = true
end
end
if copying then
emitter:add_ln('({')
emitter:inc_indent()
emitter:add_indent_ln(type, ' _t1 = {0};')
emitter:add_indent(type, '* _t2 = &')
emitter:add_val2type(type, val, valtype)
emitter:add_ln(';')
copy_variable(context, emitter, type, '_t1', '(*_t2)')
emitter:add_indent_ln('_t1;')
emitter:dec_indent()
emitter:add_indent('})')
else
emitter:add_val2type(type, val, valtype)
end
end
local function visit_assignments(context, emitter, varnodes, valnodes, decl)
local usetemporary = false
if not decl and #valnodes > 1 then
-- multiple assignments must assign to a temporary first (in case of a swap)
usetemporary = true
end
local defemitter = CEmitter(context, emitter.depth)
local multiretvalname
for _,varnode,valnode,valtype,lastcallindex in izipargnodes(varnodes, valnodes or {}) do
local varattr = varnode.attr
local noinit = varattr.noinit or varattr.cexport
local vartype = varattr.type
if not vartype.is_type and (not varattr.nodecl or not decl) and not varattr.comptime then
local declared, defined = false, false
if decl and varattr.staticstorage then
-- declare main variables in the top scope
local decemitter = CEmitter(context)
decemitter:add_indent()
if not varattr.nostatic and not varattr.cexport then
decemitter:add('static ')
end
decemitter:add(varnode)
if valnode and valnode.attr.initializer then
-- initialize to const values
decemitter:add(' = ')
assert(not lastcallindex)
local state = context:push_state()
state.ininitializer = true
decemitter:add_val2type(vartype, valnode)
context:pop_state()
defined = true
else
-- pre initialize to zeros
if not noinit then
decemitter:add(' = ')
decemitter:add_zeroinit(vartype)
end
end
decemitter:add_ln(';')
context:add_declaration(decemitter:generate())
declared = true
end
if lastcallindex == 1 then
-- last assigment value may be a multiple return call
multiretvalname = context:genuniquename('ret')
local retctype = context:funcretctype(valnode.attr.calleetype)
emitter:add_indent_ln(retctype, ' ', multiretvalname, ' = ', valnode, ';')
end
local dodestroy = not decl and vartype:has_destroyable() and traits.is_astnode(valnode)
local docopy = vartype:has_copyable() and traits.is_astnode(valnode)
if docopy or dodestroy then
usetemporary = true
end
local retvalname
if lastcallindex then
retvalname = string.format('%s.r%d', multiretvalname, lastcallindex)
elseif usetemporary then
retvalname = context:genuniquename('asgntmp')
emitter:add_indent(vartype, ' ', retvalname, ' = ')
create_variable(context, emitter, vartype, valnode)
emitter:add_ln(';')
if dodestroy then
destroy_variable(context, emitter, vartype, context:declname(varnode.attr))
end
end
if not declared or (not defined and (valnode or lastcallindex)) then
-- declare or define if needed
defemitter:add_indent()
if not declared then
defemitter:add(varnode)
else
defemitter:add(context:declname(varattr))
end
if not noinit or not decl then
-- initialize variable
defemitter:add(' = ')
if retvalname then
defemitter:add_val2type(vartype, retvalname, valtype, varnode.checkcast)
elseif valnode then
defemitter:add_val2type(vartype, valnode)
else
defemitter:add_zeroinit(vartype)
end
end
defemitter:add_ln(';')
end
elseif varattr.cinclude then
-- not declared, might be an imported variable from C
context:add_include(varattr.cinclude)
end
end
emitter:add(defemitter:generate())
end
local typevisitors = {}
local function emit_type_attributes(decemitter, type)
if type.aligned then
decemitter:add(' __attribute__((aligned(', type.aligned, ')))')
end
if type.packed then
decemitter:add(' __attribute__((packed))')
end
end
typevisitors[types.ArrayType] = function(context, type)
local decemitter = CEmitter(context, 0)
decemitter:add('typedef struct {', type.subtype, ' data[', type.length, '];} ', type.codename)
emit_type_attributes(decemitter, type)
decemitter:add_ln(';')
decemitter:add_ln('nelua_static_assert(sizeof(',type.codename,') == ', type.size,
', "Nelua and C disagree on type size");')
table.insert(context.declarations, decemitter:generate())
end
typevisitors[types.PointerType] = function(context, type)
local decemitter = CEmitter(context, 0)
local index = nil
if type.subtype.is_composite and not type.subtype.nodecl and not context.declarations[type.subtype.codename] then
-- offset declaration of pointers before records/unions
index = #context.declarations+2
end
if type.subtype.is_array and type.subtype.length == 0 then
decemitter:add_ln('typedef ', type.subtype.subtype, '* ', type.codename, ';')
else
decemitter:add_ln('typedef ', type.subtype, '* ', type.codename, ';')
end
if not index then
index = #context.declarations+1
end
table.insert(context.declarations, index, decemitter:generate())
end
local function typevisitor_CompositeType(context, type)
local decemitter = CEmitter(context, 0)
local kindname = type.is_record and 'struct' or 'union'
decemitter:add_ln('typedef ',kindname,' ', type.codename, ' ', type.codename, ';')
table.insert(context.declarations, decemitter:generate())
local defemitter = CEmitter(context, 0)
--if #type.fields > 0 then
defemitter:add(kindname, ' ', type.codename)
defemitter:add_ln(' {')
for _,field in ipairs(type.fields) do
local fieldctype
if field.type.is_array then
fieldctype = field.type.subtype
else
fieldctype = context:ctype(field.type)
end
defemitter:add(' ', fieldctype, ' ', field.name)
if field.type.is_array then
defemitter:add('[', field.type.length, ']')
end
defemitter:add_ln(';')
end
defemitter:add('}')
emit_type_attributes(defemitter, type)
defemitter:add_ln(';')
--end
defemitter:add_ln('nelua_static_assert(sizeof(',type.codename,') == ', type.size,
', "Nelua and C disagree on type size");')
table.insert(context.declarations, defemitter:generate())
end
typevisitors[types.RecordType] = typevisitor_CompositeType
typevisitors[types.UnionType] = typevisitor_CompositeType
typevisitors[types.EnumType] = function(context, type)
local decemitter = CEmitter(context, 0)
decemitter:add_ln('typedef ', type.subtype, ' ', type.codename, ';')
table.insert(context.declarations, decemitter:generate())
end
typevisitors[types.FunctionType] = function(context, type)
local decemitter = CEmitter(context, 0)
decemitter:add('typedef ', context:funcretctype(type), ' (*', type.codename, ')(')
for i,argtype in ipairs(type.argtypes) do
if i>1 then
decemitter:add(', ')
end
decemitter:add(argtype)
end
decemitter:add_ln(');')
table.insert(context.declarations, decemitter:generate())
end
typevisitors.FunctionReturnType = function(context, functype)
if not functype:has_multiple_returns() then
return context:ctype(functype:get_return_type(1))
end
local retctype = functype.codename .. '_ret'
if context:is_declared(retctype) then return retctype end
local numrets = functype:get_return_count()
local retemitter = CEmitter(context)
retemitter:add_indent_ln('typedef struct ', retctype, ' {')
retemitter:inc_indent()
for i=1,numrets do
local rettype = functype:get_return_type(i)
assert(rettype)
retemitter:add_indent_ln(rettype, ' ', 'r', i, ';')
end
retemitter:dec_indent()
retemitter:add_indent_ln('} ', retctype, ';')
context:add_declaration(retemitter:generate(), retctype)
return retctype
end
--[[
typevisitors[types.PolyFunctionType] = function(context, type)
if type.nodecl or context:is_declared(type.codename) then return end
local decemitter = CEmitter(context, 0)
decemitter:add_ln('typedef void* ', type.codename, ';')
context:add_declaration(decemitter:generate(), type.codename)
end
]]
typevisitors[types.Type] = function(context, type)
if type.is_any then --luacov:enable
context:ensure_runtime_builtin('nlany')
elseif type.is_niltype then
context:ensure_runtime_builtin('nlniltype')
else
errorer.assertf(cdefs.primitive_ctypes[type.codename],
'C type visitor for "%s" is not defined', type)
end
end
local visitors = {}
function visitors.Number(context, node, emitter)
local attr = node.attr
if not attr.type.is_float and not attr.untyped and not context.state.ininitializer then
emitter:add_ctypecast(attr.type)
end
emitter:add_numeric_literal(attr)
end
function visitors.String(_, node, emitter)
local attr = node.attr
if attr.type.is_stringy then
emitter:add_string_literal(attr.value, attr.type.is_cstring)
else
if attr.type == primtypes.cchar then
emitter:add("'", string.char(bn.tointeger(attr.value)), "'")
else
emitter:add_numeric_literal(attr)
end
end
end
function visitors.Boolean(_, node, emitter)
emitter:add_booleanlit(node.attr.value)
end
function visitors.Nil(_, _, emitter)
emitter:add_nil_literal()
end
function visitors.Varargs(_, _, emitter) --luacov:disable
assert('not implemented yet')
emitter:add('...')
end --luacov:enable
function visitors.VarargsType(_, _, emitter)
emitter:add('...')
end
function visitors.Table(context, node, emitter)
local attr = node.attr
local childnodes, type = node[1], attr.type
local len = #childnodes
if len == 0 and (type.is_composite or type.is_array) then
if not context.state.ininitializer then
emitter:add_ctypecast(type)
end
emitter:add_zeroinit(type)
elseif type.is_record then
if context.state.ininitializer then
local state = context:push_state()
state.inrecordinitializer = true
emitter:add('{', childnodes, '}')
context:pop_state()
else
local compactemit = false
if #childnodes == #type.fields then
compactemit = true
local hascall = false
for _,childnode in ipairs(childnodes) do
local childvalnode
if childnode.tag == 'Pair' then
childvalnode = childnode[2]
else
childvalnode = childnode
end
local childvaltype = childvalnode.attr.type
local iscall = childnode.tag:match('^Call')
if childvaltype.is_array or (hascall and iscall) then
compactemit = false
break
end
if iscall then hascall = true end
end
end
if compactemit then
emitter:add('(',type,'){')
else
emitter:add_ln('({')
emitter:inc_indent()
emitter:add_indent(type, ' __rec = ')
emitter:add_zeroinit(type)
emitter:add_ln(';')
end
for i,childnode in ipairs(childnodes) do
local fieldname = childnode.fieldname
local named = false
local childvalnode
if childnode.tag == 'Pair' then
childvalnode = childnode[2]
named = true
else
childvalnode = childnode
end
local childvaltype = childvalnode.attr.type
if compactemit then
if i > 1 then
emitter:add(', ')
end
if named then
emitter:add('.', fieldname, ' = ')
end
else
if childvaltype.is_array then
emitter:add_indent('(*(', childvaltype, '*)__rec.', fieldname, ') = ')
else
emitter:add_indent('__rec.', fieldname, ' = ')
end
end
local fieldtype = type.fields[fieldname].type
assert(fieldtype)
create_variable(context, emitter, fieldtype, childvalnode, childvaltype)
if not compactemit then
emitter:add_ln(';')
end
end
if compactemit then
emitter:add('}')
else
emitter:add_indent_ln('__rec;')
emitter:dec_indent()
emitter:add_indent('})')
end
end
elseif type.is_array then
if context.state.ininitializer then
if context.state.inrecordinitializer then
emitter:add('{', childnodes, '}')
else
emitter:add('{{', childnodes, '}}')
end
else
emitter:add_ctypecast(type)
emitter:add('{{', childnodes, '}}')
end
else --luacov:disable
error('not implemented yet')
end --luacov:enable
end
function visitors.Pair(context, node, emitter)
local namenode, valuenode = node:args()
local parenttype = node.parenttype
if parenttype and parenttype.is_composite then
assert(traits.is_string(namenode))
emitter:add('.', cdefs.quotename(namenode), ' = ')
local fieldtype = parenttype.fields[namenode].type
create_variable(context, emitter, fieldtype, valuenode, valuenode.attr.type)
else --luacov:disable
error('not implemented yet')
end --luacov:enable
end
-- TODO: Function
function visitors.PragmaCall(context, node, emitter)
local name, args = node:args()
if name == 'cinclude' then
context:add_include(table.unpack(args))
elseif name == 'cemit' then
local code = args[1]
if traits.is_string(code) and not stringer.endswith(code, '\n') then
code = code .. '\n'
end
if traits.is_string(code) then
emitter:add(code)
elseif traits.is_function(code) then
code(emitter)
end
elseif name == 'cemitdecl' then
local code = args[1]
if traits.is_string(code) and not stringer.endswith(code, '\n') then
code = code .. '\n'
end
if traits.is_string(code) then
context:add_declaration(code)
elseif traits.is_function(code) then
local decemitter = CEmitter(context)
code(decemitter)
context:add_declaration(decemitter:generate())
end
elseif name == 'cemitdef' then
local code = args[1]
if traits.is_string(code) and not stringer.endswith(code, '\n') then
code = code .. '\n'
end
if traits.is_string(code) then
context:add_definition(code)
elseif traits.is_function(code) then
local defemitter = CEmitter(context)
code(defemitter)
context:add_definition(defemitter:generate())
end
elseif name == 'cdefine' then
context:add_declaration(string.format('#define %s\n', args[1]))
elseif name == 'cflags' then
table.insert(context.compileopts.cflags, args[1])
elseif name == 'ldflags' then
table.insert(context.compileopts.ldflags, args[1])
elseif name == 'linklib' then
table.insert(context.compileopts.linklibs, args[1])
end
end
function visitors.Id(context, node, emitter)
local attr = node.attr
assert(not attr.type.is_comptime)
if attr.type.is_nilptr then
emitter:add_null()
elseif attr.comptime then
emitter:add_literal(attr)
else
emitter:add(context:declname(attr))
end
end
function visitors.Paren(_, node, emitter)
local innernode = node:args()
emitter:add(innernode)
--emitter:add('(', innernode, ')')
end
visitors.FuncType = visitors.Type
visitors.ArrayType = visitors.Type
visitors.PointerType = visitors.Type
function visitors.IdDecl(context, node, emitter)
local attr = node.attr
local type = attr.type
if attr.comptime or type.is_comptime then
emitter:add(context:ensure_runtime_builtin('nlniltype'), ' ', context:declname(attr))
return
end
if attr.funcdecl then
emitter:add(context:declname(attr))
return
end
if type.is_type then return end
if attr.cexport then emitter:add(context:ensure_runtime_builtin('nelua_cexport'), ' ') end
if attr.register then emitter:add('register ') end
if attr.const and attr.type.is_pointer then emitter:add('const ') end
if attr.volatile then emitter:add('volatile ') end
if attr.restrict then emitter:add('__restrict ') end
if attr.static then emitter:add('static ') end
if attr.cqualifier then emitter:add(attr.cqualifier, ' ') end
emitter:add(type, ' ', context:declname(attr))
if attr.cattribute then emitter:add(' __attribute__((', attr.cattribute, '))') end
if type:has_destroyable() then
attr.scopedestroy = true
end
end
local function visitor_Call(context, node, emitter, argnodes, callee, calleeobjnode)
local isblockcall = context:get_parent_node().tag == 'Block'
if isblockcall then
emitter:add_indent()
end
local attr = node.attr
local calleetype = attr.calleetype
if calleetype.is_procedure then
-- function call
local tmpargs = {}
local tmpcount = 0
local lastcalltmp
local sequential = false
local serialized = false
local callargtypes = attr.pseudoargtypes or calleetype.argtypes
local callargattrs = attr.pseudoargattrs or calleetype.argattrs
local ismethod = attr.ismethod
for i,funcargtype,argnode,_,lastcallindex in izipargnodes(callargtypes, argnodes) do
if funcargtype.is_cvarargs and not argnode then break end
if (argnode and argnode.attr.sideeffect) or lastcallindex == 1 then
-- expressions with side effects need to be evaluated in sequence
-- and expressions with multiple returns needs to be stored in a temporary
tmpcount = tmpcount + 1
local tmpname = '__tmp' .. tmpcount
tmpargs[i] = tmpname
if lastcallindex == 1 then
lastcalltmp = tmpname
end
if tmpcount >= 2 or lastcallindex then
-- only need to evaluate in sequence mode if we have two or more temporaries
-- or the last argument is a multiple return call
sequential = true
serialized = true
end
end
end
local handlereturns
local retvalname
local returnfirst
local enclosed = calleetype:has_multiple_returns()
local destroyable = calleetype:has_destroyable_return()
if not attr.multirets and (enclosed or destroyable) then
-- we are handling the returns
returnfirst = not isblockcall
handlereturns = true
serialized = true
end
if serialized then
-- break apart the call into many statements
if not isblockcall then
emitter:add('(')
end
emitter:add_ln('{')
emitter:inc_indent()
end
if sequential then
for _,tmparg,argnode,argtype,_,lastcalletype in izipargnodes(tmpargs, argnodes) do
-- set temporary values in sequence
if tmparg then
if lastcalletype then
-- type for result of multiple return call
argtype = context:funcretctype(lastcalletype)
end
emitter:add_indent_ln(argtype, ' ', tmparg, ' = ', argnode, ';')
end
end
end
if serialized then
emitter:add_indent()
if handlereturns then
-- save the return type
local retctype = context:funcretctype(calleetype)
retvalname = context:genuniquename('ret')
emitter:add(retctype, ' ', retvalname, ' = ')
end
end
if ismethod then
emitter:add(context:declname(attr.calleesym), '(')
emitter:add_val2type(calleetype.argtypes[1], calleeobjnode)
else
if attr.pointercall then
emitter:add('(*')
end
if not traits.is_string(callee) and attr.calleesym then
emitter:add(context:declname(attr.calleesym))
else
emitter:add(callee)
end
if attr.pointercall then
emitter:add(')')
end
emitter:add('(')
end
for i,funcargtype,argnode,argtype,lastcallindex in izipargnodes(callargtypes, argnodes) do
if funcargtype.is_cvarargs and not argnode then break end
if i > 1 or ismethod then emitter:add(', ') end
local arg = argnode
if sequential then
if lastcallindex then
arg = string.format('%s.r%d', lastcalltmp, lastcallindex)
elseif tmpargs[i] then
arg = tmpargs[i]
end
end
if callargattrs[i].comptime then
-- compile time function argument
emitter:add_nil_literal()
else
create_variable(context, emitter, funcargtype, arg, argtype)
end
end
emitter:add(')')
if serialized then
-- end sequential expression
emitter:add_ln(';')
if handlereturns and destroyable then
local ignoredestroyindexes = {}
if returnfirst then
ignoredestroyindexes[1] = true
end
destroy_callee_returns(context, emitter, retvalname, calleetype, ignoredestroyindexes)
end
if returnfirst then
-- get just the first result in multiple return functions
if enclosed then
emitter:add_indent_ln(retvalname, '.r1;')
else
emitter:add_indent_ln(retvalname, ';')
end
end
emitter:dec_indent()
emitter:add_indent('}')
if not isblockcall then
emitter:add(')')
end
end
else
--TODO: handle better calls on any types
emitter:add(callee, '(', argnodes, ')')
end
if isblockcall then
emitter:add_ln(";")
end
end
function visitors.Call(context, node, emitter)
if node.attr.omitcall then return end
local argnodes, calleenode = node:args()
local calleetype = node.attr.calleetype
local callee = calleenode
if calleenode.attr.builtin then
local builtin = cbuiltins.inlines[calleenode.attr.name]
callee = builtin(context, node, emitter)
end
if calleetype.is_type then
-- type cast
local type = node.attr.type
if #argnodes == 1 then
local argnode = argnodes[1]
if argnode.attr.type ~= type then
-- type really differs, cast it
emitter:add_val2type(type, argnode, argnode.attr.type)
else
-- same type, no need to cast
emitter:add(argnode)
end
else
emitter:add_ctyped_zerotype(type)
end
elseif callee then
visitor_Call(context, node, emitter, argnodes, callee, nil)
end
end
function visitors.CallMethod(context, node, emitter)
local name, argnodes, calleeobjnode = node:args()
visitor_Call(context, node, emitter, argnodes, nil, calleeobjnode)
--[[
local name, args, callee, block_call = node:args()
if block_call then
emitter:add_indent()
end
local sep = #args > 0 and ', ' or ''
emitter:add(callee, '.', cdefs.quotename(name), '(', callee, sep, args, ')')
if block_call then
emitter:add_ln()
end
]]
end
-- indexing
function visitors.DotIndex(context, node, emitter)
local name, objnode = node:args()
local attr = node.attr
local type = attr.type
local objtype = objnode.attr.type
local poparray = false
if type.is_array then
if objtype:implict_deref_type().is_composite and context.state.inarrayindex == node then
context.state.recordindexed = node
elseif not attr.globalfield then
emitter:add('(*(', type, '*)')
poparray = true
end
end
if objtype.is_type then
objtype = node.indextype
if objtype.is_enum then
local field = objtype.fields[name]
emitter:add_numeric_literal(field, objtype.subtype)
elseif objtype.is_composite then
if attr.comptime then
emitter:add_literal(attr)
else
emitter:add(context:declname(attr))
end
else --luacov:disable
error('not implemented yet')
end --luacov:enable
elseif objtype.is_pointer then
emitter:add(objnode, '->', cdefs.quotename(name))
else
emitter:add(objnode, '.', cdefs.quotename(name))
end
if poparray then
emitter:add(')')
end
end
visitors.ColonIndex = visitors.DotIndex
function visitors.ArrayIndex(context, node, emitter)
local indexnode, objnode = node:args()
local objtype = objnode.attr.type
local pointer = false
if objtype.is_pointer and not objtype.is_generic_pointer then
-- indexing a pointer to an array
objtype = objtype.subtype
pointer = true
end
if objtype.is_record then
local atindex = node.attr.calleesym and node.attr.calleesym.name:match('.__atindex')
if atindex then
emitter:add('(*')
end
visitor_Call(context, node, emitter, {indexnode}, nil, objnode)
if atindex then
emitter:add(')')
end
else
if not objtype.is_array then --luacov:disable
error('not implemented yet')
end --luacov:enable
if pointer then
if objtype.length == 0 then
emitter:add('(',objnode, ')[')
else
emitter:add('((', objtype.subtype, '*)', objnode, ')[')
end
elseif objtype.length == 0 then
emitter:add('((', objtype.subtype, '*)&', objnode, ')[')
else
context:push_state().inarrayindex = objnode
emitter:add(objnode)
if context.state.recordindexed ~= objnode then
emitter:add('.data')
end
emitter:add('[')
context:pop_state()
end
if not node.attr.checkbounds then
emitter:add(indexnode)
else
local indextype = indexnode.attr.type
emitter:add(context:ensure_runtime_builtin('nelua_assert_bounds_', indextype))
emitter:add('(', indexnode, ', ', objtype.length, ')')
end
emitter:add(']')
end
end
function visitors.Block(context, node, emitter)
local statnodes = node:args()
emitter:inc_indent()
local scope = context:push_forked_scope(node)
do
emitter:add_traversal_list(statnodes, '')
end
if not node.attr.returnending and not scope.alreadydestroyed then
destroy_scope_variables(context, emitter, scope)
end
context:pop_scope()
emitter:dec_indent()
end
function visitors.Return(context, node, emitter)
local retnodes = node:args()
local numretnodes = #retnodes
-- destroy parent blocks
local defemitter = CEmitter(context, emitter.depth)
local desemitter = CEmitter(context, emitter.depth)
local funcscope = context.scope:get_up_return_scope() or context.rootscope
context.scope.alreadydestroyed = true
funcscope.has_return = true
if funcscope == context.rootscope then
-- in main body
node:assertraisef(numretnodes <= 1, "multiple returns in main is not supported yet")
if numretnodes == 0 then
-- main must always return an integer
defemitter:add_indent_ln('return 0;')
else
-- return one value (an integer expected)
local retnode = retnodes[1]
defemitter:add_indent('return ')
defemitter:add_val2type(primtypes.cint, retnode)
defemitter:add_ln(';')
end
elseif funcscope.is_doexpr then
defemitter:add_indent_ln('__expr = ', retnodes[1], ';')
else
local functype = funcscope.functype
local numfuncrets = functype:get_return_count()
if not functype:has_multiple_returns() then
if numfuncrets == 0 then
-- no returns
assert(numretnodes == 0)
defemitter:add_indent_ln('return;')
elseif numfuncrets == 1 then
-- one return
local retnode, rettype = retnodes[1], functype:get_return_type(1)
defemitter:add_indent('return ')
if retnode then
-- return value is present
retnode.attr.maymove = true
create_variable(context, defemitter, rettype, retnode)
defemitter:add_ln(';')
else
-- no return value present, generate a zeroed one
defemitter:add_ctyped_zerotype(rettype)
defemitter:add_ln(';')
end
end
else
-- multiple returns
local funcretctype = context:funcretctype(functype)
local retemitter = CEmitter(context, defemitter.depth)
local multiretvalname
retemitter:add('return (', funcretctype, '){')
local ignoredestroyindexes = {}
local usedlastcalletype
for i,funcrettype,retnode,rettype,lastcallindex,lastcalletype in izipargnodes(functype.rettypes, retnodes) do
if i>1 then retemitter:add(', ') end
if lastcallindex == 1 then
usedlastcalletype = lastcalletype
assert(usedlastcalletype)
-- last assignment value may be a multiple return call
defemitter:add_indent_ln('{')
defemitter:inc_indent()
multiretvalname = context:genuniquename('ret')
local retctype = context:funcretctype(retnode.attr.calleetype)
defemitter:add_indent_ln(retctype, ' ', multiretvalname, ' = ', retnode, ';')
end
if lastcallindex then
local retvalname = string.format('%s.r%d', multiretvalname, lastcallindex)
create_variable(context, retemitter, funcrettype, retvalname, rettype)
ignoredestroyindexes[lastcallindex] = true
else
retnode.attr.maymove = true
create_variable(context, retemitter, funcrettype, retnode)
end
end
retemitter:add_ln('};')
if usedlastcalletype then
destroy_callee_returns(context, defemitter, multiretvalname, usedlastcalletype, ignoredestroyindexes)
end
defemitter:add_indent(retemitter:generate())
if multiretvalname then
defemitter:dec_indent()
defemitter:add_indent_ln('}')
end
end
end
destroy_upscopes_variables(context, desemitter, 'function')
emitter:add(desemitter:generate())
emitter:add(defemitter:generate())
end
function visitors.If(_, node, emitter)
local ifparts, elseblock = node:args()
for i,ifpart in ipairs(ifparts) do
local condnode, blocknode = ifpart[1], ifpart[2]
if i == 1 then
emitter:add_indent("if(")
emitter:add_val2type(primtypes.boolean, condnode)
emitter:add_ln(") {")
else
emitter:add_indent("} else if(")
emitter:add_val2type(primtypes.boolean, condnode)
emitter:add_ln(") {")
end
emitter:add(blocknode)
end
if elseblock then
emitter:add_indent_ln("} else {")
emitter:add(elseblock)
end
emitter:add_indent_ln("}")
end
function visitors.Switch(context, node, emitter)
local valnode, caseparts, elsenode = node:args()
emitter:add_indent_ln("switch(", valnode, ") {")
emitter:inc_indent()
context:push_forked_scope(node)
for _,casepart in ipairs(caseparts) do
local caseexprs, caseblock = casepart[1], casepart[2]
for i=1,#caseexprs-1 do
emitter:add_indent_ln("case ", caseexprs[i], ":")
end
emitter:add_indent_ln("case ", caseexprs[#caseexprs], ': {') -- last case
emitter:add(caseblock) -- block
emitter:inc_indent() emitter:add_indent_ln('break;') emitter:dec_indent()
emitter:add_indent_ln("}")
end
if elsenode then
emitter:add_indent_ln('default: {')
emitter:add(elsenode)
emitter:inc_indent() emitter:add_indent_ln('break;') emitter:dec_indent()
emitter:add_indent_ln("}")
end
context:pop_scope(node)
emitter:dec_indent()
emitter:add_indent_ln("}")
end
function visitors.Do(context, node, emitter)
local blocknode = node:args()
local doemitter = CEmitter(context, emitter.depth)
doemitter:add(blocknode)
if doemitter:is_empty() then return end
emitter:add_indent_ln("{")
emitter:add(doemitter:generate())
emitter:add_indent_ln("}")
end
function visitors.DoExpr(context, node, emitter)
local blocknode = node[1]
if blocknode[1][1].tag == 'Return' then -- single statement
emitter:add(blocknode[1][1][1][1])
else
emitter:add_ln("({")
emitter:inc_indent()
emitter:add_indent_ln(node.attr.type, ' __expr;')
emitter:dec_indent()
context:push_forked_scope(node)
emitter:add(blocknode)
context:pop_scope()
emitter:inc_indent()
emitter:add_indent_ln('__expr;')
emitter:dec_indent()
emitter:add_indent("})")
end
end
function visitors.Defer(context, node)
local blocknode = node:args()
local deferblocks = context.scope.deferblocks
if not deferblocks then
deferblocks = {}
context.scope.deferblocks = deferblocks
end
table.insert(deferblocks, blocknode)
end
function visitors.While(context, node, emitter)
local condnode, blocknode = node:args()
emitter:add_indent("while(")
emitter:add_val2type(primtypes.boolean, condnode)
emitter:add_ln(') {')
local scope = context:push_forked_scope(node)
emitter:add(blocknode)
context:pop_scope()
emitter:add_indent_ln("}")
if scope.breaklabel then
emitter:add_ln(scope.breaklabel, ':;')
end
end
function visitors.Repeat(context, node, emitter)
local blocknode, condnode = node:args()
emitter:add_indent_ln("while(true) {")
local scope = context:push_forked_scope(node)
emitter:add(blocknode)
emitter:inc_indent()
emitter:add_indent('if(')
emitter:add_val2type(primtypes.boolean, condnode)
emitter:add_ln(') {')
emitter:inc_indent()
emitter:add_indent_ln('break;')
emitter:dec_indent()
emitter:add_indent_ln('}')
context:pop_scope()
emitter:dec_indent()
emitter:add_indent_ln('}')
if scope.breaklabel then
emitter:add_ln(scope.breaklabel, ':;')
end
end
function visitors.ForNum(context, node, emitter)
local itvarnode, begvalnode, compop, endvalnode, stepvalnode, blocknode = node:args()
compop = node.attr.compop
local fixedstep = node.attr.fixedstep
local fixedend = node.attr.fixedend
local itvarattr = itvarnode.attr
local itmutate = itvarattr.mutate
local scope = context:push_forked_scope(node)
do
local ccompop = cdefs.compare_ops[compop]
local ittype = itvarattr.type
local itname = context:declname(itvarattr)
local itforname = itmutate and '__it' or itname
emitter:add_indent('for(', ittype, ' ', itforname, ' = ')
emitter:add_val2type(ittype, begvalnode)
local cmpval
if not fixedend or not compop then
emitter:add(', __end = ')
emitter:add_val2type(ittype, endvalnode)
cmpval = '__end'
else
cmpval = endvalnode
end
local stepval
if not fixedstep then
emitter:add(', __step = ')
emitter:add_val2type(ittype, stepvalnode)
stepval = '__step'
else
stepval = fixedstep
end
emitter:add('; ')
if compop then
emitter:add(itforname, ' ', ccompop, ' ')
if traits.is_string(cmpval) then
emitter:add(cmpval)
else
emitter:add_val2type(ittype, cmpval)
end
else
-- step is an expression, must detect the compare operation at runtime
assert(not fixedstep)
emitter:add('__step >= 0 ? ', itforname, ' <= __end : ', itforname, ' >= __end')
end
emitter:add_ln('; ', itforname, ' = ', itforname, ' + ', stepval, ') {')
emitter:inc_indent()
if itmutate then
emitter:add_indent_ln(itvarnode, ' = __it;')
end
emitter:dec_indent()
emitter:add(blocknode)
emitter:add_indent_ln('}')
end
context:pop_scope()
if scope.breaklabel then
emitter:add_ln(scope.breaklabel, ':;')
end
end
function visitors.ForIn() --luacov:disable
-- this should never happen
error('impossible')
end --luacov:enable
function visitors.Break(context, _, emitter)
destroy_upscopes_variables(context, emitter, 'is_loop')
context.scope.alreadydestroyed = true
local breakscope = context.scope:get_up_scope_of_any_kind('is_loop', 'is_switch')
if breakscope.is_switch then
breakscope = context.scope:get_up_scope_of_any_kind('is_loop')
local breaklabel = breakscope.breaklabel
if not breaklabel then
breaklabel = context:genuniquename('loop_break_label')
breakscope.breaklabel = breaklabel
end
emitter:add_indent_ln('goto ', breaklabel, ';')
else
emitter:add_indent_ln('break;')
end
end
function visitors.Continue(context, _, emitter)
destroy_upscopes_variables(context, emitter, 'is_loop')
context.scope.alreadydestroyed = true
emitter:add_indent_ln('continue;')
end
function visitors.Label(context, node, emitter)
emitter:add_ln(context:declname(node.attr), ':;')
end
function visitors.Goto(context, node, emitter)
emitter:add_indent_ln('goto ', context:declname(node.attr.label), ';')
end
function visitors.VarDecl(context, node, emitter)
local varscope, varnodes, valnodes = node:args()
visit_assignments(context, emitter, varnodes, valnodes, true)
end
function visitors.Assign(context, node, emitter)
local vars, vals = node:args()
visit_assignments(context, emitter, vars, vals)
end
local function resolve_function_qualifier(context, attr)
local qualifier = ''
if not attr.entrypoint and not attr.nostatic and not attr.cexport then
qualifier = 'static '
end
if attr.cinclude then
context:add_include(attr.cinclude)
end
if attr.cimport and attr.codename ~= 'nelua_main' then
qualifier = ''
end
if attr.cexport then
qualifier = qualifier .. context:ensure_runtime_builtin('nelua_cexport') .. ' '
end
if attr.volatile then
qualifier = qualifier .. 'volatile '
end
if attr.inline then
qualifier = qualifier .. 'inline '
end
if attr.noinline then
qualifier = qualifier .. context:ensure_runtime_builtin('nelua_noinline') .. ' '
end
if attr.noreturn then
qualifier = qualifier .. context:ensure_runtime_builtin('nelua_noreturn') .. ' '
end
if attr.cqualifier then qualifier = qualifier .. attr.cqualifier .. ' ' end
if attr.cattribute then
qualifier = string.format('%s__attribute__((%s)) ', qualifier, attr.cattribute)
end
return qualifier
end
function visitors.FuncDef(context, node, emitter)
local attr = node.attr
local type = attr.type
if type.is_polyfunction then
for _,polyeval in ipairs(type.evals) do
emitter:add(polyeval.node)
end
return
end
local varscope, varnode, argnodes, retnodes, annotnodes, blocknode = node:args()
local qualifier = resolve_function_qualifier(context, attr)
local hookmain = attr.cimport and attr.codename == 'nelua_main'
if hookmain then
context.maindeclared = true
end
local declare = not attr.nodecl or hookmain
local define = not attr.cimport
if not declare and not define then -- nothing to do
return
end
local decemitter, defemitter, implemitter = CEmitter(context), CEmitter(context), CEmitter(context)
local retctype = context:funcretctype(type)
decemitter:add_indent(qualifier, retctype, ' ')
defemitter:add_indent(retctype, ' ')
decemitter:add(varnode)
defemitter:add(varnode)
local funcscope = context:push_forked_scope(node)
funcscope.functype = type
do
decemitter:add('(')
defemitter:add('(')
if varnode.tag == 'ColonIndex' then
decemitter:add(node.attr.metafuncselftype, ' self')
defemitter:add(node.attr.metafuncselftype, ' self')
if #argnodes > 0 then
decemitter:add(', ')
defemitter:add(', ')
end
end
decemitter:add_ln(argnodes, ');')
defemitter:add_ln(argnodes, ') {')
implemitter:add(blocknode)
if not blocknode.attr.returnending then
implemitter:inc_indent()
destroy_scope_variables(context, implemitter, funcscope)
implemitter:dec_indent()
end
end
context:pop_scope()
implemitter:add_indent_ln('}')
if declare then
context:add_declaration(decemitter:generate())
end
if define then
context:add_definition(defemitter:generate())
if attr.entrypoint and not context.hookmain then
context:add_definition(function() return context.mainemitter:generate() end)
end
context:add_definition(implemitter:generate())
end
end
function visitors.Function(context, node, emitter)
local argnodes, retnodes, annotnodes, blocknode = node:args()
local attr = node.attr
local type = attr.type
local qualifier = resolve_function_qualifier(context, attr)
local decemitter, defemitter, implemitter = CEmitter(context), CEmitter(context), CEmitter(context)
local retctype = context:funcretctype(type)
decemitter:add_indent(qualifier, retctype, ' ')
defemitter:add_indent(retctype, ' ')
local declname = context:declname(attr)
decemitter:add(declname)
defemitter:add(declname)
local funcscope = context:push_forked_scope(node)
funcscope.functype = type
do
decemitter:add('(')
defemitter:add('(')
decemitter:add_ln(argnodes, ');')
defemitter:add_ln(argnodes, ') {')
implemitter:add(blocknode)
if not blocknode.attr.returnending then
implemitter:inc_indent()
destroy_scope_variables(context, implemitter, funcscope)
implemitter:dec_indent()
end
end
context:pop_scope()
implemitter:add_indent_ln('}')
context:add_declaration(decemitter:generate())
context:add_definition(defemitter:generate())
context:add_definition(implemitter:generate())
emitter:add(declname)
end
function visitors.UnaryOp(_, node, emitter)
local attr = node.attr
if attr.comptime then
emitter:add_literal(attr)
return
end
local opname, argnode = node:args()
local op = cdefs.unary_ops[opname]
assert(op)
local surround = not node.attr.inconditional
if surround then emitter:add('(') end
if traits.is_string(op) then
emitter:add(op, argnode)
else
local builtin = cbuiltins.operators[opname]
builtin(node, emitter, argnode)
end
if surround then emitter:add(')') end
end
function visitors.BinaryOp(context, node, emitter)
if node.attr.comptime then
emitter:add_literal(node.attr)
return
end
local opname, lnode, rnode = node:args()
local type = node.attr.type
local op = cdefs.binary_ops[opname]
assert(op)
local surround = not node.attr.inconditional
if surround then emitter:add('(') end
if node.attr.dynamic_conditional then
emitter:add_ln('({')
emitter:inc_indent()
if node.attr.ternaryor then
-- lua style "ternary" operator
emitter:add_indent_ln(type, ' t_;')
emitter:add_indent('bool cond_ = ')
emitter:add_val2type(primtypes.boolean, lnode[2])
emitter:add_ln(';')
emitter:add_indent_ln('if(cond_) {')
emitter:add_indent(' t_ = ')
create_variable(context, emitter, type, lnode[3])
emitter:add_ln(';')
emitter:add_indent(' cond_ = ')
emitter:add_val2type(primtypes.boolean, 't_', type)
emitter:add_ln(';')
emitter:add_indent_ln('}')
emitter:add_indent_ln('if(!cond_) {')
emitter:add_indent(' t_ = ')
create_variable(context, emitter, type, rnode)
emitter:add_ln(';')
emitter:add_indent_ln('}')
emitter:add_indent_ln('t_;')
else
emitter:add_indent(type, ' t1_ = ')
create_variable(context, emitter, type, lnode)
--TODO: be smart and remove this unused code
emitter:add_ln(';')
emitter:add_indent_ln(type, ' t2_ = {0};')
if opname == 'and' then
assert(not node.attr.ternaryand)
emitter:add_indent('bool cond_ = ')
emitter:add_val2type(primtypes.boolean, 't1_', type)
emitter:add_ln(';')
emitter:add_indent_ln('if(cond_) {')
emitter:inc_indent()
emitter:add_indent('t2_ = ')
create_variable(context, emitter, type, rnode)
emitter:add_ln(';')
emitter:add_indent('cond_ = ')
emitter:add_val2type(primtypes.boolean, 't2_', type)
emitter:add_ln(';')
emitter:dec_indent()
emitter:add_indent_ln('}')
destroy_variable(context, emitter, type, 't1_')
emitter:add_indent_ln('cond_ ? t2_ : (', type, '){0};')
elseif opname == 'or' then
emitter:add_indent('bool cond_ = ')
emitter:add_val2type(primtypes.boolean, 't1_', type)
emitter:add_ln(';')
emitter:add_indent_ln('if(!cond_) {')
emitter:inc_indent()
emitter:add_indent('t2_ = ')
create_variable(context, emitter, type, rnode)
emitter:add_ln(';')
destroy_variable(context, emitter, type, 't1_')
emitter:dec_indent()
emitter:add_indent_ln('}')
emitter:add_indent_ln('cond_ ? t1_ : t2_;')
end
end
emitter:dec_indent()
emitter:add_indent('})')
else
local sequential = lnode.attr.sideeffect and rnode.attr.sideeffect
local lname = lnode
local rname = rnode
if sequential then
-- need to evaluate args in sequence when one expression has side effects
emitter:add_ln('({')
emitter:inc_indent()
emitter:add_indent_ln(lnode.attr.type, ' t1_ = ', lnode, ';')
emitter:add_indent_ln(rnode.attr.type, ' t2_ = ', rnode, ';')
emitter:add_indent()
lname = 't1_'
rname = 't2_'
end
if traits.is_string(op) then
emitter:add(lname, ' ', op, ' ', rname)
else
local builtin = cbuiltins.operators[opname]
builtin(node, emitter, lnode, rnode, lname, rname)
end
if sequential then
emitter:add_ln(';')
emitter:dec_indent()
emitter:add_indent('})')
end
end
if surround then emitter:add(')') end
end
local generator = {}
local function emit_features_setup(context)
local emitter = CEmitter(context)
do -- warnings
emitter:add_ln('#ifdef __GNUC__')
-- throw error on implict declarations
emitter:add_ln('#pragma GCC diagnostic error "-Wimplicit-function-declaration"')
emitter:add_ln('#pragma GCC diagnostic error "-Wimplicit-int"')
-- importing C functions can cause this warn
emitter:add_ln('#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"')
-- C zero initialization for anything
emitter:add_ln('#pragma GCC diagnostic ignored "-Wmissing-braces"')
emitter:add_ln('#pragma GCC diagnostic ignored "-Wmissing-field-initializers"')
-- usage of no_sanitize_memory/no_sanitize_address cause this warning
emitter:add_ln('#pragma GCC diagnostic ignored "-Wattributes"')
-- the code generator may generate unused variables, parameters, functions
emitter:add_ln('#pragma GCC diagnostic ignored "-Wunused-parameter"')
emitter:add_ln('#if defined(__clang__)')
emitter:add_ln('#pragma GCC diagnostic ignored "-Wunused"')
emitter:add_ln('#else')
emitter:add_ln('#pragma GCC diagnostic ignored "-Wunused-variable"')
emitter:add_ln('#pragma GCC diagnostic ignored "-Wunused-function"')
emitter:add_ln('#pragma GCC diagnostic ignored "-Wunused-but-set-variable"')
emitter:add_ln('#pragma GCC diagnostic ignored "-Wunused-label"')
-- for ignoring const* on pointers
emitter:add_ln('#pragma GCC diagnostic ignored "-Wdiscarded-qualifiers"')
emitter:add_ln('#endif')
-- the code generator may generate always true/false expressions for integers
emitter:add_ln('#pragma GCC diagnostic ignored "-Wtype-limits"')
emitter:add_ln('#endif')
end
do -- static assert macro
emitter:add([[#if __STDC_VERSION__ >= 201112L
#define nelua_static_assert _Static_assert
#else
#define nelua_static_assert(x, y)
#endif
]])
emitter:add_ln('nelua_static_assert(sizeof(void*) == ', primtypes.pointer.size,
', "Nelua and C disagree on architecture size");')
end
context:add_declaration(emitter:generate())
end
local function emit_main(ast, context)
emit_features_setup(context)
context:add_include('<stddef.h>')
context:add_include('<stdint.h>')
context:add_include('<stdbool.h>')
local mainemitter = CEmitter(context, -1)
context.mainemitter = mainemitter
if not context.entrypoint or context.hookmain then
mainemitter:inc_indent()
mainemitter:add_ln("int nelua_main(int nelua_argc, char** nelua_argv) {")
mainemitter:add_traversal(ast)
if not context.rootscope.has_return then
-- main() must always return an integer
mainemitter:inc_indent()
mainemitter:add_indent_ln("return 0;")
mainemitter:dec_indent()
end
mainemitter:add_ln("}")
mainemitter:dec_indent()
if not context.maindeclared then
context:add_declaration('static int nelua_main(int nelua_argc, char** nelua_argv);\n')
end
else
mainemitter:inc_indent()
mainemitter:add_traversal(ast)
mainemitter:dec_indent()
end
if not context.entrypoint then
mainemitter:add_indent_ln('int main(int argc, char **argv) {')
mainemitter:inc_indent(2)
mainemitter:add_indent_ln('return nelua_main(argc, argv);')
mainemitter:dec_indent(2)
mainemitter:add_indent_ln('}')
end
if not context.entrypoint or context.hookmain then
context:add_definition(mainemitter:generate())
end
end
function generator.generate(ast, context)
CContext.promote_context(context, visitors, typevisitors)
emit_main(ast, context)
context:evaluate_templates()
local code = table.concat({
'/* ------------------------------ DECLARATIONS ------------------------------ */\n',
table.concat(context.declarations),
'/* ------------------------------ DEFINITIONS ------------------------------- */\n',
table.concat(context.definitions)
})
return code, context.compileopts
end
generator.compiler = require('nelua.ccompiler')
return generator
|
--[[
*******************************************************
* LASP - LUA AREA SCRIPTING PROJECT *
* License *
*******************************************************
This software is provided as free and open source by the
staff of The Lua Area Scripting Project, in accordance with
the AGPL license. This means we provide the software we have
created freely and it has been thoroughly tested to work for
the developers, but NO GUARANTEE is made it will work for you
as well. Please give credit where credit is due, if modifying,
redistributing and/or using this software. Thank you.
-- ]]
-- // Eversong Woods by Yerney // --
-- Amani Axe Thrower --
function AmaniAxe_OnCombat(pUnit, Event)
pUnit:RegisterEvent("AmaniAxe_Throw", 3000, 0)
end
function AmaniAxe_Throw(pUnit, Event)
pUnit:FullCastSpellOnTarget(10277, pUnit:GetClosestPlayer())
end
function AmaniAxe_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function AmaniAxe_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15641, 1, "AmaniAxe_OnCombat")
RegisterUnitEvent(15641, 2, "AmaniAxe_LeaveCombat")
RegisterUnitEvent(15641, 4, "AmaniAxe_Dead")
-- Amani Berserker --
function AmaniBerserker_OnCombat(pUnit, Event)
pUnit:RegisterEvent("AmaniBerserker_Enrage", 7000, 1)
end
function AmaniBerserker_Enrage(pUnit, Event)
pUnit:FullCastSpell(8599)
end
function AmaniBerserker_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function AmaniBerserker_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15643, 1, "AmaniBerserker_OnCombat")
RegisterUnitEvent(15643, 2, "AmaniBerserker_LeaveCombat")
RegisterUnitEvent(15643, 4, "AmaniBerserker_Dead")
-- Amani ShadowPriest --
function AmaniPriest_OnCombat(pUnit, Event)
pUnit:RegisterEvent("AmaniPriest_Pain", 6000, 1)
end
function AmaniPriest_Pain(pUnit, Event)
pUnit:FullCastSpellOnTarget(11639, pUnit:GetClosestPlayer())
end
function AmaniPriest_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function AmaniPriest_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15642, 1, "AmaniPriest_OnCombat")
RegisterUnitEvent(15642, 2, "AmaniPriest_LeaveCombat")
RegisterUnitEvent(15642, 4, "AmaniPriest_Dead")
-- AngerShade --
function AngerShade_OnCombat(pUnit, Event)
pUnit:RegisterEvent("AngerShade_Enrage", 7000, 1)
end
function AngerShade_Enrage(pUnit, Event)
pUnit:FullCastSpell(8599)
end
function AngerShade_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function AngerShade_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15656, 1, "AngerShade_OnCombat")
RegisterUnitEvent(15656, 2, "AngerShade_LeaveCombat")
RegisterUnitEvent(15656, 4, "AngerShade_Dead")
-- Arcane Wraith --
function ArcaneWraith_OnCombat(pUnit, Event)
pUnit:RegisterEvent("ArcaneWraith_ArcaneBolt", 4000, 0)
end
function ArcaneWraith_ArcaneBolt(pUnit, Event)
pUnit:FullCastSpellOnTarget(37361, pUnit:GetClosestPlayer())
end
function ArcaneWraith_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function ArcaneWraith_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15273, 1, "ArcaneWraith_OnCombat")
RegisterUnitEvent(15273, 2, "ArcaneWraith_LeaveCombat")
RegisterUnitEvent(15273, 4, "ArcaneWraith_Dead")
-- DarkWraith --
function DarkWraith_OnCombat(pUnit, Event)
pUnit:RegisterEvent("DarkWraith_Enrage", 7000, 1)
end
function DarkWraith_Enrage(pUnit, Event)
pUnit:FullCastSpell(8599)
end
function DarkWraith_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function DarkWraith_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15657, 1, "DarkWraith_OnCombat")
RegisterUnitEvent(15657, 2, "DarkWraith_LeaveCombat")
RegisterUnitEvent(15657, 4, "DarkWraith_Dead")
-- Feral Tender --
function FeralTen_OnCombat(pUnit, Event)
pUnit:RegisterEvent("FeralTen_Renew", 9000, 1)
end
function FeralTen_Renew(pUnit, Event)
pUnit:FullCastSpell(31325)
end
function FeralTen_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function FeralTen_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15294, 1, "FeralTen_OnCombat")
RegisterUnitEvent(15294, 2, "FeralTen_LeaveCombat")
RegisterUnitEvent(15294, 4, "FeralTen_Dead")
-- ManaSerpent --
function ManaSerpent_OnCombat(pUnit, Event)
pUnit:RegisterEvent("ManaSerpent_FairieFire", 4000, 1)
end
function ManaSerpent_FairieFire(pUnit, Event)
pUnit:FullCastSpellOnTarget(25602, pUnit:GetClosestPlayer())
end
function ManaSerpent_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function ManaSerpent_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15966, 1, "ManaSerpent_OnCombat")
RegisterUnitEvent(15966, 2, "ManaSerpent_LeaveCombat")
RegisterUnitEvent(15966, 4, "ManaSerpent_Dead")
-- Mana Stalker--
function ManaStalker_OnCombat(pUnit, Event)
pUnit:RegisterEvent("ManaStalker_MoonFire", 4000, 1)
end
function ManaStalker_MoonFire(pUnit, Event)
pUnit:FullCastSpellOnTarget(25602, pUnit:GetClosestPlayer())
end
function ManaStalker_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function ManaStalker_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15647, 1, "ManaStalker_OnCombat")
RegisterUnitEvent(15647, 2, "ManaStalker_LeaveCombat")
RegisterUnitEvent(15647, 4, "ManaStalker_Dead")
-- ManaWraith --
function ManaWraith_OnCombat(pUnit, Event)
pUnit:RegisterEvent("ManaWraith_FairieFire", 4000, 1)
end
function ManaWraith_FairieFire(pUnit, Event)
pUnit:FullCastSpellOnTarget(25602, pUnit:GetClosestPlayer())
end
function ManaWraith_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function ManaWraith_Dead(pUnit, Event)
pUnit:CastSpell(29109)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15648, 1, "ManaWraith_OnCombat")
RegisterUnitEvent(15648, 2, "ManaWraith_LeaveCombat")
RegisterUnitEvent(15648, 4, "ManaWraith_Dead")
-- PlagueBonePillager --
function PlagueBonePillager_OnCombat(pUnit, Event)
pUnit:RegisterEvent("PlagueBonePillager_Strike", 5000, 0)
end
function PlagueBonePillager_Strike(pUnit, Event)
pUnit:FullCastSpellOnTarget(11976, pUnit:GetClosestPlayer())
end
function PlagueBonePillager_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function PlagueBonePillager_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15654, 1, "PlagueBonePillager_OnCombat")
RegisterUnitEvent(15654, 2, "PlagueBonePillager_LeaveCombat")
RegisterUnitEvent(15654, 4, "PlagueBonePillager_Dead")
-- RotlimbMarauder --
function RotlimbMarauder_OnCombat(pUnit, Event)
pUnit:RegisterEvent("RotlimbMarauder_DiseaseTouch", 5000, 1)
end
function RotlimbMarauder_DiseaseTouch(pUnit, Event)
pUnit:FullCastSpellOnTarget(3234, pUnit:GetClosestPlayer())
end
function RotlimbMarauder_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function RotlimbMarauder_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15658, 1, "RotlimbMarauder_OnCombat")
RegisterUnitEvent(15658, 2, "RotlimbMarauder_LeaveCombat")
RegisterUnitEvent(15658, 4, "RotlimbMarauder_Dead")
-- WitheredGreenKeeper --
function WitheredGreenKeeper_OnCombat(pUnit, Event)
pUnit:RegisterEvent("WitheredGreenKeeper_Strike", 5000, 0)
end
function WitheredGreenKeeper_Strike(pUnit, Event)
pUnit:FullCastSpellOnTarget(13584, pUnit:GetClosestPlayer())
end
function WitheredGreenKeeper_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function WitheredGreenKeeper_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15637, 1, "WitheredGreenKeeper_OnCombat")
RegisterUnitEvent(15637, 2, "WitheredGreenKeeper_LeaveCombat")
RegisterUnitEvent(15637, 4, "WitheredGreenKeeper_Dead")
-- WrecthedHooligan --
function WrecthedHooligan_OnCombat(pUnit, Event)
pUnit:RegisterEvent("WrecthedHooligan_Strike", 5000, 0)
pUnit:RegisterEvent("WrecthedHooligan_Bitter", 12000, 1)
end
function WrecthedHooligan_Strike(pUnit, Event)
pUnit:FullCastSpellOnTarget(14873, pUnit:GetClosestPlayer())
end
function WrecthedHooligan_Bitter(pUnit, Event)
pUnit:FullCastSpellOnTarget(29098, pUnit:GetClosestPlayer())
end
function WrecthedHooligan_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function WrecthedHooligan_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(16162, 1, "WrecthedHooligan_OnCombat")
RegisterUnitEvent(16162, 2, "WrecthedHooligan_LeaveCombat")
RegisterUnitEvent(16162, 4, "WrecthedHooligan_Dead")
-- WrecthedThug --
function WrecthedThug_OnCombat(pUnit, Event)
pUnit:RegisterEvent("WrecthedHooligan_Strike", 5000, 0)
pUnit:RegisterEvent("WrecthedThug_Bitter", 12000, 1)
end
function WrecthedThug_Bitter(pUnit, Event)
pUnit:FullCastSpellOnTarget(29098, pUnit:GetClosestPlayer())
end
function WrecthedThug_LeaveCombat(pUnit, Event)
pUnit:RemoveEvents()
end
function WrecthedThug_Dead(pUnit, Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(15645, 1, "WrecthedThug_OnCombat")
RegisterUnitEvent(15645, 2, "WrecthedThug_LeaveCombat")
RegisterUnitEvent(15645, 4, "WrecthedThug_Dead")
|
--[[ Copyright (c) 2010 Manuel "Roujin" Wolf
Copyright (c) 2012 Henrique Poyatos
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.
Language(utf8 "Português do Brasil", "Brazilian Portuguese", "pt_br", "br")
--]]
Language("Português do Brasil", "Brazilian Portuguese", "pt_br", "br")
Inherit("English")
Encoding(utf8)
--[[
1. Menus e Janelas de Sistema
2. Menu Superior
--]]
-- 1. Menus e Janelas de Sistema
main_menu = {
new_game = "Novo Jogo",
custom_level = "Fase Personalizada",
load_game = "Carregar Jogo",
options = "Opções",
savegame_version = "versão de jogo salvo: ",
version = "Versão: ",
exit = "Sair",
}
tooltip.main_menu = {
new_game = "Iniciar na primeira fase do jogo",
custom_level = "Construir seu hospital para uma única fase",
load_game = "Carregar um jogo salvo anteriormente",
options = "Modifique várias configurações",
exit = "Não se vá!",
}
new_game_window = {
easy = "Júnior (Fácil)",
medium = "Pleno (Médio)",
hard = "Sênior (Difícil)",
tutorial = "Tutorial",
cancel = "Cancelar",
}
tooltip.new_game_window = {
easy = "Se você é novo em jogos de simulação esta é a opção para você",
medium = "Este é o meio do campinho se você está inseguro do que deve escolher",
hard = "Se você está acostumado com este tipo de jogo e quer mais desafios, escolha esta opção",
tutorial = "Se você precisa de ajuda para começar a jogar, escolha esta opção",
tutorial = "Tutorial",
cancel = "Ah, eu não queria começar um novo jogo !",
}
custom_game_window = {
caption = "Jogo Customizado",
free_build = "Construção Livre",
}
tooltip.custom_game_window = {
start_game_with_name = "Carregando fase %s",
free_build = "Escolha esta opção se você quer jogar sem dinheiro ou objetivos de jogo",
}
load_game_window = {
caption = "Carregar Jogo",
}
tooltip.load_game_window = {
load_game = "Carregar jogo %s",
load_game_number = "Carregar jogo %d",
load_autosave = "Carregar jogo salvo automaticamente",
}
menu_list_window = {
name = "Nome",
save_date = "Modificado",
back = "Voltar",
}
tooltip.menu_list_window = {
name = "Clique aqui para ordenar por nome",
save_date = "Clique aqui para ordenar por data de última modificação",
back = "Fechar esta janela",
}
options_window = {
fullscreen = "Tela cheia",
width = "Largura",
height = "Altura",
change_resolution = "Mudar resolução de tela",
browse = "Procurar",
new_th_directory = "Aqui você pode indicar outro diretório onde o jogo Theme Hospital está instalado, entretando se mudar o diretório o jogo será reiniciado.",
cancel = "Cancelar",
back = "Voltar",
}
tooltip.options_window = {
fullscreen_button = "Clique para mudar para tela cheia",
width = "Digite a largura desejada",
height = "Digite a altura desejada",
change_resolution = "Mude a resolução da janela para os valores inseridos à esquerda",
language = "Selecionar '%s' como linguagem",
original_path = "Diretório informado como sendo da instalação do Theme Hospital original",
browse = "Procurar outro diretório de instalação do Theme Hospital. %1%",
back = "Fechar a janela de opções",
}
lua_console = {
execute_code = "Executar",
close = "Fechar",
}
tooltip.lua_console = {
textbox = "Digite um código Lua para rodar aqui",
execute_code = "Run the code you have entered",
close = "Fechar o console",
}
save_game_window = {
caption = "Salvar Jogo",
new_save_game = "Novo Jogo Salvo",
}
tooltip.save_game_window = {
save_game = "Sobrescrevendo jogo salvo %s",
new_save_game = "Digite o nome para este jogo salvo",
}
totd_window = {
tips = {
"Todo hospital precisa de um balção de recepção e uma Sala de Clínica Geral para começar. Depois disso, dependará do tipo de pacientes que visitará seu hospital. Ter uma farmácia é sempre uma boa idéia, entretanto.",
"Máquina como o Inflador precisam de constante manutenção. Contrate um ou dois funcionários da Manutenção para reparos nestas máquinas, ou colocará seus funcionários e pacientes em risco.",
"Depois de um certo período de trabalho, seus funcionários ficarão cansados. Certifique-se de construir uma Sala de Relaxamento, para que posam descansar.",
"Instale radiadores o suficiente para manter seus funcionários e pacientes aquecidos, do contrário ficarão infelizes. Use o Mapa da Cidade para localizar pontos do hospital que precisem ser aquecidos.",
"O nível de habilidade de um médico reflexe na qualidade e velocidade dos diagnósticos. Coloque um médico experiente na Sala de Clínica Geral, assim não precisará de muitas salas de diagnósticos adicionais.",
"Médicos de níveis 'Junior' e 'Pleno' podem melhorar suas habilidades aprendendo com um Sênior na Sala de Treinamento. Se o Sênior possuir alguma qualificação especial (Cirurgião, Psiquiatra ou Pesquisador), ele irá passar este conhecido ao(s) seu(s) pupilo(s).",
"Você já tentou digitar o numéro europeu de emergência (112) no aparelho de fax ? Certifique-se que o seu som esteja ligado !",
"Você pode ajustar algumas configurações como a resolução de tela e linguagem na janela de opções que pode ser acessar no menu inicial e dentro do jogo.",
"Você selecionou uma linguagem que não o inglês, mas existem textos em inglês por todos os lugares? Ajude-nos a traduzir os textos restantes para sua língua !",
"A comunidade do Jogo CorsixTH está precisando de reforços em sua equipe ! Você está interessado em codificar, traduzir ou criar gráficos para o CorsixTH? Entre em contato conosco pelo nosso Fórum, Lista de Discussão ou canal de IRC (#corsix-th no freenode).",
"Se localizar um bug, por favor reporte-o em nosso bugtracker: th-issues.corsix.org",
"Cada fase possui certas metas a serem atingidas antes de passar para a próxima fase. Cheque a janela de situação para acompanhar seu progresso a fim de atingir seus objetivos.",
"Se você deseja editar ou remover um sala existente, pode fazê-lo com o botão de edição de sala na barra inferior.",
"Caso haja uma multidão de pacientes esperando, você deve descobrir rapidamente quais deles estão aguardando por uma sala em particular passando o ponteiro do mouse por cima desta sala.",
"Clique nas portas das salas para ver sua fila. Isso pode ser muito útil, já que pode reordenar a fila ou encaminhar um paciente para outra sala.",
"Funcionários infelizes irão pedir aumentos de salários com mais frequência. Certifique-se que sua equipe esteja trabalho em um ambiente de trabalho confortável para mantê-los felizes.",
"Pacientes podem ficar com sede enquanto esperam em seu hospital, ainda mais se ligar o aquecimento! Instale máquinas de venda de refrigerantes em pontos estratégicos para um ganho extra.",
"Você pode abortar o processo de diagnóstico prematuramente e presupor a cura, se você já tiver descoberto a doença. Atente-se que desta maneira aumenta-se o risco de um tratamento errado, resultando na morte do paciente.",
"Emergências podem ser uma boa fonte de grana extra, desde que você possua plena capacidade e recursos de lidar com os pacientes à tempo.",
},
previous = "Dica anterior",
next = "Próxima Dica",
}
tooltip.totd_window = {
previous = "Mostrar a dica anterior",
next = "Mostrar a próxima dica",
}
-- 2. Menu Superior
menu = {
file = " ARQUIVO ",
options = " OPÇÕES ",
display = " DISPLAY",
charts = " GRÁFICOS ",
debug = " DEBUG ",
}
-- Menu File
menu_file = {
load = " CARREGAR JOGO ",
save = " SALVAR JOGO ",
restart = " REINICIAR ",
quit = " SAIR ",
}
-- Menu Options
menu_options = {
sound = " SOM ",
announcements = " ANÚNCIOS ",
music = " MÚSICA ",
sound_vol = " VOLUME DOS SONS ",
announcements_vol = " SOM DOS ANÚNCIOS ",
music_vol = " VOLUME DA MUSICA ",
autosave = " AUTOSALVAR ",
game_speed = " VELOCIDADE DO JOGO ",
jukebox = " JUKEBOX ",
}
-- Menu Display
menu_display = {
high_res = " ALTA RESOLUÇÃO ",
mcga_lo_res = " BAIXA RESOLUÇÃO ",
shadows = " SOMBRAS ",
}
-- Menu Charts
menu_charts = {
statement = " EXTRATO BANCÁRIO ",
casebook = " PRONTUÁRIO DE DOENÇAS ",
policy = " POLÍTICAS DO HOSPITAL ",
research = " PESQUISA ",
graphs = " GRÁFICOS ",
staff_listing = " QUADRO DE FUNCIONÁRIOS ",
bank_manager = " GERENTE DO BANCO ",
status = " STATUS ",
briefing = " OBJETIVO DESTA FASE ",
}
-- Menu Options Volume
menu_options_volume = {
[10] = " 10% ",
[20] = " 20% ",
[30] = " 30% ",
[40] = " 40% ",
[50] = " 50% ",
[60] = " 60% ",
[70] = " 70% ",
[80] = " 80% ",
[90] = " 90% ",
[100] = " 100% ",
}
menu_options = {
lock_windows = " TRAVAR JANELAS ",
edge_scrolling = " EDGE SCROLLING ",
settings = " CONFIGURAÇÕES ",
adviser_disabled = " NOTIFICAÇÕES ",
warmth_colors = " WARMTH COLOURS",
}
menu_options_game_speed = {
pause = " (P) PAUSADO ",
slowest = " (1) MUITO LENTO ",
slower = " (2) LENTO ",
normal = " (3) NORMAL ",
max_speed = " (4) RÁPIDO ",
and_then_some_more = " (5) AINDA MAIS RÁPIDO ",
}
menu_options_warmth_colors = {
choice_1 = " Vermelho ",
choice_2 = " Azul Verde Vermelho ",
choice_3 = " Amarelo Laranja Vermelho ",
}
-- The demo does not contain this string
menu_file.restart = " REINICIAR "
menu_debug = {
jump_to_level = " IR PARA A FASE ",
transparent_walls = " (X) PAREDES TRANSPARENTES ",
limit_camera = " LIMIT CAMERA ",
disable_salary_raise = " DESABILITAR AUMENTOS DE SALÁRIO ",
make_debug_fax = " (F8) MAKE DEBUG FAX ",
make_debug_patient = " (F9) MAKE DEBUG PATIENT ",
cheats = " (F11) CHEATS ",
lua_console = " (F12) CONSOLE LUA ",
calls_dispatcher = " CALLS DISPATCHER ",
dump_strings = " DUMP STRINGS ",
dump_gamelog = " (CTRL+D) DUMP GAME LOG ",
map_overlay = " MAP OVERLAY ",
sprite_viewer = " SPRITE VIEWER ",
}
menu_debug_overlay = {
none = " NENHUM ",
flags = " FLAGS ",
positions = " POSIÇÕES ",
heat = " TEMPERATURA ",
byte_0_1 = " BYTE 0 & 1 ",
byte_floor = " BYTE FLOOR ",
byte_n_wall = " BYTE N WALL ",
byte_w_wall = " BYTE W WALL ",
byte_5 = " BYTE 5 ",
byte_6 = " BYTE 6 ",
byte_7 = " BYTE 7 ",
parcel = " PARCEL ",
}
dynamic_info = {
patient = {
-- emergency = "Чрезвычайная ситуация: %s",
-- guessed_diagnosis = "Диагноз навскидку: %s ",
diagnosis_progress = "Diagnóstico em:",
actions = {
-- sent_to_other_hospital = "Отправлен в другую больницу",
-- prices_too_high = "У вас слишком дорого, - я иду домой",
-- no_gp_available = "Ждет постройки кабинета терапевта",
-- waiting_for_treatment_rooms = "Ждет постройки кабинета для лечения",
-- dying = "Умирает!",
no_diagnoses_available = "Sem diagnóstico - Indo para a casa",
-- epidemic_sent_home = "Отправлен домой инспектором",
cured = "Curado !",
waiting_for_diagnosis_rooms = "Esperando você construir novas salas de diagnóstico",
-- epidemic_contagious = "Заразный",
awaiting_decision = "Esperando por sua decisão",
sent_home = "Alta - Indo para casa",
-- fed_up = "Сыт по горло и уходит",
no_treatment_available = "Sem tratamento - Indo para a casa",
on_my_way_to = "À caminho do %s",
queueing_for = "Na fila de espera do(a) %s",
},
diagnosed = "Diagnóstico: %s ",
},
-- health_inspector = "Инспектор",
-- vip = "Шишка",
object = {
times_used = "Vezes que foi usado(a): %d",
queue_size = "Tamanho da fila: %d",
-- strength = "Прочность: %d",
queue_expected = "Tamanho esperado da fila: %d",
},
staff = {
actions = {
going_to_repair = "Indo reparar %s",
fired = "Demitido",
waiting_for_patient = "Esperando por um paciente",
wandering = "Andando sem rumo",
heading_for = "Indo para %s",
},
tiredness = "Nível de Stress: ",
},
}
-- 3. Staff?
-- Staff titles
-- these are titles used e.g. in the dynamic info bar
staff_title = {
receptionist = "Recepcionista",
general = "General", -- unused?
nurse = "Enfermeira",
junior = "Júnior",
doctor = "Doutor",
surgeon = "Cirurgião",
psychiatrist = "Psiquiatra",
consultant = "Doutor Sênior",
researcher = "Pesquisador",
}
staff_list = {
morale = "MORAL",
tiredness = "CANSAÇO",
skill = "QUALIFICAÇÕES",
total_wages = "SALÁRIO",
}
bank_manager = {
current_loan = "Empréstimo atual",
balance = "Balanço",
interest_payment = "Pagamento de Juros",
hospital_value = "Valor do Hospital",
interest_rate = "Taxa de Juros",
inflation_rate = "Taxa Inflação",
insurance_owed = "Seguro Inadimplência",
statistics_page = {
balance = "Saldo",
details = "Detalhe",
date = "Data",
current_balance = "Saldo Atual",
money_in = "Entrada",
money_out = "Saída",
},
}
transactions = {
severance = "Demissão",
research = "Custos de Pesquisa",
-- eoy_trophy_bonus = "Bonificação VIP", // VIP cash award
buy_object = "Compra",
cure_colon = "Cura:",
wages = "Custos com Folha de Pagamento",
personal_bonus = "Pagamento de Bonificação Pessoal",
drug_cost = "Medicação",
heating = "Custos de Aquecimento",
treat_colon = "Tratamento:",
hire_staff = "Contratação",
bank_loan = "Empréstimo Bancário",
insurance_colon = "Seguro:",
sell_object = "Venda",
-- loan_interest = "Выплата процента по займу",
-- loan_repayment = "Возврат по займу",
buy_land = "Compra de Terreno",
-- machine_replacement = "Замена машины",
build_room = "Construção",
drinks = "Receita: Máq. de Refrigerante",
-- "vip_cash_award"?
}
town_map = {
number = "Número",
not_for_sale = "Não está à venda",
price = "Preço",
for_sale = "À Venda",
owner = "Dono",
area = "Área",
}
high_score = {
categories = {
-- deaths = "Óbitos",
-- total_value = "Общая стоимость",
-- money = "Самый богатый",
-- cures = "Пациентов вылечено",
-- visitors = "Количество посетителей",
-- salary = "",
},
}
research = {
-- allocated_amount = "Распределенное количество",
-- funds_allocation = "Распределение финасирования",
categories = {
improvements = "Melhorias",
drugs = "Novos Medicamentos",
diagnosis = "Equip. para Diagnóstico",
cure = "Equip. para Tratamento",
specialisation = "Especializações",
},
}
policy = {
header = "POLÍTICA DO HOSPITAL",
diag_termination = "Finalização de Diagnóstico",
sliders = {
guess = "Determinar Cura",
send_home = "Mandar p/ casa",
stop = "Parar",
staff_room = "Ir descansar",
},
diag_procedure = "Procedimento de Diagnóstico",
staff_rest = "Descanso dos Funcionários",
staff_leave_rooms = "Funcionário deixar sala",
}
casebook = {
sent_home = "enviados para casa",
deaths = "óbitos",
treatment_charge = "custo do tratamento",
reputation = "reputação",
-- research = "Сосредоточить исследования",
cure = "curas",
cured = "curados",
earned_money = "valor do tratamento",
}
--[[
progress_report = {
quite_unhappy = "Люди вами недовольны",
header = "Отчет об успехах",
very_unhappy = "Люди вас не любят. Уделяйте им больше внимания",
more_drinks_machines = "Пациенты умирают от жажды. Поставьте автоматы с напитками",
too_cold = "У вас слишком холодно, поставьте еще батарей",
too_hot = "Настройте систему отопления, у вас слишком жарко",
percentage_pop = "Доля клиентов",
win_criteria = "Условия для победы",
}
]]
tooltip = {
--[[
staff_list = {
= "Предыдущая страница",
next_person = "Следующая страница",
detail = "Внимание к деталям",
happiness = "Насколько ваши сотрудники довольны своей работой в целом",
tiredness = "Показывает сколько ваши сотрудники еще смогут поработать без отдыха",
ability = "Квалификация ваших сотрудников в среднем по больнице",
happiness_2 = "Моральное состояние",
ability_2 = "Профессиональные навыки",
tiredness_2 = "Запас сил",
researcher_train = "На %d%% готов к получению диплома исследователя",
surgeon_train = "На %d%% готов к получению диплома хирурга",
psychiatrist_train = "На %d%% готов к получению диплома психиатра",
researcher = "Дипломированый исследователь",
psychiatrist = "Дипломированый психиатр",
surgeon = "Дипломированый хирург",
handymen = "Показать список всех рабочих вашей больницы",
nurses = "Показать список всех медсестер вашей больницы",
doctors = "Показать список всех докторов вашей больницы",
receptionists = "Показать список всех регистраторов вашей больницы",
pay_rise = "Поднять оклад на 10%",
bonus = "Выплатить премию в размере 10% от оклада",
salary = "Текущая зарплата",
close = "Назад к игре",
sack = "Вышвырнуть на улицу",
doctor_seniority = "Авторитет доктора",
view_staff = "Наблюдать за работой",
skills = "Дополнительные умения",
total_wages = "Общая зарплата",
},]]
town_map = {
close = "Fechar",
plants = "Exibir plantas",
fire_extinguishers = "Exibir plantas",
people = "Exibir pessoas",
balance = "Saldo",
heat_dec = "Diminuir aquecimento",
heating_bill = "Preço do aquecimento",
radiators = "Exibir radiadores",
objects = "Exibir objetos",
heat_level = "Temperatura do aquecimento",
heat_inc = "Aumentar aquecimento",
},
--[[
policy = {
diag_termination = "Обследование пациента будет продолжаться, пока доктора не будут на столько процентов уверены в диагнозе или пока у них не закончатся средства диагностики",
close = "Закрыть окно политики",
staff_leave = "Нажмите здесь чтобы разрешить сотрудникам покидать кабинеты и идти туда где нужна их помощь",
diag_procedure = "Если доктор уверен в своем диагнозе менее, чем значение «Отправить домой», пациент будет отправлен домой. Если же шансы выше чем «Диагноз наугад», он будет отправлен на лечение. В остальных случаях потребуется ваше решение",
staff_rest = "Насколько усталым должен быть сотрудник, чтобы получить право на отдых",
staff_stay = "Нажмите здесь чтобы сотрудники оставались в тех кабинетах, где вы их поставили",
},
bank_manager = {
graph = "График ожидаемых выплат от %s",
close = "Закрыть окно",
hospital_value = "Текущая стоимость госпиталя вместе со всем оборудованием",
graph_return = "Вернуться назад",
current_loan = "Размер текущего займа",
borrow_5000 = "Занять у банка 5000$",
balance = "Ваш баланс",
interest_payment = "Ежемесячные выплаты по займу",
inflation_rate = "Размер инфляции за год",
interest_rate = "Годовой процент по займу",
repay_5000 = "Отдать банку 5000$",
show_graph = "Показать график ожидаемых выплат от %s",
insurance_owed = "Сколько денег вам должны %s",
},
casebook = {
sent_home = "Количество пациентов, которым было отказано в лечении",
increase = "Поднять стоимость",
decrease = "Снизить стоимость",
up = "Вверх",
down = "Вниз",
reputation = "Общая репутация этой практики",
research = "Нажмите чтобы сосредоточить бюджет специальных исследований на этой проблеме",
close = "Закрыть",
earned_money = "Всего заработано на этом",
deaths = "Количество летальных исходов",
cured = "Количество вылеченных",
treatment_charge = " Стоимость для пациентов",
cure_type = {
psychiatrist = "Это лечит психиатр",
drug_percentage = "От этого есть лекарство. Ваше эффективно на %d%",
machine = "Для лечения нужно специальное оборудование",
surgery = "Cura требует операции",
},
cure_requirement = {
possible = "Вы можете это вылечить",
build_room = "Вам нужно построить специальный кабинет для лечения",
research_machine = "Для лечения нужно изобрести машину",
hire_staff = "Вам нужно нанять специалиста для лечения",
},
},
status = {
population_chart = "Показывает соотношение числа посетителей в разных больницах",
percentage_cured = "Вам нужно вылечить %d% всех посетителей. На данный момент вам удалось вылечить %d%",
num_cured = "Вам нужно вылечить %d людей. Пока вам удалось исцелить %d",
thirst = "Средний уровень жажды людей в больнице",
close = "Закрыть окно",
win_progress_own = "Показать успехи вашей больницы",
reputation = "Ваша репутация должна достигать %d. Сейчас она составляет %d",
population = "Добейтесь чтобы к вам приходили лечиться %d%% всех пациентов",
warmth = "Средняя температура по больнице",
percentage_killed = "Постарайтесь не убивать более чем %d%% посетителей. На данный момент вы угробили %d%%",
balance = "На вашем счету должно быть не менее %d$. Сейчас у вас %d$",
value = "Ваша больница должна стоить %d$. Сейчас она стоит %d$",
win_progress_other = "Показать как идут дела у %s",
happiness = "Общее состояние пациентов в вашей больнице",
},
--]]
buy_objects_window = {
price = "Preço",
cancel = "Cancelar",
confirm = "Comprar itens",
total_value = "Total",
decrease = "Comprar menos",
increase = "Comprar mais",
},
hire_staff_window = {
doctors = "Ver Doutores disponíveis para contratação",
nurses = "Ver Enfermeiras disponíveis para contratação",
handymen = "Ver Zeladores disponíveis para contratação",
receptionists = "Ver Recepcionistas disponíveis para contratação",
prev_person = "Próxima pessoa",
next_person = "Pessoa anterior",
hire = "Contratar",
cancel = "Cancelar",
doctor_seniority = "Experiência (Júnior, Pleno, Sênior)",
staff_ability = "Habilidade",
salary = "Salário",
qualifications = "Qualificações extras",
surgeon = "Cirurgião",
psychiatrist = "Psiquiatra",
researcher = "Pesquisador",
},
}
-- 5. Doenças
diseases = {
general_practice = {
name = "Prática geral",
},
diag_ward = {
name = "Diag: Enfermaria",
},
diag_ultrascan = {
name = "Diag: Ultrasom",
},
diag_blood_machine = {
name = "Diag: Análise Sanguinea",
},
diag_x_ray = {
name = "Diag: Raio-X",
},
diag_psych = {
name = "Diag: Psiquiatria",
},
diag_general_diag = {
name = "Diag: Diagnóstico Geral",
},
diag_cardiogram = {
name = "Diag: Eletrocardiograma",
},
diag_scanner = {
name = "Diag: Scanner",
},
autopsy = {
name = "Autópsia",
},
third_degree_sideburns = {
-- cause = "Causa - непреодолимая тоска по семидесятым.",
-- cure = "Cura - психиатр должен, используя самые современные методы, убедить пациента, что чрезмерная волосатость уже не в моде.",
name = "Queimaduras de Terceiro Grau",
-- symptoms = "Sintomas - длинные волосы, смешные штаны, обувь на платформе и сверкающий макияж.",
},
discrete_itching = {
-- cause = "Causa - крошечные насекомые с очень острыми зубами.",
-- cure = "Cura - пациент выпивает липкий фармацевтический сироп, который защищает кожу.",
name = "Coceira Discreta",
-- symptoms = "Sintomas - интенсивное чесание вплоть до воспламенения.",
},
the_squits = {
cause = "Causa - Comer um pedaço de pizza encontrada embaixo do fogão.",
cure = "Cura - Uma mistura glutinoso de químicos farmacêuticos pegajosos solidificará as entranhas do paciente.",
name = "Disenteria",
symptoms = "Sintomas - Argh, tenho certeza que você pode imaginar.",
},
spare_ribs = {
-- cause = "Causa - сидение на холодном каменном полу.",
-- cure = "Cura - два хирурга должны удалить лишние ребра и завернуть их пациенту с собой.",
name = "Rim Extra",
-- symptoms = "Sintomas - неприятные ощущения от массивной груди.",
},
king_complex = {
-- cause = "Causa - дух Короля, который захватил контроль над разумом пациента.",
-- cure = "Cura - психиатр рассказывает пациенту как нелепо тот выглядит.",
name = "Complexo de Rei",
-- symptoms = "Sintomas - слабость к цветастой замшевой обуви и чизбургерам.",
},
fake_blood = {
-- cause = "Causa - скорее всего, пациент стал жертвой розыгрыша.",
-- cure = "Cura - психиатр должен помочь пациенту успокоиться.",
name = "Sangue falso",
-- symptoms = "Sintomas - красная жидкость в венах, которая испаряется при контакте с одеждой.",
},
invisibility = {
-- cause = "Causa - укус радиоактивного (и, само собой, невидимого) муравья.",
-- cure = "Cura - напиток насыщенного цвета, приготовленный в аптеке, восстанавливает видимость пациента.",
name = "Invisibilidade",
-- symptoms = "Sintomas - пациент чувствует себя нормально и даже может использовать болезнь чтобы разыгрывать близких.",
},
golf_stones = {
-- cause = "Causa - вдыхание ядовитого газа, содержащегося в мячиках для гольфа.",
-- cure = "Cura - образования удаляются хирургами в операционной.",
name = "Pedras de Golf",
-- symptoms = "Sintomas - бред и чувство стыда.",
},
infectious_laughter = {
-- cause = "Causa - просмотр классических комедий.",
-- cure = "Cura - квалифицированный психиатр должен напомнить пациенту, что не все в этой жизни смешно.",
name = "Risada contagiosa",
-- symptoms = "Sintomas - непроизвольное фырканье и повторение несмешных шуток.",
},
baldness = {
-- cause = "Causa - вранье и придумавание небылиц с целью привлечения внимания.",
-- cure = "Cura - в ходе болезненной процедуры специальная машина плавно восстанавливает волосяной покров.",
name = "Calvíce",
-- symptoms = "Sintomas - блестящесть и смущение.",
},
heaped_piles = {
cause = "Causa - Ficar muito perto de refrigeradores de água.",
cure = "Cura - Um agradável porém poderoso acído dissolverá as hemorróidas por dentro.",
name = "Hemorróidas",
symptoms = "Sintomas - Paciente tem a sensação de estar sentado em um saco de bolinhas de gude.",
},
unexpected_swelling = {
-- cause = "Causa - все внезапное.",
-- cure = "Cura - возбухание может быть уменьшено хирургами при помощи автогена.",
name = "Inchaço inesperado",
-- symptoms = "Симптом - возбухание.",
},
jellyitis = {
-- cause = "Causa - пища, богатая желатином и избыток физической активности.",
-- cure = "Cura - пациента помещают в разжелетиватель в специальном кабинете.",
name = "Gelatinite",
-- symptoms = "Sintomas - пациент чрезмерно трясется и часто падает.",
},
hairyitis = {
-- cause = "Causa - длительные прогулки в свете луны.",
-- cure = "Cura - электролизатор удаляет волосы и запаивает поры.",
name = "Cabelulite",
-- symptoms = "Sintomas - обостренное обоняние.",
},
alien_dna = {
-- cause = "Causa - прыгающие личинки разумных видов пришельцев.",
-- cure = "Cura - в специальной машине ДНК извлекается, очищается от фрагментов пришельцев и быстро вставляется на место.",
name = "DNA alienígena",
-- symptoms = "Sintomas - постепенное превращение в пришельца и стремление уничтожить человечество.",
},
bloaty_head = {
cause = "Causa - Cheirar queijo e beber água de chuva não purificada.",
cure = "Cura - A cabeça inchada é estourada e reinflada no PSI correto usando uma máquina inteligente.",
name = "Cabeça inchada",
symptoms = "Sintomas - Muito desconforto para o sofredor.",
},
gastric_ejections = {
-- cause = "Causa - острая мексиканская и индийская пища.",
-- cure = "Cura - выпивание специального связующего состава предотвращает какие бы то ни было извержения.",
name = "Vômitos",
-- symptoms = "Sintomas - полупереваренная пища извергается из пациента в случайных местах.",
},
uncommon_cold = {
cause = "Causa - pequenas partículas de muco no ar.",
cure = "Cura - Um bom gole de um xarope incomum feito a partir de ingredientes especiais na Farmária poderá curar isso.",
name = "Frio incomum",
symptoms = "Sintomas - Barulho constante, espirros e pulmões descolorados.",
},
corrugated_ankles = {
-- cause = "Causa - езда через асфальтовые гребни на дорогах.",
-- cure = "Cura - слегка токсичная смесь трав и специй позволяет пациенту выпрямить лодыжки.",
name = "Tornozelos tortos",
-- symptoms = "Sintomas - привычная обувь больше не подходит пациенту.",
},
sleeping_illness = {
cause = "Causa - Superatividade da glândula de sono localizada no céu da boca.",
cure = "Cura - Uma alta dosagem de um poderoso estimulante será administrado pela Enfermeira.",
name = "Encefalite letárgica",
symptoms = "Sintomas - Vontade incontrolável de desabar e dormir em qualquer lugar.",
},
sweaty_palms = {
-- cause = "Causa - боязнь собеседований.",
-- cure = "Cura - психиатр должен уговорить пациента избавиться от этой выдуманной болезни.",
name = "Mãos suadas",
-- symptoms = "Sintomas - рукопожатие пациента напоминает сжимание мокрой губки.",
},
serious_radiation = {
-- cause = "Causa - жевание изотопов плутония.",
-- cure = "Cura - пациента нужно как следует промыть под обеззараживающим душем.",
name = "Radiação severa",
-- symptoms = "Sintomas - пациент себя очень, очень плохо чувствует.",
},
gut_rot = {
cause = "Causa - Mistura de Whisky 12 anos Mrs. O'Mallley's com xarope.",
cure = "Cura - A Enfermeira pode administrar uma seleção de químicos dissolventes que podem revestir o estômago.",
name = "Intestino podre",
symptoms = "Sintomas - sem tosse mas sem parede do estômago também.",
},
iron_lungs = {
-- cause = "Causa - городской смог и дым от шашлыков.",
-- cure = "Cura - два хирурга проводят операцию чтобы удалить затвердевшие легкие.",
name = "Pulmões de Aço",
-- symptoms = "Sintomas - способность выдыхать огонь и громко кричать под водой.",
},
broken_wind = {
-- cause = "Causa - упражнения на беговой дорожке после еды.",
-- cure = "Cura - насыщенная особыми водянистыми атомами микстура выпивается залпом.",
name = "Vento quebrado",
-- symptoms = "Sintomas - представляют опасность для находящих позади пациента.",
},
kidney_beans = {
-- cause = "Causa - разгрызание ледяных кубиков в напитках.",
-- cure = "Cura - два хирурга должны удалить бобы, не прикасаясь к почкам.",
name = "Pedras no rim",
-- symptoms = "Sintomas - боль и частые визиты в туалет.",
},
transparency = {
-- cause = "Causa - слизывание йогурта с крышечек упаковок.",
-- cure = "Cura - специально охлажденная и подкрашенная в аптеке вода вылечит эту болезнь.",
name = "Transparência",
-- symptoms = "Sintomas - плоть становится прозрачной и ужасно выглядит.",
},
broken_heart = {
-- cause = "Causa - кто-нибудь более молодой, богатый и стройный чем пациент.",
-- cure = "Cura - два хирурга вскрывают грудную клетку и, затаив дыхание, аккуратно собирают сердце.",
name = "Coração partido",
-- symptoms = "Sintomas - плач и боли в мышцах от разрывания праздничных фотографий.",
},
slack_tongue = {
-- cause = "Causa - хроническое обсуждение мыльных опер.",
-- cure = "Cura - язык помещается в языкорезку и укорачивается быстро, точно, безжалостно.",
name = "Língua negligente",
-- symptoms = "Sintomas - язык примерно в пять раз увеличен в размерах.",
},
tv_personalities = {
cause = "Causa - Assistar à televisão o dia todo.",
cure = "Cura - Um psiquiatra bem treinado deverá convencer o paciente à vender a TV e comprar um rádio.",
name = "Personalidade da TV",
symptoms = "Sintomas - Ilusões sobre ser capaz de apresentar um programa de variedades matinal.",
},
ruptured_nodules = {
-- cause = "Causa - прыжки с тарзанкой в холодную погоду.",
-- cure = "Cura - хирург удаляет грыжу твердой, уверенной рукой.",
name = "Ruptura de Nódulos",
-- symptoms = "Sintomas - невозможность сидеть с комфортом.",
},
fractured_bones = {
-- cause = "Causa - падение с большой высоты на бетонные поверхности.",
-- cure = "Cura - сперва накладывается гипс, затем он удаляется при помощи устройства с лазером.",
name = "Fratura nos ossos",
-- symptoms = "Sintomas - громкий треск и неспособность использовать поврежденные конечности.",
},
chronic_nosehair = {
-- cause = "Causa - высокомерное фыркание в присутствии менее успешных людей.",
-- cure = "Cura - отвратительное противоволосяное зелье приготавливается в аптеке.",
name = "Pêlos no nariz crônicos",
-- symptoms = "Sintomas - нособорода, в которой можно свить гнездо.",
},
}
-- 6. Faxes
--[[
epidemic = {
cover_up_explanation_1 = "Или вы можете попытаться вылечить всех зараженных, пока про это не узнали в министерстве здравоохранения.",
cover_up_explanation_2 = "Если к приезду инспектора эпидемия все еще будет бушевать, приготовьтесь к неприятностям.",
choices = {
cover_up = "Попытаться вылечить всех зараженных пациентов пока есть время и пока он еще в больнице.",
declare = "Объявить об эпидемии. Признать свою вину и заплатить штраф.",
},
disease_name = "Ваши доктора обнаружили особо заразный подвид %s.",
declare_explanation_fine = "Вы можете объявить об эпидемии, заплатить штраф в %d$, тогда вам немедленно окажут помощь в вакцинации. Ваша репутация несколько пострадает.",
},
epidemic_result = {
fine_amount = "Правительство объявило чрезвычайное положение, а вас оштрафовали на %d$.",
close_text = "Ура!",
hospital_evacuated = "У комиссии не осталось другого выбора, кроме как объявить эвакуацию.",
succeeded = {
part_1_name = "До департамента здоровья дошли слухи, что в вашей больнице бушует эпидемия %s.",
part_2 = "Однако, инспектору не удалось найти им подтверждение.",
},
compensation_amount = "Правительство решило компенсировать ущерб, который эти враки нанесли репутации вашей больницы, в сумме %d$.",
failed = {
part_1_name = "В попытке скрыть наличие заразной инфекции %s,",
part_2 = "ваши сотрудники вызвали распространение болезни по округе.",
},
rep_loss_fine_amount = "Журналисты уже заточили карандаши. Ваша репутация серьезно пострадает. К тому же, вас оштрафовали на %d$.",
},
--]]
fax = {
-- VIP
vip_visit_query = {
choices = {
invite = "Enviar um convite oficial ao V.I.P.",
refuse = "Despiste o V.I.P. com desculpas.",
},
vip_name = "%s expressou a vontade de visitar seu hospital",
},
vip_visit_result = {
--telegram = "Телеграмма!",
remarks = {
--good = {
-- [1] = "Какая хорошая больница! Спасибо за приглашение.",
-- [2] = "Хмм... Определенно, неплохое медицинское учреждение.",
-- [3] = "Мне очень понравилась ваша милая больничка. Ну, кто со мной в ресторан?",
--},
super = {
[1] = "É um super hospital! Eu deveria saber, já estive aqui algumas vezes.",
},
--[[
bad = {
[1] = "Не надо было мне приходить. Лучше бы я просидел четырехчасовую оперу!",
[2] = "Мне до сих пор не по себе. Они правда называют свое заведение больницей? Больше похоже на свинарник!",
[3] = "Я сыт по горло визитами в подобные выгребные ямы и постоянным вниманием прессы! Я подаю в отставку.",
},
mediocre = {
[1] = "Что ж, я видал и похуже. Им есть куда расти.",
[2] = "Не знаю, стоит ли туда обращаться, если почувствуете себя неважно.",
[3] = "Что я могу сказать, больница как больница. Я ожидал большего.",
},
very_bad = {
[1] = "Ну и свалка! Я приложу все усилия чтобы ее закрыли.",
[2] = "Никогда не видел больницы хуже. Какой позор!",
[3] = "Я потрясен. Это нельзя назвать больницей! Мне надо выпить.",
},
--]]
-- tem good? Recebi um 'Now that's what I call a hospital'
},
rep_boost = "Sua reputação na comunidade acaba de aumentar.",
vip_remarked_name = "Após visitar seu hospital, %s declarou:",
cash_grant = "Você foi recompensado com uma quantia de $ %d.",
--rep_loss = "Ваша репутация пострадала.",
close_text = "Obrigado por visitar o hospital.",
},
-- Descoberta de Nova Doença
disease_discovered = {
discovered_name = "Sua equipe descobriu uma nova condição : %s",
},
disease_discovered_patient_choice = {
need_to_build = "Você precisa construir um %s para lidar com ela.",
--need_to_employ = "Наймите %s чтобы вылечить это.",
what_to_do_question = "O que deve ser feito com o paciente ?",
--guessed_percentage_name = "Мы не совсем уверены, что с этим пациентом. Существует вероятность в %d% что это %s",
choices = {
send_home = "Mandar o paciente para casa",
research = "Encaminhar o paciente ao Departamento de Pesquisas.",
wait = "Pedir ao paciente esperar um pouco no Hospital.",
},
disease_name = "Sua equipe descobriu uma nova condição: %s",
--need_to_build_and_employ = "Можно будет попробовать, если вы построите %s и наймете %s .",
can_not_cure = "Você não pode curar esta doença.",
},
diagnosis_failed = {
choices = {
send_home = "Enviar o Paciente para casa.",
take_chance = "Dar ao Paciente um possibilidade de cura.",
wait = "Pedir ao Paciente aguardar enquanto você construir mais salas de diagnóstico.",
},
situation = "Nós esgotamos todas as possibilidades de diagnóstico e ainda não temos certeza do que há de errado com o paciente.",
what_to_do_question = "O que deve ser feito com o paciente ?",
partial_diagnosis_percentage_name = "Existe, entretanto, uma possibilidade de %d% de termos identificado que tipo de %s o paciente contraiu.",
},
--[[
emergency = {
locations = {
[1] = "Новоуренгойский химзавод",
[2] = "Фальшивый Университет",
[3] = "Центр Принудительного Озеленения",
[4] = "Институт Разработки Опасных Штук",
[5] = "Клуб Хороших Танцоров",
[6] = "Издательство «МакулатураПресс»",
[7] = "Похоронное бюро «Безенчук и нимфы»",
[8] = "Китайский ресторанчик дяди Вонга",
[9] = "ГлавХимСбытСтыдЗагранПоставка",
},
num_disease = "У нас тут %d человек с диагнозом %s и им требуется немедленное лечение.",
cure_possible_drug_name_efficiency = "У вас есть все необходимое оборудование и специалисты. У вас есть нужное лекарство. Это %s и оно эффективно на %d%",
cure_not_possible_employ = "Вам потребуется нанять %s",
cure_not_possible = "Сейчас вы не можете это вылечить.",
cure_possible = "У вас есть все необходимое оборудование и специалисты, так что вы, наверное, справитесь.",
choices = {
accept = "Да. Я разберусь с этой ситуацией.",
refuse = "Нет. Я отказываюсь в этом участвовать.",
},
location = "На предприятии %s чрезвычайная ситуация.",
cure_not_possible_build = "Вам надо будет построить %s",
cure_not_possible_build_and_employ = "Вам надо будет построить %s и нанять %s",
bonus = "Вознаграждение за помощь составит %d. Если вы не справитесь, ваша репутация серьезно пострадает.",
},
--]]
emergency_result = {
earned_money = "De um bônus total de $ %d, você ganhou $ %d.",
close_text = "Clique para sair.",
saved_people = "Você salvou %d de um total de %d pacientes.",
},
}
------------------------------- OVERRIDE ----------------------------------
adviser.warnings.money_low = "Você está ficando sem dinheiro!" -- Funny. Exists in German translation, but not existent in english?
-- TODO: tooltip.graphs.reputation -- this tooltip talks about hospital value. Actually it should say reputation.
-- TODO: tooltip.status.close -- it's called status window, not overview window.
-- tooltip.staff_list.next_person, prev_person is rather next/prev page (also in german, maybe more languages?)
tooltip.staff_list.next_person = "Próxima página"
tooltip.staff_list.prev_person = "Página anterior"
tooltip.status.reputation = "Sua reputação não deve ficar abaixo de %d. Atualmente é de %d"
tooltip.status.balance = "Seu saldo bancário não deve vicar abaixo de %d. Atualmente é de %d"
-- The originals of these two contain one space too much
fax.emergency.cure_not_possible_build = "Você precisará construir um(a) %s"
fax.emergency.cure_not_possible_build_and_employ = "Você precisará construir um(a) %s e empregar um(a) %s"
fax.emergency.num_disease = "Existem %d pessoas com %s e eles precisam urgente de sua atenção."
adviser.goals.lose.kill = "Se matar mais %d pacientes perderá esta fase!"
-- Improve tooltips in staff window to mention hidden features
tooltip.staff_window.face = "This person's face - click to open management screen"
tooltip.staff_window.center_view = "Clique com o botão esquerdo para dar um zoom no quadro de funcionários e botão direito para circular membros da equipe"
-- These strings are missing in some versions of TH (unpatched?)
confirmation.restart_level = "Tem certeza que deseja reiniciar esta fase?"
-- TODO adviser.multiplayer.objective_completed
-- TODO adviser.multiplayer.objective_failed
------------------------------- NEW STRINGS -------------------------------
date_format = {
daymonth = "%1% %2:months%",
}
object.litter = "Lixo"
tooltip.objects.litter = "Lixo: Um paciente jogou no chão porque não achou uma lixeira próxima."
tooltip.fax.close = "Fechar esta janela sem apagar a mensagem"
tooltip.message.button = "Clique com o botão esquerdo para abrir a mensagem"
tooltip.message.button_dismiss = "Clique com o botão esquerdo para abrir a mensagem, e com o botão direito para descartá-la"
tooltip.casebook.cure_requirement.hire_staff = "Você precisa contratar funcionários para administrar este tratamento"
tooltip.casebook.cure_type.unknown = "Você ainda não sabe como tratar esta doença"
tooltip.research_policy.no_research = "Nenhuma pesquisa desta categoria está sendo conduzida neste momento"
tooltip.research_policy.research_progress = "Progresso para uma nova descoberta nesta categoria: %1%/%2%"
adviser = {
room_forbidden_non_reachable_parts = "Construir a sala neste local resultará em alas do hospital que não poderão ser acessadas.",
warnings = {
no_desk = "Você precisa comprar um balcão de recepção e contratar uma recepcionista em algum momento!",
no_desk_1 = "Se você quer que os pacientes venham ao seu hospital, você precisa contratar uma recepcionista e comprar um balcão para recepcioná-los!",
no_desk_2 = "Excelente, isso provavelmente é um recorde mundial - quase um ano e nenhum paciente! Se você deseja continuar administrando este hospital, você precisa urgente contratar uma recepcionista e comprar um balcão para que ela possa trabalhar!",
no_desk_3 = "That's just brilliant, nearly a year and you don't have a staffed reception! How do you expect to get any patients, now get it sorted out and stop messing around!",
cannot_afford = "Seu saldo bancário é insuficiente para contratar esta pessoa!", -- I can't see anything like this in the original strings
falling_1 = "Hey! Isso não é engraçado, cuidado onde aponta este mouse; alguém pode se machucar!",
falling_2 = "Gostou da queda? Pare de bagunçar!",
falling_3 = "Ai, isso dói, alguém chame um médico!",
falling_4 = "Isto é um Hospital, não um parque de diversões!",
falling_5 = "Este não é o local para empurar as pessoas, elas estão doentes sabia?!",
falling_6 = "Aqui não é uma pista de boliche, pessoas doentes não deveriam ser tratadas desta forma!",
research_screen_open_1 = "Você precisa construir um Departamento de Pesquisas antes de acessar a tela de Pesquisas.",
research_screen_open_2 = "Pesquisas estão desabilitadas nesta fase.",
},
cheats = {
th_cheat = "Parabéns, você habilitou os códigos de trapaça!",
crazy_on_cheat = "Oh não! Todos os médicos ficaram malucos!",
crazy_off_cheat = "Ufa… o médicos recobraram sua sanidade.",
roujin_on_cheat = "Desafio Roujin ativado! Boa sorte...",
roujin_off_cheat = "Desafio Roujin desativado.",
hairyitis_cheat = "Trapaça de Cabelulite ativada!",
hairyitis_off_cheat = "Trapaça de Cabelulite desativada.",
bloaty_cheat = "Bloaty Head cheat activated!",
bloaty_off_cheat = "Bloaty Head cheat deactivated.",
},
}
dynamic_info.patient.actions.no_gp_available = "Waiting for you to build a GP's office"
dynamic_info.staff.actions.heading_for = "Indo para %s"
dynamic_info.staff.actions.fired = "Demitido"
progress_report.free_build = "CONSTRUÇÃO LIVRE"
fax = {
choices = {
return_to_main_menu = "Retornar ao menu principal",
accept_new_level = "Ir para a próxima fase",
decline_new_level = "Continuar jogando nesta fase um pouco mais",
},
emergency = {
num_disease_singular = "Existe uma pessoa com %s que precisa urgente de sua atenção.",
free_build = "Se você for bem sucedido sua reputação aumentará, mas se você falhar sua reputação será bastante prejudicada.",
},
vip_visit_result = {
remarks = {
free_build = {
"Que hospital maravilhoso! Não é tão difícil manter tudo funcionando com dinheiro ilimitado, não é mesmo?",
"Eu não sou economista, mas acho que eu também conseguiria administrar esse hospital, se é que você me entende...",
"Um hospital em ótimo funcionamento. Mas cuidado com a recessão! Ah, me esqueci... você não teve que se preocupar com isso.",
}
}
}
}
letter = {
dear_player = "Prezado(a) %s",
custom_level_completed = "Parabéns! Você completou todos os objetivos desta fase customizada!",
return_to_main_menu = "Deseja retornar ao menu principal ou continuar jogando?",
}
install = {
title = "--------------------------------- CorsixTH Setup ---------------------------------",
th_directory = "CorsixTH precisa de uma cópia dos arquivos de dados do jogo original - Theme Hospital (ou demo) para executar. Utilize o seletor abaixo para localizar o diretório onde o jogo Theme Hospital está instalado.",
exit = "Sair",
}
misc.not_yet_implemented = "(não foi implementado ainda)"
misc.no_heliport = "Ou você ainda não descobriu nenhuma doença ou este hospital não possui heliporto. Você pode também necessitar construir uma recepção e contratar uma recepcionista."
tooltip.handyman_window = {
parcel_select = "O prédio no qual este funcionário executará suas tarefas, clique para mudar"
}
handyman_window = {
all_parcels = "Todos os prédios",
parcel = "Prédio"
}
errors = {
dialog_missing_graphics = "Desculpe, os arquivos de dados da demo não contém este diálogo.",
save_prefix = "Erro ao salvar jogo: ",
load_prefix = "Erro ao carregar jogo: ",
map_file_missing = "Não foi possível encontrar o arquivo de mapa %s para esta fase!",
minimum_screen_size = "Favor digitar dimensões de tela de pelo menos 640x480.",
maximum_screen_size = "Favor digitar dimensões de tela de no máximo 3000x2000.",
unavailable_screen_size = "O tamanho da tela que você digitou não está disponível em tela cheia.",
}
confirmation = {
needs_restart = "Para alterar esta configuração é necessário reiniciar o CorsixTH. Qualquer alteração não salva será perdida. Tem certeza que deseja fazer isso?",
abort_edit_room = "Você está editando uma sala. Se todos os objetos necessário estiverem colocados ela será completada, caso contrário ela será removida. Continuar?",
}
information = {
custom_game = "Bem-vindo ao CorsixTH. Se divirta neste mapa personalizado!",
no_custom_game_in_demo = "Desculpe, mas a versão de demonstração não pode jogar mapas pesonalizados.",
cannot_restart = "Infelizmente este mapa personalizado foi salvo antes que a funcionalidade de reiniciação fosse implementada.",
very_old_save = "Houveram muitas mudanças no jogo desde que você começou a jogar este mapa. Para ter certeza que todas as funcionalidades estão funcionando considere recomeçar o mapa.",
level_lost = {
"Parabéns! Você perdeu a fase. Mais sorte na próxima vez!",
"Você perdeu porque:",
reputation = "Sua reputação caiu abaixo de %d.",
balance = "Seu saldo no banco caiu abaixo de %d.",
percentage_killed = "Você matou mais de %d porcento dos pacientes.",
},
cheat_not_possible = "Você não pode usar esta trapaça nesta fase. Até na hora de trapacear você falha, irônico não?",
}
tooltip.information = {
close = "Fechar a janela de informações",
}
debug_patient_window = {
caption = "Depurar Paciente",
}
cheats_window = {
caption = "Cheats/Trapaças",
warning = "Aviso: você não ganhará nenhum ponto bônus no final desta fase se você trapacear!",
cheated = {
no = "Trapaças usadas: Não",
yes = "Trapaças usadas: Sim",
},
cheats = {
money = "Trapaça Financeira",
all_research = "Trapaça Todas as Pesquisas Realizadas",
emergency = "Criar Emergência",
vip = "Criar visitante VIP",
earthquake = "Criar Terremoto",
create_patient = "Criar Paciente",
end_month = "Final de Mês",
end_year = "Final de Ano",
lose_level = "Perder a Fase",
win_level = "Ganhar a Fase",
},
close = "Fechar",
}
tooltip.cheats_window = {
close = "Fechar a janela de trapaças",
cheats = {
money = "Adicionar 10.000 no saldo bancário.",
all_research = "Completar todas as pesquisas.",
emergency = "Criar uma emergência.",
vip = "Criar um visitante VIP.",
earthquake = "Criar um terremoto.",
create_patient = "Criar um Paciente na borda do mapa.",
end_month = "Pular para o final do mês.",
end_year = "Pular para o final do ano.",
lose_level = "Perder esta fase.",
win_level = "Ganhar esta fase.",
}
}
calls_dispatcher = {
-- Dispatcher description message. Visible in Calls Dispatcher dialog
summary = "%d chamadas; %d assinaladas",
staff = "%s - %s",
watering = "Regando @ %d,%d",
repair = "Consertar %s",
close = "Fechar",
}
tooltip.calls_dispatcher = {
task = "Lista de tarefas - clique na tarefa para abrir a janela do funcionário responsável e ir para o local da tarefa.",
assigned = "Esta janela será marcada se alguém for designado para a tarefa correspondente.",
close = "Fechar a janela de calls dispatcher",
}
staff_class = {
nurse = "Enfermeira",
doctor = "Doutor",
handyman = "Funcionário da Manutenção",
receptionist = "Recepcionista",
surgeon = "Cirurgião",
}
-- Objects
object = {
desk = "Secretária",
cabinet = "Arquivo",
door = "Porta",
bench = "Banco",
table1 = "Mesa", -- unused object
chair = "Cadeira",
drinks_machine = "Máquina de Bebidas",
bed = "Cama",
inflator = "Inflador",
pool_table = "Mesa de Bilhar",
reception_desk = "Recepção",
table2 = "Mesa", -- unused object & duplicate
cardio = "Máquina de Eletrocardiograma",
scanner = "Scanner",
console = "Console",
screen = "Tela",
litter_bomb = "Bomba de lixo",
couch = "Sofá",
sofa = "Sofá",
crash_trolley = "Trolley",
tv = "TV",
ultrascanner = "Ultrasom",
dna_fixer = "Fixador de DNA",
cast_remover = "Removedor de Gesso",
hair_restorer = "Restaurador de Cabelo",
slicer = "Fatiador",
x_ray = "Raio-X",
radiation_shield = "Escudo de Radiação",
x_ray_viewer = "Visualizador de Raio-X",
operating_table = "Mesa de Operação",
lamp = "Lampâda", -- unused object
toilet_sink = "Pia",
op_sink1 = "Pia",
op_sink2 = "Pia",
surgeon_screen = "Tela de Operação",
lecture_chair = "Cadeira de aluno",
projector = "Projetor",
bed2 = "Cama", -- unused duplicate
pharmacy_cabinet = "Gabinete de Farmácia",
computer = "Computador",
atom_analyser = "Analisador de Átomos",
blood_machine = "Máquina de Análise Sanguínea",
fire_extinguisher = "Extintor",
radiator = "Radiador",
plant = "Planta",
electrolyser = "Electrolisador",
jelly_moulder = "Moldador gelatinoso",
gates_of_hell = "Portões do Inferno",
bed3 = "Cama", -- unused duplicate
bin = "Lixeira",
toilet = "Cabine de Toalete",
swing_door1 = "Porta",
swing_door2 = "Porta",
shower = "Chuveiro",
auto_autopsy = "Auto-Autópsia",
bookcase = "Estante de Livros",
video_game = "Fliperama",
entrance_left = "Entrada esquerda",
entrance_right = "Entrada direita",
skeleton = "Esqueleto",
comfortable_chair = "Cadeira de conforto",
}
-- Months
months = {
"Jan",
"Fev",
"Mar",
"Abr",
"Mai",
"Jun",
"Jul",
"Ago",
"Set",
"Out",
"Nov",
"Dez",
}
-- Rooms short
-- NB: includes some special "rooms"
-- reception, destroyed room and "corridor objects"
rooms_short = {
reception = "Recepção",
destroyed = "Destruído",
corridor_objects = "Objetos de Corredor",
gps_office = "Clínica Geral",
psychiatric = "Psiquiatria",
ward = "Enfermaria",
operating_theatre = "Sala de Operações",
pharmacy = "Farmácia",
cardiogram = "Máq. de Eletrocardiograma",
scanner = "Scanner",
ultrascan = "Ultrasom",
blood_machine = "Sala de Análises Sanguíneas",
x_ray = "Raio-X",
inflation = "Inflador",
dna_fixer = "Fixador de DNA",
hair_restoration = "Recuperador de Cabelo",
tongue_clinic = "Fatiador",
fracture_clinic = "Clínica de Fraturas",
training_room = "Sala de Aula",
electrolysis = "Sala de Electrolisador",
jelly_vat = "Moldador Gelatinoso",
staffroom = "Sala de Relaxamento",
-- rehabilitation = "Reabilitação", -- unused
general_diag = "Diagnóstico Geral",
research_room = "Departamento de Pesquisas",
toilets = "Toaletes",
decontamination = "Descontaminação",
}
-- 8. Objetivos da Fase
introduction_texts = {
demo = {
"Bem-vindo ao hospital de demonstração!",
"Infelizmente esta versão demo são possui esta fase. Entretanto, teremos aqui o suficiente para mantê-lo ocupado por enquanto !",
"Você encontrará várias doenças que necessitarão de salas diferentes para cura. De tempos em tempos, emergências ocorrerão. E você precisará pesquisar por salas adicionais usando o Departamento de Pesquisas.",
"Seu objetivo é ter um saldo bancário de $100.000,00, o valor do hospital em $ 70.000,00 e uma reputação de 700, enquanto você cura pelo menos 75% de seus pacientes.",
"Certifique-se que sua reputação não fique abaixo de 300 e você não mate mais de 40% dos seus pacientes, senão você perde.",
"Boa sorte!",
},
level1 = {
[1] = "Bem-vindo(a) ao seu primeiro hospital !//",
[2] = "Tenha-o pronto e rodando colocando um balcão de recepção, construindo um consultório de clínica geral e contratando uma recepcionista e médico. ",
[3] = "Então espere os negócios prosperarem.",
[4] = "É uma boa idéia construir um departamento de psiquiatria e contratar um médico psiquiatra, além de uma farmácia e enfermeira que também serão essenciais para curar seus pacientes. ",
[5] = "Cuidado com os casos de 'Cabeça inchada' - Uma sala com um Inflador resolverá os casos rapidamente.",
[6] = "Seu objetivo será curar 10 pessoas e garantir que sua reputação não fique abaixo de 200.",
[7] = "",
},
level2 = {
[1] = "Há uma grande variedade de doenças nesta área, sendo assim planeje seu hospital para lidar com mais pacientes, além de construir um Departamento de Pesquisas. ",
[2] = "Lembre-se de manter o estabelecimento limpo e procure manter sua reputação a mais alta possível - você estará lidando com doenças como Língua negligente, então precisará de um Fatiador. Adicionalmente, poderá construir uma máquina de Eletrocardiograma para ajudá-lo a diagnosticar novas doenças",
[3] = "Ambas precisarão ser pesquisadas antes de serem construídas. Agora você poderá comprar lotes de terreno extras para expandir seu hospital - use o Mapa da Cidade para fazê-lo.",
[4] = "Tenha como objetivo uma reputação de 300, um saldo bancário de $10.000,00 e 40 pessoas curadas.",
[5] = "",
[6] = "",
},
level3 = {
[1] = "Desta vez, você irá construir seu hospital em uma área nobre da cidade.",
[2] = "O Ministro da Saúde está contando com você para manter os níveis da saúde por aqui.",
[3] = "Você precisa ganhar uma boa reputação para começar, mas uma vez que seu hospital esteja estabelecido, concentre-se em lucrar a maior quantidade de dinheiro que puder.",
[4] = "Há uma grande possibilidade de ter de lidar com Emergências - isso acontece quando um grande número de pessoas chega de uma só vez, na mesma condição clínica - Curando-as à tempo você ganhará uma boa reputação e um grande bônus.",
[5] = "Doenças como o Complexo de Rei podem ocorrer, e você deverá planejar seu orçamento para construir uma Sala de Operações com uma Enfermaria ao lado. ",
[6] = "Consiga $ 20.000,00 em dinheiro para vencer a fase.",
[7] = "",
[8] = "",
},
level4 = {
[1] = "Mantenha seus pacientes felizes, lide com eles da forma mais eficiente que puder e mantenha o número de óbitos no mínimo.",
[2] = "Sua reputação está em jogo, portanto mantenha-a a mais alta que conseguir.",
[3] = "Não se preocupe tanto com dinheiro - ele virá a medida que sua reputação cresce.",
[4] = "Você terá a possibilidade de treinar seus médicos para ampliar suas habilidades também, pois ele poderão ter que lidar com pacientes mais opacos que a maioria.",
[5] = "Consiga uma reputação acima de 500 para vencer a fase.",
[6] = "",
},
level5 = {
[1] = "Você administrará agora um hospital ocupado, lidando com um grande variedade de casos.",
[2] = "Seus médicos são todos calouros da escola de medicina, portanto será de vital importância construir um sala de treinamento e treiná-los até um nível aceitável.",
[3] = "Você possui apenas três médicos sêniores para ajudá-lo a ensinar sua inexperiente equipe, portanto mantenha-os felizes.",
[4] = "Note, também, que as fundações deste hospital ficam no centro da falha geológica de São Android - existe um risco eminente de terremotos. que causarão um estrago significativo em seus equipamentos, atrapalhando uma calma administração de seu hospital.",
[5] = "Sua reputação deve ultrapassar a marca de 400, e um saldo bancário de $ 50.000,00 para ter sucesso - além de curar pelo menos 200 pacientes.",
[6] = "",
[7] = "",
},
level6 = {
[1] = "Utilize todo seu know-how para montar um hospital eficiente que gere lucro e possa lidar com qualquer coisa que o público doente colocar em suas mãos.",
[2] = "Você deve estar ciente que a atmosfera do local é propícia para alastrar germes e infecções - Mantenha a instituição espetacularmente limpa se não quiser enfrentar uma série de epidemias envolvendo os pacientes.",
[3] = "Suas metas são fazer $ 150.000,00 em dinheiro e o valor do hospital deve valer pelo menos $140.000,00",
[4] = "",
},
level7 = {
[1] = "Você está sendo observado de perto pelo Ministro de Saúde, então certifique-se que seus números indiquem que você está ganhando muito dinheiro e reputação crescente.",
[2] = "Não se dê ao luxo de mortes desnecessárias - elas são ruins para os negócios",
[3] = "Certifique-se que seu quadro de funcionários seja hábil e que você possua todos os equipamentos que precisa.",
[4] = "Obtenha uma reputação de 600 e $ 200.000,00 de saldo bancário.",
},
level8 = {
[1] = "Só depende de você construir o hospital mais rentável e eficiente possível.",
[2] = "As pessoas por aqui são bem afortunadas, portanto 'enfie a faca' como puder. ",
[3] = "Lembre-se, curar pessoas é uma coisa muito legal, mas do que você realmente PRECISA é da grana que elas trarão.",
[4] = "Limpe estas pessoas doentes, consiga incríveis $ 300.000,00 para vencer esta fase.",
[5] = "",
},
level9 = {
[1] = "Tendo enchido os bolsos e custeado a nova limousine do Ministro da Saúde, finalmente você pode voltar a criar um hospital modelo em benefício dos mais necessitados. ",
[2] = "Você pode esperar muitos e diversos problemas por aqui - Treine muito bem seus funcionários, tenha boas salas para cobrir todas as possibilidades.",
[3] = "Seu hospital precisa valer $200.000,00 e precisará de $400.000,00 no balco - qualquer coisa menos do que isso você não poderá terminar esta fase.",
[4] = "",
[5] = "",
},
level10 = {
[1] = "Assim que você cuidar de todas as doenças que surgirem por estas bandas, o Ministro solicitou que você se concentre na eficiência de seus medicamentos. ",
[2] = "Existem algumas queixas feitas no 'SemDoenças' - que faz Auditorias na área da Saúde - então para ficar bonito na foto certifique-se que seus medicamentos sejam extremamente eficientes. Portanto, o hospital precisar ficar ótimo. Mantenha os óbitos em níveis baixos.",
[3] = "Fica a dica, deixe espaço livre para o Moldador Gelatinoso.",
[4] = "Pesquise e crie todos os medicamento com pelo menos 80% de eficiência, obtenha uma reputação de 650 e um saldo bancário de $500.000,00 para vencer! ",
[5] = "",
},
level11 = {
[1] = "Você está tendo a oportunidade de construir a última palavra em hospitais. Está em uma área extremamente privilegiada, e o ministro gostaria de ver o melhor hospital possível.",
[2] = "A expectativa é que você faça muito dinheiro, tenha uma reputação soberba e esteja preparado para qualquer eventualidade.",
[4] = "É um trabalho importante este. ",
[5] = "Você precisa ser especial para conseguir se dar bem nessa fase.",
[6] = "Existem vários relatos de OVNIs nessa área. Certifique-se que seus funcionários estejam preparados para um eventual contato imediato.",
[7] = "Seu hospital precisa valer $240,000, você precisará de $500,000 no banco e uma reputação de 700.",
},
level12 = {
},
level13 = {
},
level14 = {
},
level15 = {
},
level16 = {
},
level17 = {
},
level18 = {
},
}
graphs = {
money_in = "Receitas",
money_out = "Despesas",
wages = "Salários",
balance = "Balanço",
visitors = "Visitantes",
cures = "Curas",
deaths = "Óbitos",
reputation = "Reputação",
time_spans = {
S[7][12],
S[7][13],
S[7][14],
}
}
tooltip = {
toolbar = {
bank_button = "Clique com o botão esquerdo para consultar o Gerente do Banco, botão direito para extrato bancário",
balance = "Seu saldo bancário",
reputation = "Sua reputação",
date = "Calendário",
rooms = "Construir Salas",
objects = "Оbjetos de corredor",
edit = "Editar Salas",
hire = "Contratação de Pessoal",
staff_list = "Quadro de Funcionários",
town_map = "Mapa de Cidade",
casebook = "Livro de Diagnósticos",
research = "Pesquisa",
status = "Situação",
charts = "Gráficos",
policy = "Políticas",
},
}
-- Rooms
room_classes = {
-- S[19][2] -- "corridors" - unused for now
diagnosis = "Diagnóstico",
treatment = "Tratamento",
clinics = "Clínicas",
facilities = "Acomodações",
}
--]]
confirmation = {
abort_edit_room = "Está construindo ou editando uma sala. Se todos os objectos necessários estiverem colocados a sala estará terminada, caso contrário será eliminada. Continuar?",
return_to_blueprint = "Voltar ao modo de desenho?",
restart_level = "Deseja realmente reiniciar esta fase?",
delete_room = "Deseja realmente remover esta sala?",
quit = "Sair do jogo?",
needs_restart = "Estas alterações requerem reiniciar o jogo, todo progresso não gravado será perdido. Continuar?",
overwrite_save = "Já existe uma gravação neste arquivo. Gravar por cima?",
sack_staff = "Demitir este funcionário ?",
replace_machine = "Quer substituir %s por $%d?",
}
vip_names = {
[1] = "Presidente da Cruz Vermelha",
[2] = "Ricardo Araújo Pereira",
[3] = "D. Duarte Pio de Bragança",
[4] = "Joe Berardo",
[5] = "José Mourinho",
[6] = "Alberto João Jardim",
[7] = "Marcelo Rebelo de Sousa",
[8] = "Cavaco Silva",
[9] = "Cristiano Ronaldo",
[10] = "Tradutor Filipe Carvalho",
health_minister = "Ministro da Saúde",
}
room_descriptions = {
ultrascan = {
[1] = "Ultrasom//",
[2] = "O ultrasom é a última palavra em equipamento de diagnóstico. Custa caro, mais vale a pena se deseja um diagnóstico soberbo em seu hospital.//",
[3] = "The Ultrasom precisa de manutenção e um médico (qualquer nível) para funcionamento. ",
},
gp = {
[1] = "Clínica Geral//",
[2] = "Esta é a sala de diagnósticos primordial de um hospital. Novos pacientes sentarão aqui para descobrir o que há de errado com eles. Serão enviados posteriormente para outras salas de dianóstico ou para serem curados. Você poderá construir outra Sala de Clínica Geral se esta ficar muito ocupada. Quanto maior a sala for, mais objetos adicionais podem ser colocados nela, e maior o prestígio do médico. Isso vale igualmente para todas as outras salas.//",
[3] = "A Sala de Clínica Geral precisa de um médico de qualquer nível. ",
},
fracture_clinic = {
[1] = "Clínica de Fraturas//",
[2] = "Aqueles pacientes azarados o bastante por terem seus ossos quebrados vem aqui. A máquina de remover gesso irá empregar lasers industriais para partir o mais duro gesso, causando apenas um ligeira agonia ao paciente.//",
[3] = "A Clínica de Fraturas precisa de uma Enfermeira para funcionamento e contínua manutenção. ",
},
tv_room = {
[1] = "TV ROOM NOT USED",
},
inflation = {
[1] = "Inflador//",
[2] = "Pacientes que sofrerem da dolorosa-porém-engraçada condição de 'Cabeça Inchada' devem vir ao Inflador, onde seu avantajado crânico será estourado e reinflado instantaneamente na pressão correta.//",
[3] = "O Inflador precisa de um médico de qualquer nível, além de cuidados constantes de um Funcionário da Manutenção. ",
},
jelly_vat = {
[1] = "Clínica de Geléia//",
[2] = "Pacientes amaldiçoados com a rídicula Geléite devem ser encaminhados para a Clínica de Geléia, e colocados no tanque de Geléia, sendo curados de uma maneira até então não compreendida totalmente pela medicina.//",
[3] = "A Clínica de Geléia precisa de um médico de qualquer nível, e de cuidados dos funcionários da manutenção. ",
},
scanner = {
[1] = "Ressonância Magnética//",
[2] = "Os pacientes são diagnosticados de forma precisa usando esta máquina de Ressonância Magnética. Eles irão então ver um médico na Clínica Geral para tratamento posterior.//",
[3] = "A máquina de Ressonância Magnética precisa de um médico de qualquer nível, além de manutenção. ",
},
blood_machine = {
[1] = "Máquina de Sangue//",
[2] = "A Máquina de Sangue é uma parte do arsenal de diagnósticos que verifica as células no sangue do paciente para descobrir o que há de errado com ele.//",
[3] = "A Máquina de Sangue precisa de um médico de qualquer nível, além de manutenção. ",
},
pharmacy = {
[1] = "Farmácia//",
[2] = "Pacientes que tenham sido diagnosticados e seu tratamento prevê algum medicamento devem visitar a Farmácia para tomá-lo. Conforme novos medicamentos vão sendo pesquisados e disponibilizados, a sala vai ficando movimentada, portanto você pode ter a necessidade de construir outra no futuro.//",
[3] = "A Farmácia precisa de uma Enfermeira. ",
},
cardiogram = {
[1] = "Eletrocardiograma//",
[2] = "Pacientes são diagnosticados e checados aqui, antes de voltarem à Sala de Clínica Geral para um diagnóstico final.//",
[3] = "O Eletrocardiograma precisa de um médico de qualquer nível, além de manutenção. ",
},
ward = {
[1] = "Enfermaria//",
[2] = "Pacientes que forem mantidos aqui sob observação de uma Enfermeira durante diagnóstico. Eles permanecem aqui antes de serem operados.//",
[3] = "A Enfermaria precisa de uma Enfermeira. ",
},
psych = {
[1] = "Psiquiatria//",
[2] = "Pacientes diagnosticados com males psiquiátricos devem visitar o Departamento de Psiquiatria para receber aconselhamento. Psiquiatras podem ainda fazer diagnósticos, descobrindo que tipo de mal o paciente possui, se há origem mental, tratando-se no divã.//",
[3] = "O Departamento de Psiquiatria precisa de um Psiquiatra. ",
},
staff_room = {
[1] = "Sala de Relaxamento//",
[2] = "Sua equipe fica estressada ao longo de um dia de trabalho. Eles precisam desta sala para relaxar e descansar. Funcionários cansados trabalham em marcha lenta, exigem mais dinheiro e eventualmente pedem demissão, além de cometer mais erros. Construa uma sala de relaxamento com muitas possibilidades de entretenimento é muito interessante. Certifique-se que a sala comporte vários funcionários de uma só vez. ",
},
operating_theatre = {
[1] = "Sala de Operações//",
[2] = "Esta importante instalação é onde uma série de condições serão tratadas. Deve ter um bom tamanho, e deve ser ocupado com o equipamento correto. Ele é vital para seu hospital.//",
[3] = "A Sala de Operações precisa de dois Cirurgiões. ",
},
training = {
[1] = "Sala de Treinamento//",
[2] = "Seus médicos de nível junior e pleno podem adquirir qualificações extras estudando nesta sala. Um Cirurgião, Pesquisador e/ou Psiquiatra Sênior pode passar este conhecimento para quaisquer médicos sendo treinados, e aqueles que já possuírem estas habilidades poderão aprimorá-las aqui.//",
[3] = "A Sala de Treinamento precisa de um Doutor Sênior. ",
},
dna_fixer = {
[1] = "Clínica de DNA//",
[2] = "Pacientes que foram abduzidos por alienígenas de outro mundo deve ter seu DNA substituído nesta sala. A máquina de fixação de DNA é um equipamento complexo e pode ser sensato manter um extintor de incêndio dentro da sala, por via das dúvidas.//",
[3] = "A máquina de fixação de DNA deverá ter manutenção constante de um funcionário, precisando de um Pesquisador para operá-la. ",
},
research = {
[1] = "Departamento de Pesquisas//",
[2] = "Novos medicamentos e cruas são inventados e aprimorados no Departamento de Pesquisas. Vital para seu hospital, fará maravilhas em seu percentual de curas.//",
[3] = "A Departamento de Pesquisas precisa de um Pesquisador. ",
},
hair_restoration = {
[1] = "Clínica de Restauração de Cabelos//",
[2] = "Pacientes que sofrem de uma condição de calvície extrema serão encaminhados para a máquina de restauração de cabelos desta Clínica. Um médico irá operar a máquina, que irá fazer crescer quase instantaneamente um cabelo novo.//",
[3] = "A Clínica de Restauração de Cabelos precisa de um médico de qualquer nível, além de cuidados de um funcionário da manutenção. ",
},
general_diag = {
[1] = "Diagnósticos Gerais//",
[2] = "Pacientes que necessitem de uma investigação mais profunda são analisados aqui. Se a Clínica Geral não encontrar o que há de errado com eles, Diagnósticos Gerais geralmente irá. Daqui ele é enviado de volta à Clínica Geral para análise dos resultados produzidos aqui.//",
[3] = "O Diagnósticos Gerais precisa de um médico de qualquer nível.",
},
electrolysis = {
[1] = "Sala de Eletrólise//",
[2] = "Pacientes com Pelulite são encaminhados para esta sala, onde uma máquina especial chamada Eletrolizador arranca os pêlos e esteriliza os poros eletricamente usando um composto similar à uma argamassa.//",
[3] = "A Sala de Eletrólise precisa de um médico de qualquer nível, além de cuidados de um funcionário da manutenção. ",
},
slack_tongue = {
[1] = "Clínica de Língua Negligente//",
[2] = "Paciente diagnosticados na Clínica Geral com Língua Negligente serão enviados para esta clínica para tratamento. O médico irá usando um maquinário de última geração para extender a língua e cortá-la fora, restaurando a saúde do paciente.//",
[3] = "A Clínica de Língua Negligente precisa de um médico de qualquer nível, e manutenção frequente. ",
},
toilets = {
[1] = "Toalete//",
[2] = "Pacientes que ouvirem o chamado da natureza irão se aliviar no conforto deste toalete. Você poderá construir baias e lavatórios extras se houver a expectativa de muitos visitantes. Em alguns casos, considere construir toaletes em outros pontos do hospital. ",
},
no_room = {
[1] = "",
},
x_ray = {
[1] = "Raio-X//",
[2] = "A máquina de Raio-X fotografa as pessoas por dentro usando radiação especial, fornecendo à equipe uma boa idéia do que há de errado com elas.//",
[3] = "O Raio-X precisa de um médico de qualquer nível, além de manutenção. ",
},
decontamination = {
[1] = "Clínica de Descontaminação//",
[2] = "Pacientes que foram expostos à radiação devem ser levados rapidamente à Clínica de Descontaminação. Esta sala contém um chuveiro lavar toda a horrível radiação e.. sujeira.//",
[3] = "O chuveiro de descontaminação precisa de um médico de qualquer nível, além de cuidados de um funcionário da manutenção. ",
},
}
pay_rise = {
definite_quit = "Nada que você fizer vai me manter aqui, pra mim chega.",
regular = {
[1] = "Estou em frangalhos. Preciso de um bom descanso, além de um aumento de %d se você não quer me ver por aqui neste trabalho enfadonho.",
[2] = "Estou muito cansado. Preciso de um descanso e um aumento de salário de %d, indo para %d. Faça agora, seu tirano!",
[3] = "Veja bem, estou trabalhando como uma mula! Quero um bônus de %d para ficar neste hospital.",
[4] = "Estou infeliz. Exijo um aumento de %d, aumentando meus honorários para %d, caso contrário estou fora.",
[5] = "Meus pais haviam me dito que a área médica pagava bem. Então me dê um aumento de %d ou largo a área para fazer jogos de computador.",
[6] = "Estou de saco cheio. Pague-me um salário decente, um aumento de %d deve bastar.",
},
poached = "Recebi uma proposta de %d feita pelo %s. Pague-me o mesmo ou estou fora.",
}
level_names = {
[1] = "Toxilândia",
[2] = "Sleepy Hollow",
[3] = "Peito largo",
[4] = "Frimpton-on-Sea",
[5] = "Simplolândia",
[6] = "Festering-on-the-Wold",
[7] = "Greenpool",
[8] = "Manquay",
[9] = "Vila do Leste",
[10] = "Eggsenham",
[11] = "Croaking",
[12] = "Battenburg",
[13] = "Chumleigh",
[14] = "Sova",
[15] = "Enterra Enterra",
}
staff_descriptions = {
good = {
[1] = "Trabalha muito rápido e aplicado(a). ",
[2] = "Muito consciente. Importa-se profundamente. ",
[3] = "Possui várias habilidades. ",
[4] = "Amistoso(a) e adora uma gargalhada. ",
[5] = "Resistência admirável, trabalha pesado. ",
[6] = "Educado(a) e cordial de forma notável. ",
[7] = "Incrivelmente talentoso(a) e capaz. ",
[8] = "Dedica-se muito ao trabalho designado. ",
[9] = "Perfeccionista e persistente. ",
[10] = "Dedicado(a) a ajudar pessoas com um sorriso no rosto. ",
[11] = "Charmoso(a), educado(a) e prestativo(a). ",
[12] = "Frequentemente muito motivado(a) e dedicado(a). ",
[13] = "Bem-humorado(a) e muito trabalhador(a). ",
[14] = "Leal e amigável. ",
[15] = "Cuidadoso(a) e confiável em uma emergência.",
},
misc = {
[1] = "Joga golfe. ",
[2] = "Pratica mergulho. ",
[3] = "Faz esculturas no gelo. ",
[4] = "Bebe vinho. ",
[5] = "Participa de rally. ",
[6] = "Faz bungee-jump. ",
[7] = "Coleciona latas de cerveja. ",
[8] = "Gosta de mergulhar no público nos shows. ",
[9] = "Jogar de praticar surf. ",
[10] = "Jogar de praticar raffiting. ",
[11] = "Destila whisky. ",
[12] = "Especialista no 'faça-você-mesmo'. ",
[13] = "Gosta de filmes de arte franceses. ",
[14] = "Joga 'Theme Park' muito. ",
[15] = "Possui carteira de habilitação E. ",
[16] = "Corre de motocicleta. ",
[17] = "Toca violino e violoncelo clássicos. ",
[18] = "Adora colisões de trens. ",
[19] = "Amante de cães. ",
[20] = "Ouve rádio. ",
[21] = "Toma banho frequentemente. ",
[22] = "Instrutor de tricô. ",
[23] = "Tira o miolo dos vegetais para usar como porta sabão. ",
[24] = "Policial especial meio-período. ",
[25] = "Ex-apresentador de programa de calouros. ",
[26] = "Coleciona estilhaços da Segunda Guerra. ",
[27] = "Restaurador de mobília. ",
[28] = "Ouve rave e trip-hop. ",
[29] = "Extermina insetos com desodorante spray. ",
[30] = "Ridiculariza comediantes ruins. ",
[31] = "Arruma confusão em reunião de condomínio. ",
[32] = "Jardineiro incorrigível. ",
[33] = "Contrabandeia relógios falsificados. ",
[34] = "Vocalista de uma banda de rock and roll. ",
[35] = "Adora os programas da televisão vespertina. ",
[36] = "Cutuca trutas. ",
[37] = "Isca turistas em museus. ",
},
bad = {
[1] = "Lento e inquieto. ",
[2] = "Preguiçoso e pouco motivado. ",
[3] = "Mal treinado e ineficaz. ",
[4] = "Rude e áspero. Afasta as pessoas. ",
[5] = "Resistência terrível - tem uma gênio ruim. ",
[6] = "Surdo como uma porta. Cheira à repolho. ",
[7] = "Péssimo(a) no trabalho, meramente responsável. ",
[8] = "Imprudente e distraído. ",
[9] = "Estressado com tendência e cometer erros. ",
[10] = "Retorcido e ressentido - explodindo de raiva. ",
[11] = "Descuidado e propenso à acidentes. ",
[12] = "Não se preocupa com o trabalho. Muito preguiçoso. ",
[13] = "Tolo que gosta se assumir riscos e não se importa com nada. ",
[14] = "Dissimulado, malandro e subversivo. ",
[15] = "Arrogante e convencido. ",
},
}
|
local groupName = {
[201848376] = "合宙群01",
[604902189] = "合宙群02",
[1092305811] = "合宙群03",
[877164555] = "合宙群04",
[851800257] = "合宙群05",
[387396364] = "合宙群06",
[423804427] = "合宙群07",
[823812859] = "合宙群08",
[679177589] = "WiFi群",
[967368887] = "合宙群10",
[627242078] = "合宙群11",
[799971630] = "合宙群12",
[151645843] = "合宙群13",
[710412579] = "合宙群14",
[553477984] = "合宙群15",
[952343033] = "iRTU1群",
[1027923658] = "iRTU2群",
[1061642968] = "LuatOS群",
[827963649] = "CPE群",
[489193389] = "GPSTracker群",
[221504157] = "训练营一期",
[1108271783] = "魔盒",
}
local function saveLog(g,q,t)
local temp = 1
while temp < #t do
local ss,ee = t:find("%[CQ:image,file=.-,url=.-%]",temp)
if ss then
t = t:gsub("%[CQ:image,file=.-%]","[image"..t:match("%[CQ:image,file=.-,url=(.-)%]").."]",1)
temp = ee
else
break
end
end
asyncHttpGet("https://qq.papapoi.com/qqmsg/post.php?g="..string.urlEncode(tostring(g))..
"&q="..string.urlEncode(tostring(q))..
"&m="..string.urlEncode((Utils.ConvertBase64(CQ.Decode(t)))))
print("已上传消息记录")
end
local Groups = require("luat_groups")
local function getName(group,qq)
local info = cq.groupMemberInfo(group,qq)
return info.card ~= "" and info.card or info.nickname
end
return {
check = function (data)
for i=1,#Groups do
if Groups[i] == data.group then return true end
end
end,
run = function (data,sendMessage)
local qqName = getName(data.group,data.qq)
sys.taskInit(function()
saveLog(data.group,qqName.."("..tostring(data.qq)..")",data.msg)
end)
if groupName[data.group] then
Mqtt.Publish("luaRobot/message/"..data.group, jsonEncode({
group = tostring(data.group),
qq = qqName,
msg = data.msg:gsub("%[.-%]","[特殊]"):sub(1,100),--限制前100字
name = groupName[data.group],
}), 0)
end
end
}
|
--融合解除
function c952861650.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TODECK+CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c952861650.target)
e1:SetOperation(c952861650.activate)
c:RegisterEffect(e1)
end
function c952861650.filter(c)
return c:IsFaceup() and c:IsType(TYPE_FUSION) and c:IsAbleToExtra()
end
function c952861650.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c952861650.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c952861650.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c952861650.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,1,0,0)
end
function c952861650.mgfilter(c,e,tp,fusc)
return not c:IsControler(tp) or not c:IsLocation(LOCATION_GRAVE)
or bit.band(c:GetReason(),0x40008)~=0x40008 or c:GetReasonCard()~=fusc
or not c:IsCanBeSpecialSummoned(e,0,tp,false,false) or c:IsHasEffect(EFFECT_NECRO_VALLEY)
end
function c952861650.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not (tc:IsRelateToEffect(e) and tc:IsFaceup()) then return end
local mg=tc:GetMaterial()
local sumable=true
local sumtype=tc:GetSummonType()
if Duel.SendtoDeck(tc,nil,0,REASON_EFFECT)==0 or bit.band(sumtype,SUMMON_TYPE_FUSION)~=SUMMON_TYPE_FUSION or mg:GetCount()==0
or mg:GetCount()>Duel.GetLocationCount(tp,LOCATION_MZONE)
or mg:IsExists(c952861650.mgfilter,1,nil,e,tp,tc) then
sumable=false
end
if sumable and Duel.SelectYesNo(tp,aux.Stringid(952861650,0)) then
Duel.BreakEffect()
Duel.SpecialSummon(mg,0,tp,tp,false,false,POS_FACEUP)
end
end
|
--=========== Copyright © 2019, Planimeter, All rights reserved. ===========--
--
-- Purpose: Chat Text Box HUD
--
--==========================================================================--
class "gui.hudchattextbox" ( "gui.textbox" )
local hudchattextbox = gui.hudchattextbox
function hudchattextbox:hudchattextbox( parent, name )
gui.textbox.textbox( self, parent, name, "" )
self.hudchat = parent
self:setEditable( false )
self:setMultiline( true )
self:setScheme( "Chat" )
self.borderOpacity = 0
self:setVisible( false )
end
local CHAT_ANIM_TIME = 0.2
function hudchattextbox:activate()
if ( not self:isVisible() ) then
self:setOpacity( 0 )
self:animate( {
opacity = 1
}, CHAT_ANIM_TIME, "easeOutQuint" )
end
self:setVisible( true )
end
function hudchattextbox:hide()
if ( self.hiding ) then
return
end
self.hiding = true
self:animate( {
opacity = 0,
}, CHAT_ANIM_TIME, "easeOutQuint", function()
self:setVisible( false )
self:setOpacity( 1 )
self.hiding = nil
self.hideTime = nil
end )
end
function hudchattextbox:drawBorder()
local width = self:getWidth()
local height = self:getHeight()
local color = color( self:getScheme( "textbox.borderColor" ) )
color[ 4 ] = color[ 4 ] * self.borderOpacity
love.graphics.setColor( color )
local lineWidth = 1
love.graphics.setLineWidth( lineWidth )
love.graphics.rectangle(
"line",
lineWidth / 2,
lineWidth / 2,
width - lineWidth,
height - lineWidth
)
end
accessor( hudchattextbox, "hideTime" )
accessor( hudchattextbox, "hudchat" )
function hudchattextbox:invalidateLayout()
local parent = self:getHudchat()
local margin = 36
local textboxHeight = 46
local padding = 9
local width = parent:getWidth()
width = width - 2 * margin
local height = parent:getHeight()
height = height - textboxHeight - padding - 2 * margin
self:setWidth( width )
self:setHeight( height )
gui.panel.invalidateLayout( self )
end
function hudchattextbox:update( dt )
local parent = self:getHudchat()
local hideTime = self:getHideTime()
if ( hideTime and
hideTime <= love.timer.getTime() and
not parent:isVisible() ) then
self:hide()
end
gui.textbox.update( self, dt )
end
function hudchattextbox:updateCursor()
local hudchat = self:getHudchat()
if ( not hudchat:isVisible() ) then
love.mouse.setCursor()
return
end
gui.textbox.updateCursor( self )
end
|
scum = {
check = function(player)
local del = 0
local write = 0
if player.gmLevel == 99 then
del = 1
write = 1
end
player.boardDel = del
player.boardWrite = write
end
}
|
---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2009, olcc
--
-- This is now a standalone RSS reader for awesome:
-- * http://github.com/olcc/aware
---------------------------------------------------
-- {{{ Grab environment
local pairs = pairs
local io = { popen = io.popen }
local setmetatable = setmetatable
-- }}}
-- RSS: provides latest world news
-- vicious.contrib.rss
local rss = {}
-- {{{ RSS widget type
local function worker(format, input)
-- input: * feed - feed url
-- * object - entity to look for (typically: 'item')
-- * fields - fields to read (example: 'link', 'title', 'description')
-- output: * count - number of entities found
-- * one table for each field, containing wanted values
local feed = input.feed
local object = input.object
local fields = input.fields
-- Initialise tables
local out = {}
for _, v in pairs(fields) do
out[v] = {}
end
-- Initialise variables
local ob = nil
local i,j,k = 1, 1, 0
local curl = "curl -A 'Mozilla/4.0' -fsm 5 --connect-timeout 3 "
-- Get the feed
local f = io.popen(curl .. '"' .. feed .. '"')
local feed = f:read("*all")
f:close()
while true do
i, j, ob = feed.find(feed, "<" .. object .. ">(.-)</" .. object .. ">", i)
if not ob then break end
for _, v in pairs(fields) do
out[v][k] = ob:match("<" .. v .. ">(.*)</" .. v .. ">")
end
k = k+1
i = j+1
end
-- Update the entity count
out.count = k
return out
end
-- }}}
return setmetatable(rss, { __call = function(_, ...) return worker(...) end })
|
mg.write("HTTP/1.0 200 OK\r\n")
-- MIME type: https://www.ietf.org/rfc/rfc4627.txt, chapter 6
mg.write("Content-Type: application/json\r\n")
mg.write("\r\n")
num_threads = mg.get_option("num_threads")
num_threads = tonumber(num_threads)
function n(s)
if ((type(s) == "string") and (#s > 0)) then
return s
else
return "null"
end
end
mg.write("{\r\n\"system\" :\r\n")
mg.write(n(mg.get_info("system")))
mg.write(",\r\n\"summary\" :\r\n")
mg.write(n(mg.get_info("context")))
mg.write(",\r\n\"common\" :\r\n")
mg.write(n(mg.get_info("common")))
mg.write(",\r\n\"connections\" :\r\n[\r\n")
mg.write(n(mg.get_info("connection", 1)))
for i=2,num_threads do
mg.write(",\r\n")
mg.write(n(mg.get_info("connection", i)))
end
mg.write("]\r\n}\r\n")
|
--------------------------------------------------------------------------------
-- Module Declaration
--
local mod, CL = BigWigs:NewBoss("Millificent Manastorm", 1544, 1688)
if not mod then return end
mod:RegisterEnableMob(101976)
mod.engageId = 1847
--------------------------------------------------------------------------------
-- Locals
--
--------------------------------------------------------------------------------
-- Initialization
--
function mod:GetOptions()
return {
201159, -- Delta Finger Laser X-treme
201240, -- Elementium Squirrel Bomb
201392, -- Thorium Rocket Chicken
201572, -- Millificent's Rage
}
end
function mod:OnBossEnable()
self:Log("SPELL_AURA_APPLIED", "DeltaFinger", 201159)
self:Log("SPELL_CAST_SUCCESS", "SquirrelBomb", 201240, 201432) -- normal, overloaded
self:Log("SPELL_CAST_SUCCESS", "RocketChicken", 201392, 201438) -- normal, reinforced
self:Log("SPELL_AURA_APPLIED", "MillificentsRage", 201572)
end
function mod:OnEngage()
self:Bar(201159, 5) -- Delta Finger Laser X-treme
self:CDBar(201240, 7) -- Elementium Squirrel Bomb
self:CDBar(201392, 24) -- Thorium Rocket Chicken
end
--------------------------------------------------------------------------------
-- Event Handlers
--
function mod:DeltaFinger(args)
self:TargetMessage(args.spellId, args.destName, "orange")
self:Bar(args.spellId, 8.5)
end
function mod:SquirrelBomb()
self:Message(201240, "yellow", "Info")
self:CDBar(201240, 18)
end
function mod:RocketChicken(args)
self:Message(201392, "red", "Alarm")
self:CDBar(201392, args.spellId == 201438 and 9.7 or 18)
end
function mod:MillificentsRage(args)
self:Message(args.spellId, "cyan", "Warning")
self:CDBar(201240, 5) -- Overloaded Squirrel Bomb
self:CDBar(201392, 13.5) -- Reinforced Rocket Chicken
end
|
local arrays = require "pgmoon.arrays"
local json = require "pgmoon.json"
local cjson = require "cjson"
local cjson_safe = require "cjson.safe"
local pl_tablex = require "pl.tablex"
local kong = kong
local ngx = ngx
local encode_base64 = ngx.encode_base64
local decode_base64 = ngx.decode_base64
local encode_array = arrays.encode_array
local encode_json = json.encode_json
local setmetatable = setmetatable
local update_time = ngx.update_time
local get_phase = ngx.get_phase
local tonumber = tonumber
local concat = table.concat
local insert = table.insert
local assert = assert
local ipairs = ipairs
local pairs = pairs
local error = error
local upper = string.upper
local pack = table.pack -- luacheck: ignore
local null = ngx.null
local type = type
local load = load
local find = string.find
local now = ngx.now
local fmt = string.format
local rep = string.rep
local sub = string.sub
local log = ngx.log
local NOTICE = ngx.NOTICE
local LIMIT = {}
local UNIQUE = {}
local new_tab
local clear_tab
do
local pcall = pcall
local ok
ok, new_tab = pcall(require, "table.new")
if not ok then
new_tab = function () return {} end
end
ok, clear_tab = pcall(require, "table.clear")
if not ok then
clear_tab = function (tab)
for k, _ in pairs(tab) do
tab[k] = nil
end
end
end
end
local function noop(...)
return ...
end
local function now_updated()
update_time()
return now()
end
-- @param name Query name, for debugging purposes
-- @param query A string describing an array of single-quoted strings which
-- contain parts of an SQL query including numeric placeholders like $0, $1, etc.
-- All parts of that array were processed via using string.format("%q"),
-- so that all newlines and quotes are preserved.
-- @return Produces a function which, given an array of arguments,
-- interpolates them in the right places and outputs a ready-to-use SQL query.
local function compile(name, query)
local c = [=====[
local v = ... or {}
return concat { ]=====]
.. query:gsub("$(%d+)", [[", v[%1], "]])
.. [=====[
}
]=====]
return load(c, "=" .. name, "t", { concat = concat })
end
local function expand(name, map)
local skip = {}
local c = { "local row = ... or {}\n" }
for _, field in ipairs(map) do
local entity = field.entity
if not skip[entity] then
skip[entity] = true
local exps = {}
local keys = {}
local nils = {}
for _, key in ipairs(map) do
if key.entity == entity then
insert(exps, 'row["' .. key.from .. '"] ~= null')
if key.to ~= "ws_id" then
insert(keys, fmt('["%s"] = row["%s"]', key.to, key.from))
end
insert(nils, fmt('row["%s"] = nil', key.from))
end
end
insert(c, (([[
if $EXPS then
row["$ENTITY"] = { $KEYS }
else
row["$ENTITY"] = null
end
$NILS
]]):gsub("$(%a+)", {
ENTITY = entity,
EXPS = concat(exps, " and "),
KEYS = concat(keys, ", "),
NILS = concat(nils, "; "),
})))
end
end
insert(c, "return row")
return load(concat(c), "=" .. name, "t", { null = null })
end
local function collapse(name, map)
local skip = {}
local c = { [[
local t = { ... }
local row = {}
for _, a in ipairs(t) do
for k, v in pairs(a) do
row[k] = v
end
end
]] }
for _, field in ipairs(map) do
local entity = field.entity
if not skip[entity] then
skip[entity] = true
local keys = {}
local nulls = {}
for _, key in ipairs(map) do
if key.entity == entity then
insert(keys, fmt('row["%s"] = row["%s"]["%s"]', key.from, entity, key.to))
insert(nulls, fmt('row["%s"] = null', key.from))
end
end
insert(c, (([[
if row["$ENTITY"] ~= nil and row["$ENTITY"] ~= null then
$KEYS
row["$ENTITY"] = nil
elseif row["$ENTITY"] == null then
$NULLS
row["$ENTITY"] = nil
end
]]):gsub("$(%a+)", {
ENTITY = entity,
KEYS = concat(keys, "; "),
NULLS = concat(nulls, "; "),
})))
end
end
insert(c, "return row")
local env = { ipairs = ipairs, pairs = pairs, null = null }
return load(concat(c), "=" .. name, "t", env)
end
local function escape_identifier(connector, identifier, field)
identifier = connector:escape_identifier(identifier)
if field and field.timestamp then
return concat { "EXTRACT(EPOCH FROM ", identifier, " AT TIME ZONE 'UTC') AS ", identifier }
end
return identifier
end
local function escape_literal(connector, literal, field)
if literal == nil or literal == null then
return "NULL"
end
if field then
if field.timestamp then
return concat { "TO_TIMESTAMP(", connector:escape_literal(tonumber(fmt("%.3f", literal))), ") AT TIME ZONE 'UTC'" }
end
if field.type == "array" or field.type == "set" then
if not literal[1] then
return connector:escape_literal("{}")
end
local elements = field.elements
if elements.timestamp then
local timestamps = {}
for i, v in ipairs(literal) do
timestamps[i] = concat { "TO_TIMESTAMP(", connector:escape_literal(tonumber(fmt("%.3f", v))), ") AT TIME ZONE 'UTC'" }
end
return encode_array(timestamps)
end
local et = elements.type
if et == "array" or et == "set" then
local el = elements
repeat
el = el.elements
et = el.type
until et ~= "array" and et ~= "set"
if et == "map" or et == "record" then
return error("postgres strategy to escape multidimensional arrays of maps or records is not implemented")
end
elseif et == "map" or et == "record" then
local jsons = {}
for i, v in ipairs(literal) do
jsons[i] = cjson.encode(v)
end
return encode_array(jsons) .. '::JSONB[]'
elseif et == "string" and elements.uuid then
return encode_array(literal) .. '::UUID[]'
end
return encode_array(literal)
elseif field.type == "map" or field.type == "record" then
return encode_json(literal)
end
end
return connector:escape_literal(literal)
end
local function toerror(strategy, err, primary_key, entity)
local schema = strategy.schema
local errors = strategy.errors
if find(err, "violates unique constraint", 1, true) then
log(NOTICE, err)
if find(err, "cache_key", 1, true) then
local keys = {}
for _, k in ipairs(schema.cache_key) do
local field = schema.fields[k]
if field.type == "foreign" and entity[k] ~= null then
keys[k] = field.schema:extract_pk_values(entity[k])
else
keys[k] = entity[k]
end
end
return nil, errors:unique_violation(keys)
end
for field_name, field in schema:each_field() do
if field.unique then
if find(err, field_name, 1, true) then
return nil, errors:unique_violation({
[field_name] = entity[field_name]
})
end
end
end
if not primary_key then
primary_key = {}
if entity then
for _, key in ipairs(schema.primary_key) do
primary_key[key] = entity[key]
end
end
end
return nil, errors:primary_key_violation(primary_key)
elseif find(err, "violates not-null constraint", 1, true) then
-- not-null constraint is currently only enforced on primary key
log(NOTICE, err)
if not primary_key then
primary_key = {}
if entity then
for _, key in ipairs(schema.primary_key) do
primary_key[key] = entity[key]
end
end
end
return nil, errors:primary_key_violation(primary_key)
elseif find(err, "violates foreign key constraint .*_ws_id_fkey") then
if schema.name == "workspaces" then
local found, e = find(err, "is still referenced from table", 1, true)
if not found then
return error("could not parse foreign key violation error message: " .. err)
end
return nil, errors:foreign_key_violation_restricted(schema.name, sub(err, e + 3, -3))
else
local ws_id = err:match("ws_id%)=%(([^)]*)%)") or "null"
return nil, errors:invalid_workspace(ws_id)
end
elseif find(err, "violates foreign key constraint", 1, true) then
log(NOTICE, err)
if find(err, "is not present in table", 1, true) then
local foreign_field_name
local foreign_schema
for field_name, field in schema:each_field() do
if field.type == "foreign" then
local escaped_identifier = escape_identifier(strategy.connector,
field.schema.name)
if find(err, escaped_identifier, 1, true) then
foreign_field_name = field_name
foreign_schema = field.schema
break
end
end
end
if not foreign_schema then
return error("could not determine foreign schema for violated foreign key error")
end
local foreign_key = {}
for _, key in ipairs(foreign_schema.primary_key) do
if entity[foreign_field_name] then
foreign_key[key] = entity[foreign_field_name][key]
else
if primary_key[key] then
foreign_key[key] = primary_key[key]
elseif primary_key[foreign_field_name] then
foreign_key[key] = primary_key[foreign_field_name][key]
end
end
end
return nil, errors:foreign_key_violation_invalid_reference(foreign_key,
foreign_field_name,
foreign_schema.name)
else
local found, e = find(err, "is still referenced from table", 1, true)
if not found then
return error("could not parse foreign key violation error message: " .. err)
end
return nil, errors:foreign_key_violation_restricted(schema.name, sub(err, e + 3, -3))
end
end
return nil, errors:database_error(err)
end
local function get_ttl_value(strategy, attributes, options)
local ttl_value = options and options.ttl
local is_update = options and options.update
local fields = strategy.fields
if ttl_value == 0 or not ttl_value then
return null
end
if not is_update and
attributes.created_at and
fields.created_at and
fields.created_at.timestamp and
fields.created_at.auto then
return ttl_value + attributes.created_at
end
if is_update and
attributes.updated_at and
fields.updated_at and
fields.updated_at.timestamp and
fields.updated_at.auto then
return ttl_value + attributes.updated_at
end
return ttl_value + now_updated()
end
local function get_ws_id()
local phase = get_phase()
if phase ~= "init" and phase ~= "init_worker" then
return ngx.ctx.workspace or kong.default_workspace
end
end
local function execute(strategy, statement_name, attributes, options)
local ws_id
local has_ws_id = strategy.schema.workspaceable
if has_ws_id then
if options and options.workspace then
if options.workspace ~= null then
ws_id = options.workspace
end
else
ws_id = get_ws_id()
end
if not ws_id then
statement_name = statement_name .. "_global"
end
end
local connector = strategy.connector
local statement = strategy.statements[statement_name]
if not attributes then
return connector:query(statement[1], statement[2])
end
local fields = strategy.fields
local argn = statement.argn
local argv = statement.argv
local argc = statement.argc
clear_tab(argv)
local is_update = options and options.update
local has_ttl = strategy.schema.ttl
if has_ws_id then
assert(ws_id == nil or type(ws_id) == "string")
argv[0] = escape_literal(connector, ws_id, "ws_id")
end
for i = 1, argc do
local name = argn[i]
local value
if has_ttl and name == "ttl" then
value = (options and options.ttl)
and get_ttl_value(strategy, attributes, options)
elseif i == argc and is_update and attributes[UNIQUE] then
value = attributes[UNIQUE]
if type(value) == "table" then
value = value[name]
end
else
value = attributes[name]
end
argv[i] = (value == nil and is_update)
and escape_identifier(connector, name)
or escape_literal(connector, value, fields[name])
end
local sql = statement.make(argv)
return connector:query(sql, statement.operation)
end
local function page(self, size, token, foreign_key, foreign_entity_name, options)
if not size then
size = self.connector:get_page_size(options)
end
local limit = size + 1
local statement_name
local attributes = {
[LIMIT] = limit,
}
local suffix = token and "_next" or "_first"
if foreign_entity_name then
statement_name = "page_for_" .. foreign_entity_name .. suffix
attributes[foreign_entity_name] = foreign_key
elseif options and options.tags then
statement_name = options.tags_cond == "or" and
"page_by_tags_or" .. suffix or
"page_by_tags_and" .. suffix
attributes.tags = options.tags
else
statement_name = "page" .. suffix
end
if token then
local token_decoded = decode_base64(token)
if not token_decoded then
return nil, self.errors:invalid_offset(token, "bad base64 encoding")
end
token_decoded = cjson_safe.decode(token_decoded)
if not token_decoded then
return nil, self.errors:invalid_offset(token, "bad json encoding")
end
for i, field_name in ipairs(self.schema.primary_key) do
attributes[field_name] = token_decoded[i]
end
end
local res, err = execute(self, statement_name, self.collapse(attributes), options)
if not res then
return toerror(self, err)
end
local rows = new_tab(size, 0)
for i = 1, limit do
local row = res[i]
if not row then
break
end
if i == limit then
row = res[size]
local offset = {}
for _, field_name in ipairs(self.schema.primary_key) do
insert(offset, row[field_name])
end
offset = cjson.encode(offset)
offset = encode_base64(offset, true)
return rows, nil, offset
end
rows[i] = self.expand(row)
end
return rows
end
local function make_select_for(foreign_entity_name)
return function(self, foreign_key, size, token, options)
return page(self, size, token, foreign_key, foreign_entity_name, options)
end
end
local _mt = {}
_mt.__index = _mt
function _mt:truncate(options)
local res, err = execute(self, "truncate", nil, options)
if not res then
return toerror(self, err)
end
return true, nil
end
function _mt:insert(entity, options)
local res, err = execute(self, "insert", self.collapse(entity), options)
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, nil
end
return toerror(self, err, nil, entity)
end
function _mt:select(primary_key, options)
local res, err = execute(self, "select", self.collapse(primary_key), options)
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, nil
end
return toerror(self, err, primary_key)
end
function _mt:select_by_field(field_name, unique_value, options)
local statement_name = "select_by_" .. field_name
local filter = {
[field_name] = unique_value,
}
local res, err = execute(self, statement_name, self.collapse(filter), options)
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, nil
end
return toerror(self, err, filter)
end
local function update_options(options)
return {
update = true,
ttl = options and options.ttl,
workspace = options and options.workspace ~= null and options.workspace,
}
end
function _mt:update(primary_key, entity, options)
local res, err = execute(self, "update",
self.collapse(primary_key, entity),
update_options(options))
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, self.errors:not_found(primary_key)
end
return toerror(self, err, primary_key, entity)
end
function _mt:update_by_field(field_name, unique_value, entity, options)
local filter
if type(unique_value) == "table" then
filter = self.collapse({ [field_name] = unique_value })
else
filter = unique_value
end
local res, err = execute(self, "update_by_" .. field_name,
self.collapse({ [UNIQUE] = filter }, entity),
update_options(options))
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, self.errors:not_found_by_field {
[field_name] = unique_value,
}
end
return toerror(self, err, { [field_name] = unique_value }, entity)
end
function _mt:upsert(primary_key, entity, options)
local collapsed_entity = self.collapse(entity, primary_key)
local res, err = execute(self, "upsert", collapsed_entity, options)
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, self.errors:not_found(primary_key)
end
return toerror(self, err, primary_key, entity)
end
function _mt:upsert_by_field(field_name, unique_value, entity, options)
local collapsed_entity = self.collapse(entity, {
[field_name] = unique_value
})
local res, err = execute(self, "upsert_by_" .. field_name, collapsed_entity, options)
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, self.errors:not_found_by_field {
[field_name] = unique_value,
}
end
return toerror(self, err, { [field_name] = unique_value }, entity)
end
function _mt:delete(primary_key, options)
local res, err = execute(self, "delete", self.collapse(primary_key), options)
if res then
if res.affected_rows == 0 then
return nil, nil
end
return true, nil
end
return toerror(self, err, primary_key)
end
function _mt:delete_by_field(field_name, unique_value, options)
local statement_name = "delete_by_" .. field_name
local filter = {
[field_name] = unique_value,
}
local res, err = execute(self, statement_name, self.collapse(filter), options)
if res then
if res.affected_rows == 0 then
return nil, nil
end
return true, nil
end
return toerror(self, err, filter)
end
function _mt:page(size, token, options)
return page(self, size, token, nil, nil, options)
end
function _mt:escape_literal(literal, field_name)
return escape_literal(self.connector, literal, self.fields[field_name])
end
local function format_on_condition(on_condition)
if not on_condition then
return nil
end
on_condition = upper(on_condition)
if on_condition ~= "RESTRICT" and
on_condition ~= "CASCADE" and
on_condition ~= "NULL" and
on_condition ~= "DEFAULT" then
on_condition = nil
end
return on_condition
end
local function where_clause(where, ...)
local inputs = pack(...)
return function(add_ws)
local exps = {}
for i = 1, inputs.n do
local exp = inputs[i]
if exp then
if add_ws then
insert(exps, exp)
else
if not exp:match("%(\"ws_id\" = ") then
insert(exps, exp)
end
end
end
end
if #exps == 0 then
return ""
end
return where .. concat(exps, "\n" .. rep(" ", #where - 4) .. "AND ") .. "\n"
end
end
local function conflict_list(has_ws_id, ...)
local inputs = pack(...)
return function(add_ws)
local exps = inputs
if add_ws and has_ws_id then
insert(exps, 1, '"ws_id"')
end
return concat(exps, ", ")
end
end
-- placeholders in queries must always be constructed as a single string,
-- to avoid ending up genering code like this: `concat { "... $", "2 AND ..." }`
local function placeholder(n)
return "$" .. n
end
local _M = {}
function _M.new(connector, schema, errors)
local primary_key = schema.primary_key
local primary_key_fields = {}
for _, field_name in ipairs(primary_key) do
primary_key_fields[field_name] = true
end
local has_ttl = schema.ttl == true
local has_tags = schema.fields.tags ~= nil
local has_composite_cache_key = schema.cache_key and #schema.cache_key > 1
local has_ws_id = schema.workspaceable == true
local fields = {}
local fields_hash = {}
local table_name = schema.name
local table_name_escaped = escape_identifier(connector, table_name)
local foreign_key_list = {}
local foreign_keys = {}
local unique_fields = {}
for field_name, field in schema:each_field() do
if field.type == "foreign" then
local foreign_schema = field.schema
local foreign_key_names = {}
local foreign_key_escaped = {}
local foreign_col_names = {}
local is_unique_foreign = field.unique == true
for _, foreign_field_name in ipairs(foreign_schema.primary_key) do
local foreign_field
for foreign_schema_field_name, foreign_schema_field in foreign_schema:each_field() do
if foreign_schema_field_name == foreign_field_name then
foreign_field = foreign_schema_field
break
end
end
local name = field_name .. "_" .. foreign_field_name
fields_hash[name] = foreign_field
local prepared_field = {
referenced_table = foreign_schema.name,
referenced_column = foreign_field_name,
on_update = format_on_condition(field.on_update),
on_delete = format_on_condition(field.on_delete),
name = name,
name_escaped = escape_identifier(connector, name),
name_expression = escape_identifier(connector, name, foreign_field),
field_name = field_name,
is_used_in_primary_key = primary_key_fields[field_name] ~= nil,
is_part_of_composite_key = #foreign_schema.primary_key > 1,
is_unique = foreign_field.unique == true,
is_unique_across_ws = foreign_field.unique_across_ws == true,
is_endpoint_key = schema.endpoint_key == field_name,
is_unique_foreign = is_unique_foreign,
}
if prepared_field.is_used_in_primary_key then
primary_key_fields[field_name] = prepared_field
end
insert(fields, prepared_field)
insert(foreign_key_names, name)
insert(foreign_key_escaped, prepared_field.name_escaped)
insert(foreign_col_names, escape_identifier(connector, foreign_field_name))
insert(foreign_key_list, {
from = name,
entity = field_name,
to = foreign_field_name
})
end
foreign_keys[field_name] = {
names = foreign_key_names,
escaped = foreign_key_escaped,
}
else
fields_hash[field_name] = field
local is_used_in_primary_key = primary_key_fields[field_name] ~= nil
local is_part_of_composite_key = is_used_in_primary_key and #primary_key > 1 or false
local prepared_field = {
name = field_name,
name_escaped = escape_identifier(connector, field_name),
name_expression = escape_identifier(connector, field_name, field),
is_used_in_primary_key = is_used_in_primary_key,
is_part_of_composite_key = is_part_of_composite_key,
is_unique = field.unique == true,
is_unique_across_ws = field.unique_across_ws == true,
is_endpoint_key = schema.endpoint_key == field_name,
}
if prepared_field.is_used_in_primary_key then
primary_key_fields[field_name] = prepared_field
end
insert(fields, prepared_field)
end
end
local primary_key_names = {}
local primary_key_placeholders = {}
local insert_names = {}
local insert_columns = {}
local insert_expressions = {}
local select_expressions = {}
local update_expressions = {}
local update_names = {}
local update_placeholders = {}
local upsert_expressions = {}
local page_next_names = {}
for i, field in ipairs(fields) do
local name = field.name
local name_escaped = field.name_escaped
local name_expression = field.name_expression
local is_used_in_primary_key = field.is_used_in_primary_key
local is_part_of_composite_key = field.is_part_of_composite_key
local is_unique = field.is_unique
local is_unique_foreign = field.is_unique_foreign
local is_endpoint_key = field.is_endpoint_key
local referenced_table = field.referenced_table
insert(insert_names, name)
insert(insert_columns, name_escaped)
insert(insert_expressions, "$" .. i)
insert(select_expressions, name_expression)
if not is_used_in_primary_key then
insert(update_names, name)
insert(update_expressions, name_escaped .. " = $" .. #update_names)
insert(upsert_expressions, name_escaped .. " = " .. "EXCLUDED." .. name_escaped)
end
if ((not is_used_in_primary_key) or is_part_of_composite_key)
and ((referenced_table and not is_part_of_composite_key)
or is_unique_foreign
or is_unique
or (is_endpoint_key and not is_unique))
then
-- treat endpoint_key like a unique key anyway,
-- they are indexed (example: target.target)
insert(unique_fields, field)
end
end
local update_args_names = {}
for _, update_name in ipairs(update_names) do
insert(update_args_names, update_name)
end
local cache_key_escaped
if has_composite_cache_key then
cache_key_escaped = escape_identifier(connector, "cache_key")
insert(update_names, "cache_key")
insert(update_args_names, "cache_key")
insert(update_expressions, cache_key_escaped .. " = $" .. #update_names)
insert(upsert_expressions, cache_key_escaped .. " = " .. "EXCLUDED." .. cache_key_escaped)
end
local ws_id_escaped
if has_ws_id then
ws_id_escaped = escape_identifier(connector, "ws_id")
insert(select_expressions, ws_id_escaped)
insert(update_names, "ws_id")
insert(update_args_names, "ws_id")
insert(update_expressions, ws_id_escaped .. " = $0")
insert(upsert_expressions, ws_id_escaped .. " = " .. "EXCLUDED." .. ws_id_escaped)
end
local ttl_escaped
if has_ttl then
ttl_escaped = escape_identifier(connector, "ttl")
insert(update_names, "ttl")
insert(update_args_names, "ttl")
insert(update_expressions, ttl_escaped .. " = $" .. #update_names)
insert(upsert_expressions, ttl_escaped .. " = " .. "EXCLUDED." .. ttl_escaped)
end
local primary_key_escaped = {}
for i, key in ipairs(primary_key) do
local primary_key_field = primary_key_fields[key]
insert(page_next_names, key)
insert(primary_key_names, primary_key_field.name)
insert(primary_key_escaped, primary_key_field.name_escaped)
insert(update_args_names, primary_key_field.name)
insert(update_placeholders, "$" .. #update_args_names)
insert(primary_key_placeholders, "$" .. i)
end
insert(page_next_names, LIMIT)
local pk_escaped = concat(primary_key_escaped, ", ")
select_expressions = concat(select_expressions, ", ")
primary_key_placeholders = concat(primary_key_placeholders, ", ")
update_placeholders = concat(update_placeholders, ", ")
if has_composite_cache_key then
fields_hash.cache_key = { type = "string" }
insert(insert_names, "cache_key")
insert(insert_expressions, "$" .. #insert_names)
insert(insert_columns, cache_key_escaped)
end
local ws_id_select_where
if has_ws_id then
fields_hash.ws_id = { type = "string", uuid = true }
insert(insert_names, "ws_id")
insert(insert_expressions, "$0")
insert(insert_columns, ws_id_escaped)
ws_id_select_where = "(" .. ws_id_escaped .. " = $0)"
end
local ttl_select_where
if has_ttl then
fields_hash.ttl = { timestamp = true }
insert(insert_names, "ttl")
insert(insert_expressions, "$" .. #insert_names)
insert(insert_columns, ttl_escaped)
select_expressions = concat {
select_expressions, ",",
"FLOOR(EXTRACT(EPOCH FROM (",
ttl_escaped, " AT TIME ZONE 'UTC' - CURRENT_TIMESTAMP AT TIME ZONE 'UTC'",
"))) AS ", ttl_escaped
}
ttl_select_where = concat {
"(", ttl_escaped, " IS NULL OR ", ttl_escaped, " >= CURRENT_TIMESTAMP AT TIME ZONE 'UTC')"
}
end
insert_expressions = concat(insert_expressions, ", ")
insert_columns = concat(insert_columns, ", ")
update_expressions = concat(update_expressions, ", ")
upsert_expressions = concat(upsert_expressions, ", ")
local primary_key_args = {}
local insert_args = {}
local update_args = {}
local single_args = {}
local page_next_args = {}
local self = setmetatable({
connector = connector,
schema = schema,
errors = errors,
expand = #foreign_key_list > 0 and
expand(table_name .. "_expand", foreign_key_list) or
noop,
collapse = collapse(table_name .. "_collapse", foreign_key_list),
fields = fields_hash,
statements = {
truncate = {
concat {
"TRUNCATE ", table_name_escaped, " RESTART IDENTITY CASCADE;"
},
"write",
},
}
}, _mt)
self.statements["truncate_global"] = self.statements["truncate"]
local add_statement
do
local function add(name, opts, add_ws)
local orig_argn = opts.argn
opts = pl_tablex.deepcopy(opts)
-- ensure LIMIT table is the same
for i, n in ipairs(orig_argn) do
if type(n) == "table" then
opts.argn[i] = n
end
end
for i = 1, #opts.code do
if type(opts.code[i]) == "function" then
opts.code[i] = opts.code[i](add_ws)
end
opts.code[i] = fmt("%q", opts.code[i])
end
opts.make = compile(table_name .. "_" .. name, concat(opts.code, ", "))
opts.code = nil
opts.argc = #opts.argn
self.statements[name] = opts
end
add_statement = function(name, opts)
add(name .. "_global", opts, false)
add(name, opts, true)
end
end
add_statement("insert", {
operation = "write",
expr = insert_expressions,
cols = insert_columns,
argn = insert_names,
argv = insert_args,
code = {
"INSERT INTO ", table_name_escaped, " (", insert_columns, ")\n",
" VALUES (", insert_expressions, ")\n",
" RETURNING ", select_expressions, ";",
}
})
add_statement("upsert", {
operation = "write",
expr = upsert_expressions,
argn = insert_names,
argv = insert_args,
code = {
"INSERT INTO ", table_name_escaped, " (", insert_columns, ")\n",
" VALUES (", insert_expressions, ")\n",
"ON CONFLICT (", pk_escaped, ") DO UPDATE\n",
" SET ", upsert_expressions, "\n",
" RETURNING ", select_expressions, ";",
}
})
add_statement("update", {
operation = "write",
expr = update_expressions,
argn = update_args_names,
argv = update_args,
code = {
" UPDATE ", table_name_escaped, "\n",
" SET ", update_expressions, "\n",
where_clause(
" WHERE ", "(" .. pk_escaped .. ") = (" .. update_placeholders .. ")",
ttl_select_where,
ws_id_select_where),
"RETURNING ", select_expressions, ";",
}
})
add_statement("delete", {
operation = "write",
argn = primary_key_names,
argv = primary_key_args,
code = {
"DELETE\n",
" FROM ", table_name_escaped, "\n",
where_clause(
" WHERE ", "(" .. pk_escaped .. ") = (" .. primary_key_placeholders .. ")",
ttl_select_where,
ws_id_select_where), ";"
}
})
add_statement("select", {
operation = "read",
expr = select_expressions,
argn = primary_key_names,
argv = primary_key_args,
code = {
"SELECT ", select_expressions, "\n",
" FROM ", table_name_escaped, "\n",
where_clause(
" WHERE ", "(" .. pk_escaped .. ") = (" .. primary_key_placeholders .. ")",
ttl_select_where,
ws_id_select_where),
" LIMIT 1;"
}
})
add_statement("page_first", {
operation = "read",
argn = { LIMIT },
argv = single_args,
code = {
" SELECT ", select_expressions, "\n",
" FROM ", table_name_escaped, "\n",
where_clause(
" WHERE ", ttl_select_where,
ws_id_select_where),
"ORDER BY ", pk_escaped, "\n",
" LIMIT $1;";
}
})
add_statement("page_next", {
operation = "read",
argn = page_next_names,
argv = page_next_args,
code = {
" SELECT ", select_expressions, "\n",
" FROM ", table_name_escaped, "\n",
where_clause(
" WHERE ", "(" .. pk_escaped .. ") > (" .. primary_key_placeholders .. ")",
ttl_select_where,
ws_id_select_where),
"ORDER BY ", pk_escaped, "\n",
" LIMIT " .. placeholder(#page_next_names), ";"
}
})
if #foreign_key_list > 0 then
for foreign_entity_name, foreign_key in pairs(foreign_keys) do
local fk_names = foreign_key.names
local fk_escaped = foreign_key.escaped
local fk_placeholders = {}
local pk_placeholders = {}
local foreign_key_names = concat(fk_escaped, ", ")
local argv_first = {}
local argn_first = {}
local argv_next = {}
local argn_next = {}
for i, fk_name in ipairs(fk_names) do
insert(argn_first, fk_name)
insert(argn_next, fk_name)
insert(fk_placeholders, placeholder(i))
end
for i, primary_key_name in ipairs(primary_key_names) do
insert(argn_next, primary_key_name)
insert(pk_placeholders, placeholder(i + #fk_names))
end
insert(argn_first, LIMIT)
insert(argn_next, LIMIT)
fk_placeholders = concat(fk_placeholders, ", ")
pk_placeholders = concat(pk_placeholders, ", ")
local statement_name = "page_for_" .. foreign_entity_name
add_statement(statement_name .. "_first", {
operation = "read",
argn = argn_first,
argv = argv_first,
code = {
" SELECT ", select_expressions, "\n",
" FROM ", table_name_escaped, "\n",
where_clause(
" WHERE ", "(" .. foreign_key_names .. ") = (" .. fk_placeholders .. ")",
ttl_select_where,
ws_id_select_where),
"ORDER BY ", pk_escaped, "\n",
" LIMIT ", placeholder(#argn_first), ";";
}
})
add_statement(statement_name .. "_next", {
operation = "read",
argn = argn_next,
argv = argv_next,
code = {
" SELECT ", select_expressions, "\n",
" FROM ", table_name_escaped, "\n",
where_clause(
" WHERE ", "(" .. foreign_key_names .. ") = (" .. fk_placeholders .. ")",
"(" .. pk_escaped .. ") > (" .. pk_placeholders .. ")",
ttl_select_where,
ws_id_select_where),
"ORDER BY ", pk_escaped, "\n",
" LIMIT ", placeholder(#argn_next), ";"
}
})
self[statement_name] = make_select_for(foreign_entity_name)
end
end
if has_tags then
local pk_placeholders = {}
local argn_first = { "tags", LIMIT }
local argn_next = { "tags" }
for i, primary_key_name in ipairs(primary_key_names) do
insert(argn_next, primary_key_name)
pk_placeholders[i] = placeholder(i + 1)
end
insert(argn_next, LIMIT)
for cond, op in pairs({["_and"] = "@>", ["_or"] = "&&"}) do
add_statement("page_by_tags" .. cond .. "_first", {
operation = "read",
argn = argn_first,
argv = {},
code = {
" SELECT ", select_expressions, "\n",
" FROM ", table_name_escaped, "\n",
where_clause(
" WHERE ", "tags " .. op .. " $1",
ttl_select_where,
ws_id_select_where),
"ORDER BY ", pk_escaped, "\n",
" LIMIT $2;";
},
})
add_statement("page_by_tags" .. cond .. "_next", {
operation = "read",
argn = argn_next,
argv = {},
code = {
" SELECT ", select_expressions, "\n",
" FROM ", table_name_escaped, "\n",
where_clause(
" WHERE ", "tags " .. op .. " $1",
"(" .. pk_escaped .. ") > (" .. concat(pk_placeholders, ", ") .. ")",
ttl_select_where,
ws_id_select_where),
"ORDER BY ", pk_escaped, "\n",
" LIMIT ", placeholder(#argn_next), ";"
}
})
end
end
if has_composite_cache_key then
insert(unique_fields, {
name = "cache_key",
name_escaped = escape_identifier(connector, "cache_key"),
})
end
if #unique_fields > 0 then
local update_by_args = {}
for _, unique_field in ipairs(unique_fields) do
local field_name = unique_field.field_name or unique_field.name
local unique_name = unique_field.name
local unique_escaped = unique_field.name_escaped
local single_names = { unique_name }
add_statement("select_by_" .. field_name, {
operation = "read",
argn = single_names,
argv = single_args,
code = {
"SELECT ", select_expressions, "\n",
" FROM ", table_name_escaped, "\n",
where_clause(
" WHERE ", unique_escaped .. " = $1",
ttl_select_where,
ws_id_select_where),
" LIMIT 1;"
},
})
local update_by_args_names = {}
for _, update_name in ipairs(update_names) do
insert(update_by_args_names, update_name)
end
insert(update_by_args_names, unique_name)
add_statement("update_by_" .. field_name, {
operation = "write",
argn = update_by_args_names,
argv = update_by_args,
code = {
" UPDATE ", table_name_escaped, "\n",
" SET ", update_expressions, "\n",
where_clause(
" WHERE ", unique_escaped .. " = $" .. #update_names + 1,
ttl_select_where,
ws_id_select_where),
"RETURNING ", select_expressions, ";",
}
})
local conflict_key = unique_escaped
if has_composite_cache_key then
conflict_key = escape_identifier(connector, "cache_key")
end
local use_ws_id = has_ws_id and not unique_field.is_unique_across_ws
add_statement("upsert_by_" .. field_name, {
operation = "write",
argn = insert_names,
argv = insert_args,
code = {
"INSERT INTO ", table_name_escaped, " (", insert_columns, ")\n",
" VALUES (", insert_expressions, ")\n",
"ON CONFLICT (", conflict_list(use_ws_id, conflict_key), ") DO UPDATE\n",
" SET ", upsert_expressions, "\n",
" RETURNING ", select_expressions, ";",
}
})
add_statement("delete_by_" .. field_name, {
operation = "write",
argn = single_names,
argv = single_args,
code = {
"DELETE\n",
" FROM ", table_name_escaped, "\n",
where_clause(
" WHERE ", unique_escaped .. " = $1",
ttl_select_where,
ws_id_select_where), ";"
}
})
end
end
return self
end
return _M
|
-- define target
target("cuda_console")
-- set kind
set_kind("binary")
-- add include directories
add_includedirs("inc")
-- add files
add_files("src/*.cu")
-- generate SASS code for each SM architecture
for _, sm in ipairs({"30", "35", "37", "50", "52", "60", "61", "70"}) do
add_cuflags("-gencode arch=compute_" .. sm .. ",code=sm_" .. sm)
add_ldflags("-gencode arch=compute_" .. sm .. ",code=sm_" .. sm)
end
-- generate PTX code from the highest SM architecture to guarantee forward-compatibility
sm = "70"
add_cuflags("-gencode arch=compute_" .. sm .. ",code=compute_" .. sm)
add_ldflags("-gencode arch=compute_" .. sm .. ",code=compute_" .. sm)
|
-- definition of roman numeral chords assuming a root of C (transposable)
roman_numeral_to_chord={}
local nums={1,4,5}
local rnums={"I","IV","V"}
local notes={"C","F","G"}
local adds={"maj","maj7","min","min7"}
for i,_ in ipairs(nums) do
roman_numeral_to_chord[nums[i]]={}
local rn=rnums[i]
for j,ad in ipairs(adds) do
local rn2=rn
if string.find(ad,"min") then
rn2=string.lower(rn2)
end
if string.find(ad,"7") then
rn2=rn2.."7"
end
table.insert(roman_numeral_to_chord[nums[i]],{rn=rn2,c=notes[i]..ad})
end
end
local nums={2,3,6}
local rnums={"ii","iii","vi"}
local notes={"D","E","A"}
local adds={"min","min7","maj","maj7"}
for i,_ in ipairs(nums) do
roman_numeral_to_chord[nums[i]]={}
local rn=rnums[i]
for j,ad in ipairs(adds) do
local rn2=rn
if string.find(ad,"min") then
rn2=string.lower(rn2)
else
rn2=string.upper(rn2)
end
if string.find(ad,"7") then
rn2=rn2.."7"
end
table.insert(roman_numeral_to_chord[nums[i]],{rn=rn2,c=notes[i]..ad})
end
end
local nums={7}
local rnums={"vii"}
local notes={"B"}
local adds={"dim","dim7b5"}
for i,_ in ipairs(nums) do
roman_numeral_to_chord[nums[i]]={}
local rn=rnums[i]
for j,ad in ipairs(adds) do
local rn2=rn
if string.find(ad,"7") then
rn2=rn2.."7"
end
table.insert(roman_numeral_to_chord[nums[i]],{rn=rn2,c=notes[i]..ad})
end
end
for i,v in ipairs(roman_numeral_to_chord[7]) do
for k,v2 in pairs(v) do
print(i,k,v2)
end
end
|
object_mobile_exar_kun_cultist_f_02 = object_mobile_shared_exar_kun_cultist_f_02:new {
}
ObjectTemplates:addTemplate(object_mobile_exar_kun_cultist_f_02, "object/mobile/exar_kun_cultist_f_02.iff")
|
--
-- collisions.lua
-- General collision math
-- Includes general collisions and specific collision functions
--
local Collisions = {}
Collisions.__index = Collisions
-- MODULES --
local Constants = require ("src.logic.general")
-- END --
Collisions.__hWiggleConst = 0.1 / Constants.TERMINAL_HORIZONTAL
Collisions.__vWiggleConst = 0.1 / Constants.TERMINAL_VERTICAL
function Collisions.floorCollision (self, floor)
local cols = self.hitbox:collision (floor.hitbox)
local hWiggle = Collisions.__hWiggleConst * self.hitbox.vSpeed
local vWiggle = Collisions.__vWiggleConst * self.hitbox.hSpeed
if hWiggle < 0 then
hWiggle = hWiggle * -1
end
if vWiggle < 0 then
vWiggle = vWiggle * -1
end
if cols [Constants.Directions.DOWN] then
if self.hitbox.x > (floor.hitbox.x + floor.hitbox.width - hWiggle) then
self.hitbox.x = floor.hitbox.x + floor.hitbox.width
elseif self.hitbox.x < (floor.hitbox.x - self.hitbox.width + hWiggle) then
self.hitbox.x = floor.hitbox.x - self.hitbox.width
else
self.hitbox.grounded = true
self.hitbox.y = floor.hitbox.y - self.hitbox.height
self.hitbox:setFloor (floor)
end
end
if cols [Constants.Directions.LEFT] then
if (self.hitbox.y + self.hitbox.height) < (floor.hitbox.y + vWiggle) then
self.hitbox.y = floor.hitbox.y - self.hitbox.height
elseif self.hitbox.y > (floor.hitbox.y + floor.hitbox.height - vWiggle) then
self.hitbox.y = floor.hitbox.y + floor.hitbox.height
else
self.hitbox.leftWall = true
self.hitbox.grip = true
self.hitbox.x = floor.hitbox.x + floor.hitbox.width
end
end
if cols [Constants.Directions.RIGHT] then
if (self.hitbox.y + self.hitbox.height) < (floor.hitbox.y + vWiggle) then
self.hitbox.y = floor.hitbox.y - self.hitbox.height
elseif self.hitbox.y > (floor.hitbox.y + floor.hitbox.height - vWiggle) then
self.hitbox.y = floor.hitbox.y + floor.hitbox.height
else
self.hitbox.rightWall = true
self.hitbox.grip = true
self.hitbox.x = floor.hitbox.x - self.hitbox.width
end
end
if cols [Constants.Directions.UP] then
if self.hitbox.x > (floor.hitbox.x + floor.hitbox.width - hWiggle) then
self.hitbox.x = floor.hitbox.x + floor.hitbox.width
elseif self.hitbox.x < (floor.hitbox.x - self.hitbox.width + hWiggle) then
self.hitbox.x = floor.hitbox.x - self.hitbox.width
else
self.hitbox.roof = true
self.hitbox.y = floor.hitbox.y + floor.hitbox.height
end
end
end
return Collisions
|
--[[
/////// //////////////////
/////// PROJECT: MTA iLife - German Fun Reallife Gamemode
/////// VERSION: 1.7.2
/////// DEVELOPERS: See DEVELOPERS.md in the top folder
/////// LICENSE: See LICENSE.md in the top folder
/////// /////////////////
]]
-- #######################################
-- ## Project: HUD iLife ##
-- ## For MTA: San Andreas ##
-- ## Name: HudComponent_Weather.lua ##
-- ## Author: Noneatme ##
-- ## Version: 1.0 ##
-- ## License: See top Folder ##
-- #######################################
-- FUNCTIONS / METHODS --
local cFunc = {}; -- Local Functions
local cSetting = {}; -- Local Settings
HudComponent_Weather = {};
HudComponent_Weather.__index = HudComponent_Weather;
--[[
]]
-- ///////////////////////////////
-- ///// New //////
-- ///// Returns: Object //////
-- ///////////////////////////////
function HudComponent_Weather:New(...)
local obj = setmetatable({}, {__index = self});
if obj.Constructor then
obj:Constructor(...);
end
return obj;
end
-- ///////////////////////////////
-- ///// Toggle //////
-- ///// Returns: void //////
-- ///////////////////////////////
function HudComponent_Weather:Toggle(bBool)
local component_name = "wanteds"
if (bBool == nil) then
hud.components[component_name].enabled = not (hud.components[component_name].enabled);
else
hud.components[component_name].enabled = bBool;
end
end
-- ///////////////////////////////
-- ///// CheckBolt //////
-- ///// Returns: void //////
-- ///////////////////////////////
function HudComponent_Weather:CheckBolt()
-- Urgent:
-- Diese Methode wird in einem 'onClientRender' Event aufgerufen.
if not(isTimer(self.blitzWaitTimer)) then
self.blitzWaitTimer = setTimer(self.blitzAddFunc, math.random(500, 10000), 1)
end
end
-- ///////////////////////////////
-- ///// AddRandomBlitz //////
-- ///// Returns: void //////
-- ///////////////////////////////
function HudComponent_Weather:AddRandomBlitz()
local id = math.random(1, 3)
self.blitzAlpha[id] = 255;
end
-- ///////////////////////////////
-- ///// Render //////
-- ///// Returns: void //////
-- ///////////////////////////////
function HudComponent_Weather:Render()
local component_name = "weather"
local x, y = hud.components[component_name].sx, hud.components[component_name].sy;
local w, h = hud.components[component_name].width*hud.components[component_name].zoom, hud.components[component_name].height*hud.components[component_name].zoom;
local alpha = hud.components[component_name].alpha
dxDrawImage(x, y, w, h, hud.pfade.images.."component_weather/background.png", 0, 0, 0, tocolor(200, 255, 200, alpha));
-- Weather
local id = getWeather()
local name = self.weather_list[id]
local rightText1 = "False"
local rightText2 = 0;
if(name) then else
name = self.weather_list[1]
rightText1 = "Sunny(Default)"
end
local time = getTime()
local heatHaze = getHeatHaze()
local tempMin, tempMax = 0, 20
local temp = math.round((heatHaze/(tempMax/2.55)), 1, "round")
if(fileExists(hud.pfade.images.."component_weather/icons/"..name.."_day_night.png")) then
name = name.."_day_night"
rightText1 = self.weather_namelist[id];
else
if(time < 7) or (time > 20) then
name = name.."_night";
rightText1 = self.weather_namelist_night[id];
else
name = name.."_day";
rightText1 = self.weather_namelist[id];
end
end
-- outputChatBox(name)
-- Weather Icons
if not(fileExists(hud.pfade.images.."component_weather/icons/"..name..".png")) then
name = "state_clear_day";
rightText1 = "Blue sky"
end
dxDrawImage(x+40*hud.components[component_name].zoom, y-5*hud.components[component_name].zoom, 109*hud.components[component_name].zoom, 109*hud.components[component_name].zoom, hud.pfade.images.."component_weather/icons/"..name..".png", 0, 0, 0, tocolor(255, 255, 255, alpha));
-- Regen Blitze
if(self.is_rain[id]) then
for i = 1, 3, 1 do
local alpha2 = self.blitzAlpha[i]
if(alpha2 > 2) then
alpha2 = alpha2-2
self.blitzAlpha[i] = alpha2;
dxDrawImage(x, y, w, h, hud.pfade.images.."component_weather/bolt_"..i..".png", 0, 0, 0, tocolor(200, 200, 255, alpha2/255*alpha));
end
end
end
-- Text
if not(rightText1) then
rightText1 = "Unknow"
end
dxDrawText(rightText1, x+w/(1.6), y+10*hud.components[component_name].zoom, x+w, y+h, tocolor(255, 255, 255, alpha), 1.7*hud.components[component_name].zoom, "default-bold", "center", "top", false, false, true, false, false)
dxDrawText(temp.."' C", x+w/(1.6), y+60*hud.components[component_name].zoom, x+w, y+h, tocolor(255, 255, 255, alpha), 1.4*hud.components[component_name].zoom, "default-bold", "center", "top", false, false, true, false, false)
-- Spezielles
-- Regen
if(self.is_rain[id]) then
dxDrawImageSection(x, y, w, h, 697-getTickCount()/20, -getTickCount()/10, 697, 384/2, hud.pfade.images.."component_weather/rain_texture.png", 0, 0, 0, tocolor(255, 255, 255, alpha))
self:CheckBolt();
-- Blitz Alphas
end
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function HudComponent_Weather:Constructor(...)
-- Instanzen
self.weather_list = {
[0] = "state_clear",
[1] = "state_clear",
[2] = "state_clear",
[3] = "state_cloudy2",
[4] = "state_cloudy2",
[5] = "state_cloudy2",
[6] = "state_cloudy2",
[7] = "state_cloudy",
[8] = "state_rainy",
[9] = "state_foggy",
[10] = "state_clear",
[11] = "state_clear",
[12] = "state_cloudy2",
[13] = "state_clear",
[14] = "state_clear",
[15] = "state_clear",
[16] = "state_rainy",
[17] = "state_clear",
[18] = "state_clear",
[19] = "state_foggy",
[20] = "state_clear",
}
self.weather_namelist = {
[0] = "Blue sky",
[1] = "Blue sky",
[2] = "Blue sky",
[3] = "Cloudy",
[4] = "Cloudy",
[5] = "Cloudy",
[6] = "Cloudy",
[7] = "Cloudy",
[8] = "Rainy",
[9] = "Foggy",
[10] = "Blue sky",
[11] = "Blue sky",
[12] = "Cloudy",
[13] = "Blue sky",
[14] = "Blue sky",
[15] = "Blue sky",
[16] = "Stormy",
[17] = "Blue sky",
[18] = "Blue sky",
[19] = "Sandstorm",
[20] = "Blue sky",
}
self.weather_namelist_night = {
[1] = "Clear sky",
[2] = "Clear sky",
[3] = "Cloudy",
[4] = "Cloudy",
[5] = "Cloudy",
[6] = "Cloudy",
[7] = "Cloudy",
[8] = "Rainy",
[9] = "Foggy",
[10] = "Clear sky",
[11] = "Clear sky",
[12] = "Cloudy",
[13] = "Clear sky",
[14] = "Clear sky",
[15] = "Clear sky",
[16] = "Stormy",
[17] = "Clear sky",
[18] = "Clear sky",
[19] = "Sandstorm",
[20] = "Clear sky",
}
self.is_rain = {
[8] = true,
[16] = true,
}
self.blitzAlpha = {
[1] = 0,
[2] = 0,
[3] = 0,
}
-- Funktionen
self.blitzAddFunc = function() self:AddRandomBlitz() end;
-- Events
-- outputDebugString("[CALLING] HudComponent_Weather: Constructor");
end
-- EVENT HANDLER --
|
--By naschemaa and nathhhknowledge.
--JUST THE SCRIPT (NEED HELP=Private Message)
ragdolldeath = true
cantouchkill = false
debugmode = false
canchase = true
chasing = false
amount = 0
speed = 0.6
heartbeat = game:GetService("RunService").Heartbeat
pathfindingser = game:GetService("PathfindingService")
scphead = script.Parent
hitbox = script.Parent.Hitbox
deathsound = script.Parent.Death
killsound = script.Parent.Kill
jumpscaresounds = {scphead.Jumpscare,scphead.Jumpscare2,scphead.Jumpscare3,scphead.Jumpscare4,scphead.Jumpscare5,scphead.Jumpscare6}
concretemovesound = script.Parent["Concrete Moving"]
canjumpscare = false
distance = 120
function checkhowmanycharactersseeme()
while heartbeat:wait() do
amount = 0
for i,v in pairs(workspace:GetChildren()) do
if v.ClassName == "Model" then
local characterhumanoid = v:findFirstChildOfClass("Humanoid")
local characterscpdet = v:findFirstChild("SCPDetection")
local characterhead = v:findFirstChild("Head")
if characterhumanoid and characterscpdet then
if characterhumanoid.Health > 0 then
if (characterscpdet.Position - scphead.Position).magnitude < distance then
if characterhead.Orientation.y > characterscpdet.Orientation.y - 90 and characterhead.Orientation.y < characterscpdet.Orientation.y + 90 then
amount = amount + 1
if debugmode then
print(v.Name)
end
else
--do n o t h i n g
end
end
end
end
end
end
if debugmode then
print("people staring at this thing: "..amount)
end
end
end
function adddetectors()
while heartbeat:wait() do
for i,v in pairs(workspace:GetChildren()) do
if v.ClassName == "Model" then
local characterhumanoid = v:findFirstChildOfClass("Humanoid")
local characterhead = v:findFirstChild("Head")
if characterhumanoid and characterhead then
if characterhumanoid.Health <= 0 then
if v:findFirstChild("SCPDetection") then
v:findFirstChild("SCPDetection"):destroy()
end
else
if not v:findFirstChild("SCPDetection") then
local lookpart = Instance.new("Part", v)
lookpart.CanCollide = false
lookpart.Size = Vector3.new(1,1,1)
lookpart.Anchored = true
lookpart.Shape = "Cylinder"
lookpart.Transparency = 1
if debugmode then
lookpart.Transparency = 0
end
lookpart.Name = "SCPDetection"
local deed = false
local function lookatme()
local hed = characterhead
while heartbeat:wait() do
lookpart.CFrame = CFrame.new(hed.Position, scphead.Position)
end
end
spawn(lookatme)
end
end
end
end
end
end
end
function orientation()
while heartbeat:wait() do
scphead.Orientation = Vector3.new(0,scphead.Orientation.y,0)
end
end
function kill(part)
if cantouchkill then
if part.Parent then
local victimhumanoid = part.Parent:findFirstChildOfClass("Humanoid")
if victimhumanoid then
if victimhumanoid.Health > 0 then
killsound:Play()
for i,v in pairs(victimhumanoid.Parent:GetChildren()) do
if v.ClassName == "Script" or v.ClassName == "LocalScript" then
v.Disabled = true
end
end
victimhumanoid.Parent:BreakJoints()
victimhumanoid.Health = 0
if ragdolldeath then
ragdollkill(victimhumanoid.Parent)
end
if scphead:findFirstChild("ChaseWho") then
scphead:findFirstChild("ChaseWho"):destroy()
end
end
end
end
end
end
hitbox.Touched:connect(kill)
going = false
function attack()
while heartbeat:wait() do
if amount == 0 and canchase then
cantouchkill = true
canjumpscare = true
going = true
for i,v in pairs(workspace:GetChildren()) do
if v.ClassName == "Model" and v.Name ~= scphead.Parent.Name then
local characterhumanoid = v:findFirstChildOfClass("Humanoid")
local characterhead = v:findFirstChild("Head")
if characterhumanoid and characterhead then
if characterhumanoid.Health > 0 then
if not scphead:findFirstChild("ChaseWho") then
chasewho = Instance.new("ObjectValue", scphead)
chasewho.Name = "ChaseWho"
chasewho.Value = characterhead
end
if (chasewho.Value.Position - scphead.Position).magnitude < distance then
chasing = true
local path = pathfindingser:FindPathAsync(scphead.Position, chasewho.Value.Position, distance)
local waypoints = path:GetWaypoints()
if path.Status == Enum.PathStatus.Success then
for i,v in pairs(waypoints) do
if i >= 3 then
if amount == 0 then
scphead.Anchored = true
scphead.CFrame = CFrame.new(v.Position)
scphead.CFrame = scphead.CFrame * CFrame.new(0,6.6/2,0)
scphead.CFrame = CFrame.new(scphead.Position, chasewho.Value.Position) * CFrame.fromEulerAnglesXYZ(-0.1,0,0)
concretemovesound.Volume = 2
cantouchkill = true
wait(0.05)
end
end
end
else
scphead.Anchored = false
end
chasing = false
concretemovesound.Volume = 0
else
chasewho:destroy()
chasing = false
end
elseif characterhumanoid.Health <= 0 then
scphead.Anchored = true
chasing = false
end
end
end
end
else
if going then
for i,v in pairs(workspace:GetChildren()) do
if v.ClassName == "Model" then
local characterhumanoid = v:findFirstChildOfClass("Humanoid")
local characterhead = v:findFirstChild("Head")
if characterhumanoid and characterhead then
if characterhumanoid.Health > 0 then
if (characterhead.Position - scphead.Position).magnitude < 20 then
canjumpscare = false
local whatjumpscare = math.random(1,table.getn(jumpscaresounds))
jumpscaresounds[whatjumpscare]:Play()
end
elseif characterhumanoid.Health <= 0 then
--nothing again
end
end
end
end
end
if scphead:findFirstChild("ChaseWho") then
scphead:findFirstChild("ChaseWho"):destroy()
end
cantouchkill = false
scphead.Anchored = true
chasing = false
going = false
concretemovesound.Volume = 0
end
end
end
function ragdollkill(character)
local victimshumanoid = character:findFirstChildOfClass("Humanoid")
if not character:findFirstChild("UpperTorso") then
character.Archivable = true
local ragdoll = character:Clone()
ragdoll:findFirstChildOfClass("Humanoid").Health = 0
if ragdoll:findFirstChild("Health") then
if ragdoll:findFirstChild("Health").ClassName == "Script" then
ragdoll:findFirstChild("Health").Disabled = true
end
end
for i,v in pairs(character:GetChildren()) do
if v.ClassName == "Part" or v.ClassName == "ForceField" or v.ClassName == "Accessory" or v.ClassName == "Hat" then
v:destroy()
end
end
for i,v in pairs(character:GetChildren()) do
if v.ClassName == "Accessory" then
local attachment1 = v.Handle:findFirstChildOfClass("Attachment")
if attachment1 then
for q,w in pairs(character:GetChildren()) do
if w.ClassName == "Part" then
local attachment2 = w:findFirstChild(attachment1.Name)
if attachment2 then
local hinge = Instance.new("HingeConstraint", v.Handle)
hinge.Attachment0 = attachment1
hinge.Attachment1 = attachment2
hinge.LimitsEnabled = true
hinge.LowerAngle = 0
hinge.UpperAngle = 0
end
end
end
end
end
end
ragdoll.Parent = workspace
if ragdoll:findFirstChild("Right Arm") then
local glue = Instance.new("Glue", ragdoll.Torso)
glue.Part0 = ragdoll.Torso
glue.Part1 = ragdoll:findFirstChild("Right Arm")
glue.C0 = CFrame.new(1.5, 0.5, 0, 0, 0, 1, 0, 1, 0, -1, 0, 0)
glue.C1 = CFrame.new(0, 0.5, 0, 0, 0, 1, 0, 1, 0, -1, 0, 0)
local limbcollider = Instance.new("Part", ragdoll:findFirstChild("Right Arm"))
limbcollider.Size = Vector3.new(1.4,1,1)
limbcollider.Shape = "Cylinder"
limbcollider.Transparency = 1
limbcollider.Name = "LimbCollider"
local limbcolliderweld = Instance.new("Weld", limbcollider)
limbcolliderweld.Part0 = ragdoll:findFirstChild("Right Arm")
limbcolliderweld.Part1 = limbcollider
limbcolliderweld.C0 = CFrame.fromEulerAnglesXYZ(0,0,math.pi/2) * CFrame.new(-0.3,0,0)
end
if ragdoll:findFirstChild("Left Arm") then
local glue = Instance.new("Glue", ragdoll.Torso)
glue.Part0 = ragdoll.Torso
glue.Part1 = ragdoll:findFirstChild("Left Arm")
glue.C0 = CFrame.new(-1.5, 0.5, 0, 0, 0, -1, 0, 1, 0, 1, 0, 0)
glue.C1 = CFrame.new(0, 0.5, 0, 0, 0, -1, 0, 1, 0, 1, 0, 0)
local limbcollider = Instance.new("Part", ragdoll:findFirstChild("Left Arm"))
limbcollider.Size = Vector3.new(1.4,1,1)
limbcollider.Shape = "Cylinder"
limbcollider.Name = "LimbCollider"
limbcollider.Transparency = 1
local limbcolliderweld = Instance.new("Weld", limbcollider)
limbcolliderweld.Part0 = ragdoll:findFirstChild("Left Arm")
limbcolliderweld.Part1 = limbcollider
limbcolliderweld.C0 = CFrame.fromEulerAnglesXYZ(0,0,math.pi/2) * CFrame.new(-0.3,0,0)
end
if ragdoll:findFirstChild("Left Leg") then
local glue = Instance.new("Glue", ragdoll.Torso)
glue.Part0 = ragdoll.Torso
glue.Part1 = ragdoll:findFirstChild("Left Leg")
glue.C0 = CFrame.new(-0.5, -1, 0, -0, -0, -1, 0, 1, 0, 1, 0, 0)
glue.C1 = CFrame.new(-0, 1, 0, -0, -0, -1, 0, 1, 0, 1, 0, 0)
local limbcollider = Instance.new("Part", ragdoll:findFirstChild("Left Leg"))
limbcollider.Size = Vector3.new(1.4,1,1)
limbcollider.Shape = "Cylinder"
limbcollider.Name = "LimbCollider"
limbcollider.Transparency = 1
local limbcolliderweld = Instance.new("Weld", limbcollider)
limbcolliderweld.Part0 = ragdoll:findFirstChild("Left Leg")
limbcolliderweld.Part1 = limbcollider
limbcolliderweld.C0 = CFrame.fromEulerAnglesXYZ(0,0,math.pi/2) * CFrame.new(-0.3,0,0)
end
if ragdoll:findFirstChild("Right Leg") then
local glue = Instance.new("Glue", ragdoll.Torso)
glue.Part0 = ragdoll.Torso
glue.Part1 = ragdoll:findFirstChild("Right Leg")
glue.C0 = CFrame.new(0.5, -1, 0, 0, 0, 1, 0, 1, 0, -1, -0, -0)
glue.C1 = CFrame.new(0, 1, 0, 0, 0, 1, 0, 1, 0, -1, -0, -0)
local limbcollider = Instance.new("Part", ragdoll:findFirstChild("Right Leg"))
limbcollider.Size = Vector3.new(1.4,1,1)
limbcollider.Shape = "Cylinder"
limbcollider.Name = "LimbCollider"
limbcollider.Transparency = 1
local limbcolliderweld = Instance.new("Weld", limbcollider)
limbcolliderweld.Part0 = ragdoll:findFirstChild("Right Leg")
limbcolliderweld.Part1 = limbcollider
limbcolliderweld.C0 = CFrame.fromEulerAnglesXYZ(0,0,math.pi/2) * CFrame.new(-0.3,0,0)
end
if ragdoll:findFirstChild("Head") and ragdoll.Torso:findFirstChild("NeckAttachment") then
local HeadAttachment = Instance.new("Attachment", ragdoll["Head"])
HeadAttachment.Position = Vector3.new(0, -0.5, 0)
local connection = Instance.new('HingeConstraint', ragdoll["Head"])
connection.LimitsEnabled = true
connection.Attachment0 = ragdoll.Torso.NeckAttachment
connection.Attachment1 = HeadAttachment
connection.UpperAngle = 60
connection.LowerAngle = -60
elseif ragdoll:findFirstChild("Head") and not ragdoll.Torso:findFirstChild("NeckAttachment") then
local hedweld = Instance.new("Weld", ragdoll.Torso)
hedweld.Part0 = ragdoll.Torso
hedweld.Part1 = ragdoll.Head
hedweld.C0 = CFrame.new(0,1.5,0)
end
game.Debris:AddItem(ragdoll, 30)
elseif character:findFirstChild("UpperTorso") then
character.Archivable = true
local ragdoll = character:Clone()
ragdoll:findFirstChildOfClass("Humanoid").Health = 0
if ragdoll:findFirstChild("Health") then
if ragdoll:findFirstChild("Health").ClassName == "Script" then
ragdoll:findFirstChild("Health").Disabled = true
end
end
for i,v in pairs(character:GetChildren()) do
if v.ClassName == "Part" or v.ClassName == "ForceField" or v.ClassName == "Accessory" or v.ClassName == "Hat" or v.ClassName == "MeshPart" then
v:destroy()
end
end
for i,v in pairs(character:GetChildren()) do
if v.ClassName == "Accessory" then
local attachment1 = v.Handle:findFirstChildOfClass("Attachment")
if attachment1 then
for q,w in pairs(character:GetChildren()) do
if w.ClassName == "Part" or w.ClassName == "MeshPart" then
local attachment2 = w:findFirstChild(attachment1.Name)
if attachment2 then
local hinge = Instance.new("HingeConstraint", v.Handle)
hinge.Attachment0 = attachment1
hinge.Attachment1 = attachment2
hinge.LimitsEnabled = true
hinge.LowerAngle = 0
hinge.UpperAngle = 0
end
end
end
end
end
end
ragdoll.Parent = workspace
local Humanoid = ragdoll:findFirstChildOfClass("Humanoid")
Humanoid.PlatformStand = true
local function makeballconnections(limb, attachementone, attachmenttwo, twistlower, twistupper)
local connection = Instance.new('BallSocketConstraint', limb)
connection.LimitsEnabled = true
connection.Attachment0 = attachementone
connection.Attachment1 = attachmenttwo
connection.TwistLimitsEnabled = true
connection.TwistLowerAngle = twistlower
connection.TwistUpperAngle = twistupper
local limbcollider = Instance.new("Part", limb)
limbcollider.Size = Vector3.new(0.1,1,1)
limbcollider.Shape = "Cylinder"
limbcollider.Transparency = 1
limbcollider:BreakJoints()
local limbcolliderweld = Instance.new("Weld", limbcollider)
limbcolliderweld.Part0 = limb
limbcolliderweld.Part1 = limbcollider
limbcolliderweld.C0 = CFrame.fromEulerAnglesXYZ(0,0,math.pi/2)
end
local function makehingeconnections(limb, attachementone, attachmenttwo, lower, upper)
local connection = Instance.new('HingeConstraint', limb)
connection.LimitsEnabled = true
connection.Attachment0 = attachementone
connection.Attachment1 = attachmenttwo
connection.LimitsEnabled = true
connection.LowerAngle = lower
connection.UpperAngle = upper
local limbcollider = Instance.new("Part", limb)
limbcollider.Size = Vector3.new(0.1,1,1)
limbcollider.Shape = "Cylinder"
limbcollider.Transparency = 1
limbcollider:BreakJoints()
local limbcolliderweld = Instance.new("Weld", limbcollider)
limbcolliderweld.Part0 = limb
limbcolliderweld.Part1 = limbcollider
limbcolliderweld.C0 = CFrame.fromEulerAnglesXYZ(0,0,math.pi/2)
end
local HeadAttachment = Instance.new("Attachment", Humanoid.Parent.Head)
HeadAttachment.Position = Vector3.new(0, -0.5, 0)
makehingeconnections(Humanoid.Parent.Head, HeadAttachment, ragdoll.UpperTorso.NeckAttachment, -50, 50)
makehingeconnections(Humanoid.Parent.LowerTorso, Humanoid.Parent.LowerTorso.WaistRigAttachment, Humanoid.Parent.UpperTorso.WaistRigAttachment, -50, 50)
makeballconnections(Humanoid.Parent.LeftUpperArm, Humanoid.Parent.LeftUpperArm.LeftShoulderRigAttachment, Humanoid.Parent.UpperTorso.LeftShoulderRigAttachment, -200, 200, 180)
makehingeconnections(Humanoid.Parent.LeftLowerArm, Humanoid.Parent.LeftLowerArm.LeftElbowRigAttachment, Humanoid.Parent.LeftUpperArm.LeftElbowRigAttachment, 0, -60)
makehingeconnections(Humanoid.Parent.LeftHand, Humanoid.Parent.LeftHand.LeftWristRigAttachment, Humanoid.Parent.LeftLowerArm.LeftWristRigAttachment, -20, 20)
--
makeballconnections(Humanoid.Parent.RightUpperArm, Humanoid.Parent.RightUpperArm.RightShoulderRigAttachment, Humanoid.Parent.UpperTorso.RightShoulderRigAttachment, -200, 200, 180)
makehingeconnections(Humanoid.Parent.RightLowerArm, Humanoid.Parent.RightLowerArm.RightElbowRigAttachment, Humanoid.Parent.RightUpperArm.RightElbowRigAttachment, 0, -60)
makehingeconnections(Humanoid.Parent.RightHand, Humanoid.Parent.RightHand.RightWristRigAttachment, Humanoid.Parent.RightLowerArm.RightWristRigAttachment, -20, 20)
--
makeballconnections(Humanoid.Parent.RightUpperLeg, Humanoid.Parent.RightUpperLeg.RightHipRigAttachment, Humanoid.Parent.LowerTorso.RightHipRigAttachment, -80, 80, 80)
makehingeconnections(Humanoid.Parent.RightLowerLeg, Humanoid.Parent.RightLowerLeg.RightKneeRigAttachment, Humanoid.Parent.RightUpperLeg.RightKneeRigAttachment, 0, 60)
makehingeconnections(Humanoid.Parent.RightFoot, Humanoid.Parent.RightFoot.RightAnkleRigAttachment, Humanoid.Parent.RightLowerLeg.RightAnkleRigAttachment, -20, 20)
--
makeballconnections(Humanoid.Parent.LeftUpperLeg, Humanoid.Parent.LeftUpperLeg.LeftHipRigAttachment, Humanoid.Parent.LowerTorso.LeftHipRigAttachment, -80, 80, 80)
makehingeconnections(Humanoid.Parent.LeftLowerLeg, Humanoid.Parent.LeftLowerLeg.LeftKneeRigAttachment, Humanoid.Parent.LeftUpperLeg.LeftKneeRigAttachment, 0, 60)
makehingeconnections(Humanoid.Parent.LeftFoot, Humanoid.Parent.LeftFoot.LeftAnkleRigAttachment, Humanoid.Parent.LeftLowerLeg.LeftAnkleRigAttachment, -20, 20)
for i,v in pairs(Humanoid.Parent:GetChildren()) do
if v.ClassName == "Accessory" then
local attachment1 = v.Handle:findFirstChildOfClass("Attachment")
if attachment1 then
for q,w in pairs(Humanoid.Parent:GetChildren()) do
if w.ClassName == "Part" then
local attachment2 = w:findFirstChild(attachment1.Name)
if attachment2 then
local hinge = Instance.new("HingeConstraint", v.Handle)
hinge.Attachment0 = attachment1
hinge.Attachment1 = attachment2
hinge.LimitsEnabled = true
hinge.LowerAngle = 0
hinge.UpperAngle = 0
end
end
end
end
end
end
for i,v in pairs(ragdoll:GetChildren()) do
for q,w in pairs(v:GetChildren()) do
if w.ClassName == "Motor6D"--[[ and w.Name ~= "Neck"--]] then
w:destroy()
end
end
end
if ragdoll:findFirstChild("HumanoidRootPart") then
ragdoll.HumanoidRootPart.Anchored = true
ragdoll.HumanoidRootPart.CanCollide = false
end
game.Debris:AddItem(ragdoll, 30)
end
end
spawn(orientation)
spawn(attack)
spawn(checkhowmanycharactersseeme)
spawn(adddetectors)
|
if package.loaded.luv then
_hx_luv = _G.require("luv");
else
_hx_luv = {
run=function(mode) return false end,
loop_alive=function() return false end
}
end
|
local PluginActions = {}
PluginActions.ProgramActions = require(script.ProgramActions)
PluginActions.PrintTrackPositions = require(script.PrintTrackPositions)
return PluginActions
|
PLAYERSTATS = {}
|
-- local officeWifi = "OnePlus 7T"
-- -- local officeWifi = "clear-corporate"
-- local urlToLoad = "http://1.1.1.1"
-- local browser = "Microsoft Edge Beta"
-- local i = 0
-- local watcher = hs.wifi.watcher.new(function()
-- local ssid = hs.wifi.currentNetwork()
-- -- load the url when office wifi is connected
-- if ssid == officeWifi and i == 0 then
-- i = (i + 1)%2
-- -- wait for few seconds
-- hs.timer.doAfter(3, function()
-- -- load the url
-- hs.execute("open "..urlToLoad)
-- -- lunch or focus the app
-- hs.application.launchOrFocus(browser)
-- end)
-- end
-- end):start()
|
-- uses:
-- default_buf
-- buf
-- ledpin
c = require('config')
f = require('fade')
print("fadesrv:debug: init")
f.init(c.state.numled)
f.set_delay(c.state.fadedelay)
local function handle_request(client,request)
-- print("fadesrv:debug: got connection")
local response = {
"HTTP/1.1 200 OK\r\n",
"Content-Type: text/html\r\n",
"Access-Control-Allow-Origin: *\r\n",
"Connection: close\r\n",
"\r\n" }
local function add(txt)
table.insert(response,txt)
end
local function sender (client)
if #response>0 then
client:send(table.remove(response,1))
else
-- print("fadesrv: closing connection")
client:close()
end
end
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
if(method == nil)then
_, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
end
local _GET = {}
if (vars ~= nil)then
for k, v in string.gmatch(vars, "(%w+)=([%w.]+)&*") do
_GET[k] = v
end
end
-- end preprocessing
local function send_file(f)
file.open(f,"r")
local block = file.read(1024)
while block do
add( block )
block = file.read(1024)
end
file.close()
end
if path == '/' then
local ip,_,_=wifi.sta.getip()
send_file('static/head.html')
add("<div class='list-group'>")
function send_item(a,b)
add(string.format(
"<a href='#' class='list-group-item'>%s: <b>%s</b></a>\n",
a,b))
end
send_item("IP",ip)
send_item("MAC",wifi.sta.getmac())
send_item("Uptime",
string.format("%d seconds",tmr.time()))
send_item("Heap",
string.format("%d bytes",node.heap()))
add("</div>")
send_file('static/end.html')
elseif path == '/code.js' then
send_file('static/code.js')
elseif path == '/on' then
f:fade_color(c.state.on_color)
add("LEDs are now on")
elseif path == '/off' then
-- TODO
f:fade_color(c.state.off_color)
add("LEDs are now off")
elseif path == '/save' then
add("saving config")
c:save()
elseif path == '/fadedelay' then
local delay = tonumber(_GET.ms or c.state.fadedelay)
add("setting fade delay to ".. delay)
f.set_delay(delay)
c.state.fadedelay = delay
elseif path == '/numled' then
local numled = tonumber(_GET.v or c.state.numled)
add("setting numled to ".. numled)
f.init(numled)
c.state.numled = numled
elseif path == '/mode' then
local mode = _GET.id or "single"
add("setting mode delay to ".. mode)
c.state.mode = mode
elseif path == '/color' then
local r = tonumber(_GET.r or 0)
local g = tonumber(_GET.g or 0)
local b = tonumber(_GET.b or 0)
c.state.on_color = {r,g,b}
add("setting LEDS to ("..r..","..g..","..b..")")
f:fade_color(c.state.on_color)
elseif path == '/getcolor' then
add(cjson.encode(c.state.on_color))
elseif path == '/restart' then
add("bye")
node.restart()
else
add("unknown path "..path)
end
-- print("starting sender")
client:on("sent", sender)
sender(client)
-- collectgarbage()
end
srv=net.createServer(net.TCP,30)
srv:listen(80,function(conn)
conn:on("receive", handle_request)
end)
|
help(
[[
This module loads Expat 2.1.0
Expat is a library for parsing XML documents
]])
whatis("Loads expat libraries which provide support for parsing XML documents")
local version = "2.1.0"
local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/expat/"..version
prepend_path("LD_LIBRARY_PATH", pathJoin(base, "lib"))
prepend_path("CPATH", pathJoin(base, "include"))
prepend_path("LIBRARY_PATH", pathJoin(base, "lib"))
family('expat')
|
-- Pretty-Printed using HW2 Pretty-Printer 1.21 by Mikail.
-- LuaDC version 0.9.19
-- 5/23/2004 7:23:40 PM
-- LuaDC by Age2uN
-- on error send source file (compiled lua) and this outputfile to Age2uN@gmx.net
--
Ship = 0
SubSystem = 1
build =
{
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Production_Fighter",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 0,
DisplayedName = "$7000",
Description = "$7001",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Production_Fighter",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 0,
DisplayedName = "$7000",
Description = "$7001",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Production_Corvette",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 0,
DisplayedName = "$7002",
Description = "$7003",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Production_Corvette",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 0,
DisplayedName = "$7002",
Description = "$7003",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Production_Frigate",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 0,
DisplayedName = "$7004",
Description = "$7005",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Production_Frigate",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 0,
DisplayedName = "$7004",
Description = "$7005",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Production_CapShip",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 0,
DisplayedName = "$7006",
Description = "$7007",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_SY_Production_CapShip",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 0,
DisplayedName = "$7006",
Description = "$7007",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Module_PlatformControl",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 10,
DisplayedName = "$7008",
Description = "$7009",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Module_PlatformControl",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 20,
DisplayedName = "$7008",
Description = "$7009",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Module_Research",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 0,
DisplayedName = "$7010",
Description = "$7011",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Module_Research",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 0,
DisplayedName = "$7010",
Description = "$7011",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Module_ResearchAdvanced",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 10,
DisplayedName = "$7012",
Description = "$7013",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Module_ResearchAdvanced",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 10,
DisplayedName = "$7012",
Description = "$7013",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Module_Hyperspace",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 30,
DisplayedName = "$7014",
Description = "$7015",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Module_Hyperspace",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 30,
DisplayedName = "$7014",
Description = "$7015",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Module_HyperspaceInhibitor",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 40,
DisplayedName = "$7016",
Description = "$7017",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Module_HyperspaceInhibitor",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 40,
DisplayedName = "$7016",
Description = "$7017",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Module_CloakGenerator",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 50,
DisplayedName = "$7018",
Description = "$7019",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Module_CloakGenerator",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 50,
DisplayedName = "$7018",
Description = "$7019",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Module_FireControl",
RequiredResearch = "",
RequiredFleetSubSystems = "AdvancedResearch",
DisplayPriority = 60,
DisplayedName = "$7020",
Description = "$7021",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Module_FireControl",
RequiredResearch = "",
RequiredFleetSubSystems = "AdvancedResearch",
DisplayPriority = 60,
DisplayedName = "$7020",
Description = "$7021",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Sensors_DetectHyperspace",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 150,
DisplayedName = "$7036",
Description = "$7037",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Sensors_DetectHyperspace",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 150,
DisplayedName = "$7036",
Description = "$7037",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Sensors_AdvancedArray",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 151,
DisplayedName = "$7022",
Description = "$7023",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Sensors_AdvancedArray",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 151,
DisplayedName = "$7022",
Description = "$7023",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Sensors_DetectCloaked",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 152,
DisplayedName = "$7024",
Description = "$7025",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Sensors_DetectCloaked",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 152,
DisplayedName = "$7024",
Description = "$7025",
},
{
Type = Ship,
ThingToBuild = "Kpr_Mover",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 53,
DisplayedName = "$7913",
Description = "$7914",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Production_CorvetteMover",
RequiredResearch = "",
RequiredShipSubSystems = "CorvetteProduction",
DisplayPriority = 10,
DisplayedName = "$7910",
Description = "$7911",
},
{
Type = Ship,
ThingToBuild = "Hgn_Scout",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 10,
DisplayedName = "$7030",
Description = "$7031",
},
{
Type = Ship,
ThingToBuild = "Hgn_Interceptor",
RequiredResearch = "",
RequiredShipSubSystems = "FighterProduction",
DisplayPriority = 20,
DisplayedName = "$7032",
Description = "$7033",
},
{
Type = Ship,
ThingToBuild = "Hgn_AttackBomber",
RequiredResearch = "",
RequiredShipSubSystems = "FighterProduction",
DisplayPriority = 30,
DisplayedName = "$7034",
Description = "$7035",
},
{
Type = Ship,
ThingToBuild = "Hgn_AssaultCorvette",
RequiredResearch = "",
RequiredShipSubSystems = "CorvetteProduction",
DisplayPriority = 50,
DisplayedName = "$7038",
Description = "$7039",
},
{
Type = Ship,
ThingToBuild = "Hgn_PulsarCorvette",
RequiredResearch = "",
RequiredShipSubSystems = "CorvetteProduction",
DisplayPriority = 51,
DisplayedName = "$7040",
Description = "$7041",
},
{
Type = Ship,
ThingToBuild = "Hgn_MinelayerCorvette",
RequiredResearch = "GraviticAttractionMines",
RequiredShipSubSystems = "CorvetteProduction",
DisplayPriority = 52,
DisplayedName = "$7042",
Description = "$7043",
},
{
Type = Ship,
ThingToBuild = "Hgn_DefenseFieldFrigate",
RequiredResearch = "DefenseFieldFrigateShield",
RequiredShipSubSystems = "FrigateProduction",
DisplayPriority = 80,
DisplayedName = "$7044",
Description = "$7045",
},
{
Type = Ship,
ThingToBuild = "Hgn_TorpedoFrigate",
RequiredResearch = "",
RequiredShipSubSystems = "FrigateProduction",
DisplayPriority = 60,
DisplayedName = "$7046",
Description = "$7047",
},
{
Type = Ship,
ThingToBuild = "Hgn_AssaultFrigate",
RequiredResearch = "InstaAdvancedFrigateTech",
RequiredShipSubSystems = "FrigateProduction",
DisplayPriority = 65,
DisplayedName = "$7048",
Description = "$7049",
},
{
Type = Ship,
ThingToBuild = "Hgn_IonCannonFrigate",
RequiredResearch = "InstaAdvancedFrigateTech",
RequiredShipSubSystems = "FrigateProduction",
DisplayPriority = 70,
DisplayedName = "$7050",
Description = "$7051",
},
{
Type = Ship,
ThingToBuild = "Hgn_MarineFrigate",
RequiredResearch = "InstaAdvancedFrigateTech",
RequiredShipSubSystems = "FrigateProduction",
DisplayPriority = 75,
DisplayedName = "$7052",
Description = "$7053",
},
{
Type = Ship,
ThingToBuild = "Hgn_Carrier",
RequiredResearch = "",
RequiredShipSubSystems = "CapShipProduction",
DisplayPriority = 110,
DisplayedName = "$7054",
Description = "$7055",
},
{
Type = Ship,
ThingToBuild = "Hgn_Destroyer",
RequiredResearch = "DestroyerTech",
RequiredShipSubSystems = "CapShipProduction",
DisplayPriority = 116,
DisplayedName = "$7056",
Description = "$7057",
},
{
Type = Ship,
ThingToBuild = "Hgn_Shipyard",
RequiredResearch = "",
RequiredShipSubSystems = "Hyperspace",
DisplayPriority = 117,
DisplayedName = "$7058",
Description = "$7059",
},
{
Type = Ship,
ThingToBuild = "Hgn_Battlecruiser",
RequiredResearch = "BattlecruiserIonWeapons",
RequiredShipSubSystems = "CapShipProduction",
DisplayPriority = 118,
DisplayedName = "$7060",
Description = "$7061",
},
{
Type = Ship,
ThingToBuild = "Hgn_GunTurret",
RequiredResearch = "",
RequiredShipSubSystems = "PlatformProduction",
DisplayPriority = 141,
DisplayedName = "$7062",
Description = "$7063",
},
{
Type = Ship,
ThingToBuild = "Hgn_IonTurret",
RequiredResearch = "PlatformIonWeapons",
RequiredShipSubSystems = "PlatformProduction",
DisplayPriority = 142,
DisplayedName = "$7064",
Description = "$7065",
},
{
Type = Ship,
ThingToBuild = "Hgn_ResourceCollector",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 120,
DisplayedName = "$7066",
Description = "$7067",
},
{
Type = Ship,
ThingToBuild = "Hgn_ResourceController",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 130,
DisplayedName = "$7068",
Description = "$7069",
},
{
Type = Ship,
ThingToBuild = "Hgn_Probe",
RequiredResearch = "",
RequiredShipSubSystems = "",
DisplayPriority = 140,
DisplayedName = "$7070",
Description = "$7071",
},
{
Type = Ship,
ThingToBuild = "Hgn_ProximitySensor",
RequiredResearch = "SensDisProbe",
RequiredShipSubSystems = "",
DisplayPriority = 150,
DisplayedName = "$7072",
Description = "$7073",
},
{
Type = Ship,
ThingToBuild = "Hgn_ECMProbe",
RequiredResearch = "ECMProbe",
RequiredShipSubSystems = "",
DisplayPriority = 160,
DisplayedName = "$7074",
Description = "$7075",
},
{
Type = Ship,
ThingToBuild = "Hgn_Shipyard_SPG",
RequiredResearch = "",
RequiredShipSubSystems = "CapShipProduction",
DisplayPriority = 117,
DisplayedName = "$7058",
Description = "$7059",
},
-- HWC Hacks
{
Type = SubSystem,
ThingToBuild = "Hgn_C_Module_FireControl_nores",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 60,
DisplayedName = "$7020",
Description = "$7021",
},
{
Type = SubSystem,
ThingToBuild = "Hgn_MS_Module_FireControl_nores",
RequiredResearch = "",
RequiredFleetSubSystems = "Research",
DisplayPriority = 60,
DisplayedName = "$7020",
Description = "$7021",
},
{
Type = Ship,
ThingToBuild = "Hgn_Carrier_nores",
RequiredResearch = "",
RequiredShipSubSystems = "CapShipProduction",
DisplayPriority = 110,
DisplayedName = "$7054",
Description = "$7055",
},
{
Type = Ship,
ThingToBuild = "Hgn_Shipyard_nores",
RequiredResearch = "",
RequiredShipSubSystems = "Hyperspace",
DisplayPriority = 117,
DisplayedName = "$7058",
Description = "$7059",
},
{
Type = Ship,
ThingToBuild = "Hgn_Battlecruiser_nores",
RequiredResearch = "BattlecruiserIonWeapons",
RequiredShipSubSystems = "CapShipProduction",
DisplayPriority = 118,
DisplayedName = "$7060",
Description = "$7061",
},
}
|
local E, C, L = select(2, ...):unpack()
----------------------------------------------------------------------------------------
-- Hover Key Bind
----------------------------------------------------------------------------------------
local bind, oneBind, localmacros = CreateFrame("Frame", "HoverBind", UIParent), true, 0
SlashCmdList.MOUSEOVERBIND = function()
if InCombatLockdown() then print(L.ACTIONBAR_BINDING_INCOMBATLOCKDOWN) return end
if not bind.loaded then
bind:SetFrameStrata("DIALOG")
bind:EnableMouse(true)
bind:EnableKeyboard(true)
bind:EnableMouseWheel(true)
bind.texture = bind:CreateTexture()
bind.texture:SetPoint("TOPLEFT", bind, 2, -2)
bind.texture:SetPoint("BOTTOMRIGHT", bind, -2, 2)
bind.texture:SetColorTexture(1, 1, 1, 0.3)
bind:Hide()
local elapsed = 0
GameTooltip:HookScript("OnUpdate", function(self, e)
elapsed = elapsed + e
if elapsed < 0.2 then return else elapsed = 0 end
if not self.comparing and IsModifiedClick("COMPAREITEMS") then
GameTooltip_ShowCompareItem(self)
self.comparing = true
elseif self.comparing and not IsModifiedClick("COMPAREITEMS") then
for _, frame in pairs(self.shoppingTooltips) do
frame:Hide()
end
self.comparing = false
end
end)
hooksecurefunc(GameTooltip, "Hide", function(self) for _, tt in pairs(self.shoppingTooltips) do tt:Hide() end end)
bind:SetScript("OnEvent", function(self) self:Deactivate(false) end)
bind:SetScript("OnLeave", function(self) self:HideFrame() end)
bind:SetScript("OnKeyDown", function(self, key) self:Listener(key) end)
bind:SetScript("OnMouseDown", function(self, key) self:Listener(key) end)
bind:SetScript("OnMouseWheel", function(self, delta) if delta>0 then self:Listener("MOUSEWHEELUP") else self:Listener("MOUSEWHEELDOWN") end end)
function bind:Update(b, spellmacro)
if not self.enabled or InCombatLockdown() then return end
self.button = b
self.spellmacro = spellmacro
self:ClearAllPoints()
self:SetAllPoints(b)
self:Show()
ShoppingTooltip1:Hide()
if spellmacro=="SPELL" then
self.button.id = SpellBook_GetSpellBookSlot(self.button)
self.button.name = GetSpellBookItemName(self.button.id, SpellBookFrame.bookType)
GameTooltip:Show()
GameTooltip:SetScript("OnHide", function(self)
self:SetOwner(bind, "ANCHOR_NONE")
self:SetPoint("BOTTOM", bind, "TOP", 0, 1)
self:AddLine(bind.button.name, 1, 1, 1)
bind.button.bindings = {GetBindingKey(spellmacro.." "..bind.button.name)}
if #bind.button.bindings == 0 then
self:AddLine(L.ACTIONBAR_BINDING_NOBINDING, .6, .6, .6)
else
self:AddDoubleLine(L.ACTIONBAR_BINDING_BINDING, L.ACTIONBAR_BINDING_KEY, .6, .6, .6, .6, .6, .6)
for i = 1, #bind.button.bindings do
self:AddDoubleLine(i, bind.button.bindings[i])
end
end
self:Show()
self:SetScript("OnHide", nil)
end)
elseif spellmacro=="MACRO" then
self.button.id = self.button:GetID()
if localmacros == 1 then self.button.id = self.button.id + MAX_ACCOUNT_MACROS end
self.button.name = GetMacroInfo(self.button.id)
GameTooltip:SetOwner(bind, "ANCHOR_NONE")
GameTooltip:SetPoint("BOTTOM", bind, "TOP", 0, 1)
GameTooltip:AddLine(bind.button.name, 1, 1, 1)
bind.button.bindings = {GetBindingKey(spellmacro.." "..bind.button.name)}
if #bind.button.bindings == 0 then
GameTooltip:AddLine(L.ACTIONBAR_BINDING_NOBINDING, .6, .6, .6)
else
GameTooltip:AddDoubleLine(L.ACTIONBAR_BINDING_BINDING, L.ACTIONBAR_BINDING_KEY, .6, .6, .6, .6, .6, .6)
for i = 1, #bind.button.bindings do
GameTooltip:AddDoubleLine(L.ACTIONBAR_BINDING_BINDING..i, bind.button.bindings[i], 1, 1, 1)
end
end
GameTooltip:Show()
elseif spellmacro=="STANCE" or spellmacro=="PET" then
self.button.id = tonumber(b:GetID())
self.button.name = b:GetName()
if not self.button.name then return end
if not self.button.id or self.button.id < 1 or self.button.id > (spellmacro=="STANCE" and 10 or 12) then
self.button.bindstring = "CLICK "..self.button.name..":LeftButton"
else
self.button.bindstring = (spellmacro=="STANCE" and "SHAPESHIFTBUTTON" or "BONUSACTIONBUTTON")..self.button.id
end
GameTooltip:Show()
GameTooltip:SetScript("OnHide", function(self)
self:SetOwner(bind, "ANCHOR_NONE")
self:SetPoint("BOTTOM", bind, "TOP", 0, 1)
self:AddLine(bind.button.name, 1, 1, 1)
bind.button.bindings = {GetBindingKey(bind.button.bindstring)}
if #bind.button.bindings == 0 then
self:AddLine(L.ACTIONBAR_BINDING_NOBINDING, .6, .6, .6)
else
self:AddDoubleLine(L.ACTIONBAR_BINDING_BINDING, L.ACTIONBAR_BINDING_KEY, .6, .6, .6, .6, .6, .6)
for i = 1, #bind.button.bindings do
self:AddDoubleLine(i, bind.button.bindings[i])
end
end
self:Show()
self:SetScript("OnHide", nil)
end)
else
self.button.action = tonumber(b.action)
self.button.name = b:GetName()
if not self.button.name then return end
if not self.button.action or self.button.action < 1 or self.button.action > 132 then
self.button.bindstring = "CLICK "..self.button.name..":LeftButton"
else
local modact = 1+(self.button.action-1)%12
if self.button.name == "ExtraActionButton1" then
self.button.bindstring = "EXTRAACTIONBUTTON1"
elseif self.button.action < 13 or self.button.action > 72 then
self.button.bindstring = "ACTIONBUTTON"..modact
elseif self.button.action < 73 and self.button.action > 60 then
self.button.bindstring = "MULTIACTIONBAR1BUTTON"..modact
elseif self.button.action < 61 and self.button.action > 48 then
self.button.bindstring = "MULTIACTIONBAR2BUTTON"..modact
elseif self.button.action < 49 and self.button.action > 36 then
self.button.bindstring = "MULTIACTIONBAR4BUTTON"..modact
elseif self.button.action < 37 and self.button.action > 24 then
self.button.bindstring = "MULTIACTIONBAR3BUTTON"..modact
elseif self.button.action < 25 and self.button.action > 12 then
self.button.bindstring = "CLICK "..self.button.name..":LeftButton"
end
end
GameTooltip:AddLine(bind.button.name)
GameTooltip:Show()
bind.button.bindings = {GetBindingKey(bind.button.bindstring)}
GameTooltip:SetScript("OnHide", function(self)
self:SetOwner(bind, "ANCHOR_NONE")
self:SetPoint("BOTTOM", bind, "TOP", 0, 1)
self:AddLine(bind.button.name, 1, 1, 1)
if #bind.button.bindings == 0 then
self:AddLine(L.ACTIONBAR_BINDING_NOBINDING, .6, .6, .6)
else
self:AddDoubleLine(L.ACTIONBAR_BINDING_BINDING, L.ACTIONBAR_BINDING_KEY, .6, .6, .6, .6, .6, .6)
for i = 1, #bind.button.bindings do
self:AddDoubleLine(i, bind.button.bindings[i])
end
end
self:Show()
self:SetScript("OnHide", nil)
end)
end
end
function bind:Listener(key)
if GetBindingKey(key) == "OPENCHAT" then
DEFAULT_CHAT_FRAME.editBox:Show()
return
end
if GetBindingByKey(key) == "SCREENSHOT" then
RunBinding("SCREENSHOT")
return
end
if #self.button.bindings > 0 and oneBind then
for i = 1, #self.button.bindings do
SetBinding(self.button.bindings[i])
end
self:Update(self.button, self.spellmacro)
if self.spellmacro ~= "MACRO" then GameTooltip:Hide() end
end
if key == "ESCAPE" or key == "RightButton" then
for i = 1, #self.button.bindings do
SetBinding(self.button.bindings[i])
end
print(string.format(L.ACTIONBAR_BINDING_ALLCLEAR, self.button.name))
self:Update(self.button, self.spellmacro)
if self.spellmacro~="MACRO" then GameTooltip:Hide() end
return
end
if key == "LSHIFT" or key == "RSHIFT" or key == "LCTRL" or key == "RCTRL" or key == "LALT"
or key == "RALT" or key == "UNKNOWN" or key == "LeftButton" then return end
if key == "MiddleButton" then key = "BUTTON3" end
if key:find("Button%d") then key = key:upper() end
local alt = IsAltKeyDown() and "ALT-" or ""
local ctrl = IsControlKeyDown() and "CTRL-" or ""
local shift = IsShiftKeyDown() and "SHIFT-" or ""
if not self.spellmacro or self.spellmacro=="PET" or self.spellmacro=="STANCE" then
SetBinding(alt..ctrl..shift..key, self.button.bindstring)
else
SetBinding(alt..ctrl..shift..key, self.spellmacro.." "..self.button.name)
end
print(string.format(L.ACTIONBAR_BINDING_BINDTO, alt..ctrl..shift..key, self.button.name))
self:Update(self.button, self.spellmacro)
if self.spellmacro~="MACRO" then GameTooltip:Hide() end
end
function bind:HideFrame()
self:ClearAllPoints()
self:Hide()
GameTooltip:Hide()
end
function bind:Activate()
self.enabled = true
self:RegisterEvent("PLAYER_REGEN_DISABLED")
end
function bind:Deactivate(save)
local which = GetCurrentBindingSet()
if save then
SaveBindings(2)
print(L.ACTIONBAR_BINDING_SAVE)
else
LoadBindings(2)
print(L.ACTIONBAR_BINDING_DISCARDED)
end
self.enabled = false
self:HideFrame()
self:UnregisterEvent("PLAYER_REGEN_DISABLED")
StaticPopup_Hide("KEYBIND_MODE")
end
StaticPopupDialogs["KEYBIND_MODE"] = {
text = L.ACTIONBAR_BINDING_MODETEXT,
button1 = L.ACTIONBAR_BINDING_SAVEBTN,
button2 = L.ACTIONBAR_BINDING_DISCARDEBTN,
OnAccept = function() bind:Deactivate(true) end,
OnCancel = function() bind:Deactivate(false) end,
timeout = 0,
whileDead = 1,
hideOnEscape = false,
preferredIndex = 5,
}
-- REGISTERING
for i = 1, 12 do
local b = _G["ActionButton"..i]
b:HookScript("OnEnter", function(self) bind:Update(self) end)
b = _G["MultiBarBottomLeftButton"..i]
b:HookScript("OnEnter", function(self) bind:Update(self) end)
b = _G["MultiBarLeftButton"..i]
b:HookScript("OnEnter", function(self) bind:Update(self) end)
b = _G["MultiBarRightButton"..i]
b:HookScript("OnEnter", function(self) bind:Update(self) end)
b = _G["MultiBarBottomRightButton"..i]
b:HookScript("OnEnter", function(self) bind:Update(self) end)
end
for i = 1, NUM_STANCE_SLOTS do
local b = _G["StanceButton"..i]
b:HookScript("OnEnter", function(self) bind:Update(self, "STANCE") end)
end
for i = 1, NUM_PET_ACTION_SLOTS do
local b = _G["PetActionButton"..i]
b:HookScript("OnEnter", function(self) bind:Update(self, "PET") end)
end
for i=1,12 do
local b = _G["SpellButton"..i]
b:HookScript("OnEnter", function(self) bind:Update(self, "SPELL") end)
end
ExtraActionButton1:HookScript("OnEnter", function(self) bind:Update(self) end)
local function registermacro()
for i = 1, MAX_ACCOUNT_MACROS do
local b = _G["MacroButton"..i]
b:HookScript("OnEnter", function(self) bind:Update(self, "MACRO") end)
end
MacroFrameTab1:HookScript("OnMouseUp", function() localmacros = 0 end)
MacroFrameTab2:HookScript("OnMouseUp", function() localmacros = 1 end)
end
if not IsAddOnLoaded("Blizzard_MacroUI") then
hooksecurefunc("LoadAddOn", function(addon)
if addon=="Blizzard_MacroUI" then
registermacro()
end
end)
else
registermacro()
end
bind.loaded = 1
end
if not bind.enabled then
bind:Activate()
StaticPopup_Show("KEYBIND_MODE")
end
end
SLASH_MOUSEOVERBIND1 = "/hvb"
|
PLUGIN.name = "Acts"
PLUGIN.author = "Chessnut"
PLUGIN.desc = "Adds acts that can be performed."
PLUGIN.acts = PLUGIN.acts or {}
nut.util.include("sh_setup.lua")
local Entity_Meta = FindMetaTable("Entity")
local Player_GetNetVar = Entity_Meta.getNetVar
for k, v in pairs(PLUGIN.acts) do
local data = {}
local multiple = false
for k2, v2 in pairs(v) do
if (type(v2.sequence) == "table" and #v2.sequence > 1) then
multiple = true
break
end
end
if (multiple) then
data.syntax = "[number type]"
end
data.onRun = function(client, arguments)
if (client.nutSeqUntimed) then
client:setNetVar("actAng")
client:Freeze(false)
client:leaveSequence()
client.nutSeqUntimed = nil
return
end
if (!client:Alive() or
client:setLocalVar("ragdoll")) then
return
end
if ((client.nutNextAct or 0) < CurTime()) then
local class = nut.anim.getModelClass(client:GetModel())
local info = v[class]
if (info) then
if (info.onCheck) then
local result = info.onCheck(client)
if (result) then
return result
end
end
local sequence
if (type(info.sequence) == "table") then
local index = math.Clamp(math.floor(tonumber(arguments[1]) or 1), 1, #info.sequence)
sequence = info.sequence[index]
else
sequence = info.sequence
end
local duration = client:forceSequence(sequence, nil, info.untimed and 0 or nil)
client.nutSeqUntimed = info.untimed
client.nutNextAct = CurTime() + (info.untimed and 4 or duration) + 1
client:setNetVar("actAng", client:GetAngles())
client:Freeze(true)
else
return "@modelNoSeq"
end
end
end
nut.command.add("act"..k, data)
end
function PLUGIN:UpdateAnimation(client, moveData)
local angles = client:getNetVar("actAng")
if (angles) then
client:SetRenderAngles(angles)
end
end
function PLUGIN:OnPlayerLeaveSequence(client)
client:setNetVar("actAng")
client:Freeze(false)
end
function PLUGIN:PlayerDeath(client)
if (client.nutSeqUntimed) then
client:setNetVar("actAng")
client:Freeze(false)
client:leaveSequence()
client.nutSeqUntimed = nil
end
end
function PLUGIN:OnCharFallover(client)
if (client.nutSeqUntimed) then
client:setNetVar("actAng")
client:Freeze(false)
client:leaveSequence()
client.nutSeqUntimed = nil
end
end
function PLUGIN:ShouldDrawLocalPlayer(client)
if (client:getNetVar("actAng")) then
return true
end
end
local GROUND_PADDING = Vector(0, 0, 8)
local PLAYER_OFFSET = Vector(0, 0, 72)
function PLUGIN:CalcView(client, origin, angles, fov)
if (Player_GetNetVar(client, "actAng")) then
local view = {}
local data = {}
data.start = client:GetPos() + PLAYER_OFFSET
data.endpos = data.start - client:EyeAngles():Forward()*72
view.origin = util.TraceLine(data).HitPos + GROUND_PADDING
view.angles = client:EyeAngles()
return view
end
end
function PLUGIN:PlayerBindPress(client, bind, pressed)
if (Player_GetNetVar(client, "actAng")) then
bind = bind:lower()
if (bind:find("+jump") and pressed) then
nut.command.send("actsit")
return true
end
end
end
|
object_tangible_meatlump_event_meatlump_map_01_07 = object_tangible_meatlump_event_shared_meatlump_map_01_07:new {
}
ObjectTemplates:addTemplate(object_tangible_meatlump_event_meatlump_map_01_07, "object/tangible/meatlump/event/meatlump_map_01_07.iff")
|
if not math.sin then dofile("lib-MATH.lua") end
gps={ lat0=0, long0=0}
function gps.Ref(lat, long) -- in degrees
gps.lat0=lat * math.rad
gps.long0=long * math.rad
end
function gps.Distance(lat, long) -- in degrees
local lat1 = lat * math.rad
local long1 = long * math.rad
local R = 6371 -- Radius of the earth in km
local dLat = lat1-gps.lat0
local dLon = long1-gps.long0
local a = math.sin(dLat/2) * math.sin(dLat/2) + math.cos(gps.lat0) * math.cos(lat1) * math.sin(dLon/2) * math.sin(dLon/2)
local c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
local direc = math.atan2(math.sin(dLon)*math.cos(lat1), math.cos(gps.lat0)*math.sin(lat1)-math.sin(gps.lat0)*math.cos(lat1)*math.cos(dLon))
return R*c, ((direc / math.rad) + 360) % 360 -- km, degrees
end
|
-- On Linux We have to query the dependencies of gtk+3 for sr_gui, we do this on the host for now.
if os.ishost("linux") then
listing, code = os.outputof("pkg-config --libs libnotify gtk+-3.0")
liballLibs = string.explode(string.gsub(listing, "-l", ""), " ")
end
workspace("Calco")
-- Configuration.
configurations({ "Release", "Dev"})
location("build")
targetdir ("build/%{prj.name}/%{cfg.longname}")
debugdir ("build/%{prj.name}/%{cfg.longname}")
architecture("x64")
systemversion("latest")
-- Configuration specific settings.
filter("configurations:Release")
defines({ "NDEBUG" })
optimize("On")
filter("configurations:Dev")
defines({ "DEBUG" })
symbols("On")
filter({})
startproject("Calco")
-- Projects
function CommonFlags()
kind("ConsoleApp")
language("C++")
cppdialect("C++17")
-- Compiler flags
filter("toolset:not msc*")
buildoptions({ "-Wall", "-Wextra" })
filter("toolset:msc*")
buildoptions({ "-W3"})
filter({})
-- visual studio filters
filter("action:vs*")
defines({ "_CRT_SECURE_NO_WARNINGS" })
filter({})
end
group("Libs")
-- Include sr_gui and GLFW premake files.
include("libs/sr_gui/premake5.lua")
include("libs/glfw/premake5.lua")
group("Calco")
project("CalcoTool")
CommonFlags()
includedirs({"src/"})
sysincludedirs({ "libs/", "src/libs" })
-- common files
files({"src/core/**", "src/tool/**", "premake5.lua"})
removefiles({"**.DS_STORE", "**.thumbs"})
project("CalcoApp")
CommonFlags()
includedirs({"src/"})
sysincludedirs({ "libs/", "src/libs", "libs/glfw/include/" })
-- common files
files({"src/core/**", "src/libs/**.hpp", "src/libs/*/*.cpp", "src/libs/**.h", "src/libs/*/*.c", "src/app/**", "premake5.lua"})
removefiles({"**.DS_STORE", "**.thumbs"})
-- per platform files
filter("system:windows")
files({"resources/windows/*"})
filter({})
links({"sr_gui", "glfw3"})
-- Libraries for each platform.
filter("system:macosx")
links({"OpenGL.framework", "Cocoa.framework", "IOKit.framework", "CoreVideo.framework", "AppKit.framework"})
filter("system:windows")
links({"opengl32", "User32", "Comdlg32", "Comctl32", "runtimeobject"})
filter("system:linux")
links({"GL", "X11", "Xi", "Xrandr", "Xxf86vm", "Xinerama", "Xcursor", "Xext", "Xrender", "Xfixes", "xcb", "Xau", "Xdmcp", "rt", "m", "pthread", "dl", liballLibs})
filter({})
newaction {
trigger = "clean",
description = "Clean the build directory",
execute = function ()
print("Cleaning...")
os.rmdir("./build")
print("Done.")
end
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.