content
stringlengths 5
1.05M
|
|---|
-- highlight on yank
vim.api.nvim_exec(
[[
augroup YankHighlight
autocmd!
autocmd TextYankPost * silent! lua vim.highlight.on_yank()
augroup end
]],
false
)
-- Y yank until the end of line (note: this is now a default on master)
vim.api.nvim_set_keymap('n', 'Y', 'y$', { noremap = true })
|
SPECIAL_MSGTYPE_REFRESHACTORLIST = "refreshactorlist";
SPECIAL_MSGTYPE_REFRESHINITSLOTLIST = "refreshinitslotlist";
SPECIAL_MSGTYPE_ADDTOINITSLOT = "clientaddtoinitslot";
SPECIAL_MSGTYPE_NEXTACTOR = "clientnextactor";
local actorlistnode = nil;
local actorlistcontrol = nil;
local initslotlistcontrol = nil;
local initslotlistnode = nil;
local activeinitslotnode = nil;
local actedthisroundlist = {};
function onInit()
-- if host then create the actor list node and subscribe to user logins
if User.isHost() then
-- create the actor list node
actorlistnode = DB.createNode("initiativetracker.actors");
-- Create the init slot list node
initslotlistnode = DB.createNode("initiativetracker.initslots");
-- Create the indicator for the currently active init slot class (npc or charsheet) - used to control the addtoinitslot button state
--initslotlistnode.createChild("..activeslotclass", "string");
--DB.createNode("initiativetracker.activeslotclass", "string");
local activeslotnode = DB.createNode("initiativetracker.activeslotclass");
--Debug.console("initiativemanager.lua:onInit() - activeslotnode = " .. activeslotnode.getNodeName());
activeslotnode.createChild("slotactiveclass", "string").setValue("blank");
activeslotnode.createChild("slotactiveactornode", "string").setValue("blank");
--Debug.console("initiativemanager.lua:onInit() - activeslotnode.getValue = " .. activeslotnode.getChild("slotactiveclass").getValue());
getActiveInitSlot();
-- subscribe to the login events
User.onLogin = onLogin;
-- subscribe to module changes
-- Trenloe - not sure why these are needed - these initiate cleaning the actor list when modules are activated/deactivated - shouldn't be needed??? Or, do these cause module state persisting?
Module.onModuleAdded = onModuleAdded;
Module.onModuleRemoved = onModuleRemoved;
Module.onModuleUpdated = onModuleUpdated;
-- Build actedthisroundlist table
buildActedThisRound();
end
-- register special messages
ChatManager.registerSpecialMessageHandler(SPECIAL_MSGTYPE_REFRESHACTORLIST, handleRefreshActorList);
ChatManager.registerSpecialMessageHandler(SPECIAL_MSGTYPE_REFRESHINITSLOTLIST, handleRefreshInitSlotList);
ChatManager.registerSpecialMessageHandler(SPECIAL_MSGTYPE_ADDTOINITSLOT, handleClientAddToInitSlot);
ChatManager.registerSpecialMessageHandler(SPECIAL_MSGTYPE_NEXTACTOR, handleNextActor);
end
function clientAddToInitSlot(actornode)
msg = {};
msg[1] = actornode.getNodeName();
ChatManager.sendSpecialMessage(SPECIAL_MSGTYPE_ADDTOINITSLOT, msg);
end
function handleClientAddToInitSlot(msguser, msgidentity, msgparams)
if User.isHost() then
local actornodename = msgparams[1];
local actornode = DB.findNode(actornodename);
if actornode then
addToInitSlot(actornode);
end
end
end
function onLogin(username, activated)
-- if User.isHost() and activated then
-- add the user as a holder of the initiative tracker node
-- DB.findNode("initiativetracker").addHolder(username);
-- add the user as a holder for each of the source nodes
-- for k, v in pairs(actorlistnode.getChildren()) do
-- local recordnode = v.getChild("actor.recordname");
-- if recordnode then
-- local sourcenode = DB.findNode(recordnode.getValue());
-- if sourcenode then
-- sourcenode.createChild("actor.active", "number").addHolder(username);
-- sourcenode.createChild("actor.initiative", "number").addHolder(username);
-- sourcenode.createChild("name", "string").addHolder(username);
-- end
-- end
-- end
-- end
end
function registerControl(control)
--Debug.console("InitiativeManager.registerControl - control name = " .. control.getName());
if control.getName() == "trackerinitslotlist" then
initslotlistcontrol = control;
handleRefreshInitSlotList();
else
actorlistcontrol = control;
handleRefreshActorList();
end
end
function addInitSlot(classname, recordname)
Debug.console("addInitSlot - classname = " .. classname .. ", recordname = " .. recordname);
-- Add a new init slot - called from addActor.
if initslotlistcontrol then
-- ensure that we have the initslot list node
if not initslotlistnode then
initslotlistnode = DB.findNode("initiativetracker.initslots");
end
--Debug.console("handleRefreshActorList. initslotlistnode = " .. initslotlistnode.getName());
--initslotlistcontrol.createWindowWithClass("initslotempty", n);
-- add the actor
local sourcenode = DB.findNode(recordname);
--Debug.console("addInitSlot - sourcenode = " .. sourcenode.getNodeName());
if sourcenode then
-- create the actor node
local initslotnode = initslotlistnode.createChild();
initslotnode.createChild("actor.classname", "string").setValue(classname);
-- if the sourcenode is static, then the actor node is the source
if sourcenode.isStatic() then
-- create the active, initiative, and name nodes for the actor
initslotnode.createChild("actor.active", "number").setValue(0);
initslotnode.createChild("actor.initiative", "number").setValue(0);
initslotnode.createChild("name", "string");
-- copy the details of the static node
--DatabaseManager.copyNode(sourcenode, actornode);
else
-- create the record name node for the actor
initslotnode.createChild("actor.recordname", "string").setValue(recordname);
initslotnode.createChild("actor.initiative", "number").setValue(0);
if classname == "charsheet" then
initslotnode.createChild("initslotname", "string").setValue("Player Party Slot");
elseif classname == "npc" then
initslotnode.createChild("initslotname", "string").setValue("GM NPC Slot");
end
-- add all users as a holder
for k, v in ipairs(UserManager.getCurrentUsers()) do
initslotnode.addHolder(v);
end
end
--Debug.console("addInitSlot - adding window class with sourcenode of " .. initslotnode.getNodeName());
initslotlistcontrol.createWindowWithClass("initslotempty", initslotnode);
refreshInitSlotList();
end
end
end
function unregisterControl(control)
if control then
--Debug.console("InitiativeManager.unregisterControl - control name = " .. control.getName());
if control.getName() == "trackerinitslotlist" then
initslotlistcontrol = nil;
else
actorlistcontrol = nil;
end
end
end
function refreshActorList()
ChatManager.sendSpecialMessage(SPECIAL_MSGTYPE_REFRESHACTORLIST, {});
end
function handleRefreshActorList(msguser, msgidentity, msgparams)
if actorlistcontrol then
-- ensure that we have the actor list node
if not actorlistnode then
actorlistnode = DB.findNode("initiativetracker.actors");
end
--Debug.console("handleRefreshActorList. actorlistnode = " .. actorlistnode.getName());
-- add any new windows. Step through database actorlist node and compare nodes with windows in windowlist actorlistcontrol
for k, n in pairs(actorlistnode.getChildren()) do
local exists = false;
for i, w in ipairs(actorlistcontrol.getWindows()) do
local recordnode = n.getChild("actor.recordname");
if recordnode then
if w.getDatabaseNode().getNodeName() == recordnode.getValue() then
exists = true;
end
else
if w.getDatabaseNode().getNodeName() == n.getNodeName() then
exists = true;
end
end
end
if not exists then
local classnode = n.getChild("actor.classname");
local recordnode = n.getChild("actor.recordname");
if recordnode then
Debug.console("handleRefreshActorList - looking to add record to actorlistcontrol: " .. recordnode.getValue());
local sourcenode = DB.findNode(recordnode.getValue());
if sourcenode then
actorlistcontrol.createWindowWithClass("actor" .. classnode.getValue(), sourcenode);
else
Debug.console("handleRefreshActorList - Cannot add " .. recordnode.getValue() .. " to actor list. DB.findNode returns nil");
end
else
actorlistcontrol.createWindowWithClass("actor" .. classnode.getValue(), n);
end
end
end
-- remove any deleted windows
for i, w in ipairs(actorlistcontrol.getWindows()) do
local exists = false;
for k, n in pairs(actorlistnode.getChildren()) do
local recordnode = n.getChild("actor.recordname");
if recordnode then
if w.getDatabaseNode().getNodeName() == recordnode.getValue() then
exists = true;
end
else
if w.getDatabaseNode().getNodeName() == n.getNodeName() then
exists = true;
end
end
end
if not exists then
--Debug.console("handleRefreshActorList - removing window for actor: " .. k);
w.close();
end
end
end
return true;
end
function refreshInitSlotList()
--Debug.console("refreshInitSlotList - starting");
ChatManager.sendSpecialMessage(SPECIAL_MSGTYPE_REFRESHINITSLOTLIST, {});
end
function handleRefreshInitSlotList(msguser, msgidentity, msgparams)
Debug.console("handleRefreshInitSlotList - starting");
--if Interface.findWindow("initiativetracker","initiativetracker") then
--Debug.console("handleRefreshInitSlotList - initiative tracker window open.");
if initslotlistcontrol then
-- ensure that we have the actor list node
if not initslotlistnode then
initslotlistnode = DB.findNode("initiativetracker.initslots");
end
--Debug.console("handleRefreshInitSlotList. initslotlistnode = " .. initslotlistnode.getNodeName());
-- add any new windows
if initslotlistcontrol.getWindowCount() then
for k, n in pairs(initslotlistnode.getChildren()) do
--Debug.console("handleRefreshInitSlotList - stepping through initslot children: " .. n.getNodeName());
local exists = false;
--Debug.console("handleRefreshInitSlotList - about to call initslotlistcontrol.getWindows(), total windows to get : " .. initslotlistcontrol.getWindowCount());
if initslotlistcontrol.getWindowCount() > 0 then
for i, w in pairs(initslotlistcontrol.getWindows()) do
--Debug.console("handleRefreshInitSlotList - stepping through initslot control windows: " .. i);
local recordnode = n.getChild("actor.recordname");
--Debug.console("handleRefreshInitSlotList - w.getDatabaseNode().getNodeName() = " .. w.getDatabaseNode().getNodeName());
if recordnode then
--Debug.console("handleRefreshInitSlotList - about to call w.getDatabaseNode().getChild(actor.recordname).");
--if w.getDatabaseNode().getNodeName() == recordnode.getValue() then
local windowdbnode = w.getDatabaseNode().getChild("actor.recordname");
if windowdbnode then
--Debug.console("handleRefreshInitSlotList - have a windowdbnode of: " .. windowdbnode.getNodeName());
if windowdbnode.getNodeName() == recordnode.getNodeName() then
exists = true;
end
end
else
if w.getDatabaseNode().getNodeName() == n.getNodeName() then
exists = true;
end
end
end
end
--Debug.console("handleRefreshInitSlotList. After stepping through initslot control windows.");
if not exists then
local classnode = n.getChild("actor.classname");
local recordnode = n.getChild("actor.recordname");
if recordnode then
local initslotnode = n;
if initslotnode then
--Debug.console("handleRefreshInitSlotList - adding window class with sourcenode of initslotnode = " .. initslotnode.getNodeName());
--addInitSlot(classnode.getValue(), recordnode.getValue());
initslotlistcontrol.createWindowWithClass("initslotempty", initslotnode);
--Debug.console("handleRefreshInitSlotList - after createWindowWithClass.");
end
else
--Debug.console("handleRefreshInitSlotList - adding window class with sourcenode of n = " .. n.getNodeName());
initslotlistcontrol.createWindowWithClass("initslotempty", n);
end
end
end
end
--Debug.console("handleRefreshInitSlotList - about to remove deleted windows from the list.");
-- remove any deleted windows
for i, w in ipairs(initslotlistcontrol.getWindows()) do
local exists = false;
for k, n in pairs(initslotlistnode.getChildren()) do
local recordnode = n.getChild("actor.recordname");
if recordnode then
if w.getDatabaseNode().getChild("actor.recordname").getNodeName() == recordnode.getNodeName() then
exists = true;
end
else
if w.getDatabaseNode().getNodeName() == n.getNodeName() then
exists = true;
end
end
end
if not exists then
w.close();
end
end
end
--Debug.console("handleRefreshInitSlotList - ending - about to call getActiveInitSlot()");
getActiveInitSlot();
--Debug.console("handleRefreshInitSlotList - returning true.");
--end
return true;
end
function removeInitSlot(sourcenode)
if User.isHost() then
--Debug.console("removeInitSlot - starting. Sourcenode = " .. sourcenode.getNodeName());
for k, v in pairs(initslotlistnode.getChildren()) do
--local recordnode = v.getChild("actor.recordname");
if recordnode then
if sourcenode.getNodeName() == v.getNodeName() then
v.delete();
break;
end
else
if sourcenode.getNodeName() == v.getNodeName() then
v.delete();
break;
end
end
end
--refreshActorList();
refreshInitSlotList();
end
end
function onDrop(x, y, draginfo)
if User.isHost() then
if draginfo.isType("playercharacter") or draginfo.isType("partyidentity") or draginfo.isType("npc") or draginfo.isType("retainer") or draginfo.isType("shortcut") then
local classname, recordname = draginfo.getShortcutData();
--Debug.console("initiativemanager.lua:onDrop. Classname = " .. classname .. ", recordname = " .. recordname);
if classname == "partysheet" then
return addParty(classname, recordname);
elseif classname == "npcgroup" then
return addNpcGroup(classname, recordname);
elseif classname == "charsheet" or classname == "npc" or classname == "pet" or classname == "horse" or classname == "retainer" then
return addActor(classname, recordname);
end
end
end
return false;
end
function addParty(classname, recordname)
if User.isHost() then
for k,v in pairs(User.getAllActiveIdentities()) do
addActor("charsheet", "charsheet." .. v, false);
end
return true;
end
return false;
end
function addNpcGroup(classname, recordname)
if User.isHost() then
local npcgroupnode = DB.findNode(recordname);
if npcgroupnode then
for k,v in pairs(npcgroupnode.createChild("npcs").getChildren()) do
addActor("npc", v.getNodeName(), false);
end
return true;
end
end
return false;
end
function addActor(classname, recordname)
if User.isHost() then
-- ensure that the actor does not already exist - only do this for PCs
if classname == "charsheet" then
for k, v in pairs(actorlistnode.getChildren()) do
local recordnode = v.getChild("actor.recordname");
if recordnode and recordnode.getValue() == recordname then
return false;
end
end
end
-- add the actor
local sourcenode = DB.findNode(recordname);
local newNPCName = "";
if sourcenode then
Debug.console("Record class = " .. classname);
-- If an NPC - get the new NPC name - appending a number if it exists already.
if classname == "npc" then
newNPCName = getActorNPCName(sourcenode);
end
-- create the actor node
local actornode = actorlistnode.createChild();
actornode.createChild("actor.classname", "string").setValue(classname);
-- if the sourcenode is static (cannot be edited, from a module, etc.), then the actor node is the source
if sourcenode.isStatic() then
-- create the active, initiative, and name nodes for the actor
actornode.createChild("actor.active", "number").setValue(0);
actornode.createChild("actor.initiative", "number").setValue(0);
actornode.createChild("name", "string");
-- copy the details of the static node
DatabaseManager.copyNode(sourcenode, actornode);
else
if classname == "charsheet" then
-- create the record name node for the actor - this is a link.
actornode.createChild("actor.recordname", "string").setValue(recordname);
recordname = actornode.getNodeName();
elseif classname == "npc" then
-- Copy the node
DB.copyNode(sourcenode, actornode);
-- set the new name
actornode.getChild("name").setValue(newNPCName);
recordname = actornode.getNodeName();
Debug.console("Actornode recordname = " .. recordname);
end
-- add the active, initiative, and name nodes to the source
local activenode = sourcenode.createChild("actor.active", "number");
activenode.setValue(0);
local initiativenode = sourcenode.createChild("actor.initiative", "number");
initiativenode.setValue(0);
local namenode = sourcenode.createChild("name", "string");
-- add all users as a holder
for k, v in ipairs(UserManager.getCurrentUsers()) do
activenode.addHolder(v);
initiativenode.addHolder(v);
namenode.addHolder(v);
end
end
addInitSlot(classname, recordname);
-- refresh the actor node list
refreshActorList();
-- and return
return true;
end
end
return false;
end
function getActorNPCName(sourcenode)
-- Looks for other instances of the same NPC name in the actor list and returns a new name with the next numeric at the end.
local npcName = sourcenode.getChild("name").getValue();
local newNPCName = npcName;
Debug.console("Running getActorNPCName, name = " .. npcName);
local actorlistNode = DB.findNode("initiativetracker.actors");
if actorlistNode then
local isMatch = false;
local nNextNumber = 1;
for k, v in pairs(actorlistnode.getChildren()) do
Debug.console("Processing actor " .. k);
if v.getChild("actor.classname").getValue() == "npc" then
local actorName = v.getChild("name").getValue();
Debug.console("Comparing actorName " .. actorName .. " with npcName " .. npcName);
if actorName == npcName then
-- We already have an actor with the same name.
isMatch = true;
break;
end
end
end
if isMatch then
repeat
-- We already have an actor with the same name - work out which number to add on the end.
newNPCName = npcName .. " " .. nNextNumber;
isMatch = false;
for k, v in pairs(actorlistnode.getChildren()) do
Debug.console("Processing actor " .. k);
if v.getChild("actor.classname").getValue() == "npc" then
local actorName = v.getChild("name").getValue();
Debug.console("Comparing actorName " .. actorName .. " with npcName " .. newNPCName);
if actorName == newNPCName then
-- We already have an actor with the same name.
isMatch = true;
break;
end
end
end
nNextNumber = nNextNumber + 1;
until not isMatch
end
end
Debug.console("End of getActorNPCName, name = " .. npcName);
return newNPCName;
end
function removeActor(sourcenode)
if User.isHost() then
for k, v in pairs(actorlistnode.getChildren()) do
local recordnode = v.getChild("actor.recordname");
if recordnode then
if sourcenode.getNodeName() == recordnode.getValue() then
-- clear init values in base record
local baseactornode = sourcenode.getChild("actor");
if baseactornode then
baseactornode.getChild("active").setValue(0);
baseactornode.getChild("boost_dice").setValue(0);
baseactornode.getChild("initiative").setValue(0);
baseactornode.getChild("setback_dice").setValue(0);
end
v.delete();
break;
end
else
if sourcenode.getNodeName() == v.getNodeName() then
v.delete();
break;
end
end
end
refreshActorList();
end
end
function activateActor(actornode)
-- Usually called by the actoractiveindactor.lua onClickRelease event, when the GM clicks on the active indicator icon to the left of the initslot.
--Debug.console("activateActor. init tracker initslot node = " .. actornode.getNodeName());
local activechartype = "";
if User.isHost() then
--for k, v in pairs(actorlistnode.getChildren()) do
for k, v in pairs(initslotlistnode.getChildren()) do
local sourcenode = v;
--Debug.console("activateActor. sourcenode = " .. sourcenode.getNodeName());
-- set the active node
local activenode = sourcenode.createChild("actor.active", "number");
if sourcenode.getNodeName() == actornode.getNodeName() then
activenode.setValue(1);
-- Set activeinitslotnode for future use.
activeinitslotnode = activenode;
-- Store classname (charsheet or npc) so we can update the AddInitSlotButtons later
activechartype = activenode.getChild("..classname").getValue();
--Debug.console("activateActor. activechartype = " .. activechartype);
else
activenode.setValue(0);
end
end
-- Check if this slot already contains an actor from a previous action - don't want to the actor from the acted this round table.
--if actornode.getChild("initslot_actornodename").getValue() ~= "" then
-- setAddToInitSlotButtons("none");
--else
-- setAddToInitSlotButtons(activechartype);
--end
refreshInitSlotList();
return true;
end
end
function cleanActorList()
if User.isHost() then
for k, v in pairs(actorlistnode.getChildren()) do
local recordnode = v.getChild("actor.recordname");
if recordnode then
local sourcenode = DB.findNode(recordnode.getValue());
if not sourcenode then
v.delete();
end
end
end
refreshActorList();
end
end
function onModuleAdded(name)
if User.isHost() then
cleanActorList()
end
end
function onModuleRemoved(name)
if User.isHost() then
cleanActorList()
end
end
function onModuleUpdated(name)
if User.isHost() then
cleanActorList()
end
end
function endOfTurn()
--enable all turn indicator flags
--characterlist.enableAllTurnIndicators();
if User.isHost() then
--hostEndOfTurn();
resetInitSlotList();
else
playerEndOfTurn();
end
end
function playerEndOfTurn()
if not User.isHost() then
local identity = User.getCurrentIdentity();
if identity then
CharacterManager.endOfTurn(DB.findNode("charsheet." .. identity));
end
end
end
function hostEndOfTurn()
if User.isHost() then
local npcgroups = {};
local npcs = {};
-- remove party recharge
PartySheetManager.endOfTurn();
-- loop through each actor
for k, v in pairs(actorlistnode.getChildren()) do
local classnode = v.getChild("actor.classname");
local recordnode = v.getChild("actor.recordname");
if classnode and recordnode then
local sourcenode = DB.findNode(recordnode.getValue());
if sourcenode then
local classname = classnode.getValue();
if classname == "npc" then
-- this actor represents an npc so add to the npc list
if not npcs[sourcenode.getNodeName()] then
npcs[sourcenode.getNodeName()] = sourcenode;
end
-- determine if this npc is a member of an npc group
local parentnode = sourcenode.getParent();
if parentnode then
if parentnode.getName() == "npcs" then
local npcgroupnode = parentnode.getParent();
if npcgroupnode then
if not npcgroups[npcgroupnode.getNodeName()] then
npcgroups[npcgroupnode.getNodeName()] = npcgroupnode;
end
end
end
end
end
end
end
end
-- remove recharge from each npc group that is referenced
for k, v in pairs(npcgroups) do
NpcGroupManager.endOfTurn(v);
end
-- remove recharge from each npc that is referenced
for k, v in pairs(npcs) do
NpcManager.endOfTurn(v);
end
end
end
function updateActorInitiative(characternode, initiativecount)
if User.isHost() then
local characterNodeName = characternode.getNodeName();
Debug.console("InitiativeManager.updateActorInitiative. characternode = " .. characterNodeName .. ", initiativecount = " .. initiativecount);
--DB.setValue(characternode, "actor.initiative", "number", initiativecount);
if string.match(characterNodeName, "charsheet") then
-- We have a character sheet reference (PC not NPC) - need to find the correct initiativetracker.actors.id-XXXXX reference.
local actorNode = nil;
for k,v in pairs(actorlistnode.getChildren()) do
Debug.console("Actor list node = " .. v.getNodeName());
if v.getChild("actor.recordname") then
Debug.console("Checking " .. v.getChild("actor.recordname").getValue() .. " with " .. characterNodeName);
if v.getChild("actor.recordname").getValue() == characterNodeName then
-- We have a match - use this record as the characternode
characternode = v;
break;
end
end
end
end
-- Step through initslots records and find the record added by this character - update that node with the new initiative.
for k,v in pairs(initslotlistnode.getChildren()) do
Debug.console("Looking at current child: " .. k .. " comparing " .. v.getChild("actor.recordname").getValue() .. " with " .. characternode.getNodeName());
if v.getChild("actor.recordname").getValue() == characternode.getNodeName() then
--Debug.console("Have the " .. initskillname .. " db node = " .. v.getNodeName());
DB.setValue(v, "actor.initiative", "number", initiativecount);
break;
end
end
end
end
function getActiveInitSlot()
if initslotlistnode then
for k, v in pairs(initslotlistnode.getChildren()) do
local sourcenode = v;
-- Clear the current activeinitslotnode
activeinitslotnode = nil;
--Debug.console("getActiveInitSlot. sourcenode = " .. sourcenode.getNodeName());
-- set the active node
--local activenode = sourcenode.getChild("actor.active");
if sourcenode.getChild("actor.active").getValue() == 1 then
-- Set activeinitslotnode for future use.
activeinitslotnode = sourcenode;
--Set the active classname (npc or charsheet) so that addtoinitslot buttons get enabled/disabled
local activechartype = activeinitslotnode.getChild("actor.classname").getValue();
-- Check if this slot already contains an actor from a previous action - don't want to activate buttons for the actor if they acted this round.
if activeinitslotnode then
if activeinitslotnode.getChild("initslot_actornodename") then
if activeinitslotnode.getChild("initslot_actornodename").getValue() ~= "" then
setAddToInitSlotButtons("none");
else
setAddToInitSlotButtons(activechartype);
end
end
end
--setAddToInitSlotButtons(activechartype);
return activeinitslotnode;
end
end
end
return activeinitslotnode;
end
function setAddToInitSlotButtons(activechartype)
-- activechartype can be npc or charsheet - use this to set the addToInitSlot button states
--Debug.console("InitiativeManager.setAddToInitSlotButtons: activechartype = " .. activechartype);
-- Only host can set the DB node value - should trigger onUpdate code on all clients to update he button state
if User.isHost() then
DB.findNode("initiativetracker.activeslotclass.slotactiveclass").setValue(activechartype);
end
end
function addToInitSlot(actornode)
--Debug.console("InitiativeManager.addToInitSlot - actornode.getNodeName = " .. actornode.getNodeName());
if getActiveInitSlot() then
--Debug.console("InitiativeManager.addToInitSlot - activeinitslotnode = " .. activeinitslotnode.getNodeName());
local charactername = actornode.getChild("name").getValue();
local charactertoken = actornode.getChild("token").getValue();
local actornodename = actornode.getNodeName();
local npcCategoryNode = actornode.getChild("npc_category");
if npcCategoryNode then
category = npcCategoryNode.getValue();
else
category = "pc";
end
--Debug.console("InitiativeManager.addToInitSlot - charactername = " .. charactername .. ", charactertoken = " .. charactertoken);
-- Set name and token in the init slot
activeinitslotnode.getChild("initslot_actornodename").setValue(actornodename);
activeinitslotnode.getChild("initslotname").setValue(charactername);
activeinitslotnode.getChild("initslotactor_token").setValue(charactertoken);
-- Create the category - NPC type (minion, rival, nemesis) or pc
activeinitslotnode.createChild("npc_category").setValue(category);
table.insert(actedthisroundlist, actornode);
end
--Refresh the init slot list and buttons
refreshInitSlotList();
return true;
end
function resetInitSlotList()
-- Used at the end of the round to remove all actors assigned to init slots.
local maxinitslotdbnode = nil;
local maxinit = 0.0;
local initslotlisttable = initslotlistcontrol.getWindows();
if #initslotlisttable > 0 then
for k, v in pairs(initslotlisttable) do
local initslotdbnode = v.getDatabaseNode();
local charactername = "";
if initslotdbnode.getChild("actor.classname").getValue() == "npc" then
charactername = "GM NPC Slot";
elseif initslotdbnode.getChild("actor.classname").getValue() == "charsheet" then
charactername= "Player Party Slot";
end
initslotdbnode.getChild("initslot_actornodename").setValue("");
initslotdbnode.getChild("initslotname").setValue(charactername);
initslotdbnode.getChild("initslotactor_token").setValue("");
initslotdbnode.getChild("actor.active").setValue(0);
local thisslotinit = initslotdbnode.getChild("actor.initiative").getValue();
if #initslotlisttable == 1 then
initslotdbnode.getChild("actor.active").setValue(1);
else
if thisslotinit > maxinit then
maxinit = thisslotinit;
maxinitslotdbnode = initslotdbnode;
elseif thisslotinit == maxinit then
-- if maxinit values are equal, make a PC init higher
if initslotdbnode.getChild("actor.initiative").getValue() == "charsheet" then
maxinitslotdbnode = initslotdbnode;
end
end
end
end
if #initslotlisttable > 1 and maxinitslotdbnode then
-- Set the active init slot as the first
maxinitslotdbnode.getChild("actor.active").setValue(1);
else
if User.isHost() then
Debug.chat("Cannot set init marker to first initslot as no initiative values are available. Have all PCs and NPCs roll their initiative from the combat tab of their character sheets");
end
end
end
-- Send the "reset" command to listening actorslots so as to change the name colour
local nodeslotactiveclass = DB.findNode("initiativetracker.activeslotclass.slotactiveclass");
if nodeslotactiveclass then
nodeslotactiveclass.setValue("reset");
end
-- Reset acted this round table.
actedthisroundlist = {};
--Refresh the init slot list and buttons
refreshInitSlotList();
end
function listActedThisRound()
buildActedThisRound();
for k,v in pairs(actedthisroundlist) do
--Debug.console("InitiativeManager.listActedThisRound - actedthisroundlist table, row " .. k .. " = " .. v.getNodeName());
end
return actedthisroundlist;
end
function buildActedThisRound()
-- Used when init tracker is opened to build the table of already acted actornodes from the database
-- ensure that we have the initslot list node
if not initslotlistnode then
initslotlistnode = DB.findNode("initiativetracker.initslots");
end
--Clear the table before rebuilding
actedthisroundlist = {};
for k, v in pairs(initslotlistnode.getChildren()) do
local initslotdbnode = v;
if initslotdbnode.getChild("initslot_actornodename") then
local actornodename = initslotdbnode.getChild("initslot_actornodename").getValue();
if actornodename ~= "" then
table.insert(actedthisroundlist, DB.findNode(actornodename));
end
end
end
end
function clearInitSlot(initslotdbnode)
-- Used at the end of the round to remove all actors assigned to init slots.
--Debug.console("InitiativeManager.clearInitSlot - initslotdbnode name = " .. initslotdbnode.getNodeName());
if initslotdbnode then
local initslotactordbnodename = initslotdbnode.getChild("initslot_actornodename").getValue();
--Debug.console("InitiativeManager.clearInitSlot - initslotactordbnodename = " .. initslotactordbnodename);
local charactername = "";
if initslotdbnode.getChild("actor.classname").getValue() == "npc" then
charactername = "GM NPC Slot";
elseif initslotdbnode.getChild("actor.classname").getValue() == "charsheet" then
charactername= "Player Party Slot";
end
initslotdbnode.getChild("initslotname").setValue(charactername);
initslotdbnode.getChild("initslotactor_token").setValue("");
initslotdbnode.getChild("initslot_actornodename").setValue("");
-- Remove the actor from the acted this round table.
for k,v in pairs(actedthisroundlist) do
--Debug.console("InitiativeManager.clearInitSlot - actedthisround list line = " .. k .. ", " .. v.getNodeName());
if v.getNodeName() == initslotactordbnodename then
--Debug.console("InitiativeManager.clearInitSlot - removing " .. v.getNodeName());
table.remove(actedthisroundlist, k);
-- Reset the indicators
getActiveInitSlot();
end
end
refreshInitSlotList();
end
end
function isOwnedIdentity(charsheetdbnode)
-- Checks the nodename of the character sheet dbnode passed into the function and if this is an owned (controlled) identity then returns true.
local ownedidentitylist = User.getOwnedIdentities();
--Debug.console("InitiativeManager.isOwnedIdentity - owned identities = " .. table.concat(ownedidentitylist, ", ") .. ", node to check = " .. charsheetdbnode.getNodeName());
for k,v in pairs(ownedidentitylist) do
--Debug.console("InitiativeManager.isOwnedIdentity - k, v = " .. k .. ", " .. v);
if charsheetdbnode.getNodeName() == ("charsheet." .. v) then
--Debug.console("InitiativeManager.isOwnedIdentity = true!");
return true;
end
end
return false;
end
function clientNextActor()
-- Only allow a player to advance the active indicator if the currently active node is a PC
-- only allow the owner of the current PC assigned to the init slot to advance the active indicator.
local activeinitslotdbnode = getActiveInitSlot();
if activeinitslotdbnode then
if isOwnedIdentity(DB.findNode(activeinitslotdbnode.getChild("initslot_actornodename").getValue())) then
--Debug.console("InitiativeManager.clientNextActor - owned identities = " .. table.concat(User.getOwnedIdentities(), ", "));
--if activeinitslotdbnode.getChild("actor.classname").getValue() == "charsheet" then
ChatManager.sendSpecialMessage(SPECIAL_MSGTYPE_NEXTACTOR, msg);
--end
end
end
end
function handleNextActor(msguser, msgidentity, msgparams)
if User.isHost() then
nextActor();
end
end
function nextActor()
if User.isHost() then
local activeinitslotdbnode = getActiveInitSlot();
if activeinitslotdbnode then
local initslotwindows = initslotlistcontrol.getWindows();
for k,v in ipairs(initslotwindows) do
if v.getDatabaseNode().getNodeName() == activeinitslotdbnode.getNodeName() then
local nextinitslotwindow = initslotlistcontrol.getNextWindow(v);
if nextinitslotwindow then
v.getDatabaseNode().getChild("actor.active").setValue(0);
nextinitslotwindow.getDatabaseNode().getChild("actor.active").setValue(1);
refreshInitSlotList();
return;
elseif nextinitslotwindow == nil then
-- We are at the end of the windows in the windowlist, set this last slot to inactive - i.e. all slots will now not be active - no active indicators shown.
v.getDatabaseNode().getChild("actor.active").setValue(0);
local nodeslotactiveclass = DB.findNode("initiativetracker.activeslotclass.slotactiveclass");
if nodeslotactiveclass then
nodeslotactiveclass.setValue("blank");
end
-- nextinitslotwindow.getDatabaseNode().getChild("actor.active").setValue(1);
refreshInitSlotList();
-- Write end of rounds message to all the chat window on all clients
local msg = {};
msg.font = "msgfont";
msg.text = "End of Round.";
ChatManager.deliverMessage(msg);
return;
end
end
end
end
end
end
function rebuildInitSlots()
-- Deletes the current init slots and rebuilds them based on the current actor list.
-- Handy if some init slots or actors have been deleted and the links between actors and init slots need tidying up.
if User.isHost() then
-- Delete all current init slots
for k, v in pairs(initslotlistnode.getChildren()) do
v.delete();
end
for k,actornode in pairs(actorlistnode.getChildren()) do
recordname = actornode.getNodeName();
classname = actornode.getChild("actor.classname").getValue();
Debug.console("About to add " .. classname .. " with record " .. recordname)
addInitSlot(classname, recordname);
end
-- refresh the init slot list
refreshInitSlotList();
end
end
function removeAllInitSlots()
if User.isHost() then
--Debug.console("removeInitSlot - starting. Sourcenode = " .. sourcenode.getNodeName());
for k, v in pairs(initslotlistnode.getChildren()) do
v.delete();
end
--refreshActorList();
--refreshInitSlotList();
end
end
|
object_tangible_destructible_gcw_imperial_vehicle = object_tangible_destructible_shared_gcw_imperial_vehicle:new {
}
ObjectTemplates:addTemplate(object_tangible_destructible_gcw_imperial_vehicle, "object/tangible/destructible/gcw_imperial_vehicle.iff")
|
local gamemode = ScriptedGamemode()
gamemode.ScoreboardColumns = { "Name", "Ping" }
gamemode:On("InitScoreboard", function (self, scoreboard)
self.Scoreboard = scoreboard
self.ScoreboardColumnIndexes = {}
self.ScoreboardTeamIndexes = {}
-- Retrieve active gamemode instead of base gamemode
local derivedGamemode = match.GetGamemode()
for _, columnName in pairs(derivedGamemode.ScoreboardColumns) do
self.ScoreboardColumnIndexes[columnName] = scoreboard:AddColumn(columnName)
end
for _, team in pairs(self:GetTeams()) do
local teamName = team:GetName()
self.ScoreboardTeamIndexes[teamName] = scoreboard:AddTeam(teamName, team:GetColor())
end
for _, player in pairs(match.GetPlayers()) do
derivedGamemode:RegisterScoreboardPlayer(player)
end
end)
gamemode:On("PlayerJoined", function (self, player)
local scoreboard = self.Scoreboard
if (not scoreboard) then
return
end
-- Retrieve active gamemode instead of base gamemode
match.GetGamemode():RegisterScoreboardPlayer(player)
end)
function gamemode:RegisterScoreboardPlayer(player)
local scoreboard = assert(self.Scoreboard)
local playerIndex = player:GetPlayerIndex()
local isLocalPlayer = false
local localPlayerCount = engine_GetLocalPlayerCount()
for i = 1, localPlayerCount do
if (engine_GetLocalPlayer_PlayerIndex(i - 1) == playerIndex) then
isLocalPlayer = true
break
end
end
-- Retrieve active gamemode instead of base gamemode
local derivedGamemode = match.GetGamemode()
local columnValues = {}
table.insert(columnValues, player:GetName())
for _, scoreType in pairs(derivedGamemode.ScoreTypes) do
table.insert(columnValues, tostring(derivedGamemode:GetPlayerScore(player, scoreType) or 0))
end
table.insert(columnValues, tostring(player:GetPing() or ""))
local playerTeam = self:GetPlayerTeam(player)
scoreboard:RegisterPlayer({
PlayerIndex = playerIndex,
TeamIndex = playerTeam and self.ScoreboardTeamIndexes[playerTeam:GetName()] or nil,
Values = columnValues,
Color = derivedGamemode:GetPlayerColor(player),
IsLocalPlayer = isLocalPlayer
})
end
function gamemode:UpdateScoreboard(playerScores)
local scoreboard = self.Scoreboard
if (not scoreboard) then
return
end
local derivedGamemode = match.GetGamemode()
for playerIndex, scores in pairs(playerScores) do
for _, scoreType in pairs(derivedGamemode.ScoreTypes) do
scoreboard:UpdatePlayerValue(playerIndex, self.ScoreboardColumnIndexes[scoreType], tostring(scores[scoreType] or 0))
end
end
end
gamemode:On("PlayerLeave", function (self, player)
local scoreboard = self.Scoreboard
if (not scoreboard) then
return
end
scoreboard:UnregisterPlayer(player:GetPlayerIndex())
end)
gamemode:On("PlayerNameUpdate", function (self, player, newName)
print(player:GetName() .. " has changed name to " .. newName)
local scoreboard = self.Scoreboard
if (not scoreboard) then
return
end
scoreboard:UpdatePlayerValue(player:GetPlayerIndex(), self.ScoreboardColumnIndexes.Name, newName)
end)
gamemode:On("PlayerPingUpdate", function (self, player, newName)
local scoreboard = self.Scoreboard
if (not scoreboard) then
return
end
for _, player in pairs(match.GetPlayers()) do
scoreboard:UpdatePlayerValue(player:GetPlayerIndex(), self.ScoreboardColumnIndexes.Ping, tostring(player:GetPing() or ""))
end
end)
gamemode:On("PlayerTeamUpdate", function (self, player, team)
local scoreboard = self.Scoreboard
if (not scoreboard) then
return
end
scoreboard:UpdatePlayerTeam(player:GetPlayerIndex(), team and self.ScoreboardTeamIndexes[team:GetName()] or -1)
end)
|
local key = ModPath .. ' ' .. RequiredScript
if _G[key] then return else _G[key] = true end
local fs_original_carrydata_init = CarryData.init
function CarryData:init(unit)
fs_original_carrydata_init(self, unit)
if Network:is_client() or self._carry_id and not self:can_explode() then
unit:set_extension_update_enabled(Idstring("carry_data"), false)
end
end
|
ERR_SEAT = 255
SEAT_STATE = {
null = 0x00,
unready = 0x01,
ready = 0x02,
gaming = 0x04,
offline = 0x08,
exit = 0x10,
}
|
require("lib_gamesense")
local maf = require("lib_maf")
local ui_new_checkbox = ui.new_checkbox
local ui_new_combobox = ui.new_combobox
local ui_new_multiselect = ui.new_multiselect
local ui_new_slider = ui.new_slider
local ui_new_color_picker = ui.new_color_picker
local ui_set_callback = ui.set_callback
local ui_get = ui.get
local ui_set = ui.set
local ui_reference = ui.reference
local ui_set_visible = ui.set_visible
local math_abs = math.abs
local math_floor = math.floor
local math_cos = math.cos
local math_sin = math.sin
local math_max = math.max
local math_min = math.min
local renderer_world_to_screen = renderer.world_to_screen
local renderer_text = renderer.text
local renderer_rectangle = renderer.rectangle
local renderer_line = renderer.line
local renderer_measure_text = renderer.measure_text
local entity_get_local_player = entity.get_local_player
local entity_get_players = entity.get_players
local entity_get_classname = entity.get_classname
local entity_get_prop = entity.get_prop
local string_find = string.find
local string_match = string.match
local client_draw_hitboxes = client.draw_hitboxes
local client_userid_to_entindex = client.userid_to_entindex
local client_screen_size = client.screen_size
local globals_tickinterval = globals.tickinterval
local globals_frametime = globals.frametime
-- [About]------------------------------------------------------------------------------------------------------------------------------------------------------
-- Made by: w7rus (Astolfo)
-- Credits: Aviarita [lib_gamesense]
-- bjornbytes [lib_maf]
-- [Configuration] ["Do not edit below this line"]-------------------------------- [Value/Description] ---------------------------------------------------------
local ref_extesp_enable = ui_new_checkbox("VISUALS", "Player ESP", "Ext-ESP")
local ref_extesp_filter_players = ui_new_combobox("VISUALS", "Player ESP", "Players", {"Off", "On (Ally/Enemy)", "On (CT/T)"})
local ref_extesp_filter_playersSubtype = ui_new_multiselect("VISUALS", "Player ESP", "Player Subtype", {"Ally", "Enemy", "CT", "T"})
local ref_extesp_filter_weapons = ui_new_checkbox("VISUALS", "Player ESP", "Weapons")
local ref_extesp_filter_mapObjective = ui_new_checkbox("VISUALS", "Player ESP", "Objectives")
local ref_extesp_filter_projectiles = ui_new_combobox("VISUALS", "Player ESP", "Projectiles", {"Off", "On (Owner)", "On (Subtype)"})
local ref_extesp_filter_other = ui_new_checkbox("VISUALS", "Player ESP", "Other")
local ref_extesp_boundingBox = ui_new_combobox("VISUALS", "Player ESP", "Any > Bounding Box", {"Off", "On (Static 3D)", "On (Static 2D)"})
local ref_extesp_snapline = ui_new_checkbox("VISUALS", "Player ESP", "Any > Snapline")
local ref_extesp_snaplineStartX = ui_new_slider("VISUALS", "Player ESP", "Any > Snapline (Start X)", 0, 100, 50, true, "%", 1)
local ref_extesp_snaplineStartY = ui_new_slider("VISUALS", "Player ESP", "Any > Snapline (Start Y)", 0, 100, 50, true, "%", 1)
local ref_extesp_originPoint = ui_new_checkbox("VISUALS", "Player ESP", "Any > Origin Point")
local ref_extesp_skeleton = ui_new_checkbox("VISUALS", "Player ESP", "Any > Skeleton")
local ref_extesp_hitbox = ui_new_multiselect("VISUALS", "Player ESP", "Any > Hitbox", {"Head", "Neck", "Spine 1", "Spine 2", "Spine 3", "Spine 4", "Pelvis", "Arm Upper L", "Arm Upper R", "Arm Lower L", "Arm Lower R", "Hand L", "Hand R", "Leg Upper L", "Leg Upper R", "Leg Lower L", "Leg Lower R", "Foot L", "Foot R"})
local ref_extesp_hitbox_antiflicker = ui_new_slider("VISUALS", "Player ESP", "Any > Hitbox > Antiflicker History", 1, 128, 1, true, "f.", 1)
local ref_extesp_name = ui_new_checkbox("VISUALS", "Player ESP", "Any > Name/Classname")
local ref_extesp_health = ui_new_checkbox("VISUALS", "Player ESP", "Any > Health")
local ref_extesp_armor = ui_new_checkbox("VISUALS", "Player ESP", "Any > Armor")
local ref_extesp_distance = ui_new_combobox("VISUALS", "Player ESP", "Any > Distance", {"Off", "Units", "Metric", "Imperial"})
local ref_extesp_navlocation = ui_new_checkbox("VISUALS", "Player ESP", "Any > NAV Location")
local ref_extesp_equipment = ui_new_checkbox("VISUALS", "Player ESP", "Any > Equipment")
local ref_extesp_ammo = ui_new_checkbox("VISUALS", "Player ESP", "Any > Equipment > Ammo")
local ref_extesp_flags = ui_new_checkbox("VISUALS", "Player ESP", "Any > Flags")
local ref_extesp_padding = ui_new_slider("VISUALS", "Player ESP", "Any > Screen Padding", 0, math_floor(math_min(client.screen_size()) / 2), 128, true, "px", 1)
local b_esp_filter_playerEnemy_accentColor01 = {255, 0, 170, 255}
local b_esp_filter_playerEnemy_accentColor02 = {170, 255, 0, 255}
local b_esp_filter_playerAlly_accentColor01 = {0, 170, 255, 255}
local b_esp_filter_playerAlly_accentColor02 = {0, 255, 170, 255}
local b_esp_filter_playerEnemy_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Players > Enemy (Color Invis.)")
local b_esp_filter_playerEnemy_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Players > Enemy (Color Invis.)", 255, 0, 170, 255)
ui.set_callback(b_esp_filter_playerEnemy_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_playerEnemy_accentColor01_colorPicker);
b_esp_filter_playerEnemy_accentColor01 = {r, g, b , a}
end)
local b_esp_filter_playerEnemy_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Players > Enemy (Color Vis.)")
local b_esp_filter_playerEnemy_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Players > Enemy (Color Vis.)", 170, 255, 0, 255)
ui.set_callback(b_esp_filter_playerEnemy_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_playerEnemy_accentColor02_colorPicker);
b_esp_filter_playerEnemy_accentColor02 = {r, g, b , a}
end)
local b_esp_filter_playerAlly_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Players > Ally (Color Invis.)")
local b_esp_filter_playerAlly_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Players > Ally (Color Invis.)", 0, 170, 255, 255)
ui.set_callback(b_esp_filter_playerAlly_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_playerAlly_accentColor01_colorPicker);
b_esp_filter_playerAlly_accentColor01 = {r, g, b , a}
end)
local b_esp_filter_playerAlly_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Players > Ally (Color Vis.)")
local b_esp_filter_playerAlly_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Players > Ally (Color Vis.)", 0, 255, 170, 255)
ui.set_callback(b_esp_filter_playerAlly_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_playerAlly_accentColor02_colorPicker);
b_esp_filter_playerAlly_accentColor02 = {r, g, b , a}
end)
local b_esp_filter_playerT_accentColor01 = {255, 0, 170, 255}
local b_esp_filter_playerT_accentColor02 = {170, 255, 0, 255}
local b_esp_filter_playerCT_accentColor01 = {0, 170, 255, 255}
local b_esp_filter_playerCT_accentColor02 = {0, 255, 170, 255}
local b_esp_filter_playerT_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Players > T (Color Invis.)")
local b_esp_filter_playerT_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Players > T (Color Invis.)", 255, 0, 170, 255)
ui.set_callback(b_esp_filter_playerT_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_playerT_accentColor01_colorPicker);
b_esp_filter_playerT_accentColor01 = {r, g, b , a}
end)
local b_esp_filter_playerT_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Players > T (Color Vis.)")
local b_esp_filter_playerT_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Players > T (Color Vis.)", 170, 255, 0, 255)
ui.set_callback(b_esp_filter_playerT_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_playerT_accentColor02_colorPicker);
b_esp_filter_playerT_accentColor02 = {r, g, b , a}
end)
local b_esp_filter_playerCT_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Players > CT (Color Invis.)")
local b_esp_filter_playerCT_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Players > CT (Color Invis.)", 0, 170, 255, 255)
ui.set_callback(b_esp_filter_playerCT_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_playerCT_accentColor01_colorPicker);
b_esp_filter_playerCT_accentColor01 = {r, g, b , a}
end)
local b_esp_filter_playerCT_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Players > CT (Color Vis.)")
local b_esp_filter_playerCT_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Players > CT (Color Vis.)", 0, 255, 170, 255)
ui.set_callback(b_esp_filter_playerCT_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_playerCT_accentColor02_colorPicker);
b_esp_filter_playerCT_accentColor02 = {r, g, b , a}
end)
local b_esp_filter_weapons_accentColor01 = {127, 127, 127, 63}
local b_esp_filter_weapons_accentColor02 = {255, 255, 255, 63}
local b_esp_filter_weapons_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Weapons (Color Invis.)")
local b_esp_filter_weapons_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Weapons (Color Invis.)", 127, 127, 127, 63)
ui.set_callback(b_esp_filter_weapons_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_weapons_accentColor01_colorPicker);
b_esp_filter_weapons_accentColor01 = {r, g, b , a}
end)
local b_esp_filter_weapons_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Weapons (Color Vis.)")
local b_esp_filter_weapons_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Weapons (Color Vis.)", 255, 255, 255, 63)
ui.set_callback(b_esp_filter_weapons_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_weapons_accentColor02_colorPicker);
b_esp_filter_weapons_accentColor02 = {r, g, b , a}
end)
b_esp_filter_mapObjective_accentColor01 = {} -- Autofilled using func_extesp_rainbowise function
b_esp_filter_mapObjective_accentColor02 = {} -- Autofilled using func_extesp_rainbowise function
b_esp_filter_other_accentColor01 = {127, 127, 127, 63}
b_esp_filter_other_accentColor02 = {255, 255, 255, 63}
b_esp_filter_other_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Other (Color Invis.)")
b_esp_filter_other_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Other (Color Invis.)", 127, 127, 127, 63)
ui.set_callback(b_esp_filter_other_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_other_accentColor01_colorPicker);
b_esp_filter_other_accentColor01 = {r, g, b , a}
end)
b_esp_filter_other_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Other (Color Vis.)")
b_esp_filter_other_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Other (Color Vis.)", 255, 255, 255, 63)
ui.set_callback(b_esp_filter_other_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_other_accentColor02_colorPicker);
b_esp_filter_other_accentColor02 = {r, g, b , a}
end)
b_esp_filter_projectile_stHEG_accentColor01 = {170, 0, 0, 255}
b_esp_filter_projectile_stHEG_accentColor02 = {255, 0, 0, 255}
b_esp_filter_projectile_stHEG_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile HEG (Color Invis.)")
b_esp_filter_projectile_stHEG_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile HEG (Color Invis.)", 170, 0, 0, 255)
ui.set_callback(b_esp_filter_projectile_stHEG_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stHEG_accentColor01_colorPicker);
b_esp_filter_projectile_stHEG_accentColor01 = {r, g, b , a}
end)
b_esp_filter_projectile_stHEG_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile HEG (Color Vis.)")
b_esp_filter_projectile_stHEG_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile HEG (Color Vis.)", 255, 0, 0, 255)
ui.set_callback(b_esp_filter_projectile_stHEG_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stHEG_accentColor02_colorPicker);
b_esp_filter_projectile_stHEG_accentColor02 = {r, g, b , a}
end)
b_esp_filter_projectile_stTAG_accentColor01 = {113, 0, 170, 255}
b_esp_filter_projectile_stTAG_accentColor02 = {170, 0, 255, 255}
b_esp_filter_projectile_stTAG_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile TAG (Color Invis.)")
b_esp_filter_projectile_stTAG_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile TAG (Color Invis.)", 113, 0, 170, 255)
ui.set_callback(b_esp_filter_projectile_stTAG_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stTAG_accentColor01_colorPicker);
b_esp_filter_projectile_stTAG_accentColor01 = {r, g, b , a}
end)
b_esp_filter_projectile_stTAG_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile TAG (Color Vis.)")
b_esp_filter_projectile_stTAG_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile TAG (Color Vis.)", 170, 0, 255, 255)
ui.set_callback(b_esp_filter_projectile_stTAG_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stTAG_accentColor02_colorPicker);
b_esp_filter_projectile_stTAG_accentColor02 = {r, g, b , a}
end)
b_esp_filter_projectile_stSmokeG_accentColor01 = {0, 170, 0, 255}
b_esp_filter_projectile_stSmokeG_accentColor02 = {0, 255, 0, 255}
b_esp_filter_projectile_stSmokeG_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile SmokeG (Color Invis.)")
b_esp_filter_projectile_stSmokeG_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile SmokeG (Color Invis.)", 0, 170, 0, 255)
ui.set_callback(b_esp_filter_projectile_stSmokeG_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stSmokeG_accentColor01_colorPicker);
b_esp_filter_projectile_stSmokeG_accentColor01 = {r, g, b , a}
end)
b_esp_filter_projectile_stSmokeG_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile SmokeG (Color Vis.)")
b_esp_filter_projectile_stSmokeG_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile SmokeG (Color Vis.)", 0, 255, 0, 255)
ui.set_callback(b_esp_filter_projectile_stSmokeG_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stSmokeG_accentColor02_colorPicker);
b_esp_filter_projectile_stSmokeG_accentColor02 = {r, g, b , a}
end)
b_esp_filter_projectile_stMolotov_accentColor01 = {170, 113, 0, 255}
b_esp_filter_projectile_stMolotov_accentColor02 = {255, 170, 0, 255}
b_esp_filter_projectile_stMolotov_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile Molotov/Incendiary (Color Invis.)")
b_esp_filter_projectile_stMolotov_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile Molotov/Incendiary (Color Invis.)", 170, 113, 0, 255)
ui.set_callback(b_esp_filter_projectile_stMolotov_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stMolotov_accentColor01_colorPicker);
b_esp_filter_projectile_stMolotov_accentColor01 = {r, g, b , a}
end)
b_esp_filter_projectile_stMolotov_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile Molotov/Incendiary (Color Vis.)")
b_esp_filter_projectile_stMolotov_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile Molotov/Incendiary (Color Vis.)", 255, 170, 0, 255)
ui.set_callback(b_esp_filter_projectile_stMolotov_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stMolotov_accentColor02_colorPicker);
b_esp_filter_projectile_stMolotov_accentColor02 = {r, g, b , a}
end)
b_esp_filter_projectile_stFlashbang_accentColor01 = {170, 170, 170, 255}
b_esp_filter_projectile_stFlashbang_accentColor02 = {255, 255, 255, 255}
b_esp_filter_projectile_stFlashbang_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile Flashbang (Color Invis.)")
b_esp_filter_projectile_stFlashbang_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile Flashbang (Color Invis.)", 170, 170, 170, 255)
ui.set_callback(b_esp_filter_projectile_stFlashbang_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stFlashbang_accentColor01_colorPicker);
b_esp_filter_projectile_stFlashbang_accentColor01 = {r, g, b , a}
end)
b_esp_filter_projectile_stFlashbang_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile Flashbang (Color Vis.)")
b_esp_filter_projectile_stFlashbang_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile Flashbang (Color Vis.)", 255, 255, 255, 255)
ui.set_callback(b_esp_filter_projectile_stFlashbang_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stFlashbang_accentColor02_colorPicker);
b_esp_filter_projectile_stFlashbang_accentColor02 = {r, g, b , a}
end)
b_esp_filter_projectile_stDecoy_accentColor01 = {113, 113, 113, 255}
b_esp_filter_projectile_stDecoy_accentColor02 = {170, 170, 170, 255}
b_esp_filter_projectile_stDecoy_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile Decoy (Color Invis.)")
b_esp_filter_projectile_stDecoy_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile Decoy (Color Invis.)", 113, 113, 113, 255)
ui.set_callback(b_esp_filter_projectile_stDecoy_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stDecoy_accentColor01_colorPicker);
b_esp_filter_projectile_stDecoy_accentColor01 = {r, g, b , a}
end)
b_esp_filter_projectile_stDecoy_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile Decoy (Color Vis.)")
b_esp_filter_projectile_stDecoy_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile Decoy (Color Vis.)", 170, 170, 170, 255)
ui.set_callback(b_esp_filter_projectile_stDecoy_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stDecoy_accentColor02_colorPicker);
b_esp_filter_projectile_stDecoy_accentColor02 = {r, g, b , a}
end)
b_esp_filter_projectile_stSnowball_accentColor01 = {113, 170, 170, 255}
b_esp_filter_projectile_stSnowball_accentColor02 = {170, 255, 255, 255}
b_esp_filter_projectile_stSnowball_accentColor01_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile Snowball (Color Invis.)")
b_esp_filter_projectile_stSnowball_accentColor01_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile Snowball (Color Invis.)", 113, 170, 170, 255)
ui.set_callback(b_esp_filter_projectile_stSnowball_accentColor01_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stSnowball_accentColor01_colorPicker);
b_esp_filter_projectile_stSnowball_accentColor01 = {r, g, b , a}
end)
b_esp_filter_projectile_stSnowball_accentColor02_label = ui_new_checkbox("VISUALS", "Player ESP", "Projectile Snowball (Color Vis.)")
b_esp_filter_projectile_stSnowball_accentColor02_colorPicker = ui_new_color_picker("VISUALS", "Player ESP", "Projectile Snowball (Color Vis.)", 170, 255, 255, 255)
ui.set_callback(b_esp_filter_projectile_stSnowball_accentColor02_colorPicker, function ()
local r, g, b, a = ui_get(b_esp_filter_projectile_stSnowball_accentColor02_colorPicker);
b_esp_filter_projectile_stSnowball_accentColor02 = {r, g, b , a}
end)
-- [Calculated configuration] ----------------------------------------------------------------------------------------------------------------------------------
local i_esp_drawScreenWidth,
i_esp_drawScreenHeight = client_screen_size()
local i_extesp_tickinterval = globals_tickinterval()
local i_extesp_tickrate = 1 / i_extesp_tickinterval
local i_extesp_frametime = nil
local t_extesp_frametime_history = {}
local i_extesp_absframetime = nil
ui.set_callback(ref_extesp_hitbox_antiflicker, function()
for i in pairs(t_extesp_frametime_history) do
t_extesp_frametime_history[i] = nil
end
end)
t_extesp_playerBoneTable = {
[0] = "Head",
[1] = "Neck",
[2] = "Pelvis",
[3] = "Spine 4",
[4] = "Spine 3",
[5] = "Spine 2",
[6] = "Spine 1",
[7] = "Leg Upper L",
[8] = "Leg Upper R",
[9] = "Leg Lower L",
[10] = "Leg Lower R",
[11] = "Foot L",
[12] = "Foot R",
[13] = "Hand L",
[14] = "Hand R",
[15] = "Arm Upper L",
[17] = "Arm Upper R",
[16] = "Arm Lower L",
[18] = "Arm Lower R",
}
-- [Functions] -------------------------------------------------------------------------------------------------------------------------------------------------
local func_extesp_clampToViewport = function(mediaScreenWidth, mediaScreenHeight, mediaScreenAnchorX, mediaScreenAnchorY, entityScreenPosX, entityScreenPosY, entityScreenPosPadding)
if entityScreenPosX <= 0 + entityScreenPosPadding then
local X_XC_DELTA = math_abs(entityScreenPosX - mediaScreenAnchorX);
local Y_YC_DELTA = math_abs(entityScreenPosY - mediaScreenAnchorY);
local DELTA_YX_RATIO = Y_YC_DELTA / X_XC_DELTA;
if entityScreenPosY > mediaScreenAnchorY then
entityScreenPosY = entityScreenPosY + math_floor(entityScreenPosX * DELTA_YX_RATIO);
end
if entityScreenPosY < mediaScreenAnchorY then
entityScreenPosY = entityScreenPosY - math_floor(entityScreenPosX * DELTA_YX_RATIO);
end
entityScreenPosX = 0 + entityScreenPosPadding;
if entityScreenPosY > mediaScreenAnchorY then
entityScreenPosY = entityScreenPosY - math_floor(entityScreenPosX * DELTA_YX_RATIO);
end
if entityScreenPosY < mediaScreenAnchorY then
entityScreenPosY = entityScreenPosY + math_floor(entityScreenPosX * DELTA_YX_RATIO);
end
end
if entityScreenPosX >= mediaScreenWidth - entityScreenPosPadding then
local X_XC_DELTA = math_abs(entityScreenPosX - mediaScreenAnchorX);
local Y_YC_DELTA = math_abs(entityScreenPosY - mediaScreenAnchorY);
local DELTA_YX_RATIO = -(Y_YC_DELTA / X_XC_DELTA);
if entityScreenPosY > mediaScreenAnchorY then
entityScreenPosY = entityScreenPosY + math_floor((entityScreenPosX - mediaScreenWidth) * DELTA_YX_RATIO);
end
if entityScreenPosY < mediaScreenAnchorY then
entityScreenPosY = entityScreenPosY - math_floor((entityScreenPosX - mediaScreenWidth) * DELTA_YX_RATIO);
end
entityScreenPosX = mediaScreenWidth - entityScreenPosPadding;
if entityScreenPosY > mediaScreenAnchorY then
entityScreenPosY = entityScreenPosY - math_floor((entityScreenPosX - mediaScreenWidth) * DELTA_YX_RATIO);
end
if entityScreenPosY < mediaScreenAnchorY then
entityScreenPosY = entityScreenPosY + math_floor((entityScreenPosX - mediaScreenWidth) * DELTA_YX_RATIO);
end
end
if entityScreenPosY <= 0 + entityScreenPosPadding then
local X_XC_DELTA = math_abs(entityScreenPosX - mediaScreenAnchorX);
local Y_YC_DELTA = math_abs(entityScreenPosY - mediaScreenAnchorY);
local DELTA_XY_RATIO = X_XC_DELTA / Y_YC_DELTA;
if entityScreenPosX > mediaScreenAnchorX then
entityScreenPosX = entityScreenPosX + math_floor(entityScreenPosY * DELTA_XY_RATIO);
end
if entityScreenPosX < mediaScreenAnchorX then
entityScreenPosX = entityScreenPosX - math_floor(entityScreenPosY * DELTA_XY_RATIO);
end
entityScreenPosY = (0 + entityScreenPosPadding);
if entityScreenPosX > mediaScreenAnchorX then
entityScreenPosX = entityScreenPosX - math_floor(entityScreenPosY * DELTA_XY_RATIO);
end
if entityScreenPosX < mediaScreenAnchorX then
entityScreenPosX = entityScreenPosX + math_floor(entityScreenPosY * DELTA_XY_RATIO);
end
end
if entityScreenPosY >= mediaScreenHeight - entityScreenPosPadding then
local X_XC_DELTA = math_abs(entityScreenPosX - mediaScreenAnchorX);
local Y_YC_DELTA = math_abs(entityScreenPosY - mediaScreenAnchorY);
local DELTA_XY_RATIO = -(X_XC_DELTA / Y_YC_DELTA);
if entityScreenPosX > mediaScreenAnchorX then
entityScreenPosX = entityScreenPosX + math_floor((entityScreenPosY - mediaScreenHeight) * DELTA_XY_RATIO);
end
if entityScreenPosX < mediaScreenAnchorX then
entityScreenPosX = entityScreenPosX - math_floor((entityScreenPosY - mediaScreenHeight) * DELTA_XY_RATIO);
end
entityScreenPosY = mediaScreenHeight - entityScreenPosPadding;
if entityScreenPosX > mediaScreenAnchorX then
entityScreenPosX = entityScreenPosX - math_floor((entityScreenPosY - mediaScreenHeight) * DELTA_XY_RATIO);
end
if entityScreenPosX < mediaScreenAnchorX then
entityScreenPosX = entityScreenPosX + math_floor((entityScreenPosY - mediaScreenHeight) * DELTA_XY_RATIO);
end
end
return entityScreenPosX, entityScreenPosY;
end
local func_extesp_getClampToViewport = function(mediaScreenWidth, mediaScreenHeight, entityScreenPosX, entityScreenPosY, entityScreenPosPadding)
if entityScreenPosX <= 0 + entityScreenPosPadding then
return false
elseif entityScreenPosX >= mediaScreenWidth - entityScreenPosPadding then
return false
elseif entityScreenPosY <= 0 + entityScreenPosPadding then
return false
elseif entityScreenPosY >= mediaScreenHeight - entityScreenPosPadding then
return false
end
return true
end
local func_extesp_rainbowise = function(a,b,c,d,e,f,g)local h,i,j=math_cos(a*(f+g))*b+math_floor(b/2),math_cos(a*(f+g)+2*math.pi/3*c)*b+math_floor(b/2),math_cos(a*(f+g)-2*math.pi/3*c)*b+math_floor(b/2)if h<d then h=d end;if j<d then j=d end;if i<d then i=d end;if h>e then h=e end;if j>e then j=e end;if i>e then i=e end;return {h,i,j} end
local func_extesp_rotate3D = function(pitch, yaw, roll, nodes)
for i = 1, #nodes do
local vec = maf.vec3(nodes[i].x, nodes[i].y, nodes[i].z)
local p, y, r = .5 * math.rad(pitch), .5 * math.rad(yaw), .5 * math.rad(roll)
local cx = math.cos(p)
local sx = math.sin(p)
local cy = math.cos(y)
local sy = math.sin(y)
local cz = math.cos(r)
local sz = math.sin(r)
local x = sx * cy * cz - cx * sy * sz
local y = cx * sy * cz + sx * cy * sz
local z = cx * cy * sz - sx * sy * cz
local w = cx * cy * cz + sx * sy * sz
local rot = maf.quat(x, y, z, w)
vec:rotate(rot)
nodes[i] = vec
end
end
local table_contains_str = function(table, str)
for _, v in ipairs(table) do
if v == str then
return true
end
end
return false
end
local table_is_empty = function(table)
if next(table) == nil then
return true
end
return false
end
local func_extesp_snapline = function(entIndex_serverEntCAny, accentColor01, accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
local obj_serverEntCAny = Entity(entIndex_serverEntCAny)
local obj_localEntCCSPlayer = Player(entIndex_localEntCCSPlayer)
local vec_serverEntCAny_WorldPos = obj_serverEntCAny:get_vec_origin()
local i_serverEntCAny_ScreenPosX, i_serverEntCAny_ScreenPosY = renderer_world_to_screen(vec_serverEntCAny_WorldPos.x, vec_serverEntCAny_WorldPos.y, vec_serverEntCAny_WorldPos.z)
if i_serverEntCAny_ScreenPosX ~= nil and i_serverEntCAny_ScreenPosY ~= nil then
i_serverEntCAny_ScreenPosX, i_serverEntCAny_ScreenPosY = func_extesp_clampToViewport(i_esp_drawScreenWidth, i_esp_drawScreenHeight, i_esp_anchorPosX, i_esp_anchorPosY, i_serverEntCAny_ScreenPosX, i_serverEntCAny_ScreenPosY, ui_get(ref_extesp_padding))
if obj_serverEntCAny:is_player() == true then
obj_serverEntCAny = Player(entIndex_serverEntCAny)
vec_serverEntCAny_WorldPos = obj_serverEntCAny:get_hitbox_pos("head_0")
end
b_serverEntCAny_IsVisible = obj_localEntCCSPlayer:can_see_point(vec_serverEntCAny_WorldPos)
if ui_get(ref_extesp_originPoint) then
renderer_rectangle(i_serverEntCAny_ScreenPosX - 3, i_serverEntCAny_ScreenPosY - 3, 7, 7, 0, 0, 0, 127)
if b_serverEntCAny_IsVisible == true then
renderer_rectangle(i_serverEntCAny_ScreenPosX - 2, i_serverEntCAny_ScreenPosY - 2, 5, 5, accentColor02[1], accentColor02[2], accentColor02[3], accentColor02[4])
else
renderer_rectangle(i_serverEntCAny_ScreenPosX - 2, i_serverEntCAny_ScreenPosY - 2, 5, 5, accentColor01[1], accentColor01[2], accentColor01[3], accentColor01[4])
end
end
if ui_get(ref_extesp_snapline) then
if b_serverEntCAny_IsVisible == true then
renderer_line(i_serverEntCAny_ScreenPosX, i_serverEntCAny_ScreenPosY, i_esp_anchorPosX, i_esp_anchorPosY, accentColor02[1], accentColor02[2], accentColor02[3], accentColor02[4])
else
renderer_line(i_serverEntCAny_ScreenPosX, i_serverEntCAny_ScreenPosY, i_esp_anchorPosX, i_esp_anchorPosY, accentColor01[1], accentColor01[2], accentColor01[3], accentColor01[4])
end
end
end
end
local func_extesp_boundingBoxStatic = function(entIndex_serverEntCAny, accentColor01, accentColor02)
if not (ui_get(ref_extesp_boundingBox) == "Off") then
local obj_serverEntCAny = Entity(entIndex_serverEntCAny)
local obj_localEntCCSPlayer = Player(entIndex_localEntCCSPlayer)
local vec_serverEntCAny_WorldPos = {x, y, z}
local vec_serverEntCAny_WorldAng = {pitch, yaw, roll}
vec_serverEntCAny_WorldPos = obj_serverEntCAny:get_vec_origin()
vec_serverEntCAny_WorldAng.pitch, vec_serverEntCAny_WorldAng.yaw, vec_serverEntCAny_WorldAng.roll = entity_get_prop(entIndex_serverEntCAny, "m_angRotation", array_index)
local vec_serverEntCAny_WorldPosVecMins = obj_serverEntCAny:get_vec_mins()
local vec_serverEntCAny_WorldPosVecMaxs = obj_serverEntCAny:get_vec_maxs()
local vec_serverEntCAny_WorldPosP1P8 = {
[1] = {
x = vec_serverEntCAny_WorldPosVecMins.x,
y = vec_serverEntCAny_WorldPosVecMins.y,
z = vec_serverEntCAny_WorldPosVecMins.z,
},
[2] = {
x = vec_serverEntCAny_WorldPosVecMaxs.x,
y = vec_serverEntCAny_WorldPosVecMins.y,
z = vec_serverEntCAny_WorldPosVecMins.z,
},
[3] = {
x = vec_serverEntCAny_WorldPosVecMaxs.x,
y = vec_serverEntCAny_WorldPosVecMaxs.y,
z = vec_serverEntCAny_WorldPosVecMins.z,
},
[4] = {
x = vec_serverEntCAny_WorldPosVecMins.x,
y = vec_serverEntCAny_WorldPosVecMaxs.y,
z = vec_serverEntCAny_WorldPosVecMins.z,
},
[5] = {
x = vec_serverEntCAny_WorldPosVecMins.x,
y = vec_serverEntCAny_WorldPosVecMins.y,
z = vec_serverEntCAny_WorldPosVecMaxs.z,
},
[6] = {
x = vec_serverEntCAny_WorldPosVecMaxs.x,
y = vec_serverEntCAny_WorldPosVecMins.y,
z = vec_serverEntCAny_WorldPosVecMaxs.z,
},
[7] = {
x = vec_serverEntCAny_WorldPosVecMaxs.x,
y = vec_serverEntCAny_WorldPosVecMaxs.y,
z = vec_serverEntCAny_WorldPosVecMaxs.z,
},
[8] = {
x = vec_serverEntCAny_WorldPosVecMins.x,
y = vec_serverEntCAny_WorldPosVecMaxs.y,
z = vec_serverEntCAny_WorldPosVecMaxs.z,
},
}
func_extesp_rotate3D(vec_serverEntCAny_WorldAng.roll, vec_serverEntCAny_WorldAng.pitch, vec_serverEntCAny_WorldAng.yaw, vec_serverEntCAny_WorldPosP1P8)
vec_serverEntCAny_WorldPosP1P8 = {
[1] = {
x = vec_serverEntCAny_WorldPosP1P8[1].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[1].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[1].z + vec_serverEntCAny_WorldPos.z,
},
[2] = {
x = vec_serverEntCAny_WorldPosP1P8[2].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[2].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[2].z + vec_serverEntCAny_WorldPos.z,
},
[3] = {
x = vec_serverEntCAny_WorldPosP1P8[3].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[3].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[3].z + vec_serverEntCAny_WorldPos.z,
},
[4] = {
x = vec_serverEntCAny_WorldPosP1P8[4].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[4].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[4].z + vec_serverEntCAny_WorldPos.z,
},
[5] = {
x = vec_serverEntCAny_WorldPosP1P8[5].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[5].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[5].z + vec_serverEntCAny_WorldPos.z,
},
[6] = {
x = vec_serverEntCAny_WorldPosP1P8[6].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[6].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[6].z + vec_serverEntCAny_WorldPos.z,
},
[7] = {
x = vec_serverEntCAny_WorldPosP1P8[7].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[7].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[7].z + vec_serverEntCAny_WorldPos.z,
},
[8] = {
x = vec_serverEntCAny_WorldPosP1P8[8].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[8].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[8].z + vec_serverEntCAny_WorldPos.z,
},
}
local renderer_world_to_screen_asTable = function(Wx, Wy, Wz)
local returnObj = {x, y}
returnObj.x, returnObj.y = renderer_world_to_screen(Wx, Wy, Wz)
return returnObj
end
local vec_serverEntCAny_ScreenPosP1P8 = {
[1] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[1].x, vec_serverEntCAny_WorldPosP1P8[1].y, vec_serverEntCAny_WorldPosP1P8[1].z),
[2] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[2].x, vec_serverEntCAny_WorldPosP1P8[2].y, vec_serverEntCAny_WorldPosP1P8[2].z),
[3] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[3].x, vec_serverEntCAny_WorldPosP1P8[3].y, vec_serverEntCAny_WorldPosP1P8[3].z),
[4] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[4].x, vec_serverEntCAny_WorldPosP1P8[4].y, vec_serverEntCAny_WorldPosP1P8[4].z),
[5] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[5].x, vec_serverEntCAny_WorldPosP1P8[5].y, vec_serverEntCAny_WorldPosP1P8[5].z),
[6] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[6].x, vec_serverEntCAny_WorldPosP1P8[6].y, vec_serverEntCAny_WorldPosP1P8[6].z),
[7] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[7].x, vec_serverEntCAny_WorldPosP1P8[7].y, vec_serverEntCAny_WorldPosP1P8[7].z),
[8] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[8].x, vec_serverEntCAny_WorldPosP1P8[8].y, vec_serverEntCAny_WorldPosP1P8[8].z),
}
for i = 1, #vec_serverEntCAny_ScreenPosP1P8 do
if vec_serverEntCAny_ScreenPosP1P8[i].x == nil or vec_serverEntCAny_ScreenPosP1P8[i].y == nil then
return
end
end
if obj_serverEntCAny:is_player() == true then
obj_serverEntCAny = Player(entIndex_serverEntCAny)
vec_serverEntCAny_WorldPos = obj_serverEntCAny:get_hitbox_pos("head_0")
end
b_serverEntCAny_IsVisible = false
b_serverEntCAny_IsVisible = obj_localEntCCSPlayer:can_see_point(vec_serverEntCAny_WorldPos)
if ui_get(ref_extesp_boundingBox) == "On (Static 3D)" then
local Color = {r, g, b, a};
if b_serverEntCAny_IsVisible == true then
Color.r, Color.g, Color.b, Color.a = accentColor02[1], accentColor02[2], accentColor02[3], accentColor02[4]
else
Color.r, Color.g, Color.b, Color.a = accentColor01[1], accentColor01[2], accentColor01[3], accentColor01[4]
end
-- Bottom
renderer_line(vec_serverEntCAny_ScreenPosP1P8[1].x, vec_serverEntCAny_ScreenPosP1P8[1].y, vec_serverEntCAny_ScreenPosP1P8[2].x, vec_serverEntCAny_ScreenPosP1P8[2].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCAny_ScreenPosP1P8[2].x, vec_serverEntCAny_ScreenPosP1P8[2].y, vec_serverEntCAny_ScreenPosP1P8[3].x, vec_serverEntCAny_ScreenPosP1P8[3].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCAny_ScreenPosP1P8[3].x, vec_serverEntCAny_ScreenPosP1P8[3].y, vec_serverEntCAny_ScreenPosP1P8[4].x, vec_serverEntCAny_ScreenPosP1P8[4].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCAny_ScreenPosP1P8[4].x, vec_serverEntCAny_ScreenPosP1P8[4].y, vec_serverEntCAny_ScreenPosP1P8[1].x, vec_serverEntCAny_ScreenPosP1P8[1].y, Color.r, Color.g, Color.b, Color.a)
-- Top
renderer_line(vec_serverEntCAny_ScreenPosP1P8[5].x, vec_serverEntCAny_ScreenPosP1P8[5].y, vec_serverEntCAny_ScreenPosP1P8[6].x, vec_serverEntCAny_ScreenPosP1P8[6].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCAny_ScreenPosP1P8[6].x, vec_serverEntCAny_ScreenPosP1P8[6].y, vec_serverEntCAny_ScreenPosP1P8[7].x, vec_serverEntCAny_ScreenPosP1P8[7].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCAny_ScreenPosP1P8[7].x, vec_serverEntCAny_ScreenPosP1P8[7].y, vec_serverEntCAny_ScreenPosP1P8[8].x, vec_serverEntCAny_ScreenPosP1P8[8].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCAny_ScreenPosP1P8[8].x, vec_serverEntCAny_ScreenPosP1P8[8].y, vec_serverEntCAny_ScreenPosP1P8[5].x, vec_serverEntCAny_ScreenPosP1P8[5].y, Color.r, Color.g, Color.b, Color.a)
-- Sides
renderer_line(vec_serverEntCAny_ScreenPosP1P8[1].x, vec_serverEntCAny_ScreenPosP1P8[1].y, vec_serverEntCAny_ScreenPosP1P8[5].x, vec_serverEntCAny_ScreenPosP1P8[5].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCAny_ScreenPosP1P8[2].x, vec_serverEntCAny_ScreenPosP1P8[2].y, vec_serverEntCAny_ScreenPosP1P8[6].x, vec_serverEntCAny_ScreenPosP1P8[6].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCAny_ScreenPosP1P8[3].x, vec_serverEntCAny_ScreenPosP1P8[3].y, vec_serverEntCAny_ScreenPosP1P8[7].x, vec_serverEntCAny_ScreenPosP1P8[7].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCAny_ScreenPosP1P8[4].x, vec_serverEntCAny_ScreenPosP1P8[4].y, vec_serverEntCAny_ScreenPosP1P8[8].x, vec_serverEntCAny_ScreenPosP1P8[8].y, Color.r, Color.g, Color.b, Color.a)
end
if ui_get(ref_extesp_boundingBox) == "On (Static 2D)" then
local vec_serverEntCAny_ScreenPosOffsetX = 0;
local vec_serverEntCAny_ScreenPosOffsetY = 0;
local vec_serverEntCAny_ScreenPosStartX = i_esp_drawScreenWidth;
local vec_serverEntCAny_ScreenPosStartY = i_esp_drawScreenHeight;
for i = 1, 8 do
for j = i + 1, 8 do
vec_serverEntCAny_ScreenPosOffsetX = math_max(vec_serverEntCAny_ScreenPosOffsetX, math_abs(vec_serverEntCAny_ScreenPosP1P8[i].x - vec_serverEntCAny_ScreenPosP1P8[j].x))
vec_serverEntCAny_ScreenPosOffsetY = math_max(vec_serverEntCAny_ScreenPosOffsetY, math_abs(vec_serverEntCAny_ScreenPosP1P8[i].y - vec_serverEntCAny_ScreenPosP1P8[j].y))
end
vec_serverEntCAny_ScreenPosStartX = math_min(vec_serverEntCAny_ScreenPosStartX, vec_serverEntCAny_ScreenPosP1P8[i].x)
vec_serverEntCAny_ScreenPosStartY = math_min(vec_serverEntCAny_ScreenPosStartY, vec_serverEntCAny_ScreenPosP1P8[i].y)
end
local Color = {r, g, b, a};
if b_serverEntCAny_IsVisible == true then
Color.r, Color.g, Color.b, Color.a = accentColor02[1], accentColor02[2], accentColor02[3], accentColor02[4]
else
Color.r, Color.g, Color.b, Color.a = accentColor01[1], accentColor01[2], accentColor01[3], accentColor01[4]
end
-- Bottom
renderer_line(vec_serverEntCAny_ScreenPosStartX, vec_serverEntCAny_ScreenPosStartY + vec_serverEntCAny_ScreenPosOffsetY, vec_serverEntCAny_ScreenPosStartX + vec_serverEntCAny_ScreenPosOffsetX, vec_serverEntCAny_ScreenPosStartY + vec_serverEntCAny_ScreenPosOffsetY, Color.r, Color.g, Color.b, Color.a)
-- Top
renderer_line(vec_serverEntCAny_ScreenPosStartX, vec_serverEntCAny_ScreenPosStartY, vec_serverEntCAny_ScreenPosStartX + vec_serverEntCAny_ScreenPosOffsetX, vec_serverEntCAny_ScreenPosStartY, Color.r, Color.g, Color.b, Color.a)
-- Sides
renderer_line(vec_serverEntCAny_ScreenPosStartX, vec_serverEntCAny_ScreenPosStartY, vec_serverEntCAny_ScreenPosStartX, vec_serverEntCAny_ScreenPosStartY + vec_serverEntCAny_ScreenPosOffsetY, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCAny_ScreenPosStartX + vec_serverEntCAny_ScreenPosOffsetX, vec_serverEntCAny_ScreenPosStartY, vec_serverEntCAny_ScreenPosStartX + vec_serverEntCAny_ScreenPosOffsetX, vec_serverEntCAny_ScreenPosStartY + vec_serverEntCAny_ScreenPosOffsetY, Color.r, Color.g, Color.b, Color.a)
end
end
end
local func_extesp_getBoundingBoxStatic = function(entIndex_serverEntCAny)
local obj_serverEntCAny = Entity(entIndex_serverEntCAny)
local vec_serverEntCAny_WorldPos = {x, y, z}
local vec_serverEntCAny_WorldAng = {pitch, yaw, roll}
vec_serverEntCAny_WorldPos = obj_serverEntCAny:get_vec_origin()
vec_serverEntCAny_WorldAng.pitch, vec_serverEntCAny_WorldAng.yaw, vec_serverEntCAny_WorldAng.roll = entity_get_prop(entIndex_serverEntCAny, "m_angRotation", array_index)
local vec_serverEntCAny_WorldPosVecMins = obj_serverEntCAny:get_vec_mins()
local vec_serverEntCAny_WorldPosVecMaxs = obj_serverEntCAny:get_vec_maxs()
local vec_serverEntCAny_WorldPosP1P8 = {
[1] = {
x = vec_serverEntCAny_WorldPosVecMins.x,
y = vec_serverEntCAny_WorldPosVecMins.y,
z = vec_serverEntCAny_WorldPosVecMins.z,
},
[2] = {
x = vec_serverEntCAny_WorldPosVecMaxs.x,
y = vec_serverEntCAny_WorldPosVecMins.y,
z = vec_serverEntCAny_WorldPosVecMins.z,
},
[3] = {
x = vec_serverEntCAny_WorldPosVecMaxs.x,
y = vec_serverEntCAny_WorldPosVecMaxs.y,
z = vec_serverEntCAny_WorldPosVecMins.z,
},
[4] = {
x = vec_serverEntCAny_WorldPosVecMins.x,
y = vec_serverEntCAny_WorldPosVecMaxs.y,
z = vec_serverEntCAny_WorldPosVecMins.z,
},
[5] = {
x = vec_serverEntCAny_WorldPosVecMins.x,
y = vec_serverEntCAny_WorldPosVecMins.y,
z = vec_serverEntCAny_WorldPosVecMaxs.z,
},
[6] = {
x = vec_serverEntCAny_WorldPosVecMaxs.x,
y = vec_serverEntCAny_WorldPosVecMins.y,
z = vec_serverEntCAny_WorldPosVecMaxs.z,
},
[7] = {
x = vec_serverEntCAny_WorldPosVecMaxs.x,
y = vec_serverEntCAny_WorldPosVecMaxs.y,
z = vec_serverEntCAny_WorldPosVecMaxs.z,
},
[8] = {
x = vec_serverEntCAny_WorldPosVecMins.x,
y = vec_serverEntCAny_WorldPosVecMaxs.y,
z = vec_serverEntCAny_WorldPosVecMaxs.z,
},
}
func_extesp_rotate3D(vec_serverEntCAny_WorldAng.roll, vec_serverEntCAny_WorldAng.pitch, vec_serverEntCAny_WorldAng.yaw, vec_serverEntCAny_WorldPosP1P8)
vec_serverEntCAny_WorldPosP1P8 = {
[1] = {
x = vec_serverEntCAny_WorldPosP1P8[1].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[1].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[1].z + vec_serverEntCAny_WorldPos.z,
},
[2] = {
x = vec_serverEntCAny_WorldPosP1P8[2].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[2].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[2].z + vec_serverEntCAny_WorldPos.z,
},
[3] = {
x = vec_serverEntCAny_WorldPosP1P8[3].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[3].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[3].z + vec_serverEntCAny_WorldPos.z,
},
[4] = {
x = vec_serverEntCAny_WorldPosP1P8[4].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[4].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[4].z + vec_serverEntCAny_WorldPos.z,
},
[5] = {
x = vec_serverEntCAny_WorldPosP1P8[5].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[5].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[5].z + vec_serverEntCAny_WorldPos.z,
},
[6] = {
x = vec_serverEntCAny_WorldPosP1P8[6].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[6].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[6].z + vec_serverEntCAny_WorldPos.z,
},
[7] = {
x = vec_serverEntCAny_WorldPosP1P8[7].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[7].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[7].z + vec_serverEntCAny_WorldPos.z,
},
[8] = {
x = vec_serverEntCAny_WorldPosP1P8[8].x + vec_serverEntCAny_WorldPos.x,
y = vec_serverEntCAny_WorldPosP1P8[8].y + vec_serverEntCAny_WorldPos.y,
z = vec_serverEntCAny_WorldPosP1P8[8].z + vec_serverEntCAny_WorldPos.z,
},
}
local renderer_world_to_screen_asTable = function(Wx, Wy, Wz)
local returnObj = {x, y}
returnObj.x, returnObj.y = renderer_world_to_screen(Wx, Wy, Wz)
return returnObj
end
local vec_serverEntCAny_ScreenPosP1P8 = {
[1] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[1].x, vec_serverEntCAny_WorldPosP1P8[1].y, vec_serverEntCAny_WorldPosP1P8[1].z),
[2] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[2].x, vec_serverEntCAny_WorldPosP1P8[2].y, vec_serverEntCAny_WorldPosP1P8[2].z),
[3] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[3].x, vec_serverEntCAny_WorldPosP1P8[3].y, vec_serverEntCAny_WorldPosP1P8[3].z),
[4] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[4].x, vec_serverEntCAny_WorldPosP1P8[4].y, vec_serverEntCAny_WorldPosP1P8[4].z),
[5] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[5].x, vec_serverEntCAny_WorldPosP1P8[5].y, vec_serverEntCAny_WorldPosP1P8[5].z),
[6] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[6].x, vec_serverEntCAny_WorldPosP1P8[6].y, vec_serverEntCAny_WorldPosP1P8[6].z),
[7] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[7].x, vec_serverEntCAny_WorldPosP1P8[7].y, vec_serverEntCAny_WorldPosP1P8[7].z),
[8] = renderer_world_to_screen_asTable(vec_serverEntCAny_WorldPosP1P8[8].x, vec_serverEntCAny_WorldPosP1P8[8].y, vec_serverEntCAny_WorldPosP1P8[8].z),
}
local returnObj = {x, y, width, height, onScreen}
for i = 1, #vec_serverEntCAny_ScreenPosP1P8 do
if vec_serverEntCAny_ScreenPosP1P8[i].x == nil or vec_serverEntCAny_ScreenPosP1P8[i].y == nil then
returnObj.onScreen = false
return returnObj
end
end
local vec_serverEntCAny_ScreenPosOffsetX = 0;
local vec_serverEntCAny_ScreenPosOffsetY = 0;
local vec_serverEntCAny_ScreenPosStartX = i_esp_drawScreenWidth;
local vec_serverEntCAny_ScreenPosStartY = i_esp_drawScreenHeight;
for i = 1, 8 do
for j = i + 1, 8 do
vec_serverEntCAny_ScreenPosOffsetX = math_max(vec_serverEntCAny_ScreenPosOffsetX, math_abs(vec_serverEntCAny_ScreenPosP1P8[i].x - vec_serverEntCAny_ScreenPosP1P8[j].x))
vec_serverEntCAny_ScreenPosOffsetY = math_max(vec_serverEntCAny_ScreenPosOffsetY, math_abs(vec_serverEntCAny_ScreenPosP1P8[i].y - vec_serverEntCAny_ScreenPosP1P8[j].y))
end
vec_serverEntCAny_ScreenPosStartX = math_min(vec_serverEntCAny_ScreenPosStartX, vec_serverEntCAny_ScreenPosP1P8[i].x)
vec_serverEntCAny_ScreenPosStartY = math_min(vec_serverEntCAny_ScreenPosStartY, vec_serverEntCAny_ScreenPosP1P8[i].y)
end
returnObj.x = vec_serverEntCAny_ScreenPosStartX
returnObj.y = vec_serverEntCAny_ScreenPosStartY
returnObj.width = vec_serverEntCAny_ScreenPosOffsetX
returnObj.height = vec_serverEntCAny_ScreenPosOffsetY
returnObj.onScreen = true
return returnObj
end
local func_extesp_skeleton = function(entIndex_serverEntCCSPlayer, accentColor01, accentColor02)
if ui_get(ref_extesp_skeleton) then
local obj_serverEntCCSPlayer = Player(entIndex_serverEntCCSPlayer)
local obj_localEntCCSPlayer = Player(entIndex_localEntCCSPlayer)
local renderer_world_to_screen_asTable = function(Wx, Wy, Wz)
local returnObj = {x, y}
returnObj.x, returnObj.y = renderer_world_to_screen(Wx, Wy, Wz)
return returnObj
end
local vec_serverEntCCSPlayer_ScreenPosTable = {}
for i = 0, 18 do
local vec_serverEntCCSPlayer_WorldPos = obj_serverEntCCSPlayer:get_hitbox_pos(i)
local vec_serverEntCCSPlayer_ScreenPos = renderer_world_to_screen_asTable(vec_serverEntCCSPlayer_WorldPos.x, vec_serverEntCCSPlayer_WorldPos.y, vec_serverEntCCSPlayer_WorldPos.z)
table.insert(vec_serverEntCCSPlayer_ScreenPosTable, vec_serverEntCCSPlayer_ScreenPos)
end
for i = 1, 19 do
if vec_serverEntCCSPlayer_ScreenPosTable[i].x == nil or vec_serverEntCCSPlayer_ScreenPosTable[i].y == nil then
return
end
-- renderer.text(vec_serverEntCCSPlayer_ScreenPosTable[i].x, vec_serverEntCCSPlayer_ScreenPosTable[i].y, 255, 255, 255, 255, nil, 0, i)
end
b_serverEntCCSPlayer_IsVisible = false
b_serverEntCCSPlayer_IsVisible = obj_localEntCCSPlayer:can_see_point(obj_serverEntCCSPlayer:get_hitbox_pos("head_0"))
local Color = {r, g, b, a};
if b_serverEntCCSPlayer_IsVisible == true then
Color.r, Color.g, Color.b, Color.a = accentColor02[1], accentColor02[2], accentColor02[3], accentColor02[4]
else
Color.r, Color.g, Color.b, Color.a = accentColor01[1], accentColor01[2], accentColor01[3], accentColor01[4]
end
-- Middle
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[1].x, vec_serverEntCCSPlayer_ScreenPosTable[1].y, vec_serverEntCCSPlayer_ScreenPosTable[2].x, vec_serverEntCCSPlayer_ScreenPosTable[2].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[2].x, vec_serverEntCCSPlayer_ScreenPosTable[2].y, vec_serverEntCCSPlayer_ScreenPosTable[7].x, vec_serverEntCCSPlayer_ScreenPosTable[7].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[7].x, vec_serverEntCCSPlayer_ScreenPosTable[7].y, vec_serverEntCCSPlayer_ScreenPosTable[6].x, vec_serverEntCCSPlayer_ScreenPosTable[6].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[6].x, vec_serverEntCCSPlayer_ScreenPosTable[6].y, vec_serverEntCCSPlayer_ScreenPosTable[5].x, vec_serverEntCCSPlayer_ScreenPosTable[5].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[5].x, vec_serverEntCCSPlayer_ScreenPosTable[5].y, vec_serverEntCCSPlayer_ScreenPosTable[4].x, vec_serverEntCCSPlayer_ScreenPosTable[4].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[4].x, vec_serverEntCCSPlayer_ScreenPosTable[4].y, vec_serverEntCCSPlayer_ScreenPosTable[3].x, vec_serverEntCCSPlayer_ScreenPosTable[3].y, Color.r, Color.g, Color.b, Color.a)
-- Arms
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[7].x, vec_serverEntCCSPlayer_ScreenPosTable[7].y, vec_serverEntCCSPlayer_ScreenPosTable[16].x, vec_serverEntCCSPlayer_ScreenPosTable[16].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[16].x, vec_serverEntCCSPlayer_ScreenPosTable[16].y, vec_serverEntCCSPlayer_ScreenPosTable[17].x, vec_serverEntCCSPlayer_ScreenPosTable[17].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[17].x, vec_serverEntCCSPlayer_ScreenPosTable[17].y, vec_serverEntCCSPlayer_ScreenPosTable[14].x, vec_serverEntCCSPlayer_ScreenPosTable[14].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[7].x, vec_serverEntCCSPlayer_ScreenPosTable[7].y, vec_serverEntCCSPlayer_ScreenPosTable[18].x, vec_serverEntCCSPlayer_ScreenPosTable[18].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[18].x, vec_serverEntCCSPlayer_ScreenPosTable[18].y, vec_serverEntCCSPlayer_ScreenPosTable[19].x, vec_serverEntCCSPlayer_ScreenPosTable[19].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[19].x, vec_serverEntCCSPlayer_ScreenPosTable[19].y, vec_serverEntCCSPlayer_ScreenPosTable[15].x, vec_serverEntCCSPlayer_ScreenPosTable[15].y, Color.r, Color.g, Color.b, Color.a)
-- Legs
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[3].x, vec_serverEntCCSPlayer_ScreenPosTable[3].y, vec_serverEntCCSPlayer_ScreenPosTable[8].x, vec_serverEntCCSPlayer_ScreenPosTable[8].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[3].x, vec_serverEntCCSPlayer_ScreenPosTable[3].y, vec_serverEntCCSPlayer_ScreenPosTable[9].x, vec_serverEntCCSPlayer_ScreenPosTable[9].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[8].x, vec_serverEntCCSPlayer_ScreenPosTable[8].y, vec_serverEntCCSPlayer_ScreenPosTable[10].x, vec_serverEntCCSPlayer_ScreenPosTable[10].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[10].x, vec_serverEntCCSPlayer_ScreenPosTable[10].y, vec_serverEntCCSPlayer_ScreenPosTable[12].x, vec_serverEntCCSPlayer_ScreenPosTable[12].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[9].x, vec_serverEntCCSPlayer_ScreenPosTable[9].y, vec_serverEntCCSPlayer_ScreenPosTable[11].x, vec_serverEntCCSPlayer_ScreenPosTable[11].y, Color.r, Color.g, Color.b, Color.a)
renderer_line(vec_serverEntCCSPlayer_ScreenPosTable[11].x, vec_serverEntCCSPlayer_ScreenPosTable[11].y, vec_serverEntCCSPlayer_ScreenPosTable[13].x, vec_serverEntCCSPlayer_ScreenPosTable[13].y, Color.r, Color.g, Color.b, Color.a)
end
end
local func_extesp_hitbox = function(entIndex_serverEntCCSPlayer, accentColor01, accentColor02)
if not(table_is_empty(ui_get(ref_extesp_hitbox))) then
local obj_serverEntCCSPlayer = Player(entIndex_serverEntCCSPlayer)
local obj_localEntCCSPlayer = Player(entIndex_localEntCCSPlayer)
b_serverEntCCSPlayer_IsVisible = false
b_serverEntCCSPlayer_IsVisible = obj_localEntCCSPlayer:can_see_point(obj_serverEntCCSPlayer:get_hitbox_pos("head_0"))
local Color = {r, g, b, a};
if b_serverEntCCSPlayer_IsVisible == true then
Color.r, Color.g, Color.b, Color.a = accentColor02[1], accentColor02[2], accentColor02[3], accentColor02[4]
else
Color.r, Color.g, Color.b, Color.a = accentColor01[1], accentColor01[2], accentColor01[3], accentColor01[4]
end
for i = 0, 18 do
if table_contains_str(ui_get(ref_extesp_hitbox), t_extesp_playerBoneTable[i]) then
client_draw_hitboxes(entIndex_serverEntCCSPlayer, i_extesp_absframetime, i, Color.r, Color.g, Color.b, Color.a)
end
end
end
end
local func_extesp_CCSPlayerInfo = function(entIndex_serverEntCCSPlayer, accentColor01, accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
local obj_serverEntCCSPlayer = Player(entIndex_serverEntCCSPlayer)
local obj_localEntCCSPlayer = Player(entIndex_localEntCCSPlayer)
local i_serverEntCCSPlayer_WorldPos = obj_serverEntCCSPlayer:get_vec_origin()
local i_serverEntCCSPlayer_ScreenPosX, i_serverEntCCSPlayer_ScreenPosY = renderer_world_to_screen(i_serverEntCCSPlayer_WorldPos.x, i_serverEntCCSPlayer_WorldPos.y, i_serverEntCCSPlayer_WorldPos.z)
if i_serverEntCCSPlayer_ScreenPosX ~= nil and i_serverEntCCSPlayer_ScreenPosY ~= nil then
if func_extesp_getClampToViewport(i_esp_drawScreenWidth, i_esp_drawScreenHeight, i_serverEntCCSPlayer_ScreenPosX, i_serverEntCCSPlayer_ScreenPosY, ui_get(ref_extesp_padding)) == false then
i_serverEntCCSPlayer_ScreenPosX, i_serverEntCCSPlayer_ScreenPosY = func_extesp_clampToViewport(i_esp_drawScreenWidth, i_esp_drawScreenHeight, i_esp_anchorPosX, i_esp_anchorPosY, i_serverEntCCSPlayer_ScreenPosX, i_serverEntCCSPlayer_ScreenPosY, ui_get(ref_extesp_padding))
local i_esp_draw_strOffset = 1
--
--
-- Name
--
--
if ui_get(ref_extesp_name) then
local i_esp_draw_name_strSizeX, i_esp_draw_name_strSizeY = renderer_measure_text("b", "Name: " .. obj_serverEntCCSPlayer:get_name())
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_name_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_name_strSizeY * i_esp_draw_strOffset, i_esp_draw_name_strSizeX + 8, i_esp_draw_name_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_name_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_name_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "Name: " .. obj_serverEntCCSPlayer:get_name())
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Health
--
--
if ui_get(ref_extesp_health) then
local i_esp_draw_health_strSizeX, i_esp_draw_health_strSizeY = renderer_measure_text("b", "Health: " .. obj_serverEntCCSPlayer:get_health() .. "%")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_health_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_health_strSizeY * i_esp_draw_strOffset, i_esp_draw_health_strSizeX + 8, i_esp_draw_health_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_health_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_health_strSizeY * i_esp_draw_strOffset, 255 - 255 * obj_serverEntCCSPlayer:get_health() / 100, 255 * obj_serverEntCCSPlayer:get_health() / 100, 0, 255, "b", 0, "Health: " .. obj_serverEntCCSPlayer:get_health() .. "%")
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Armor
--
--
if ui_get(ref_extesp_armor) then
if obj_serverEntCCSPlayer:playerresource():get_armor() > 0 then
local i_esp_draw_armor_strSizeX, i_esp_draw_armor_strSizeY = renderer_measure_text("b", "Armor: " .. obj_serverEntCCSPlayer:playerresource():get_armor() .. "%")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_armor_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_armor_strSizeY * i_esp_draw_strOffset, i_esp_draw_armor_strSizeX + 8, i_esp_draw_armor_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_armor_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_armor_strSizeY * i_esp_draw_strOffset, 127 + 127 * obj_serverEntCCSPlayer:playerresource():get_armor() / 100, 127 + 127 * obj_serverEntCCSPlayer:playerresource():get_armor() / 100, 127 + 127 * obj_serverEntCCSPlayer:playerresource():get_armor() / 100, 255, "b", 0, "Armor: " .. obj_serverEntCCSPlayer:playerresource():get_armor() .. "%")
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
end
--
--
-- Distance
--
--
if ui_get(ref_extesp_distance) ~= "Off" then
local i_localEntCCSPlayer_WorldPos = obj_localEntCCSPlayer:get_vec_origin()
local value = math.sqrt((i_serverEntCCSPlayer_WorldPos.x - i_localEntCCSPlayer_WorldPos.x) ^ 2 + (i_serverEntCCSPlayer_WorldPos.y - i_localEntCCSPlayer_WorldPos.y) ^ 2 + (i_serverEntCCSPlayer_WorldPos.z - i_localEntCCSPlayer_WorldPos.z) ^ 2)
local valueUnit = " u."
if ui_get(ref_extesp_distance) == "Metric" then
value = value * 0.01905
valueUnit = " m."
end
if ui_get(ref_extesp_distance) == "Imperial" then
value = value * 0.075
valueUnit = " ft."
end
local i_esp_draw_distance_strSizeX, i_esp_draw_distance_strSizeY = renderer_measure_text("b", "Distance: " .. string.format("%d", value) .. valueUnit)
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_distance_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_distance_strSizeY * i_esp_draw_strOffset, i_esp_draw_distance_strSizeX + 8, i_esp_draw_distance_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_distance_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_distance_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "Distance: " .. string.format("%d", value) .. valueUnit)
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- NAV Location
--
--
if ui_get(ref_extesp_navlocation) then
local str_esp_draw_navlocation = entity_get_prop(entIndex_serverEntCCSPlayer, "m_szLastPlaceName", array_index)
local i_esp_draw_navlocation_strSizeX, i_esp_draw_navlocation_strSizeY = renderer_measure_text("b", "Location: " .. str_esp_draw_navlocation)
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_navlocation_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_navlocation_strSizeY * i_esp_draw_strOffset, i_esp_draw_navlocation_strSizeX + 8, i_esp_draw_navlocation_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_navlocation_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_navlocation_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "Location: " .. str_esp_draw_navlocation)
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Weapons
--
--
if ui_get(ref_extesp_equipment) then
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
local arr_esp_draw_weapons = obj_serverEntCCSPlayer:get_all_weapons()
for i = 1, #arr_esp_draw_weapons do
local ent_esp_draw_weapon = arr_esp_draw_weapons[i]
local str_esp_draw_weapon = ""
if ui_get(ref_extesp_ammo) and not(ent_esp_draw_weapon:is_knife()) and ent_esp_draw_weapon:get_current_ammo() ~= nil and ent_esp_draw_weapon:get_max_ammo() ~= nil then
str_esp_draw_weapon = ent_esp_draw_weapon:get_name() .. " (" .. ent_esp_draw_weapon:get_current_ammo() .. "/" .. ent_esp_draw_weapon:get_max_ammo() .. ")"
else
str_esp_draw_weapon = ent_esp_draw_weapon:get_name()
end
local i_esp_draw_weapon_strSizeX, i_esp_draw_weapon_strSizeY = renderer_measure_text("b", str_esp_draw_weapon)
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_weapon_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_weapon_strSizeY * i_esp_draw_strOffset, i_esp_draw_weapon_strSizeX + 8, i_esp_draw_weapon_strSizeY, 0, 0, 0, 127)
if ent_esp_draw_weapon:get_index() == obj_serverEntCCSPlayer:get_active_weapon():get_index() then
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_weapon_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_weapon_strSizeY * i_esp_draw_strOffset, 255, 255, 0, 255, "b", 0, str_esp_draw_weapon)
else
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_weapon_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_weapon_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, str_esp_draw_weapon)
end
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
end
--
--
-- Player State
--
--
if ui_get(ref_extesp_flags) then
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
--
--
-- Is Scoped
--
--
if obj_serverEntCCSPlayer:is_scoped() then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "Scoped")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 255, 255, 0, 255, "b", 0, "Scoped")
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Is Flashed
--
--
if obj_serverEntCCSPlayer:is_flashed() then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "Flashed")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 193, 240, 255, 255, "b", 0, "Flashed")
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Has Bomb
--
--
if obj_serverEntCCSPlayer:has_bomb() then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "Bombcarrier")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 255, 127, 0, 255, "b", 0, "Bombcarrier")
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Has Defuser
--
--
if obj_serverEntCCSPlayer:has_defuser() then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "Has Kit")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 0, 127, 255, 255, "b", 0, "Has Kit")
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Is In Air
--
--
if bit.band(obj_serverEntCCSPlayer:get_flags(), 1) ~= 1 then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "In Air")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "In Air")
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Is Ducking
--
--
if bit.band(obj_serverEntCCSPlayer:get_flags(), 2) == 2 and bit.band(obj_serverEntCCSPlayer:get_flags(), 3) == 3 and bit.band(obj_serverEntCCSPlayer:get_flags(), 4) == 4 then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "Ducking")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "Ducking")
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Is In Water
--
--
if bit.band(obj_serverEntCCSPlayer:get_flags(), 10) == 10 then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "In Water")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosX - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosY + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "In Water")
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
end
else
local i_serverEntCCSPlayer_ScreenBoundingBox = func_extesp_getBoundingBoxStatic(entIndex_serverEntCCSPlayer)
if i_serverEntCCSPlayer_ScreenBoundingBox.onScreen == false then
return
end
local i_serverEntCCSPlayer_ScreenPosTop = {x = i_serverEntCCSPlayer_ScreenBoundingBox.x + math_floor(i_serverEntCCSPlayer_ScreenBoundingBox.width / 2), y = i_serverEntCCSPlayer_ScreenBoundingBox.y - 4}
local i_serverEntCCSPlayer_ScreenPosBottom = {x = i_serverEntCCSPlayer_ScreenBoundingBox.x + math_floor(i_serverEntCCSPlayer_ScreenBoundingBox.width / 2), y = i_serverEntCCSPlayer_ScreenBoundingBox.y + i_serverEntCCSPlayer_ScreenBoundingBox.height - 8}
local i_serverEntCCSPlayer_ScreenPosSideLeft = {x = i_serverEntCCSPlayer_ScreenBoundingBox.x - 8, y = i_serverEntCCSPlayer_ScreenBoundingBox.y}
local i_serverEntCCSPlayer_ScreenPosSideRight = {x = i_serverEntCCSPlayer_ScreenBoundingBox.x + i_serverEntCCSPlayer_ScreenBoundingBox.width + 5, y = i_serverEntCCSPlayer_ScreenBoundingBox.y}
--Top
do
local i_esp_draw_strOffset = -1
--
--
-- Name
--
--
if ui_get(ref_extesp_name) then
local i_esp_draw_name_strSizeX, i_esp_draw_name_strSizeY = renderer_measure_text("b", "Name: " .. obj_serverEntCCSPlayer:get_name())
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_name_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_name_strSizeY * i_esp_draw_strOffset, i_esp_draw_name_strSizeX + 8, i_esp_draw_name_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_name_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_name_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "Name: " .. obj_serverEntCCSPlayer:get_name())
i_esp_draw_strOffset = i_esp_draw_strOffset - 1
end
--
--
-- Player State
--
--
if ui_get(ref_extesp_flags) then
i_esp_draw_strOffset = i_esp_draw_strOffset - 1
--
--
-- Is Scoped
--
--
if obj_serverEntCCSPlayer:is_scoped() then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "Scoped")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 255, 255, 0, 255, "b", 0, "Scoped")
i_esp_draw_strOffset = i_esp_draw_strOffset - 1
end
--
--
-- Is Flashed
--
--
if obj_serverEntCCSPlayer:is_flashed() then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "Flashed")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 193, 240, 255, 255, "b", 0, "Flashed")
i_esp_draw_strOffset = i_esp_draw_strOffset - 1
end
--
--
-- Has Bomb
--
--
if obj_serverEntCCSPlayer:has_bomb() then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "Bombcarrier")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 255, 127, 0, 255, "b", 0, "Bombcarrier")
i_esp_draw_strOffset = i_esp_draw_strOffset - 1
end
--
--
-- Has Defuser
--
--
if obj_serverEntCCSPlayer:has_defuser() then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "Has Kit")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 0, 127, 255, 255, "b", 0, "Has Kit")
i_esp_draw_strOffset = i_esp_draw_strOffset - 1
end
--
--
-- Is In Air
--
--
if bit.band(obj_serverEntCCSPlayer:get_flags(), 1) ~= 1 then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "In Air")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "In Air")
i_esp_draw_strOffset = i_esp_draw_strOffset - 1
end
--
--
-- Is Ducking
--
--
if bit.band(obj_serverEntCCSPlayer:get_flags(), 2) == 2 and bit.band(obj_serverEntCCSPlayer:get_flags(), 3) == 3 and bit.band(obj_serverEntCCSPlayer:get_flags(), 4) == 4 then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "Ducking")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "Ducking")
i_esp_draw_strOffset = i_esp_draw_strOffset - 1
end
--
--
-- Is In Water
--
--
if bit.band(obj_serverEntCCSPlayer:get_flags(), 10) == 10 then
local i_esp_draw_state_strSizeX, i_esp_draw_state_strSizeY = renderer_measure_text("b", "In Water")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, i_esp_draw_state_strSizeX + 8, i_esp_draw_state_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosTop.x - i_esp_draw_state_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosTop.y + i_esp_draw_state_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "In Water")
i_esp_draw_strOffset = i_esp_draw_strOffset - 1
end
end
end
--Bottom
do
local i_esp_draw_strOffset = 1
--
--
-- Distance
--
--
if ui_get(ref_extesp_distance) ~= "Off" then
local i_localEntCCSPlayer_WorldPos = obj_localEntCCSPlayer:get_vec_origin()
local value = math.sqrt((i_serverEntCCSPlayer_WorldPos.x - i_localEntCCSPlayer_WorldPos.x) ^ 2 + (i_serverEntCCSPlayer_WorldPos.y - i_localEntCCSPlayer_WorldPos.y) ^ 2 + (i_serverEntCCSPlayer_WorldPos.z - i_localEntCCSPlayer_WorldPos.z) ^ 2)
local valueUnit = " u."
if ui_get(ref_extesp_distance) == "Metric" then
value = value * 0.01905
valueUnit = " m."
end
if ui_get(ref_extesp_distance) == "Imperial" then
value = value * 0.075
valueUnit = " ft."
end
local i_esp_draw_distance_strSizeX, i_esp_draw_distance_strSizeY = renderer_measure_text("b", "Distance: " .. string.format("%d", value) .. valueUnit)
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosBottom.x - i_esp_draw_distance_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosBottom.y + i_esp_draw_distance_strSizeY * i_esp_draw_strOffset, i_esp_draw_distance_strSizeX + 8, i_esp_draw_distance_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosBottom.x - i_esp_draw_distance_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosBottom.y + i_esp_draw_distance_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "Distance: " .. string.format("%d", value) .. valueUnit)
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Weapons
--
--
if ui_get(ref_extesp_equipment) then
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
local arr_esp_draw_weapons = obj_serverEntCCSPlayer:get_all_weapons()
for i = 1, #arr_esp_draw_weapons do
local ent_esp_draw_weapon = arr_esp_draw_weapons[i]
local str_esp_draw_weapon = ""
if ui_get(ref_extesp_ammo) and not(ent_esp_draw_weapon:is_knife()) and ent_esp_draw_weapon:get_current_ammo() ~= nil and ent_esp_draw_weapon:get_max_ammo() ~= nil then
str_esp_draw_weapon = ent_esp_draw_weapon:get_name() .. " (" .. ent_esp_draw_weapon:get_current_ammo() .. "/" .. ent_esp_draw_weapon:get_max_ammo() .. ")"
else
str_esp_draw_weapon = ent_esp_draw_weapon:get_name()
end
local i_esp_draw_weapon_strSizeX, i_esp_draw_weapon_strSizeY = renderer_measure_text("b", str_esp_draw_weapon)
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosBottom.x - i_esp_draw_weapon_strSizeX / 2 - 4, i_serverEntCCSPlayer_ScreenPosBottom.y + i_esp_draw_weapon_strSizeY * i_esp_draw_strOffset, i_esp_draw_weapon_strSizeX + 8, i_esp_draw_weapon_strSizeY, 0, 0, 0, 127)
if ent_esp_draw_weapon:get_index() == obj_serverEntCCSPlayer:get_active_weapon():get_index() then
renderer_text(i_serverEntCCSPlayer_ScreenPosBottom.x - i_esp_draw_weapon_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosBottom.y + i_esp_draw_weapon_strSizeY * i_esp_draw_strOffset, 255, 255, 0, 255, "b", 0, str_esp_draw_weapon)
else
renderer_text(i_serverEntCCSPlayer_ScreenPosBottom.x - i_esp_draw_weapon_strSizeX / 2, i_serverEntCCSPlayer_ScreenPosBottom.y + i_esp_draw_weapon_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, str_esp_draw_weapon)
end
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
end
end
--Side Left
do
local i_esp_draw_strOffset = 0
--
--
-- Health
--
--
if ui_get(ref_extesp_health) then
local i_esp_draw_health_strSizeX, i_esp_draw_health_strSizeY = renderer_measure_text("b", "HP: " .. obj_serverEntCCSPlayer:get_health() .. "%")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosSideLeft.x - 4, i_serverEntCCSPlayer_ScreenPosSideLeft.y, 6, i_serverEntCCSPlayer_ScreenBoundingBox.height + 1, 0, 0, 0, 127)
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosSideLeft.x - 3, i_serverEntCCSPlayer_ScreenPosSideLeft.y + 1 + (i_serverEntCCSPlayer_ScreenBoundingBox.height - math_floor(i_serverEntCCSPlayer_ScreenBoundingBox.height * obj_serverEntCCSPlayer:get_health() / 100)), 4, math_floor(i_serverEntCCSPlayer_ScreenBoundingBox.height * obj_serverEntCCSPlayer:get_health() / 100) - 1, 255 - 255 * obj_serverEntCCSPlayer:get_health() / 100, 255 * obj_serverEntCCSPlayer:get_health() / 100, 0, 255)
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosSideLeft.x - i_esp_draw_health_strSizeX - 12, i_serverEntCCSPlayer_ScreenPosSideLeft.y + i_esp_draw_health_strSizeY * i_esp_draw_strOffset + (i_serverEntCCSPlayer_ScreenBoundingBox.height - math_floor(i_serverEntCCSPlayer_ScreenBoundingBox.height * obj_serverEntCCSPlayer:get_health() / 100)), i_esp_draw_health_strSizeX + 8, i_esp_draw_health_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosSideLeft.x - 8, i_serverEntCCSPlayer_ScreenPosSideLeft.y + i_esp_draw_health_strSizeY * i_esp_draw_strOffset + (i_serverEntCCSPlayer_ScreenBoundingBox.height - math_floor(i_serverEntCCSPlayer_ScreenBoundingBox.height * obj_serverEntCCSPlayer:get_health() / 100)), 255 - 255 * obj_serverEntCCSPlayer:get_health() / 100, 255 * obj_serverEntCCSPlayer:get_health() / 100, 0, 255, "br", 0, "HP: " .. obj_serverEntCCSPlayer:get_health() .. "%")
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Armor
--
--
if ui_get(ref_extesp_armor) then
if obj_serverEntCCSPlayer:playerresource():get_armor() > 0 then
local i_esp_draw_armor_strSizeX, i_esp_draw_armor_strSizeY = renderer_measure_text("b", "Armor: " .. obj_serverEntCCSPlayer:playerresource():get_armor() .. "%")
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosSideLeft.x - i_esp_draw_armor_strSizeX - 12, i_serverEntCCSPlayer_ScreenPosSideLeft.y + i_esp_draw_armor_strSizeY * i_esp_draw_strOffset + (i_serverEntCCSPlayer_ScreenBoundingBox.height - math_floor(i_serverEntCCSPlayer_ScreenBoundingBox.height * obj_serverEntCCSPlayer:get_health() / 100)), i_esp_draw_armor_strSizeX + 8, i_esp_draw_armor_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosSideLeft.x - 8, i_serverEntCCSPlayer_ScreenPosSideLeft.y + i_esp_draw_armor_strSizeY * i_esp_draw_strOffset + (i_serverEntCCSPlayer_ScreenBoundingBox.height - math_floor(i_serverEntCCSPlayer_ScreenBoundingBox.height * obj_serverEntCCSPlayer:get_health() / 100)), 127 + 127 * obj_serverEntCCSPlayer:playerresource():get_armor() / 100, 127 + 127 * obj_serverEntCCSPlayer:playerresource():get_armor() / 100, 127 + 127 * obj_serverEntCCSPlayer:playerresource():get_armor() / 100, 255, "br", 0, "Armor: " .. obj_serverEntCCSPlayer:playerresource():get_armor() .. "%")
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
end
end
--Side Right
do
local i_esp_draw_strOffset = 0
--
--
-- NAV Location
--
--
if ui_get(ref_extesp_navlocation) then
local str_esp_draw_navlocation = entity_get_prop(entIndex_serverEntCCSPlayer, "m_szLastPlaceName", array_index)
local i_esp_draw_navlocation_strSizeX, i_esp_draw_navlocation_strSizeY = renderer_measure_text("b", "Location: " .. str_esp_draw_navlocation)
renderer_rectangle(i_serverEntCCSPlayer_ScreenPosSideRight.x, i_serverEntCCSPlayer_ScreenPosSideRight.y + i_esp_draw_navlocation_strSizeY * i_esp_draw_strOffset, i_esp_draw_navlocation_strSizeX + 8, i_esp_draw_navlocation_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCCSPlayer_ScreenPosSideRight.x + 4, i_serverEntCCSPlayer_ScreenPosSideRight.y + i_esp_draw_navlocation_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "Location: " .. str_esp_draw_navlocation)
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
end
end
end
end
local func_extesp_CWeaponCSBaseInfo = function(entIndex_serverEntCWeaponCSBase, accentColor01, accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
local obj_serverEntCWeaponCSBase = Entity(entIndex_serverEntCWeaponCSBase)
local obj_localEntCCSPlayer = Player(entIndex_localEntCCSPlayer)
local i_serverEntCWeaponCSBase_WorldPos = obj_serverEntCWeaponCSBase:get_vec_origin()
local i_serverEntCWeaponCSBase_ScreenPosX, i_serverEntCWeaponCSBase_ScreenPosY = renderer_world_to_screen(i_serverEntCWeaponCSBase_WorldPos.x, i_serverEntCWeaponCSBase_WorldPos.y, i_serverEntCWeaponCSBase_WorldPos.z)
obj_serverEntCWeaponCSBase = Weapon(entIndex_serverEntCWeaponCSBase)
if i_serverEntCWeaponCSBase_ScreenPosX ~= nil and i_serverEntCWeaponCSBase_ScreenPosY ~= nil then
i_serverEntCWeaponCSBase_ScreenPosX, i_serverEntCWeaponCSBase_ScreenPosY = func_extesp_clampToViewport(i_esp_drawScreenWidth, i_esp_drawScreenHeight, i_esp_anchorPosX, i_esp_anchorPosY, i_serverEntCWeaponCSBase_ScreenPosX, i_serverEntCWeaponCSBase_ScreenPosY, ui_get(ref_extesp_padding))
local i_esp_draw_strOffset = 1
--
--
-- Name
--
--
if ui_get(ref_extesp_name) then
local str_esp_draw_weapon = ""
if ui_get(ref_extesp_ammo) and not(obj_serverEntCWeaponCSBase:is_grenade()) and not(obj_serverEntCWeaponCSBase:is_knife()) and not(string_match(entity_get_classname(entIndex_serverEntCWeaponCSBase), "CSnowball") ~= nil) and not(string_match(entity_get_classname(entIndex_serverEntCWeaponCSBase), "CSensorGrenade") ~= nil) then
if entity_get_classname(entIndex_serverEntCWeaponCSBase) ~= "CWeaponTaser" then
str_esp_draw_weapon = obj_serverEntCWeaponCSBase:get_name() .. " (" .. obj_serverEntCWeaponCSBase:get_current_ammo() .. "/" .. obj_serverEntCWeaponCSBase:get_max_ammo() .. ")"
else
if entity_get_prop(entIndex_serverEntCWeaponCSBase, "m_iClip1", array_index) > 0 then
str_esp_draw_weapon = obj_serverEntCWeaponCSBase:get_name() .. " (" .. "Charged" .. ")"
else
str_esp_draw_weapon = obj_serverEntCWeaponCSBase:get_name() .. " (" .. "Empty" .. ")"
end
end
else
if string_match(entity_get_classname(entIndex_serverEntCWeaponCSBase), "CSnowball") ~= nil then
str_esp_draw_weapon = "Snowball"
elseif string_match(entity_get_classname(entIndex_serverEntCWeaponCSBase), "CSensorGrenade") ~= nil then
str_esp_draw_weapon = "TA Grenade"
else
str_esp_draw_weapon = obj_serverEntCWeaponCSBase:get_name()
end
end
local i_esp_draw_name_strSizeX, i_esp_draw_name_strSizeY = renderer_measure_text("b", str_esp_draw_weapon)
renderer_rectangle(i_serverEntCWeaponCSBase_ScreenPosX - i_esp_draw_name_strSizeX / 2 - 4, i_serverEntCWeaponCSBase_ScreenPosY + i_esp_draw_name_strSizeY * i_esp_draw_strOffset, i_esp_draw_name_strSizeX + 8, i_esp_draw_name_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCWeaponCSBase_ScreenPosX - i_esp_draw_name_strSizeX / 2, i_serverEntCWeaponCSBase_ScreenPosY + i_esp_draw_name_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, str_esp_draw_weapon)
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Distance
--
--
if ui_get(ref_extesp_distance) ~= "Off" then
local i_localEntCCSPlayer_WorldPos = obj_localEntCCSPlayer:get_vec_origin()
local value = math.sqrt((i_serverEntCWeaponCSBase_WorldPos.x - i_localEntCCSPlayer_WorldPos.x) ^ 2 + (i_serverEntCWeaponCSBase_WorldPos.y - i_localEntCCSPlayer_WorldPos.y) ^ 2 + (i_serverEntCWeaponCSBase_WorldPos.z - i_localEntCCSPlayer_WorldPos.z) ^ 2)
local valueUnit = " u."
if ui_get(ref_extesp_distance) == "Metric" then
value = value * 0.01905
valueUnit = " m."
end
if ui_get(ref_extesp_distance) == "Imperial" then
value = value * 0.075
valueUnit = " ft."
end
local i_esp_draw_distance_strSizeX, i_esp_draw_distance_strSizeY = renderer_measure_text("b", "Distance: " .. string.format("%d", value) .. valueUnit)
renderer_rectangle(i_serverEntCWeaponCSBase_ScreenPosX - i_esp_draw_distance_strSizeX / 2 - 4, i_serverEntCWeaponCSBase_ScreenPosY + i_esp_draw_distance_strSizeY * i_esp_draw_strOffset, i_esp_draw_distance_strSizeX + 8, i_esp_draw_distance_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCWeaponCSBase_ScreenPosX - i_esp_draw_distance_strSizeX / 2, i_serverEntCWeaponCSBase_ScreenPosY + i_esp_draw_distance_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "Distance: " .. string.format("%d", value) .. valueUnit)
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
end
end
local func_extesp_CAnyInfo = function(entIndex_serverEntCAny, accentColor01, accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
local obj_serverEntCAny = Entity(entIndex_serverEntCAny)
local obj_localEntCCSPlayer = Player(entIndex_localEntCCSPlayer)
local i_serverEntCAny_WorldPos = obj_serverEntCAny:get_vec_origin()
local i_serverEntCAny_ScreenPosX, i_serverEntCAny_ScreenPosY = renderer_world_to_screen(i_serverEntCAny_WorldPos.x, i_serverEntCAny_WorldPos.y, i_serverEntCAny_WorldPos.z)
if i_serverEntCAny_ScreenPosX ~= nil and i_serverEntCAny_ScreenPosY ~= nil then
i_serverEntCAny_ScreenPosX, i_serverEntCAny_ScreenPosY = func_extesp_clampToViewport(i_esp_drawScreenWidth, i_esp_drawScreenHeight, i_esp_anchorPosX, i_esp_anchorPosY, i_serverEntCAny_ScreenPosX, i_serverEntCAny_ScreenPosY, ui_get(ref_extesp_padding))
local i_esp_draw_strOffset = 1
--
--
-- Name
--
--
if ui_get(ref_extesp_name) then
local str_esp_draw_name = ""
local i_esp_draw_name_strSizeX, i_esp_draw_name_strSizeY
if entity_get_classname(entIndex_serverEntCAny) == "CC4" then
str_esp_draw_name = "C4"
elseif entity_get_classname(entIndex_serverEntCAny) == "CPlantedC4" then
-- TODO: Add timer
str_esp_draw_name = "C4 (Planted)"
elseif entity_get_classname(entIndex_serverEntCAny) == "CHostage" then
str_esp_draw_name = "Hostage"
elseif entity_get_classname(entIndex_serverEntCAny) == "CEconEntity" then
str_esp_draw_name = "Kit"
elseif entity_get_classname(entIndex_serverEntCAny) == "CSmokeGrenadeProjectile" then
str_esp_draw_name = "Smoke"
elseif entity_get_classname(entIndex_serverEntCAny) == "CSensorGrenadeProjectile" then
str_esp_draw_name = "TA Grenade"
elseif entity_get_classname(entIndex_serverEntCAny) == "CSnowballProjectile" then
str_esp_draw_name = "Snowball"
elseif entity_get_classname(entIndex_serverEntCAny) == "CDecoyProjectile" then
str_esp_draw_name = "Decoy"
elseif entity_get_classname(entIndex_serverEntCAny) == "CMolotovProjectile" then
if entity_get_prop(entIndex_serverEntCAny, "m_bIsIncGrenade", array_index) == 1 then
str_esp_draw_name = "Incendiary"
else
str_esp_draw_name = "Molotov"
end
elseif entity_get_classname(entIndex_serverEntCAny) == "CBaseCSGrenadeProjectile" then
if entity_get_prop(entIndex_serverEntCAny, "m_DmgRadius", array_index) == 350 then
str_esp_draw_name = "HE Grenade"
else
str_esp_draw_name = "Flashbang"
end
else
str_esp_draw_name = obj_serverEntCAny:get_classname()
end
i_esp_draw_name_strSizeX, i_esp_draw_name_strSizeY = renderer_measure_text("b", str_esp_draw_name)
renderer_rectangle(i_serverEntCAny_ScreenPosX - i_esp_draw_name_strSizeX / 2 - 4, i_serverEntCAny_ScreenPosY + i_esp_draw_name_strSizeY * i_esp_draw_strOffset, i_esp_draw_name_strSizeX + 8, i_esp_draw_name_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCAny_ScreenPosX - i_esp_draw_name_strSizeX / 2, i_serverEntCAny_ScreenPosY + i_esp_draw_name_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, str_esp_draw_name)
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
--
--
-- Distance
--
--
if ui_get(ref_extesp_distance) ~= "Off" then
local i_localEntCCSPlayer_WorldPos = obj_localEntCCSPlayer:get_vec_origin()
local value = math.sqrt((i_serverEntCAny_WorldPos.x - i_localEntCCSPlayer_WorldPos.x) ^ 2 + (i_serverEntCAny_WorldPos.y - i_localEntCCSPlayer_WorldPos.y) ^ 2 + (i_serverEntCAny_WorldPos.z - i_localEntCCSPlayer_WorldPos.z) ^ 2)
local valueUnit = " u."
if ui_get(ref_extesp_distance) == "Metric" then
value = value * 0.01905
valueUnit = " m."
end
if ui_get(ref_extesp_distance) == "Imperial" then
value = value * 0.075
valueUnit = " ft."
end
local i_esp_draw_distance_strSizeX, i_esp_draw_distance_strSizeY = renderer_measure_text("b", "Distance: " .. string.format("%d", value) .. valueUnit)
renderer_rectangle(i_serverEntCAny_ScreenPosX - i_esp_draw_distance_strSizeX / 2 - 4, i_serverEntCAny_ScreenPosY + i_esp_draw_distance_strSizeY * i_esp_draw_strOffset, i_esp_draw_distance_strSizeX + 8, i_esp_draw_distance_strSizeY, 0, 0, 0, 127)
renderer_text(i_serverEntCAny_ScreenPosX - i_esp_draw_distance_strSizeX / 2, i_serverEntCAny_ScreenPosY + i_esp_draw_distance_strSizeY * i_esp_draw_strOffset, 255, 255, 255, 255, "b", 0, "Distance: " .. string.format("%d", value) .. valueUnit)
i_esp_draw_strOffset = i_esp_draw_strOffset + 1
end
end
end
function func_extesp_eDraw(ctx)
local arr = ui_get(ref_extesp_filter_playersSubtype);
if not ui_get(ref_extesp_enable) then
return
end
if not(table_is_empty(ui_get(ref_extesp_hitbox))) then
i_extesp_frametime = globals_frametime()
table.insert(t_extesp_frametime_history, i_extesp_frametime)
if #t_extesp_frametime_history > ui_get(ref_extesp_hitbox_antiflicker) then
table.remove(t_extesp_frametime_history, 1)
end
i_extesp_absframetime = math_max(unpack(t_extesp_frametime_history))
end
local i_esp_anchorPosX = math_floor(i_esp_drawScreenWidth * (ui_get(ref_extesp_snaplineStartX) / 100))
local i_esp_anchorPosY = math_floor(i_esp_drawScreenHeight * (ui_get(ref_extesp_snaplineStartY) / 100))
i_esp_anchorPosX = math_min(i_esp_drawScreenWidth - ui_get(ref_extesp_padding), math_max(ui_get(ref_extesp_padding), i_esp_anchorPosX))
i_esp_anchorPosY = math_min(i_esp_drawScreenHeight - ui_get(ref_extesp_padding), math_max(ui_get(ref_extesp_padding), i_esp_anchorPosY))
local f_extesp_globalRealtime = globals.realtime()
b_esp_filter_mapObjective_accentColor01 = func_extesp_rainbowise(4, 255, 1, 0, 255, f_extesp_globalRealtime, 0, 127)
b_esp_filter_mapObjective_accentColor02 = func_extesp_rainbowise(4, 255, 1, 0, 255, f_extesp_globalRealtime, 0, 255)
b_esp_filter_mapObjective_accentColor01[4] = 255
b_esp_filter_mapObjective_accentColor02[4] = 255
local array_index = {}
local entIndex_localEntCCSPlayer = entity_get_local_player()
local entIndex_localEntCCSPlayer_kTeamid = entity_get_prop(entIndex_localEntCCSPlayer, "m_iTeamNum", array_index)
if ui_get(ref_extesp_filter_players) ~= "Off" then
local arr_entIndex_serverEntCCSPlayer = entity_get_players(false)
if ui_get(ref_extesp_filter_players) == "On (Ally/Enemy)" and not(entIndex_localEntCCSPlayer_kTeamid == 1) and not(entIndex_localEntCCSPlayer_kTeamid == 0) then --Differentiate by relationship
for i = 1, #arr_entIndex_serverEntCCSPlayer do
local entIndex_serverEntCCSPlayer = arr_entIndex_serverEntCCSPlayer[i]
local obj_serverEntCCSPlayer = Player(entIndex_serverEntCCSPlayer)
if obj_serverEntCCSPlayer:is_alive() then
local i_serverEntCCSPlayer_kTeamid = obj_serverEntCCSPlayer:get_teamnum()
if table_contains_str(ui_get(ref_extesp_filter_playersSubtype), "Enemy") then
if entIndex_serverEntCCSPlayer ~= entIndex_localEntCCSPlayer and i_serverEntCCSPlayer_kTeamid ~= entIndex_localEntCCSPlayer_kTeamid then
func_extesp_snapline(entIndex_serverEntCCSPlayer, b_esp_filter_playerEnemy_accentColor01, b_esp_filter_playerEnemy_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCCSPlayer, b_esp_filter_playerEnemy_accentColor01, b_esp_filter_playerEnemy_accentColor02)
func_extesp_CCSPlayerInfo(entIndex_serverEntCCSPlayer, b_esp_filter_playerEnemy_accentColor01, b_esp_filter_playerEnemy_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_skeleton(entIndex_serverEntCCSPlayer, b_esp_filter_playerEnemy_accentColor01, b_esp_filter_playerEnemy_accentColor02)
func_extesp_hitbox(entIndex_serverEntCCSPlayer, b_esp_filter_playerEnemy_accentColor01, b_esp_filter_playerEnemy_accentColor02)
end
end
if table_contains_str(ui_get(ref_extesp_filter_playersSubtype), "Ally") then
if entIndex_serverEntCCSPlayer ~= entIndex_localEntCCSPlayer and i_serverEntCCSPlayer_kTeamid == entIndex_localEntCCSPlayer_kTeamid then
func_extesp_snapline(entIndex_serverEntCCSPlayer, b_esp_filter_playerAlly_accentColor01, b_esp_filter_playerAlly_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCCSPlayer, b_esp_filter_playerAlly_accentColor01, b_esp_filter_playerAlly_accentColor02)
func_extesp_CCSPlayerInfo(entIndex_serverEntCCSPlayer, b_esp_filter_playerAlly_accentColor01, b_esp_filter_playerAlly_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_skeleton(entIndex_serverEntCCSPlayer, b_esp_filter_playerAlly_accentColor01, b_esp_filter_playerAlly_accentColor02)
func_extesp_hitbox(entIndex_serverEntCCSPlayer, b_esp_filter_playerAlly_accentColor01, b_esp_filter_playerAlly_accentColor02)
end
end
end
end
end
if ui_get(ref_extesp_filter_players) == "On (CT/T)" or entIndex_localEntCCSPlayer_kTeamid == 1 or entIndex_localEntCCSPlayer_kTeamid == 0 then --Differentiate by team
for i = 1, #arr_entIndex_serverEntCCSPlayer do
local entIndex_serverEntCCSPlayer = arr_entIndex_serverEntCCSPlayer[i]
local obj_serverEntCCSPlayer = Player(entIndex_serverEntCCSPlayer)
if obj_serverEntCCSPlayer:is_alive() then
local i_serverEntCCSPlayer_kTeamid = obj_serverEntCCSPlayer:get_teamnum()
if table_contains_str(ui_get(ref_extesp_filter_playersSubtype), "T") then
if entIndex_serverEntCCSPlayer ~= entIndex_localEntCCSPlayer and i_serverEntCCSPlayer_kTeamid == 2 then
func_extesp_snapline(entIndex_serverEntCCSPlayer, b_esp_filter_playerT_accentColor01, b_esp_filter_playerT_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCCSPlayer, b_esp_filter_playerT_accentColor01, b_esp_filter_playerT_accentColor02)
func_extesp_CCSPlayerInfo(entIndex_serverEntCCSPlayer, b_esp_filter_playerT_accentColor01, b_esp_filter_playerT_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_skeleton(entIndex_serverEntCCSPlayer, b_esp_filter_playerT_accentColor01, b_esp_filter_playerT_accentColor02)
func_extesp_hitbox(entIndex_serverEntCCSPlayer, b_esp_filter_playerT_accentColor01, b_esp_filter_playerT_accentColor02)
end
end
if table_contains_str(ui_get(ref_extesp_filter_playersSubtype), "CT") then
if entIndex_serverEntCCSPlayer ~= entIndex_localEntCCSPlayer and i_serverEntCCSPlayer_kTeamid == 3 then
func_extesp_snapline(entIndex_serverEntCCSPlayer, b_esp_filter_playerCT_accentColor01, b_esp_filter_playerCT_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCCSPlayer, b_esp_filter_playerCT_accentColor01, b_esp_filter_playerCT_accentColor02)
func_extesp_CCSPlayerInfo(entIndex_serverEntCCSPlayer, b_esp_filter_playerCT_accentColor01, b_esp_filter_playerCT_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_skeleton(entIndex_serverEntCCSPlayer, b_esp_filter_playerCT_accentColor01, b_esp_filter_playerCT_accentColor02)
func_extesp_hitbox(entIndex_serverEntCCSPlayer, b_esp_filter_playerCT_accentColor01, b_esp_filter_playerCT_accentColor02)
end
end
end
end
end
end
if ui_get(ref_extesp_filter_weapons) then
local arr_entIndex_serverEntCWeaponCSBase = entity.get_all()
for i = 1, #arr_entIndex_serverEntCWeaponCSBase do
local entIndex_serverEntCWeaponCSBase = arr_entIndex_serverEntCWeaponCSBase[i]
local obj_serverEntCWeaponCSBase = Entity(entIndex_serverEntCWeaponCSBase) ---------------------------------------------------!!!!!!!!!
if (string_find(entity_get_classname(entIndex_serverEntCWeaponCSBase), "CWeapon") ~= nil or
entity_get_classname(entIndex_serverEntCWeaponCSBase) == "CDEagle" or
string_find(entity_get_classname(entIndex_serverEntCWeaponCSBase), "CKnife") ~= nil or
entity_get_classname(entIndex_serverEntCWeaponCSBase) == "CMolotovGrenade" or
entity_get_classname(entIndex_serverEntCWeaponCSBase) == "CIncendiaryGrenade" or
entity_get_classname(entIndex_serverEntCWeaponCSBase) == "CHEGrenade" or
entity_get_classname(entIndex_serverEntCWeaponCSBase) == "CFlashbang" or
entity_get_classname(entIndex_serverEntCWeaponCSBase) == "CSensorGrenade" or
entity_get_classname(entIndex_serverEntCWeaponCSBase) == "CSmokeGrenade" or
entity_get_classname(entIndex_serverEntCWeaponCSBase) == "CDecoyGrenade" or
entity_get_classname(entIndex_serverEntCWeaponCSBase) == "CSnowball" or
entity_get_classname(entIndex_serverEntCWeaponCSBase) == "CAK47") and entity_get_prop(entIndex_serverEntCWeaponCSBase, "m_hOwner", array_index) == nil then
func_extesp_snapline(entIndex_serverEntCWeaponCSBase, b_esp_filter_weapons_accentColor01, b_esp_filter_weapons_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCWeaponCSBase, b_esp_filter_weapons_accentColor01, b_esp_filter_weapons_accentColor02)
func_extesp_CWeaponCSBaseInfo(entIndex_serverEntCWeaponCSBase, b_esp_filter_weapons_accentColor01, b_esp_filter_weapons_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
end
end
end
if ui_get(ref_extesp_filter_mapObjective) then
local arr_entIndex_serverEntCAny = entity.get_all()
for i = 1, #arr_entIndex_serverEntCAny do
local entIndex_serverEntCAny = arr_entIndex_serverEntCAny[i]
if (entity_get_classname(entIndex_serverEntCAny) == "CC4" and entity_get_prop(entIndex_serverEntCAny, "m_hOwner", array_index) == nil) or
(entity_get_classname(entIndex_serverEntCAny) == "CHostage") or
(entity_get_classname(entIndex_serverEntCAny) == "CEconEntity" and entIndex_localEntCCSPlayer_kTeamid ~= 2) or
entity_get_classname(entIndex_serverEntCAny) == "CPlantedC4" then
func_extesp_snapline(entIndex_serverEntCAny, b_esp_filter_mapObjective_accentColor01, b_esp_filter_mapObjective_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCAny, b_esp_filter_mapObjective_accentColor01, b_esp_filter_mapObjective_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCAny, b_esp_filter_mapObjective_accentColor01, b_esp_filter_mapObjective_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
end
end
end
if ui_get(ref_extesp_filter_projectiles) ~= "Off" then
local arr_entIndex_serverEntCProjectile = entity.get_all()
for i = 1, #arr_entIndex_serverEntCProjectile do
local entIndex_serverEntCProjectile = arr_entIndex_serverEntCProjectile[i]
if ui_get(ref_extesp_filter_projectiles) == "On (Owner)" then --Differentiate by owner
if entity_get_classname(entIndex_serverEntCProjectile) == "CSmokeGrenadeProjectile" or
entity_get_classname(entIndex_serverEntCProjectile) == "CSensorGrenadeProjectile" or
entity_get_classname(entIndex_serverEntCProjectile) == "CSnowballProjectile" or
entity_get_classname(entIndex_serverEntCProjectile) == "CMolotovProjectile" or
entity_get_classname(entIndex_serverEntCProjectile) == "CDecoyProjectile" or
entity_get_classname(entIndex_serverEntCProjectile) == "CBaseCSGrenadeProjectile" then
if entity_get_prop(entIndex_serverEntCProjectile, "m_hThrower", array_index) ~= 0 and entity_get_prop(entIndex_serverEntCProjectile, "m_hThrower", array_index) ~= nil then
local i_serverEntCProjectile_kTeamid = entity_get_prop(entity_get_prop(entIndex_serverEntCProjectile, "m_hThrower", array_index), "m_iTeamNum", array_index)
if ui_get(ref_extesp_filter_players) == "On (Ally/Enemy)" and not(entIndex_localEntCCSPlayer_kTeamid == 1) and not(entIndex_localEntCCSPlayer_kTeamid == 0) then --Differentiate by relationship
if table_contains_str(ui_get(ref_extesp_filter_playersSubtype), "Enemy") then
if i_serverEntCProjectile_kTeamid ~= entIndex_localEntCCSPlayer_kTeamid then
func_extesp_snapline(entIndex_serverEntCProjectile, b_esp_filter_playerEnemy_accentColor01, b_esp_filter_playerEnemy_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCProjectile, b_esp_filter_playerEnemy_accentColor01, b_esp_filter_playerEnemy_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCProjectile, b_esp_filter_playerEnemy_accentColor01, b_esp_filter_playerEnemy_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
end
end
if table_contains_str(ui_get(ref_extesp_filter_playersSubtype), "Ally") then
if i_serverEntCProjectile_kTeamid == entIndex_localEntCCSPlayer_kTeamid then
func_extesp_snapline(entIndex_serverEntCProjectile, b_esp_filter_playerAlly_accentColor01, b_esp_filter_playerAlly_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCProjectile, b_esp_filter_playerAlly_accentColor01, b_esp_filter_playerAlly_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCProjectile, b_esp_filter_playerAlly_accentColor01, b_esp_filter_playerAlly_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
end
end
end
if ui_get(ref_extesp_filter_players) == "On (CT/T)" or entIndex_localEntCCSPlayer_kTeamid == 1 or entIndex_localEntCCSPlayer_kTeamid == 0 then --Differentiate by team
if table_contains_str(ui_get(ref_extesp_filter_playersSubtype), "T") then
if i_serverEntCProjectile_kTeamid == 2 then
func_extesp_snapline(entIndex_serverEntCProjectile, b_esp_filter_playerT_accentColor01, b_esp_filter_playerT_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCProjectile, b_esp_filter_playerT_accentColor01, b_esp_filter_playerT_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCProjectile, b_esp_filter_playerT_accentColor01, b_esp_filter_playerT_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
end
end
if table_contains_str(ui_get(ref_extesp_filter_playersSubtype), "CT") then
if i_serverEntCProjectile_kTeamid == 3 then
func_extesp_snapline(entIndex_serverEntCProjectile, b_esp_filter_playerCT_accentColor01, b_esp_filter_playerCT_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCProjectile, b_esp_filter_playerCT_accentColor01, b_esp_filter_playerCT_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCProjectile, b_esp_filter_playerCT_accentColor01, b_esp_filter_playerCT_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
end
end
end
end
end
end
if ui_get(ref_extesp_filter_projectiles) == "On (Subtype)" then --Differentiate by Subtype
if entity_get_classname(entIndex_serverEntCProjectile) == "CSmokeGrenadeProjectile" or
entity_get_classname(entIndex_serverEntCProjectile) == "CSensorGrenadeProjectile" or
entity_get_classname(entIndex_serverEntCProjectile) == "CSnowballProjectile" or
entity_get_classname(entIndex_serverEntCProjectile) == "CMolotovProjectile" or
entity_get_classname(entIndex_serverEntCProjectile) == "CDecoyProjectile" or
entity_get_classname(entIndex_serverEntCProjectile) == "CBaseCSGrenadeProjectile" then
if entity_get_prop(entIndex_serverEntCProjectile, "m_hThrower", array_index) ~= 0 and entity_get_prop(entIndex_serverEntCProjectile, "m_hThrower", array_index) ~= nil then
if entity_get_classname(entIndex_serverEntCProjectile) == "CSmokeGrenadeProjectile" then
func_extesp_snapline(entIndex_serverEntCProjectile, b_esp_filter_projectile_stSmokeG_accentColor01, b_esp_filter_projectile_stSmokeG_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCProjectile, b_esp_filter_projectile_stSmokeG_accentColor01, b_esp_filter_projectile_stSmokeG_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCProjectile, b_esp_filter_projectile_stSmokeG_accentColor01, b_esp_filter_projectile_stSmokeG_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
end
if entity_get_classname(entIndex_serverEntCProjectile) == "CSensorGrenadeProjectile" then
func_extesp_snapline(entIndex_serverEntCProjectile, b_esp_filter_projectile_stTAG_accentColor01, b_esp_filter_projectile_stTAG_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCProjectile, b_esp_filter_projectile_stTAG_accentColor01, b_esp_filter_projectile_stTAG_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCProjectile, b_esp_filter_projectile_stTAG_accentColor01, b_esp_filter_projectile_stTAG_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
end
if entity_get_classname(entIndex_serverEntCProjectile) == "CSnowballProjectile" then
func_extesp_snapline(entIndex_serverEntCProjectile, b_esp_filter_projectile_stSnowball_accentColor01, b_esp_filter_projectile_stSnowball_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCProjectile, b_esp_filter_projectile_stSnowball_accentColor01, b_esp_filter_projectile_stSnowball_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCProjectile, b_esp_filter_projectile_stSnowball_accentColor01, b_esp_filter_projectile_stSnowball_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
end
if entity_get_classname(entIndex_serverEntCProjectile) == "CMolotovProjectile" then
func_extesp_snapline(entIndex_serverEntCProjectile, b_esp_filter_projectile_stMolotov_accentColor01, b_esp_filter_projectile_stMolotov_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCProjectile, b_esp_filter_projectile_stMolotov_accentColor01, b_esp_filter_projectile_stMolotov_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCProjectile, b_esp_filter_projectile_stMolotov_accentColor01, b_esp_filter_projectile_stMolotov_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
end
if entity_get_classname(entIndex_serverEntCProjectile) == "CDecoyProjectile" then
func_extesp_snapline(entIndex_serverEntCProjectile, b_esp_filter_projectile_stDecoy_accentColor01, b_esp_filter_projectile_stDecoy_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCProjectile, b_esp_filter_projectile_stDecoy_accentColor01, b_esp_filter_projectile_stDecoy_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCProjectile, b_esp_filter_projectile_stDecoy_accentColor01, b_esp_filter_projectile_stDecoy_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
end
if entity_get_classname(entIndex_serverEntCProjectile) == "CBaseCSGrenadeProjectile" then
if entity_get_prop(entIndex_serverEntCProjectile, "m_DmgRadius", array_index) == 350 then
func_extesp_snapline(entIndex_serverEntCProjectile, b_esp_filter_projectile_stHEG_accentColor01, b_esp_filter_projectile_stHEG_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCProjectile, b_esp_filter_projectile_stHEG_accentColor01, b_esp_filter_projectile_stHEG_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCProjectile, b_esp_filter_projectile_stHEG_accentColor01, b_esp_filter_projectile_stHEG_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
else
func_extesp_snapline(entIndex_serverEntCProjectile, b_esp_filter_projectile_stFlashbang_accentColor01, b_esp_filter_projectile_stFlashbang_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCProjectile, b_esp_filter_projectile_stFlashbang_accentColor01, b_esp_filter_projectile_stFlashbang_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCProjectile, b_esp_filter_projectile_stFlashbang_accentColor01, b_esp_filter_projectile_stFlashbang_accentColor02s, i_esp_anchorPosX, i_esp_anchorPosY)
end
end
end
end
end
end
end
if ui_get(ref_extesp_filter_other) then
local arr_entIndex_serverEntCAny = entity.get_all()
for i = 1, #arr_entIndex_serverEntCAny do
local entIndex_serverEntCAny = arr_entIndex_serverEntCAny[i]
if (string_find(entity_get_classname(entIndex_serverEntCAny), "CWeapon") == nil and -- filter out most weapons
not(entity_get_classname(entIndex_serverEntCAny) == "CDEagle") and
not(entity_get_classname(entIndex_serverEntCAny) == "CAK47") and
not(entity_get_classname(entIndex_serverEntCAny) == "CC4") and
not(entity_get_classname(entIndex_serverEntCAny) == "CHostage") and
not(entity_get_classname(entIndex_serverEntCAny) == "CEconEntity") and
not(entity_get_classname(entIndex_serverEntCAny) == "CPlantedC4") and
string_find(entity_get_classname(entIndex_serverEntCAny), "CKnife") == nil and -- filter out most knives
string_find(entity_get_classname(entIndex_serverEntCAny), "CSmokeGrenade") == nil and -- filter out SmokeG and it's projectile
string_find(entity_get_classname(entIndex_serverEntCAny), "CSensorGrenade") == nil and -- filter out TAG and it's projectile
string_find(entity_get_classname(entIndex_serverEntCAny), "CMolotov") == nil and -- filter out Molotov and it's projectile
string_find(entity_get_classname(entIndex_serverEntCAny), "CDecoy") == nil and -- filter out Decoy and it's projectile
string_find(entity_get_classname(entIndex_serverEntCAny), "CSnowball") == nil and -- filter out Decoy and it's projectile
not(entity_get_classname(entIndex_serverEntCAny) == "CIncendiaryGrenade") and
not(entity_get_classname(entIndex_serverEntCAny) == "CBaseCSGrenadeProjectile") and
not(entity_get_classname(entIndex_serverEntCAny) == "CHEGrenade") and
not(entity_get_classname(entIndex_serverEntCAny) == "CFlashbang") and
string_find(entity_get_classname(entIndex_serverEntCAny), "CCSPlayer") == nil and -- filter out all players and CCSPlayerResource which does not have origin
string_find(entity_get_classname(entIndex_serverEntCAny), "CCSTeam") == nil and -- entity which does not have origin
string_find(entity_get_classname(entIndex_serverEntCAny), "CCSGameRulesProxy") == nil) then -- entity which does not have origin
func_extesp_snapline(entIndex_serverEntCAny, b_esp_filter_other_accentColor01, b_esp_filter_other_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
func_extesp_boundingBoxStatic(entIndex_serverEntCAny, b_esp_filter_other_accentColor01, b_esp_filter_other_accentColor02)
func_extesp_CAnyInfo(entIndex_serverEntCAny, b_esp_filter_other_accentColor01, b_esp_filter_other_accentColor02, i_esp_anchorPosX, i_esp_anchorPosY)
end
end
end
end
local function func_extesp_ePlayerConnectFull(event)
local entIndex_localEntCCSPlayer = entity_get_local_player()
if client_userid_to_entindex(event.userid) == entIndex_localEntCCSPlayer then
i_extesp_tickinterval = globals_tickinterval()
i_extesp_tickrate = 1 / i_extesp_tickinterval
end
end
client.set_event_callback("player_connect_full", func_extesp_ePlayerConnectFull)
client.set_event_callback("paint", func_extesp_eDraw)
-- [End of file] -----------------------------------------------------------------------------------------------------------------------------------------------
|
function generateTriangleOfVertices()
line = world:newLineCollider(200,200, 1030, 1030)
line2 = world:newLineCollider(200,200,200,1030)
joint = world:addJoint('RevoluteJoint', line, line2, 200, 200, true)--Joint that forms the slope for physical interactions
end
function setTriangleOfVerticesProperties()
line:setType("static")
line2:setType("static")
end
function generateBoundries()
ground = world:newRectangleCollider(0, love.graphics.getHeight() - 30 , love.graphics.getWidth(), 30)
ceiling = world:newRectangleCollider(0,love.graphics.getHeight() - (love.graphics.getHeight() ),love.graphics.getWidth(),30)
leftWall = world:newRectangleCollider(0,0,30,love.graphics.getHeight())
rightWall = world:newRectangleCollider(love.graphics.getWidth() - 30,0,30,love.graphics.getHeight())
end
function setBoundriesProperties()
ground:setType("static")
ceiling:setType("static")
leftWall:setType("static")
rightWall:setType("static")
end
function generateParticleSizeIconShowcase()
particleSizeIcon = world:newRectangleCollider(love.graphics.getWidth() - 100,love.graphics.getHeight() - 110,10,10)
end
function setParticleSizeIconProperties()
particleSizeIcon:setType("static")
particleSizeIcon:setCollisionClass("Ghost")
end
function generateCubeObject()
cube = world:newRectangleCollider(love.mouse.getX() + 40,love.mouse.getY(),10 + particleSizeIncrement,10 + particleSizeIncrement)
end
function setCubeObjectProperties()
cube:setCollisionClass("Solid")
cube:setFriction(frictionVal)
end
function distanceBetweenFormula(x1,y1,x2,y2)
-- distance between two points in the cartesian coordinate system.
return math.sqrt((x1-x2)^2 + (y1 - y2)^2)
end
function disperseCubeObject()
if dispersionButton == "active" then
local colliders = world:queryCircleArea(love.mouse.getX() + 40, love.mouse.getY() + 40, 100)
for _, collider in ipairs(colliders) do
if love.mouse.getX() < (love.graphics.getWidth() / 2) then
collider:applyLinearImpulse(800,-400)
else if love.mouse.getX() >= (love.graphics.getWidth() / 2) then
collider:applyLinearImpulse(-800,-400)
end
end
end
end
end
|
local addonName, G = ...
local makeAction = (function()
local function consume(mealDB, potionDB, nethergon)
local potionText = (function()
local s = ''
for _, consumable in ipairs(potionDB) do
s = s .. '/use item:' .. consumable[1] .. '\n'
end
return s
end)()
local nethergonText = '/use item:' .. nethergon .. '\n' .. potionText
local currentDB
local function inNethergonZone()
local id = select(8, GetInstanceInfo())
return id == 550 or id == 552 or id == 553 or id == 554
end
local function computeItem(levelarg)
local level = levelarg or UnitLevel('player')
if inNethergonZone() and currentDB == potionDB and level >= 55 and GetItemCount(nethergon) > 0 then
return nethergon
end
for _, consumable in ipairs(currentDB) do
local item, minlevel = unpack(consumable)
if level >= minlevel and GetItemCount(item) > 0 then
return item
end
end
end
local function computeAttr(item)
if currentDB == mealDB then
return '/use item:' .. item
elseif inNethergonZone() then
return nethergonText
else
return potionText
end
end
local function updateItem(level)
local item = computeItem(level)
return {
attr = item and computeAttr(item) or nil,
ui = item and { item = item } or { hide = true },
}
end
local function updateDB(db)
currentDB = db
return updateItem()
end
return function()
return updateDB(mealDB), {
BAG_UPDATE_DELAYED = function()
return updateItem()
end,
PLAYER_ENTERING_WORLD = function()
return updateItem()
end,
PLAYER_LEVEL_UP = function(level)
return updateItem(level)
end,
PLAYER_REGEN_DISABLED = function()
return updateDB(potionDB)
end,
PLAYER_REGEN_ENABLED = function()
return updateDB(mealDB)
end,
}
end
end
local lang = {
action = function(action)
local num = action.action
local function update()
return {
attr = HasAction(num) and ('#action:' .. num) or '',
icon = GetActionTexture(num),
name = GetActionText(num),
}
end
local init = Mixin(update(), {
cooldown = { action = num },
count = { action = num },
tooltip = { action = num },
update = { action = num },
})
return init, {
ACTIONBAR_SLOT_CHANGED = function(slot)
return slot == num and update() or {}
end,
}
end,
aura = function(action)
local index, filter = action.aura.index, action.aura.filter
local function update(unit)
if not UnitIsUnit(unit, 'player') then
return {}
else
local _, icon = UnitAura('player', index, filter)
return {
alpha = icon and 1.0 or 0.0,
icon = icon,
}
end
end
local attr = string.format('#cancelaura:%2d:%s', index, filter)
return Mixin({ attr = attr }, update('player')), { UNIT_AURA = update }
end,
bandage = function()
local macro = ''
for _, entry in ipairs(G.BandageDB) do
macro = macro .. '/use item:' .. entry[1] .. '\n'
end
local function currentSkill()
for i = 1, GetNumSkillLines() do
local name, _, _, value = GetSkillLineInfo(i)
if name == PROFESSIONS_FIRST_AID then
return value
end
end
return 0
end
local function currentItem()
local skill = currentSkill()
for _, entry in ipairs(G.BandageDB) do
local item, minskill = unpack(entry)
if skill >= minskill and GetItemCount(item) > 0 then
return item
end
end
end
local function update()
local item = currentItem()
return { ui = item and { item = item } or { hide = true } }
end
return Mixin(update(), { attr = macro }), {
BAG_UPDATE_DELAYED = update,
CHAT_MSG_SKILL = update,
}
end,
buff = function(action)
return {
attr = '/click PallyPowerAuto RightButton\n/click ' .. addonName .. 'BuffButton',
count = action.reagent and { item = action.reagent },
icon = 135938,
tooltip = { text = 'Buff' },
}
end,
drink = consume(G.DrinkDB, G.ManaPotionDB, 32902),
eat = consume(G.FoodDB, G.HealthPotionDB, 32905),
emote = function(action)
local emote = action.emote
local keyName = 'CLICK ' .. addonName .. 'ActionButton' .. action.index .. ':LeftButton'
local function update()
local key = GetBindingKey(keyName)
local keystr = key and (LibStub('LibKeyBound-1.0'):ToShortKey(key) .. ' - ') or ''
return { name = keystr .. emote }
end
return Mixin(update(), { attr = '/' .. emote }), { UPDATE_BINDINGS = update }
end,
healset = function(action)
local healset = action.healset
local spellset = {}
for _, spell in ipairs(healset.spells) do
local ranks = G.SpellDB[spell]
for i, rank in ipairs(ranks) do
local rn = #ranks - i + 1
local fullName = ('%s(Rank %d)'):format(spell, rn)
local actionText = ''
for w in spell:gmatch('%S+') do
actionText = actionText .. w:sub(1, 1)
end
actionText = actionText .. rn
table.insert(spellset, {
action = {
attr = '/dismount [noflying]\n/stand\n/cast [@mouseover,help,nodead][] ' .. fullName,
icon = GetSpellTexture(spell),
name = actionText,
ui = { spell = fullName },
},
id = rank[1],
})
end
end
local idealpcts = healset.ranks
local myrank = #idealpcts - action.rank + 1
local function makeDistance(t, k)
return function(a, b)
local aa = math.abs(t[a] - k)
local bb = math.abs(t[b] - k)
return aa < bb
end
end
local function update()
local known = {}
for i, spell in ipairs(spellset) do
if IsSpellKnown(spell.id) then
table.insert(known, i)
end
end
if #known <= #idealpcts then
local myindex = known[myrank]
return myindex and spellset[myindex].action or { attr = '' }
else
local klo, khi = known[1], known[#known]
local assignedpcts = {}
for i, j in ipairs(known) do
assignedpcts[i] = 1 - (j - klo) / (khi - klo)
end
local assigneds = {}
for i, j in ipairs(assignedpcts) do
assigneds[i] = makeDistance(idealpcts, j)
end
local ideals = {}
for i, j in ipairs(idealpcts) do
ideals[i] = makeDistance(assignedpcts, j)
end
for assigned, ideal in pairs(G.StableMarriage(ideals, assigneds)) do
if ideal == myrank then
return spellset[known[assigned]].action
end
end
-- This shouldn't happen...
return { attr = '' }
end
end
return update(), { SPELLS_CHANGED = update }
end,
invslot = function(action)
local slot = action.invslot
local function update()
local item = GetInventoryItemID('player', slot)
return not item and { attr = '' } or {
attr = '/use ' .. slot,
ui = { item = item },
}
end
return update(), { PLAYER_EQUIPMENT_CHANGED = update }
end,
item = function(action)
return {
attr = '/use item:' .. action.item,
ui = { item = action.item },
}
end,
macro = function(action)
return {
attr = action.macro,
icon = action.texture,
name = action.actionText,
tooltip = action.tooltip and { text = action.tooltip },
ui = action.ui,
}
end,
mount = function()
local function getMount(db)
for _, entry in ipairs(db) do
local item, spell = unpack(entry)
if item and GetItemCount(item) > 0 then
return '/use', 'item:' .. item, {
ui = { item = item },
}
elseif IsSpellKnown(spell) then
return '/cast', (GetSpellInfo(spell)), {
ui = { spell = spell },
}
end
end
end
local function update()
local gcmd, garg, ground = getMount(G.MountGroundDB)
local fcmd, farg, flight = getMount(G.MountFlightDB)
if gcmd and fcmd then
local macro = (
string.format('%s [nomounted,flyable] %s\n', fcmd, farg) ..
string.format('%s [nomounted,noflyable] %s\n', gcmd, garg) ..
'/dismount [mounted]'
)
-- TODO update icon etc to use flight mount based on OnUpdate IsFlyableArea
return Mixin({ attr = macro }, ground)
elseif gcmd then
local macro = string.format('%s [nomounted] %s\n/dismount [mounted]', gcmd, garg)
return Mixin({ attr = macro }, ground)
elseif fcmd then
local macro = string.format('%s [nomounted] %s\n/dismount [mounted]', fcmd, farg)
return Mixin({ attr = macro }, flight)
else
return { attr = '' }
end
end
return update(), {
BAG_UPDATE_DELAYED = update,
SPELLS_CHANGED = update,
}
end,
noncombat = function(action)
local macro = ('/run SelectGossipOption(%d)'):format(action.noncombat)
local init = {
attr = '',
icon = 134400,
}
return init, {
GOSSIP_SHOW = function()
return { attr = macro }
end,
GOSSIP_CLOSED = function()
return { attr = '' }
end,
}
end,
oneof = function(action)
local page, spells = action.oneofpage, action.oneof
local function update()
local known = {}
for _, name in ipairs(spells) do
local id = select(7, GetSpellInfo(name))
if id and IsSpellKnown(id) then
known[id] = true
end
end
if not next(known) then
return { attr = '' }
end
local spell = spells[1]
for i = 1, 40 do
local buff = select(10, UnitBuff('player', i))
if not buff then
break
end
if known[buff] then
spell = buff
break
end
end
return { attr = '#page:' .. page, ui = { spell = spell } }
end
return {}, {
SPELLS_CHANGED = update,
UNIT_AURA = update,
}
end,
page = function(action)
return {
attr = '#page:' .. action.page,
count = action.reagent and { item = action.reagent },
icon = action.texture,
name = action.actionText,
tooltip = action.tooltip and { text = action.tooltip },
}
end,
petaction = function(action)
local num = action.petaction
local function update()
local _, texture, isToken, isActive, autoCastAllowed, autoCastEnabled = GetPetActionInfo(num)
local icon = isToken and _G[texture] or texture
return {
alpha = icon and 1.0 or 0.0,
autocast = autoCastAllowed and (autoCastEnabled and 'enabled' or 'disabled') or 'disallowed',
checked = { value = isActive or false },
icon = icon,
}
end
local init = Mixin(update(), {
attr = '#petaction:' .. num,
cooldown = { petaction = num },
tooltip = { petaction = num },
})
return init, {
PET_BAR_UPDATE = update,
PET_UI_UPDATE = update,
UNIT_PET = update,
}
end,
shapeshift = function(action)
local shapes = action.shapeshift
local macro = '/cast'
for shape, spell in pairs(shapes) do
macro = macro .. (' [form:%d] %s;'):format(shape, spell)
end
local function update()
local shape = GetShapeshiftForm()
local spell = shape and shapes[shape] or nil
local spellid = spell and select(7, GetSpellInfo(spell)) or nil
return { ui = spellid and IsSpellKnown(spellid) and { spell = spellid } or { hide = true } }
end
return { attr = macro }, {
SPELLS_CHANGED = update,
UPDATE_SHAPESHIFT_FORM = update,
}
end,
shoot = function()
local macro = table.concat({
'/cast [equipped:bows] Shoot Bow',
'/cast [equipped:crossbows] Shoot Crossbow',
'/cast [equipped:guns] Shoot Gun',
'/cast [equipped:thrown] Throw',
'/cast [equipped:wand] !Shoot',
}, '\n')
local function update()
local item = GetInventoryItemID('player', 18)
local count = GetInventoryItemCount('player', GetInventoryItemID('player', 0) == 0 and 18 or 0) or 0
return {
color = 1.0,
count = { value = count },
ui = item and { item = item } or { hide = true },
update = { reset = true },
}
end
return Mixin(update(), { attr = macro }), { PLAYER_EQUIPMENT_CHANGED = update }
end,
spell = function(action)
local shortName = action.spell
local rankStr = action.rank and ('Rank ' .. action.rank) or nil
local fullName = shortName .. (rankStr and ('(' .. rankStr .. ')') or '')
local macrot = {'/cast'}
if action.mouseover then
table.insert(macrot, '[@mouseover,help,nodead][]')
elseif action.options then
table.insert(macrot, action.options)
end
table.insert(macrot, fullName)
local macro = (
(action.dismount ~= false and '/dismount [noflying]\n' or '')..
(action.stand ~= false and '/stand\n' or '')..
(action.stopcasting and '/stopcasting\n' or '')..
table.concat(macrot, ' '))
local function update()
local spellid = select(7, GetSpellInfo(shortName, rankStr))
return {
attr = spellid and IsSpellKnown(spellid) and macro or '',
-- Use the spell base name for GetSpellTexture; more likely to work on login.
icon = GetSpellTexture(shortName),
}
end
local init = Mixin(update(), {
count = { spell = fullName },
name = action.actionText,
ui = { spell = fullName },
})
return init, { SPELLS_CHANGED = update }
end,
spells = function(action)
local spells = action.spells
local prefix = (
(action.stopcasting and '/stopcasting\n' or '')..
'/cast'..(action.mouseover and ' [@mouseover,help,nodead][] ' or ' '))
local function update()
for _, name in ipairs(spells) do
local id = select(7, GetSpellInfo(name))
if id and IsSpellKnown(id) then
return {
attr = prefix .. name,
ui = { spell = name },
}
end
end
return {}
end
return {}, { SPELLS_CHANGED = update }
end,
}
return function(action)
for k, v in pairs(lang) do
if action[k] then
return v(action)
end
end
error('invalid action')
end
end)()
local updateButton = (function()
local lang = {
alpha = function(button, alpha)
button:SetAlpha(alpha)
end,
autocast = (function()
local autocastLang = {
disabled = function(button)
button.AutoCastable:Show()
AutoCastShine_AutoCastStop(button.AutoCastShine)
end,
disallowed = function(button)
button.AutoCastable:Hide()
AutoCastShine_AutoCastStop(button.AutoCastShine)
end,
enabled = function(button)
button.AutoCastable:Show()
AutoCastShine_AutoCastStart(button.AutoCastShine)
end,
}
return function(button, autocast)
if button.AutoCastable then
assert(autocastLang[autocast], 'invalid autocast ' .. autocast)(button)
end
end
end)(),
checked = (function()
local checkedLang = {
spell = function(spell)
return IsCurrentSpell(spell)
end,
value = function(value)
return value
end,
}
return function(button, checked)
if button.SetChecked then
local k, v = next(checked)
local fn = assert(checkedLang[k], 'invalid checked program ' .. tostring(k))
local chfn = function() return fn(v) end
button:SetChecked(chfn())
button.chfn = chfn
end
end
end)(),
color = function(button, color)
if button.icon then
button.icon:SetVertexColor(color, color, color)
end
end,
cooldown = (function()
local cooldownLang = {
action = function(action)
return GetActionCooldown(action)
end,
item = function(item)
return GetItemCooldown(item)
end,
petaction = function(petaction)
return GetPetActionCooldown(petaction)
end,
reset = function()
return 0, 0, 0
end,
spell = function(spell)
return GetSpellCooldown(spell)
end,
}
return function(button, prog)
if button.cooldown then
local k, v = next(prog)
local start, duration, enable, modRate = cooldownLang[k](v)
CooldownFrame_Set(button.cooldown, start, duration, enable, false, modRate)
end
end
end)(),
count = (function()
local countLang = {
action = function(action)
return IsConsumableAction(action) and GetActionCount(action) or -1
end,
item = function(item)
return GetItemCount(item)
end,
spell = function(spell)
return IsConsumableSpell(spell) and GetSpellCount(spell) or -1
end,
value = function(value)
return value
end,
}
return function(button, prog)
if button.Count then
local k, v = next(prog)
local count = countLang[k](v)
button.Count:SetText(count < 0 and '' or count > 9999 and '*' or tostring(count))
end
end
end)(),
icon = function(button, icon)
if button.icon then
button.icon:SetTexture(icon)
end
end,
name = function(button, name)
(button.Name or button.Text):SetText(name)
end,
tooltip = (function()
local tooltipLang = {
action = function(action)
GameTooltip:SetAction(action)
end,
item = function(item)
GameTooltip:SetHyperlink('item:' .. item)
end,
petaction = function(petaction)
GameTooltip:SetPetAction(petaction)
end,
spell = function(spell)
if type(spell) == 'string' then
spell = select(7, GetSpellInfo(spell))
end
GameTooltip:SetSpellByID(spell)
local subtext = GetSpellSubtext(spell)
if subtext then
GameTooltipTextRight1:SetText(subtext)
GameTooltipTextRight1:SetTextColor(0.5, 0.5, 0.5)
GameTooltipTextRight1:Show()
GameTooltip:Show()
end
end,
text = function(text)
GameTooltip:SetText(text)
end,
}
return function(button, tooltip)
local k, v = next(tooltip)
local fn = tooltipLang[k]
button.ttfn = fn and function() fn(v) end or nil
end
end)(),
update = (function()
local function updateColor(isFooInRange, isUsableFoo)
local function getColor(foo)
if isFooInRange(foo, 'target') == 0 then
return 0.8, 0.1, 0.1
end
local isUsable, notEnoughMana = isUsableFoo(foo)
if isUsable then
return 1.0, 1.0, 1.0
elseif notEnoughMana then
return 0.5, 0.5, 1.0
else
return 0.4, 0.4, 0.4
end
end
return function(foo, button)
if button.icon then
button.icon:SetVertexColor(getColor(foo))
end
end
end
local updateLang = {
action = updateColor(IsActionInRange, IsUsableAction),
item = updateColor(IsItemInRange, IsUsableItem),
reset = function() end,
spell = updateColor(IsSpellInRange, IsUsableSpell),
}
return function(button, prog)
local k, v = next(prog)
updateLang[k](v, button)
end
end)(),
}
return function(button, update)
if button then
for k, v in pairs(update) do
assert(lang[k], 'unknown function ' .. k)(button, v)
end
end
end
end)()
local function makeActionButtons()
local attachToIconGrid, attachToTextGrid = (function()
local width, height = 36, 18
local frames = {}
for _ = 1, 96 do
local frame = CreateFrame('Frame')
frame:SetSize(width, height)
table.insert(frames, frame)
end
for i, frame in ipairs(frames) do
if i <= 84 then
frame:SetPoint('BOTTOM', frames[i + 12], 'TOP')
end
if (i - 1) % 12 < 5 then
frame:SetPoint('RIGHT', frames[i + 1], 'LEFT')
elseif (i - 1) % 12 > 6 then
frame:SetPoint('LEFT', frames[i - 1], 'RIGHT')
end
end
frames[90]:SetPoint('BOTTOMRIGHT', UIParent, 'BOTTOM')
frames[91]:SetPoint('BOTTOMLEFT', UIParent, 'BOTTOM')
local function icon(frame, row, col)
local index = (row - 1) * 24 + col
frame:ClearAllPoints()
frame:SetPoint('TOPLEFT', frames[index], 'TOPLEFT')
frame:SetPoint('BOTTOMRIGHT', frames[index + 12], 'BOTTOMRIGHT')
end
local function text(frame, row, col)
local index = (row - 1) * 12 + (col - 1) * 2 + 1
frame:ClearAllPoints()
frame:SetPoint('TOPLEFT', frames[index], 'TOPLEFT')
frame:SetPoint('BOTTOMRIGHT', frames[index + 1], 'BOTTOMRIGHT')
end
return icon, text
end)()
local scripts = {
OnEnter = function(self)
if self.ttfn then
GameTooltip_SetDefaultAnchor(GameTooltip, self)
self.ttfn()
end
end,
OnEvent = function(self)
local binder = addonName .. 'ActionButton' .. self:GetID()
local key = GetBindingKey('CLICK ' .. binder .. ':LeftButton')
if key then
self.HotKey:SetText(LibStub('LibKeyBound-1.0'):ToShortKey(key))
self.HotKey:Show()
else
self.HotKey:Hide()
end
end,
OnLeave = function()
GameTooltip:Hide()
end,
PostClick = function(self)
if self.chfn then
self:SetChecked(self.chfn())
end
end,
}
local iconButtons = {}
for row = 1, 4 do
for col = 1, 12 do
local button = CreateFrame(
'CheckButton',
addonName .. 'ActionIconButton' .. (#iconButtons + 1),
UIParent,
'ActionButtonTemplate, SecureActionButtonTemplate')
attachToIconGrid(button, row, col)
button:SetMotionScriptsWhileDisabled(true)
button.icon:SetTexCoord(0.07, 0.93, 0.07, 0.93)
button.HotKey:SetFont(button.HotKey:GetFont(), 13, 'OUTLINE')
button.HotKey:SetVertexColor(0.75, 0.75, 0.75)
button.HotKey:SetPoint('TOPLEFT', button, 'TOPLEFT', -2, -4)
button.Count:SetFont(button.Count:GetFont(), 16, 'OUTLINE')
button:SetNormalTexture('Interface\\Buttons\\UI-Quickslot2')
button.NormalTexture:SetTexCoord(0, 0, 0, 0)
button.cooldown:SetSwipeColor(0, 0, 0)
button:RegisterEvent('UPDATE_BINDINGS')
for k, v in pairs(scripts) do
button:SetScript(k, v)
end
table.insert(iconButtons, button)
end
end
local textButtons = {}
for row = 1, 8 do
for col = 1, 6 do
local idx = (row - 1) * 6 + col
local button = CreateFrame(
'Button',
addonName .. 'ActionTextButton' .. idx,
UIParent,
'UIPanelButtonTemplate, SecureActionButtonTemplate')
attachToTextGrid(button, row, col)
table.insert(textButtons, button)
end
end
return {
icon = iconButtons,
text = textButtons,
}
end
local actionPage = 'invalid'
local actionButtonState = {}
local function setupHeader(actions, defaultPage, actionButtons, getActionButton)
local prefix = addonName .. 'ActionButton'
local header = CreateFrame('Frame', prefix .. 'Header', UIParent, 'SecureHandlerStateTemplate')
header:Execute(([[defaultPage = %q]]):format(defaultPage))
header:Execute([[
actionPages = newtable()
buttonPages = newtable()
keybinders = newtable()
updateActionButton = [=[
local idx = ...
local currentPage = owner:GetAttribute('fractionpage')
local actionPage = actionPages[currentPage]
local attr = actionPage.attrs[idx] or ''
local type_, action, macrotext, index, filter
if attr:sub(1, 8) == '#action:' then
type_, action = 'action', tonumber(attr:sub(9))
elseif attr:sub(1, 11) == '#petaction:' then
type_, action = 'pet', tonumber(attr:sub(12))
elseif attr:sub(1, 12) == '#cancelaura:' then
type_, index, filter = 'cancelaura', tonumber(attr:sub(13, 14)), attr:sub(16)
else
type_, macrotext = 'macro', attr
end
local button = buttonPages[actionPage.buttonPage][idx]
button:SetAttribute('type', type_)
button:SetAttribute('action', action)
button:SetAttribute('macrotext', macrotext)
button:SetAttribute('index', index)
button:SetAttribute('filter', filter)
if attr ~= '' then
owner:CallMethod('InsecureActionButtonRefresh', idx)
button:Show()
else
button:Hide()
end
]=]
updateActionAttr = [=[
local pageName, idx, attr = ...
actionPages[pageName].attrs[idx] = attr
if pageName == owner:GetAttribute('fractionpage') then
owner:Run(updateActionButton, idx)
end
]=]
updateActionPage = [=[
local page = ...
local currentPage = owner:GetAttribute('fractionpage')
if page ~= currentPage then
owner:CallMethod('InsecureUpdateActionPage', page)
local newButtonPage = actionPages[page].buttonPage
if currentPage then
local oldButtonPage = actionPages[currentPage].buttonPage
if oldButtonPage ~= newButtonPage then
for _, button in ipairs(buttonPages[oldButtonPage]) do
button:Hide()
end
end
end
owner:SetAttribute('fractionpage', page)
for i, keybinder in ipairs(keybinders) do
local button = buttonPages[newButtonPage][i]
local macrotext = button and ('/click ' .. button:GetName()) or ''
keybinder:SetAttribute('macrotext', macrotext)
end
for buttonid, button in ipairs(buttonPages[newButtonPage]) do
owner:Run(updateActionButton, buttonid)
end
end
]=]
updatePageOnClick = [=[
local buttonid = ...
local currentPage = actionPages[owner:GetAttribute('fractionpage')]
local attr = currentPage.attrs[buttonid] or ''
local page = attr:sub(1, 6) == '#page:' and attr:sub(7) or currentPage.nextActionPage
owner:Run(updateActionPage, page)
]=]
]])
for name, page in pairs(actions) do
header:Execute(([[
local name, buttonPage, nextActionPage = %q, %q, %q
local t = newtable()
t.attrs = newtable()
t.buttonPage = buttonPage
t.nextActionPage = nextActionPage
actionPages[name] = t
]]):format(name, page.buttonPage, page.nextActionPage))
end
for buttonPageName, buttons in pairs(actionButtons) do
header:Execute(([[
local buttonPageName = %q
buttonPages[buttonPageName] = buttonPages[buttonPageName] or newtable()
]]):format(buttonPageName))
for idx, button in ipairs(buttons) do
button:Hide()
button:SetID(idx)
header:WrapScript(button, 'OnClick', 'return nil, true', [[
owner:Run(updatePageOnClick, self:GetID())
]])
header:SetFrameRef('tmp', button)
header:Execute(([[
tinsert(buttonPages[%q], self:GetFrameRef('tmp'))
]]):format(buttonPageName))
end
end
local len = 0
for _, buttons in pairs(actionButtons) do
len = math.max(len, #buttons)
end
for i = 1, len do
local button = CreateFrame('Button', prefix .. i, nil, 'SecureActionButtonTemplate')
button:SetAttribute('type', 'macro')
header:SetFrameRef('tmp', button)
header:Execute([[tinsert(keybinders, self:GetFrameRef('tmp'))]])
end
RegisterAttributeDriver(header, 'state-petexists', '[@pet,exists] true; false')
header:SetAttribute('_onstate-petexists', [=[
-- If we just got a pet and it's not a hunter/warlock pet, switch to the pet page.
-- If we just lost a pet and we're on the pet page, go back to the default page.
local petExists = newstate == 'true'
local creatureFamily, petName = PlayerPetSummary()
if petExists and not creatureFamily and petName ~= 'Shadowfiend' then
owner:Run(updateActionPage, 'pet')
elseif not petExists and owner:GetAttribute('fractionpage') == 'pet' then
owner:Run(updateActionPage, defaultPage)
end
]=])
header.InsecureActionButtonRefresh = function(_, idx)
local reset = {
alpha = 1.0,
autocast = 'disallowed',
checked = { value = false },
color = 1.0,
cooldown = { reset = true },
count = { value = -1 },
icon = 136235, -- samwise
name = '',
tooltip = { reset = true },
}
updateButton(getActionButton(idx), Mixin(reset, actionButtonState[actionPage][idx]))
end
header.InsecureUpdateActionPage = function(_, newPage)
actionPage = newPage
end
header:RegisterEvent('PLAYER_ENTERING_WORLD')
header:SetScript('OnEvent', function(self)
self:Execute([[self:Run(updateActionPage, defaultPage)]])
end)
for page in pairs(actions) do
local name = page:gsub('^%l', string.upper)
local switch = CreateFrame('Button', prefix .. name .. 'Switcher', header, 'SecureActionButtonTemplate')
header:WrapScript(switch, 'OnClick', 'return nil, true', ([=[
local page = %q
owner:Run(updateActionPage, owner:GetAttribute('fractionpage') == page and defaultPage or page)
]=]):format(page))
end
local defaultSwitch = CreateFrame('Button', prefix .. 'DefaultSwitcher', header, 'SecureActionButtonTemplate')
header:WrapScript(defaultSwitch, 'OnClick', 'return nil, true', 'owner:Run(updateActionPage, defaultPage)')
local function updateAttr(pageName, idx, attr)
header:Execute(([[self:Run(updateActionAttr, %q, %d, %q)]]):format(pageName, idx, attr))
end
return updateAttr
end
local function setupActions(actions, defaultPage, actionButtons)
local function getActionButton(idx)
local buttonPage = actions[actionPage].buttonPage
return actionButtons[buttonPage][idx]
end
local updateAttr = setupHeader(actions, defaultPage, actionButtons, getActionButton)
local maybeSetAttr, drainPendingAttrs = (function()
local pendingAttrs = {}
local function maybeSetAttr(pageName, idx, attr)
if InCombatLockdown() then
pendingAttrs[pageName] = pendingAttrs[pageName] or {}
pendingAttrs[pageName][idx] = attr
else
updateAttr(pageName, idx, attr)
end
end
local function drainPendingAttrs()
for pageName, pageAttrs in pairs(pendingAttrs) do
for idx, attr in pairs(pageAttrs) do
updateAttr(pageName, idx, attr)
end
wipe(pageAttrs)
end
end
return maybeSetAttr, drainPendingAttrs
end)()
local updateAction = (function()
local uiLang = {
hide = function()
return {
alpha = 0.0,
tooltip = { reset = true },
}
end,
item = function(item)
return {
alpha = 1.0,
color = IsUsableItem(item) and 1.0 or 0.4,
cooldown = { item = item },
count = { item = item },
icon = GetItemIcon(item),
tooltip = { item = item },
update = { item = item },
}
end,
spell = function(spell)
return {
alpha = 1.0,
checked = { spell = spell },
cooldown = { spell = spell },
count = { spell = spell },
icon = GetSpellTexture(spell),
tooltip = { spell = spell },
update = { spell = spell },
}
end,
}
return function(pageName, idx, update)
if update.attr then
maybeSetAttr(pageName, idx, update.attr)
update.attr = nil
end
if update.ui then
local k, v = next(update.ui)
update = Mixin({}, uiLang[k](v), update)
update.ui = nil
end
Mixin(actionButtonState[pageName][idx], update)
if pageName == actionPage then
updateButton(getActionButton(idx), update)
end
end
end)()
local handlers = {}
local function addHandler(ev, handler)
handlers[ev] = handlers[ev] or {}
table.insert(handlers[ev], handler)
end
for pageName, page in pairs(actions) do
actionButtonState[pageName] = {}
for idx, action in pairs(page.actions) do
actionButtonState[pageName][idx] = {}
local init, tyhandlers = makeAction(action)
updateAction(pageName, idx, init)
for ev, handler in pairs(tyhandlers or {}) do
addHandler(ev, function(...)
return updateAction(pageName, idx, handler(...))
end)
end
end
end
local function updateHandler(name)
return function()
for idx, state in pairs(actionButtonState[actionPage]) do
if state[name] then
updateButton(getActionButton(idx), { [name] = state[name] })
end
end
end
end
local genericHandlers = {
BAG_UPDATE_DELAYED = updateHandler('count'),
CURRENT_SPELL_CAST_CHANGED = updateHandler('checked'),
SPELL_UPDATE_COOLDOWN = updateHandler('cooldown'),
}
for ev, handler in pairs(genericHandlers) do
addHandler(ev, handler)
end
local handlersHandlers = {}
for ev, hs in pairs(handlers) do
handlersHandlers[ev] = function(...)
for _, h in ipairs(hs) do
h(...)
end
end
end
-- Run post-combat attr updates before delivering messages to actions.
-- These happened earlier in time.
local postCombatHandler = handlersHandlers.PLAYER_REGEN_ENABLED
handlersHandlers.PLAYER_REGEN_ENABLED = function(...)
drainPendingAttrs()
return postCombatHandler and postCombatHandler(...)
end
G.Eventer(handlersHandlers)
G.Updater(TOOLTIP_UPDATE_TIME, updateHandler('update'))
end
local function makeActions()
local fractionPages, extraPages = (function()
local classActionPages = G.ClassActionSpecs[select(3, UnitClass('player'))]
local fractions, extra = {}, {}
for z, classActions in ipairs(classActionPages or {}) do
local page = {}
table.insert(fractions, page)
for i, v in pairs(classActions) do
if v.page then
local pageName = 'fraction' .. z .. 'x' .. i .. 'x'
page[i] = Mixin({}, v, { page = pageName })
local subpage = {}
for j, x in pairs(v.page) do
subpage[j] = x
end
extra[pageName] = subpage
elseif v.oneof then
local spells, subpage = {}, {}
for j, sp in pairs(v.oneof) do
table.insert(spells, sp)
subpage[j] = { spell = sp }
end
local pageName = 'fraction' .. z .. 'x' .. i .. 'x'
page[i] = Mixin({}, v, { oneof = spells, oneofpage = pageName })
extra[pageName] = subpage
elseif v.stopcasting and not (v.spell or v.spells) then
page[i] = {
actionText = 'Stop',
macro = '/stopcasting',
texture = 135768,
tooltip = 'Stop Casting',
}
elseif v.racial then
page[i] = {
spell = ({
['Blood Elf'] = 'Arcane Torrent',
Draenei = 'Gift of the Naaru',
Dwarf = 'Stoneform',
Gnome = 'Escape Artist',
Human = 'Perception',
['Night Elf'] = 'Shadowmeld',
Orc = 'Blood Fury',
Tauren = 'War Stomp',
Troll = 'Berserking',
Undead = 'Will of the Forsaken',
})[UnitRace('player')]
}
elseif v.racial2 then
local spell = ({
['Blood Elf'] = 'Mana Tap',
Undead = 'Cannibalize',
})[UnitRace('player')]
page[i] = spell and { spell = spell } or nil
else
page[i] = v
end
end
end
return fractions, extra
end)()
local actionPages = Mixin(extraPages, {
action1 = (function()
local page = {}
for i = 1, 48 do
table.insert(page, { action = i })
end
return page
end)(),
action2 = (function()
local page = {}
for i = 49, 72 do
table.insert(page, { action = i })
end
return page
end)(),
aura = (function()
local page = {}
for i = 1, 40 do
table.insert(page, {
aura = {
filter = 'CANCELABLE',
index = i,
},
})
end
return page
end)(),
emote = (function()
local emotes = {
'lol',
'thank',
'cheer',
'wave',
'hello',
'train',
'rude',
'congratulate',
'moo',
'oom',
'attacktarget',
'charge',
'mourn',
'tickle',
'roar',
'rofl',
'hug',
'kiss',
'love',
'hungry',
'thirsty',
'ready',
'sleep',
'sigh',
'nod',
'no',
'threaten',
'silly',
'question',
'welcome',
'hail',
}
local page = {}
for i, emote in ipairs(emotes) do
table.insert(page, {
emote = emote,
index = i,
})
end
return page
end)(),
noncombat = (function()
local page = {}
for i = 1, 10 do
table.insert(page, { noncombat = i })
end
return page
end)(),
pet = (function()
local page = {}
for i = 1, NUM_PET_ACTION_SLOTS do
table.insert(page, { petaction = i })
end
table.insert(page, {
macro = '/cancelaura Mind Control',
texture = 136206,
tooltip = 'Cancel Mind Control',
})
table.insert(page, {
macro = '/petdismiss',
texture = 'interface/icons/spell_nature_spiritwolf',
tooltip = 'Dismiss Pet',
})
return page
end)(),
profession = (function()
local professions = {
'Alchemy',
'Cooking',
'Disenchant',
'Enchanting',
'First Aid',
'Engineering',
'Tailoring',
'Smelting',
'Leatherworking',
'Blacksmithing',
'Jewelcrafting',
'Prospecting',
}
local page = {}
for _, spell in ipairs(professions) do
table.insert(page, {
dismount = false,
spell = spell,
stand = false,
})
end
return page
end)(),
})
local defaultPage = next(fractionPages) and 'fraction1' or 'action1'
local actions = (function()
local t = {}
for k, v in pairs(actionPages) do
t[k] = {
actions = v,
buttonPage = k == 'emote' and 'text' or 'icon',
nextActionPage = k == 'pet' and k or defaultPage,
}
end
for i, v in pairs(fractionPages) do
local n = 'fraction' .. i
t[n] = {
actions = v,
buttonPage = 'icon',
nextActionPage = n,
}
end
return t
end)()
return actions, defaultPage
end
G.Eventer({
PLAYER_LOGIN = function()
G.ReparentFrame(MainMenuBar)
local actions, defaultPage = makeActions()
local actionButtons = makeActionButtons()
setupActions(actions, defaultPage, actionButtons)
end,
})
|
-- Simplified implementation of mw for running WikiMedia Scribunto code
-- under Python
--
-- Copyright (c) 2020-2021 Tatu Ylonen. See file LICENSE and https://ylonen.org
local mw_autoload = {
hash = "mw_hash",
html = "mw_html",
language = "mw_language",
site = "mw_site",
text = "mw_text",
title = "mw_title",
uri = "mw_uri",
ustring = "ustring:ustring",
wikibase = "mw_wikibase",
getContentLanguage = function(table)
return table.language.getContentLanguage
end,
getLanguage = function(table)
return table.language.getContentLanguage
end
}
local mw_meta = {}
-- This is intentionally a global variable, as this is accessed by many modules
mw = {
-- addWarning (see below)
-- allToString (see below)
-- clone (see below)
-- dumpObject (see below)
-- getCurrentFrame -- assigned in lua_invoke for each call
-- hash - autoloaded
-- html - autoloaded
-- incrementExpensiveFunctionCount (see below)
-- isSubsting (see below)
-- language - autoloaded
-- loadData (see below)
-- log (see below)
-- logObject (see below)
-- XXX message.*
-- site - autoloaded
-- text - autoloaded
-- title - autoloaded
-- uri - autoloaded
-- ustring - autoloaded
}
setmetatable(mw, mw_meta)
function mw_meta.__index(table, key)
local modname = mw_autoload[key]
if modname == nil then return nil end
local ret
if type(modname) == "string" then
ret = require(modname)
elseif type(modname) == "function" then
ret = modname(table)
else
error("mw_meta.__index had modname", modname)
end
table[key] = ret
return ret
end
function mw.addWarning(text)
print("mw.addWarning", text)
end
function mw.allToString(...)
local ret = ""
for k, v in pairs(...) do
ret = ret .. tostring(v)
end
return ret
end
local function _mw_deepcopy(obj, visited)
-- non-table objects can be returned as-is
if type(obj) ~= "table" then return obj end
-- handle cyclic data structures
if visited[obj] ~= nil then return visited[obj] end
-- Create new table
local new_table = {}
-- track that we have visited this node and save the copy
visited[obj] = new_table
-- clear metatable during the copy, as it could interfere
local old_meta = getmetatable(obj)
setmetatable(obj, nil)
-- Copy fields of the object
for k, v in pairs(obj) do
new_table[_mw_deepcopy(k, visited)] = _mw_deepcopy(v, visited)
end
-- copy metatable pointer for copy
setmetatable(obj, old_meta)
setmetatable(new_table, old_meta)
return new_table
end
function mw.clone(v)
local ret = _mw_deepcopy(v, {})
-- print("mw_clone: " .. tostring(ret))
return ret
end
function mw.dumpObject(obj)
print("mw.dumpObject", obj)
end
function mw.incrementExpensiveFunctionCount()
print("mw.incrementExpensiveFunctionCount")
end
function mw.isSubsting()
return false
end
-- mw.loadData function - loads a data file. This is same as require(),
-- which already implements caching.
function mw.loadData(modname)
return _new_loadData(modname)
end
function mw.log(...)
-- print("mw.log", ...)
end
function mw.logObject(obj)
-- print("mw.logObject", obj)
end
function mw.getCurrentFrame()
return _mw_frame
end
return mw
|
local Scope = {}
Scope.__index = Scope
Mlc.classes.Scope = Scope
|
-- @docclass
UIWindow = extends(UIWidget, "UIWindow")
function UIWindow.create()
local window = UIWindow.internalCreate()
window:setTextAlign(AlignTopCenter)
window:setDraggable(true)
window:setAutoFocusPolicy(AutoFocusFirst)
return window
end
function UIWindow:onKeyPress(keyCode, keyboardModifiers)
if keyboardModifiers == KeyboardNoModifier then
if keyCode == KeyEnter then
signalcall(self.onEnter, self)
elseif keyCode == KeyEscape then
signalcall(self.onEscape, self)
end
end
end
function UIWindow:onFocusChange(focused) if focused then self:raise() end end
function UIWindow:onDragEnter(mousePos)
self:breakAnchors()
self.movingReference = {
x = mousePos.x - self:getX(),
y = mousePos.y - self:getY()
}
return true
end
function UIWindow:onDragLeave(droppedWidget, mousePos)
-- TODO: auto detect and reconnect anchors
end
function UIWindow:onDragMove(mousePos, mouseMoved)
local pos = {
x = mousePos.x - self.movingReference.x,
y = mousePos.y - self.movingReference.y
}
self:setPosition(pos)
self:bindRectToParent()
end
function UIWindow:show(dontDisableHotkeys)
if modules.game_hotkeys and not dontDisableHotkeys then
modules.game_hotkeys.enableHotkeys(false)
end
self:setVisible(true)
end
function UIWindow:hide(dontDisableHotkeys)
if modules.game_hotkeys and not dontDisableHotkeys then
modules.game_hotkeys.enableHotkeys(true)
end
self:setVisible(false)
end
|
function impulse.Ops.EventManager.SequenceLoad(path)
local fileData = file.Read(path, "DATA")
local json = util.JSONToTable(fileData)
if not json or not istable(json) then
return false, "Corrupted sequence file"
end
if not json.Name or not json.Events or not json.FileName then
return false, "Corrupted sequence file vital metadata"
end
impulse.Ops.EventManager.Sequences[json.Name] = json
return true
end
function impulse.Ops.EventManager.SequenceSave(name)
local sequence = impulse.Ops.EventManager.Sequences[name]
file.Write("impulse/ops/eventmanager/"..sequence.FileName..".json", util.TableToJSON(sequence, true))
end
function impulse.Ops.EventManager.SequencePush(name)
local sequence = impulse.Ops.EventManager.Sequences[name]
local events = sequence.Events
local eventCount = table.Count(events)
print("[ops-em] Starting push of "..name..". (This might take a while)")
net.Start("impulseOpsEMPushSequence")
net.WriteString(name)
net.WriteUInt(eventCount, 16)
for v,k in pairs(events) do
local edata = pon.encode(k)
net.WriteUInt(#edata, 16)
net.WriteData(edata, #edata)
print("[ops-em] Packaged event "..v.."/"..eventCount.." ("..k.Type..")")
end
net.SendToServer()
print("[ops-em] Push fully sent to server!")
end
function impulse.Ops.EventManager.GetVersionHash()
return util.CRC(util.TableToJSON(impulse.Ops.EventManager.Config.Events))
end
|
if not modules then modules = { } end modules ['mtx-mtxworks'] = {
version = 1.002,
comment = "companion to mtxrun.lua",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
-- this is a shortcut to "mtxrun --script texworks --start"
environment.setargument("start",true)
require "mtx-texworks"
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Knit = require(ReplicatedStorage.Knit)
local Janitor = require(Knit.Util.Janitor)
local TableUtil = require(Knit.Util.TableUtil)
local Roact = require(ReplicatedStorage.Roact)
local elements = script.Parent.Elements
local Frame = require(elements.Frame)
local TextLabel = require(elements.TextLabel)
local Key = Roact.PureComponent:extend("Key")
local images = {
[Enum.UserInputType.Touch] = "rbxassetid://7625493742";
[Enum.UserInputType.MouseButton1] = "rbxassetid://7625494008";
[Enum.UserInputType.MouseButton2] = "rbxassetid://7625494406";
[Enum.UserInputType.MouseButton3] = "rbxassetid://7625494225";
[Enum.KeyCode.ButtonA] = "rbxassetid://7625502583";
[Enum.KeyCode.ButtonB] = "rbxassetid://7625502327";
[Enum.KeyCode.ButtonX] = "rbxassetid://7625500057";
[Enum.KeyCode.ButtonY] = "rbxassetid://7625499774";
[Enum.KeyCode.ButtonStart] = "rbxassetid://7626956529";
[Enum.KeyCode.ButtonSelect] = "rbxassetid://7626957065";
[Enum.KeyCode.DPadUp] = "rbxassetid://7625498976";
[Enum.KeyCode.DPadDown] = "rbxassetid://7625499590";
[Enum.KeyCode.DPadLeft] = "rbxassetid://7625499420";
[Enum.KeyCode.DPadRight] = "rbxassetid://7625499185";
[Enum.KeyCode.ButtonL1] = "rbxassetid://7625501623";
[Enum.KeyCode.ButtonL2] = "rbxassetid://7625501219";
[Enum.KeyCode.ButtonR1] = "rbxassetid://7625500678";
[Enum.KeyCode.ButtonR2] = "rbxassetid://7625500426";
[Enum.KeyCode.ButtonL3] = "rbxassetid://7625498721";
[Enum.KeyCode.ButtonR3] = "rbxassetid://7625498497";
}
local largeKeys = {
Enum.KeyCode.Space;
Enum.KeyCode.CapsLock;
Enum.KeyCode.Backspace;
Enum.KeyCode.Tab;
}
local buttonFillProps = {
anchor = Vector2.new(0.5, 0.5);
pos = UDim2.fromScale(0.51, 0.5);
size = UDim2.fromScale(0.75, 0.75);
cornerRadius = UDim.new(1, 0);
}
local menuButtonsFillProps = {
anchor = Vector2.new(0.5, 0.5);
pos = UDim2.fromScale(0.51, 0.52);
size = UDim2.fromScale(0.94, 0.55);
cornerRadius = UDim.new(0.12, 0);
}
local bumperFillProps = {
anchor = Vector2.new(0.5, 0.5);
pos = UDim2.fromScale(0.5, 0.51);
size = UDim2.fromScale(0.7, 0.4);
cornerRadius = UDim.new(0.2, 0);
}
local specialFillProps = {
[Enum.KeyCode.ButtonA] = buttonFillProps;
[Enum.KeyCode.ButtonB] = buttonFillProps;
[Enum.KeyCode.ButtonX] = buttonFillProps;
[Enum.KeyCode.ButtonY] = buttonFillProps;
[Enum.KeyCode.ButtonStart] = menuButtonsFillProps;
[Enum.KeyCode.ButtonSelect] = menuButtonsFillProps;
[Enum.KeyCode.ButtonL1] = bumperFillProps;
[Enum.KeyCode.ButtonL2] = bumperFillProps;
[Enum.KeyCode.ButtonR1] = bumperFillProps;
[Enum.KeyCode.ButtonR2] = bumperFillProps;
[Enum.KeyCode.ButtonL3] = buttonFillProps;
[Enum.KeyCode.ButtonR3] = buttonFillProps;
}
function Key:init()
local UI = require(ReplicatedStorage.UI)
self:setState({
device = UI:GetInputDevice(true);
})
self.janitor = Janitor.new()
end
function Key:render()
local children = self.props[Roact.Children] or { }
self.props[Roact.Children] = nil
local input = self.props.inputs[self.state.device]
or Enum.UserInputType.None
local image = images[input]
local isKey = not image
if isKey then
image = "rbxassetid://7626320648"
end
children.Image = Roact.createElement("ImageLabel", {
Image = image;
ImageTransparency = self.props.trans;
ImageColor3 = self.props.color;
ScaleType = Enum.ScaleType.Fit;
Size = UDim2.fromScale(1, 1);
BackgroundTransparency = 1;
ZIndex = self.props.index;
})
if isKey then
children.Text = Roact.createElement(TextLabel, {
trans = self.props.trans;
text = input.Name;
color = self.props.color;
size = UDim2.fromScale(0.7, 0.7);
anchor = Vector2.new(0.5, 0);
pos = UDim2.fromScale(0.5, 0.1);
})
end
local index = (
self.props.fill
and (self.props.index and self.props.index + 1)
or self.props.index
) or 1
if self.props.fill then
local fillProps = TableUtil.Assign({
anchor = Vector2.new(0.5, 0.5);
pos = UDim2.fromScale(0.5, 0.5);
size = UDim2.fromScale(0.9, 0.9);
cornerRadius = isKey and UDim.new(0.15, 0) or UDim.new(1, 0);
index = index - 1;
}, specialFillProps[input] or { })
children.Fill = Roact.createElement(self.props.fill, fillProps)
end
return Roact.createElement(Frame, {
anchor = self.props.anchor;
pos = self.props.pos;
size = self.props.size;
constraint = self.props.constraint;
clip = self.props.clip;
order = self.props.order;
index = index;
[Roact.Ref] = self.props[Roact.Ref];
}, children)
end
function Key:didMount()
local UI = require(ReplicatedStorage.UI)
self.janitor:Add(UI.InputDeviceChanged:Connect(function(_id, device)
self:setState({
device = device;
})
end))
end
function Key:willUnmount()
self.janitor:Destroy()
end
return Key
|
:: # Copyright 2013, Big Switch Networks, Inc.
:: #
:: # LoxiGen is licensed under the Eclipse Public License, version 1.0 (EPL), with
:: # the following special exception:
:: #
:: # LOXI Exception
:: #
:: # As a special exception to the terms of the EPL, you may distribute libraries
:: # generated by LoxiGen (LoxiGen Libraries) under the terms of your choice, provided
:: # that copyright and licensing notices generated by LoxiGen are not altered or removed
:: # from the LoxiGen Libraries and the notice provided below is (i) included in
:: # the LoxiGen Libraries, if distributed in source code form and (ii) included in any
:: # documentation for the LoxiGen Libraries, if distributed in binary form.
:: #
:: # Notice: "Copyright 2013, Big Switch Networks, Inc. This library was generated by the LoxiGen Compiler."
:: #
:: # You may not use this file except in compliance with the EPL or LOXI Exception. You may obtain
:: # a copy of the EPL at:
:: #
:: # http://www.eclipse.org/legal/epl-v10.html
:: #
:: # 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
:: # EPL for the specific language governing permissions and limitations
:: # under the EPL.
function read_scalar(reader, subtree, field_name, length)
subtree:add(fields[field_name], reader.read(length))
end
function read_uint8_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 1)
end
function read_uint16_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 2)
end
function read_uint32_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 4)
end
function read_uint64_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 8)
end
function read_of_bitmap_128_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 16)
end
function read_of_bitmap_512_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 64)
end
function read_of_checksum_128_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 16)
end
function read_of_octets_t(reader, version, subtree, field_name)
if not reader.is_empty() then
subtree:add(fields[field_name], reader.read_all())
end
end
function read_list_of_hello_elem_t(reader, version, subtree, field_name)
-- TODO
end
function read_of_match_t(reader, version, subtree, field_name)
if version == 1 then
dissect_of_match_v1_v1(reader, subtree:add("of_match"))
elseif version == 2 then
dissect_of_match_v2_v2(reader, subtree:add("of_match"))
elseif version == 3 then
dissect_of_match_v3_v3(reader, subtree:add("of_match"))
elseif version == 4 then
dissect_of_match_v3_v4(reader, subtree:add("of_match"))
elseif version == 5 then
dissect_of_match_v3_v5(reader, subtree:add("of_match"))
elseif version == 6 then
dissect_of_match_v3_v6(reader, subtree:add("of_match"))
else
error("Unsupported match version")
end
end
function read_of_stat_t(reader, version, subtree, field_name)
if version == 1 then
error("Unsupported statistics version")
elseif version == 2 then
error("Unsupported statistics version")
elseif version == 3 then
error("Unsupported statistics version")
elseif version == 4 then
error("Unsupported statistics version")
elseif version == 5 then
error("Unsupported statistics version")
elseif version == 6 then
dissect_of_stat_v6_v6(reader, subtree:add("of_stat"))
else
error("Unsupported statistics version")
end
end
function read_of_wc_bmap_t(reader, version, subtree, field_name)
if version <= 2 then
read_scalar(reader, subtree, field_name, 4)
else
read_scalar(reader, subtree, field_name, 8)
end
end
function read_of_port_no_t(reader, version, subtree, field_name)
if version == 1 then
read_scalar(reader, subtree, field_name, 2)
else
read_scalar(reader, subtree, field_name, 4)
end
end
function read_of_port_name_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 16)
end
function read_of_mac_addr_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 6)
end
function read_of_ipv4_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 4)
end
function read_of_ipv6_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 16)
end
function read_of_fm_cmd_t(reader, version, subtree, field_name)
if version == 1 then
read_scalar(reader, subtree, field_name, 2)
else
read_scalar(reader, subtree, field_name, 1)
end
end
function read_of_desc_str_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 256)
end
function read_of_serial_num_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 32)
end
function read_of_table_name_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 32)
end
function read_of_str64_t(reader, version, subtree, field_name)
read_scalar(reader, subtree, field_name, 64)
end
function read_of_port_desc_t(reader, version, subtree, field_name)
if reader.is_empty() then
return
end
local child_subtree = subtree:add(fields[field_name], reader.peek_all(0))
local info = of_port_desc_dissectors[version](reader, child_subtree)
child_subtree:set_text(info)
end
function read_of_oxm_t(reader, version, subtree, field_name)
if reader.is_empty() then
return
end
local child_subtree = subtree:add(fields[field_name], reader.peek_all(0))
local info = of_oxm_dissectors[version](reader, child_subtree)
child_subtree:set_text(info)
end
function read_of_oxs_t(reader, version, subtree, field_name)
if reader.is_empty() then
return
end
local child_subtree = subtree:add(fields[field_name], reader.peek_all(0))
local info = of_oxs_dissectors[version](reader, child_subtree)
child_subtree:set_text(info)
end
function read_list(reader, dissector, subtree, field_name)
if not reader.is_empty() then
local list_subtree = subtree:add(field_name .. " list", reader.peek_all(0))
while not reader.is_empty() do
local atom_subtree = list_subtree:add(field_name, reader.peek_all(0))
local info = dissector(reader, atom_subtree)
atom_subtree:set_text(info)
end
else
return
end
end
function read_ethernet(reader, version, subtree, field_name)
if reader.is_empty() then
return
end
local child_subtree = subtree:add(fields[field_name], reader.peek_all(0))
child_subtree:set_text("Ethernet packet")
ethernet_dissector:call(reader.read_all():tvb(), current_pkt, child_subtree)
end
function read_of_bsn_vport_q_in_q_t(reader, version, subtree, field_name)
if reader.is_empty() then
return
end
local child_subtree = subtree:add(fields[field_name], reader.peek_all(0))
local info = of_bsn_vport_q_in_q_dissectors[version](reader, child_subtree)
child_subtree:set_text(info)
end
function read_openflow(reader, version, subtree, field_name)
if reader.is_empty() then
return
end
local child_subtree = subtree:add(fields[field_name], reader.peek_all(0))
child_subtree:set_text("OpenFlow message")
pcall(function () -- Message may be truncated, ignore errors dissecting
p_of.dissector:call(reader.read_all():tvb(), current_pkt, child_subtree)
end)
end
|
-- player.lua
local Modern = require 'modern'
--
local AABB = Modern:extend()
function AABB:new()
-- using `Player` variables to create some more
self.left = self.x
self.top = self.y
self.right = self.x + self.width
self.bottom = self.y + self.height
end
-- ...
-- Really cool, useful functions removed for brevity :p
-- ...
function AABB:draw()
if self.debug then
love.graphics.setColor(1, 0, 0, 1)
love.graphics.rectangle('line', self.x, self.y, self.width, self.height)
end
end
--
local Player = Modern:extend(AABB)
function Player:new(x, y, src)
local image = love.graphics.newImage(src)
local w, h = image:getDimensions( )
self.x = x
self.y = y
self.image = image
self.scale = 0.5
self.width = w * self.scale
self.height = h * self.scale
self.debug = false
end
function Player:draw()
love.graphics.setColor(1, 1, 1, 1)
love.graphics.draw(self.image, self.x, self.y, 0, self.scale)
end
return Player
|
donor_scroll = {
use = function(player)
local invItem = player:getInventoryItem(player.invSlot)
local scrollName = invItem.name
if not player:canAction(1, 1, 1) then
return
end
if player.state == 1 then
player:sendMinitext("How can you open this with no hands?")
return
end
if player:hasLegend("donor_tierone") then
player:sendMinitext("Thanks for your contribution, but you already have the legend mark!")
player:removeItemSlot(player.invSlot, 1, 9)
return
end
if player:hasLegend("donor_tiertwo") then
player:sendMinitext("Thanks for your contribution, but you already have the legend mark!")
player:removeItemSlot(player.invSlot, 1, 9)
return
end
if player:hasLegend("donor_tierthree") then
player:sendMinitext("Thanks for your contribution, but you already have the legend mark!")
player:removeItemSlot(player.invSlot, 1, 9)
return
end
if player:hasLegend("donor_tierfour") then
player:sendMinitext("Thanks for your contribution, but you already have the legend mark!")
player:removeItemSlot(player.invSlot, 1, 9)
return
end
if player:hasLegend("donor_tierfive") then
player:sendMinitext("Thanks for your contribution, but you already have the legend mark!")
player:removeItemSlot(player.invSlot, 1, 9)
return
end
if scrollName == "Donor Scroll 1" then
player:sendAnimation(278)
player:sendAnimation(251)
player:playSound(739)
player:playSound(123)
broadcast(
-1,
"[RTK Team] A huge thank you to " .. player.name .. " for their donation!"
)
player:addLegend(
"Supporter of the Kingdoms (" .. curT() .. ")",
"donor_tierone",
20,
9
)
player:removeItemSlot(player.invSlot, 1, 9)
end
if scrollName == "Donor Scroll 2" then
player:sendAnimation(278)
player:sendAnimation(251)
player:playSound(739)
player:playSound(123)
broadcast(
-1,
"[RTK Team] A huge thank you to " .. player.name .. " for their great donation!"
)
player:addLegend(
"Patron of the Kingdoms (" .. curT() .. ")",
"donor_tiertwo",
20,
9
)
player:removeItemSlot(player.invSlot, 1, 9)
end
if scrollName == "Donor Scroll 3" then
player:sendAnimation(278)
player:sendAnimation(251)
player:playSound(739)
player:playSound(123)
broadcast(
-1,
"[RTK Team] A huge thank you to " .. player.name .. " for their amazing donation!"
)
player:addLegend(
"Benefactor of the Kingdoms (" .. curT() .. ")",
"donor_tierthree",
20,
9
)
player:removeItemSlot(player.invSlot, 1, 9)
end
if scrollName == "Donor Scroll 4" then
player:sendAnimation(278)
player:sendAnimation(251)
player:playSound(739)
player:playSound(123)
broadcast(
-1,
"[RTK Team] A huge thank you to " .. player.name .. " for their fantastic donation!"
)
player:addLegend(
"Curator of the Kingdoms (" .. curT() .. ")",
"donor_tierfour",
20,
9
)
player:removeItemSlot(player.invSlot, 1, 9)
end
if scrollName == "Donor Scroll 5" then
player:sendAnimation(278)
player:sendAnimation(251)
player:playSound(739)
player:playSound(123)
broadcast(
-1,
"[RTK Team] A huge thank you to " .. player.name .. " for their astounding donation!"
)
player:addLegend(
"Saviour of the Kingdoms (" .. curT() .. ")",
"donor_tierfive",
20,
9
)
player:removeItemSlot(player.invSlot, 1, 9)
end
end
}
consumable = {
cast = function(player)
player:setAether("consumable", 1000)
return
end
}
|
---
-- @author Alf21
-- @author saibotk
-- @author Mineotopia
-- @class ROLE
ROLE.isAbstract = true
ROLE.score = {
-- The multiplier that is used to calculate the score penalty
-- that is added if this role kills a team member.
teamKillsMultiplier = 0,
-- The multiplier that is used to calculate the gained score
-- by killing someone from a different team.
killsMultiplier = 0,
-- The amount of score points gained by confirming a body.
bodyFoundMuliplier = 1,
-- The amount of score points gained by surviving a round,
-- based on the amount of dead enemy players. Only applied when
-- in winning team.
surviveBonusMultiplier = 0,
-- The amount of score point lost by surviving a round, based
-- on the amount of surviving team players. Only applied when
-- not in winning team.
survivePenaltyMultiplier = 0,
-- The amount of score points granted due to a survival of the
-- round for every teammate alive.
aliveTeammatesBonusMultiplier = 1,
-- Multiplier for a score for every player alive at the end of
-- the round. Can be negative for roles that should kill everyone.
allSurviveBonusMultiplier = 0,
-- The amount of score points gained by being alive if the
-- round ended with nobody winning, usually a negative number.
timelimitMultiplier = 0,
-- the amount of points gained by killing yourself. Should be a
-- negative number for most roles.
suicideMultiplier = -1
}
ROLE.conVarData = {
-- The percentage of players that get this role.
pct = 0.4,
-- The maximum amount of players that get this role.
maximum = 32,
-- The minimum amount of players that have to be available fot this role to be selected.
minPlayers = 1,
-- The minimum amount of Karma needed for selection.
minKarma = 0,
-- Defines if the role has access to traitor buttons.
traitorButton = 1,
-- Sets the amount of credits the role is starting with.
credits = 0,
-- Defines if this role gains credits if a certain percentage of players
-- from other teams is dead.
creditsAwardDeadEnable = 0,
-- Defines if this role is awarded with credits for the kill of a high profile.
-- policing role, such as a detective.
creditsAwardKillEnable = 0,
-- Sets the shop for this role, by default roles have no shop set.
shopFallback = SHOP_DISABLED,
-- If this is enabled the 'avoid role selection' can be toggled for this role.
togglable = true
}
-- This role variable makes the role unselectable if set to true. This might be
-- useful for roles that are applied during a round and not in the initial role
-- selection process.
ROLE.notSelectable = false
-- This variable can be used to add roles that can see the role of the
-- player with the role defined in this file. While this table can be updated
-- on runtime, it is strongly advised against. Use custom hook based
-- syncing for specific syncing.
ROLE.visibleForTeam = {}
-- If set to true, this role doesn't know about their teammates. A normal innocent
-- for example knows that they are in team innocent, but doesn't know who else is.
-- If set to false, this player knows about the role of all their teamm ates.
ROLE.unknownTeam = false
-- This can be used to force prevent picking up credits from corpses. Keep in mind
-- that this only applies to shopping roles, as roles without a shop are unable to
-- pick up credits anyway.
ROLE.preventFindCredits = false
-- Normally a team can win if at least one role of the team is still alive, while no
-- other role that is able to win is alive. If this convar is set to true, this role
-- is unable to win by staying alive. A custom wincondition might be added.
ROLE.preventWin = false
-- If a player knows the role of their team mate, their role is shown overhead with
-- an icon. However this can be disabled with this role variable.
ROLE.avoidTeamIcons = false
-- Disables the sync of this role to the owner of the role. This means the owner doesn't
-- know about their own role. Should probably extended by custom role syncing.
ROLE.disableSync = false
-- Set this flag to true to make a role public known. This results in a
-- detective-like behavior.
ROLE.isPublicRole = false
-- A policing role is a role that works like a detective. They can be called to
-- a corpse and evil roles can be rewarded more points for them being killed.
ROLE.isPolicingRole = false
---
-- This function is called before initializing a @{ROLE}, but after all
-- global variables like "ROLE_TRAITOR" have been initialized.
-- Use this function to define role attributes, which is dependant on other
-- global variables (eg. from other roles).
-- This is mostly used to register the defaultTeam, shopFallback, etc...
-- @hook
-- @realm shared
function ROLE:PreInitialize()
end
---
-- This function is called after all roles have been loaded with their
-- ConVars, that are created for each role automatically, and their global
-- variables.
-- Please use this function to register your SubRole with the BaseRole, by
-- calling @{roles.SetBaseRole} and initialize any other needed data
-- (eg. @{LANG} function calls).
-- @hook
-- @realm shared
function ROLE:Initialize()
end
---
-- Returns the starting credits of a @{ROLE} based on ConVar settings or default traitor settings
-- @return[default=0] number
-- @realm shared
function ROLE:GetStartingCredits()
local cv = GetConVar("ttt_" .. self.abbr .. "_credits_starting")
return cv and cv:GetInt() or 0
end
---
-- Returns whether a @{ROLE} is able to access the shop based on ConVar settings
-- @return[default=false] boolean
-- @realm shared
function ROLE:IsShoppingRole()
if self.subrole == ROLE_NONE then
return false
end
local shopFallback = GetGlobalString("ttt_" .. self.abbr .. "_shop_fallback")
return shopFallback ~= SHOP_DISABLED
end
---
-- Returns whether a @{ROLE} is a BaseRole
-- @return boolean
-- @realm shared
function ROLE:IsBaseRole()
return self.baserole == nil
end
---
-- Connects a SubRole with its BaseRole
-- @param ROLE baserole the BaseRole
-- @deprecated
-- @realm shared
function ROLE:SetBaseRole(baserole)
print("[TTT2][DEPRECATION] ROLE:SetBaseRole will be removed in the near future! You should call roles.SetBaseRole(self, ROLENAME) in the ROLE:Initialize() function!")
roles.SetBaseRole(self, baserole)
end
---
-- Returns the baserole of a specific @{ROLE}
-- @return number subrole id of the BaseRole (@{ROLE})
-- @realm shared
function ROLE:GetBaseRole()
return self.baserole or self.index
end
---
-- Returns a list of subroles of this BaseRole (this subrole's BaseRole)
-- @return table list of @{ROLE}
-- @realm shared
function ROLE:GetSubRoles()
local br = self:GetBaseRole()
local tmp = {}
local rlsList = roles.GetList()
for k = 1, #rlsList do
local v = rlsList[k]
if v.baserole and v.baserole == br or v.index == br then
tmp[#tmp + 1] = v
end
end
return tmp
end
---
-- Returns whether a @{ROLE} can use traitor buttons.
-- @return boolean
-- @realm shared
function ROLE:CanUseTraitorButton()
local cv = GetConVar("ttt_" .. self.name .. "_traitor_button")
return cv and cv:GetBool() or false
end
|
local Mesh3D=Core.class(Mesh,function() return true end)
Mesh3D.MODE_TEXTURE=1
Mesh3D.MODE_LIGHTING=2 --ie normals
Mesh3D.MODE_BUMP=4
Mesh3D.MODE_SHADOW=8
Mesh3D.MODE_ANIMATED=16
Mesh3D.MODE_INSTANCED=32
function Mesh3D:init()
self.mode=0
end
function Mesh3D:updateMode(set,clear)
local nm=(self.mode|(set or 0))&~(clear or 0)
if nm~=self.mode then
self.mode=nm
if (nm&Mesh3D.MODE_LIGHTING)>0 then
local tc=""
if (nm&Mesh3D.MODE_TEXTURE)>0 then
tc=tc.."t"
end
if (nm&Mesh3D.MODE_SHADOW)>0 then
tc=tc.."s"
end
if (nm&Mesh3D.MODE_BUMP)>0 then
tc=tc.."n"
end
if (nm&Mesh3D.MODE_ANIMATED)>0 then
tc=tc.."a"
end
if (nm&Mesh3D.MODE_INSTANCED)>0 then
tc=tc.."i"
end
Lighting.setSpriteMode(self,tc)
end
end
end
function Mesh3D:setInstanceCount(n)
self._im1,self._im2,self._im3,self._im4=self._im1 or {}, self._im2 or {},self._im3 or {},self._im4 or {}
self._icount=n
if n==0 then
self:updateMode(0,Mesh3D.MODE_INSTANCED)
else
self:updateMode(Mesh3D.MODE_INSTANCED,0)
end
Mesh.setInstanceCount(self,n)
end
function Mesh3D:setInstanceMatrix(i,m)
local mm={m:getMatrix()}
local is=i*4-3
self._im1[is],self._im1[is+1],self._im1[is+2],self._im1[is+3]=mm[1],mm[2],mm[3],mm[4]
self._im2[is],self._im2[is+1],self._im2[is+2],self._im2[is+3]=mm[5],mm[6],mm[7],mm[8]
self._im3[is],self._im3[is+1],self._im3[is+2],self._im3[is+3]=mm[9],mm[10],mm[11],mm[12]
self._im4[is],self._im4[is+1],self._im4[is+2],self._im4[is+3]=mm[13],mm[14],mm[15],mm[16]
end
function Mesh3D:updateInstances()
local icc=self._icount*4
for i=1,icc do
self._im1[i]=self._im1[i] or 0
self._im2[i]=self._im2[i] or 0
self._im3[i]=self._im3[i] or 0
self._im4[i]=self._im4[i] or 0
end
self:setGenericArray(6,Shader.DFLOAT,4,self._icount,self._im1)
self:setGenericArray(7,Shader.DFLOAT,4,self._icount,self._im2)
self:setGenericArray(8,Shader.DFLOAT,4,self._icount,self._im3)
self:setGenericArray(9,Shader.DFLOAT,4,self._icount,self._im4)
end
function Mesh3D:setLocalMatrix(m)
self:setShaderConstant("InstanceMatrix",Shader.CMATRIX,1,m:getMatrix())
end
--Unit Cube
local Box=Core.class(Mesh3D)
function Box:init(w,h,d)
w=w or 1 h=h or 1 d=d or 1
if not Box.ia then
Box.ia={
1,2,3,1,3,4,
5,6,7,5,7,8,
9,10,11,9,11,12,
13,14,15,13,15,16,
17,18,19,17,19,20,
21,22,23,21,23,24}
Box.na={
0,0,-1,0,0,-1,0,0,-1,0,0,-1,
0,0,1,0,0,1,0,0,1,0,0,1,
0,-1,0,0,-1,0,0,-1,0,0,-1,0,
0,1,0,0,1,0,0,1,0,0,1,0,
-1,0,0,-1,0,0,-1,0,0,-1,0,0,
1,0,0,1,0,0,1,0,0,1,0,0,
}
end
self._va={
-w,-h,-d, w,-h,-d, w,h,-d, -w,h,-d,
-w,-h,d, w,-h,d, w,h,d, -w,h,d,
-w,-h,-d, w,-h,-d, w,-h,d, -w,-h,d,
-w,h,-d, w,h,-d, w,h,d, -w,h,d,
-w,-h,-d, -w,h,-d, -w,h,d, -w,-h,d,
w,-h,-d, w,h,-d, w,h,d, w,-h,d,
}
self:setGenericArray(3,Shader.DFLOAT,3,24,Box.na)
self:setVertexArray(self._va)
self:setIndexArray(Box.ia)
self._va=Box.va self._ia=Box.ia
end
function Box:mapTexture(texture,sw,sh)
self:setTexture(texture)
if texture then
local tw,th=texture:getWidth()*(sw or 1),texture:getHeight()*(sh or 1)
self:setTextureCoordinateArray{
0,0,tw,0,tw,th,0,th,
0,0,tw,0,tw,th,0,th,
0,0,tw,0,tw,th,0,th,
0,0,tw,0,tw,th,0,th,
0,0,tw,0,tw,th,0,th,
0,0,tw,0,tw,th,0,th,
}
self:updateMode(Mesh3D.MODE_TEXTURE,0)
else
self:updateMode(0,Mesh3D.MODE_TEXTURE)
end
end
function Box:getCollisionShape()
if not self._r3dshape then
self._r3dshape=r3d.BoxShape.new(1,1,1)
end
return self._r3dshape
end
--Unit Sphere
local Sphere=Core.class(Mesh3D)
function Sphere:init(steps)
local va,ia={},{}
local rs=(2*3.141592654)/steps
local i,ni=4,1
--Vertices
va[1]=0 va[2]=1 va[3]=0
for iy=1,(steps//2)-1 do
local y=math.cos(iy*rs)
local r=math.sin(iy*rs)
for ix=0,steps do
local x=r*math.cos(ix*rs)
local z=r*math.sin(ix*rs)
va[i]=x i+=1
va[i]=y i+=1
va[i]=z i+=1
end
end
va[i]=0 va[i+1]=-1 va[i+2]=0
local lvi=i//3+1
--Indices
--a) top and bottom fans
for i=1,steps do
ia[ni]=1 ni+=1 ia[ni]=i+1 ni+=1 ia[ni]=i+2 ni+=1
ia[ni]=lvi ni+=1 ia[ni]=lvi-i ni+=1 ia[ni]=lvi-i-1 ni+=1
end
--b) quads
for iy=1,(steps//2)-2 do
local b=1+(steps+1)*(iy-1)
for ix=1,steps do
ia[ni]=b+ix ni+=1 ia[ni]=b+ix+1 ni+=1 ia[ni]=b+ix+steps+1 ni+=1
ia[ni]=b+ix+steps+1 ni+=1 ia[ni]=b+ix+1 ni+=1 ia[ni]=b+ix+steps+2 ni+=1
end
end
self:setGenericArray(3,Shader.DFLOAT,3,lvi,va)
self:setVertexArray(va)
self:setIndexArray(ia)
self._steps=steps
self._va=va self._ia=ia
end
function Sphere:mapTexture(texture)
self:setTexture(texture)
if texture then
local tw,th=texture:getWidth(),texture:getHeight()
local va={}
local i=3
--TexCoords
va[1]=tw/2 va[2]=0
for iy=1,(self._steps//2)-1 do
local y=th*(1-iy*2/self._steps)
for ix=0,self._steps do
local x=tw*(ix/self._steps)
va[i]=x i+=1
va[i]=y i+=1
end
end
va[i]=tw/2 va[i+1]=th
self:setTextureCoordinateArray(va)
self:updateMode(Mesh3D.MODE_TEXTURE,0)
else
self:updateMode(0,Mesh3D.MODE_TEXTURE)
end
end
function Sphere:getCollisionShape()
if not self._r3dshape then
self._r3dshape=r3d.SphereShape.new(1)
end
return self._r3dshape
end
--Unit Cylinder along Y axis
local Cylinder=Core.class(Mesh3D)
function Cylinder:init(steps)
local va,ia,na={},{},{}
local rs=(2*3.141592654)/steps
local i,ni=7,1
--Vertices/Normals
va[1]=0 va[2]=1 va[3]=0
va[4]=0 va[5]=-1 va[6]=0
na[1]=0 na[2]=1 na[3]=0
na[4]=0 na[5]=-1 na[6]=0
for ix=0,steps do
local x=math.cos(ix*rs)
local z=-math.sin(ix*rs)
va[i]=x na[i]=0 i+=1
va[i]=1 na[i]=1 i+=1
va[i]=z na[i]=0 i+=1
va[i]=x na[i]=x i+=1
va[i]=1 na[i]=0 i+=1
va[i]=z na[i]=z i+=1
va[i]=x na[i]=x i+=1
va[i]=-1 na[i]=0 i+=1
va[i]=z na[i]=z i+=1
va[i]=x na[i]=0 i+=1
va[i]=-1 na[i]=-1 i+=1
va[i]=z na[i]=0 i+=1
end
--Indices
for i=3,steps*4-1,4 do
--For rendering, take care of normals
ia[ni]=1 ni+=1 ia[ni]=i ni+=1 ia[ni]=i+4 ni+=1
ia[ni]=2 ni+=1 ia[ni]=i+3 ni+=1 ia[ni]=i+7 ni+=1
ia[ni]=i+1 ni+=1 ia[ni]=i+2 ni+=1 ia[ni]=i+5 ni+=1
ia[ni]=i+2 ni+=1 ia[ni]=i+6 ni+=1 ia[ni]=i+5 ni+=1
end
self:setGenericArray(3,Shader.DFLOAT,3,#na//3,na)
self:setVertexArray(va)
self:setIndexArray(ia)
self._steps=steps
self._va=va self._ia=ia
end
function Cylinder:mapTexture(texture)
self:setTexture(texture)
if texture then
local tw,th=texture:getWidth(),texture:getHeight()
local va={}
local i=5
--TexCoords
local twh,thh=tw/2,th/2
va[1]=twh va[2]=0
va[3]=twh va[4]=th
for xi=0,self._steps do
local x=tw*(xi/self._steps)
va[i]=x i+=1
va[i]=0 i+=1
va[i]=x i+=1
va[i]=0 i+=1
va[i]=x i+=1
va[i]=th i+=1
va[i]=x i+=1
va[i]=th i+=1
end
self:setTextureCoordinateArray(va)
self:updateMode(Mesh3D.MODE_TEXTURE,0)
else
self:updateMode(0,Mesh3D.MODE_TEXTURE)
end
end
function Cylinder:getCollisionShape()
if not self._r3dshape then
--For collision, ensure closed/CCW shape
local steps=self._steps
local ca,fa={},{}
local nc,nf=1,1
for i=3,steps*4-1,4 do ca[nc]=i+1 nc+=1 end
fa[nf]=steps nf+=1
for i=3,steps*4-1,4 do
ca[nc]=i+1 nc+=1 ca[nc]=i+2 nc+=1
ca[nc]=i+6 nc+=1 ca[nc]=i+5 nc+=1
fa[nf]=4 nf+=1
end
ca[nc-2]=5 ca[nc-1]=4
for i=steps*4-1,3,-4 do ca[nc]=i+2 nc+=1 end
fa[nf]=steps nf+=1
self._r3dshape=r3d.ConvexMeshShape.new(self._va,ca,fa)
end
return self._r3dshape
end
local Group3D=Core.class(Sprite)
function Group3D:updateMode(set,clear)
for _,v in pairs(self.objs) do
v:updateMode(set,clear)
end
end
D3=D3 or {}
D3.Group=Group3D
D3.Mesh=Mesh3D
D3.Cube=Box
D3.Sphere=Sphere
D3.Cylinder=Cylinder
D3.checkCCW=function(v,i,f)
local fi=1
for fn=1,#f do
local s=""
for l=fi,fi+f[fn]-1 do
local ii=i[l]*3-2
local ax,ay,az=v[ii],v[ii+1],v[ii+2]
s=s..string.format("%d:[%f,%f,%f] ",i[l],ax,ay,az)
end
fi+=f[fn]
print(fn,f[fn],s)
end
end
|
local initiative = Initiative:by_id(param.get("initiative_id"))
local member = app.session.member
if member then
initiative:load_everything_for_member_id(member.id)
initiative.issue:load_everything_for_member_id(member.id)
end
local initiator = Initiator:by_pk(initiative.id, app.session.member.id)
if not initiator or initiator.accepted ~= true then
error("access denied")
end
execute.view {
module = "issue", view = "_head", params = {
issue = initiative.issue,
member = app.session.member
}
}
execute.view{ module = "issue", view = "_sidebar_state", params = {
initiative = initiative
} }
execute.view {
module = "issue", view = "_sidebar_issue",
params = {
issue = initiative.issue,
highlight_initiative_id = initiative.id
}
}
execute.view {
module = "issue", view = "_sidebar_whatcanido",
params = { initiative = initiative }
}
execute.view {
module = "issue", view = "_sidebar_members", params = {
issue = initiative.issue, initiative = initiative
}
}
ui.form{
attr = { class = "vertical section" },
module = "initiative",
action = "remove_initiator",
params = {
initiative_id = initiative.id,
},
routing = {
ok = {
mode = "redirect",
module = "initiative",
view = "show",
id = initiative.id,
params = {
tab = "initiators",
}
}
},
content = function()
ui.sectionHead( function()
ui.link{
module = "initiative", view = "show", id = initiative.id,
content = function ()
ui.heading {
level = 1,
content = initiative.display_name
}
end
}
ui.heading { level = 2, content = _"Remove an initiator from initiative" }
end )
ui.sectionRow( function()
local records = initiative:get_reference_selector("initiating_members"):add_where("accepted OR accepted ISNULL"):exec()
ui.heading{ level = 2, content = _"Choose an initiator to remove" }
ui.field.select{
name = "member_id",
foreign_records = records,
foreign_id = "id",
foreign_name = "name",
}
slot.put("<br />")
ui.tag{
tag = "input",
attr = {
type = "submit",
class = "btn btn-dangerous",
value = _"Remove initiator"
},
content = ""
}
slot.put("<br />")
slot.put("<br />")
ui.link{
content = _"Cancel",
module = "initiative",
view = "show",
id = initiative.id,
params = {
tab = "initiators"
}
}
end )
end
}
|
/*
if !SERVER then return false; end
local PLUGIN = {}
PLUGIN.Name = "Ban Words"
PLUGIN.Author = "RedMist"
PLUGIN.Date = "15th March 2011"
PLUGIN.Filename = PLUGIN_FILENAME
PLUGIN.ClientSide = false
PLUGIN.ServerSide = true
PLUGIN.APIVersion = 2
PLUGIN.Gamemodes = {}
--PLUGIN.BannedWords = {};
PLUGIN.BannedWords = {"nigger", "white power", "nigga", "fag", "queer", "kike", "whitepower", "whitpower", "nigg3r", "niggar", "niglet", "niger", "n1gger", "n1gg3r", "nlgger", "nlgg3r", "reggin", "pineapple", "cuntskikbut", "cuntskickbut", "n!gger", "n!gg3r", "pine@pple", "p1ne@pple", "pinapple", "pin@apple", "p1n@pple", "p1ne@ppl", "p1neappl", "k1k3", "kik3", "k1ke"};
function PLUGIN.MonitorChat ( Player, Text, Bool )
for k, v in pairs(PLUGIN.BannedWords) do
if string.find(string.lower(Text), string.lower(v)) then
if Player:GetLevel() < 4 then
Player:PrintMessage(HUD_PRINTTALK, "As an Admin, you are immune from the auto-kicker, but please watch your language as to avoid aggrivating other players.");
elseif Player:GetLevel() == 99 then
Player:PrintMessage(HUD_PRINTTALK, "As a Gold Member, you are immune from the auto-kicker, but please watch your language as to avoid aggrivating other players.");
elseif Player:GetLevel() == 100 then
Player:PrintMessage(HUD_PRINTTALK, "As a VIP member, you are immune from the auto-kicker, but please watch your language as to avoid aggrivating other players.");
else
Player:Kick("'" .. v .. "' is an auto-kick word.");
for l, j in pairs(player.GetAll()) do
j:PrintMessage(HUD_PRINTTALK, Player:Nick() .. " was kicked for saying '" .. v .. "', which is an auto-kick word.");
end
SendLog("Auto Kicker", "AUTO_WORD_KICK", Player:Nick(), v)
return "";
end
end
end
PLUGIN.PlayerLastChats[Player] = CurTime()
end
hook.Add("PlayerSay", "PLUGIN.MonitorChat", PLUGIN.MonitorChat);
*/
|
require "ratchet"
function ctx1()
local socket_a, socket_b = ratchet.socket.new_pair()
ratchet.thread.attach(ctx2, socket_b)
socket_a:send("hello")
local data = socket_a:recv(5)
assert(data == "world")
local data = socket_a:recv()
assert(data == "foo")
socket_a:send("bar")
end
function ctx2(socket_b)
local data = socket_b:recv(5)
assert(data == "hello")
socket_b:send("world")
socket_b:send("foo")
local data = socket_b:recv()
assert(data == "bar")
end
kernel = ratchet.new(function ()
ratchet.thread.attach(ctx1)
end)
kernel:loop()
-- vim:foldmethod=marker:sw=4:ts=4:sts=4:et:
|
--- Item
-- @classmod Item
local Item = {}
setmetatable(Item, {__index = require("stdlib/data/core")})
local item_types = {
"item",
"ammo",
"armor",
"gun",
"capsule",
"repair-tool",
"mining-tool",
"item-with-entity-data",
"rail-planner",
"tool",
"blueprint",
"deconstruction-item",
"blueprint-book",
"selection-tool",
"item-with-tags",
"item-with-label",
"item-with-inventory",
"module"
}
function Item:get(item, itype, opts)
local object = self.get_object(item)
if not object then
for _, type_name in pairs(itype and {itype} or item_types) do
object = self.get_object(item, type_name)
if object then
break
end
end
end
if object then
return setmetatable(object, Item._mt):extend(object.update_data):save_options(opts)
end
local msg = "Item: " .. (itype and (itype .. "/") or "") .. tostring(item) .. " does not exist."
self.log(msg)
return self
end
Item:set_caller(Item.get)
Item._mt = {
type = "item",
__index = Item,
__call = Item.get,
__tostring = Item.tostring
}
return Item
|
object_building_kashyyyk_poi_kash_rryatt_lvl4_tree_root_a4 = object_building_kashyyyk_shared_poi_kash_rryatt_lvl4_tree_root_a4:new {
}
ObjectTemplates:addTemplate(object_building_kashyyyk_poi_kash_rryatt_lvl4_tree_root_a4, "object/building/kashyyyk/poi_kash_rryatt_lvl4_tree_root_a4.iff")
|
-----------------------------------------
-- Spell: Sleepga
-----------------------------------------
require("scripts/globals/magic")
require("scripts/globals/msg")
require("scripts/globals/status")
-----------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
local dINT = caster:getStat(tpz.mod.INT) - target:getStat(tpz.mod.INT)
local duration = calculateDuration(60, spell:getSkillType(), spell:getSpellGroup(), caster, target)
local params = {}
params.diff = dINT
params.skillType = tpz.skill.ENFEEBLING_MAGIC
params.bonus = 0
params.effect = tpz.effect.SLEEP_I
local resist = applyResistanceEffect(caster, target, spell, params)
if (caster:isMob()) then
if (caster:getPool() == 5310) then -- Amnaf (Flayer)
caster:resetEnmity(target)
end
-- Todo: get rid of this whole block by handling it in the mob script
-- this requires a multi target enmity without specifying a target (have to get hate list from mob)
-- OR by altering onSpellPrecast to have a target param..
-- onMonsterMagicPrepare is not a realistic option.
-- You'd have to script the use of every individual spell in Amnaf's list..
end
if resist >= 0.5 then
if target:addStatusEffect(params.effect, 1, 0, duration * resist) then
spell:setMsg(tpz.msg.basic.MAGIC_ENFEEB_IS)
else
spell:setMsg(tpz.msg.basic.MAGIC_NO_EFFECT) -- No effect
end
else
spell:setMsg(tpz.msg.basic.MAGIC_RESIST)
end
return params.effect
end
|
local Tunnel = module("vrp", "lib/Tunnel")
local Proxy = module("vrp", "lib/Proxy")
local cfg = module("vrp_id_display", "cfg/blips")
vRPidd = {}
IDDclient = Tunnel.getInterface("vrp_id_display","vrp_id_display")
vRPclient = Tunnel.getInterface("vRP","vrp_id_display")
Tunnel.bindInterface("vrp_id_display",vRPidd)
Proxy.addInterface("vrp_id_display",vRPidd)
vRP = Proxy.getInterface("vRP")
AddEventHandler("vRP:playerLeave",function(user_id, source)
local users = vRP.getUsers({})
for k,v in pairs(users) do
IDDclient.removeUser(v,{user_id})
IDDclient.removeBlip(v,{user_id})
end
end)
AddEventHandler("vRP:playerSpawn", function(user_id, source, first_spawn)
local users = vRP.getUsers({})
local job = vRP.getUserGroupByType({user_id,"job"})
local team = vRPidd.getUserTeamByGroup(user_id,job)
for k,v in pairs(users) do
IDDclient.insertUser(source,{k,v})
IDDclient.insertUser(v,{user_id,source})
local ujob = vRP.getUserGroupByType({k,"job"})
local uteam = vRPidd.getUserTeamByGroup(k,ujob)
IDDclient.insertBlip(source,{k,v,ujob,uteam})
IDDclient.insertBlip(v,{user_id,source,job,team})
end
end)
AddEventHandler("vRP:playerJoinGroup", function(user_id, group, gtype)
if gtype == "job" then
local player = vRP.getUserSource({user_id})
local users = vRP.getUsers({})
local job = vRP.getUserGroupByType({user_id,"job"})
local team = vRPidd.getUserTeamByGroup(user_id,job)
for k,v in pairs(users) do
local ujob = vRP.getUserGroupByType({k,"job"})
local uteam = vRPidd.getUserTeamByGroup(k,ujob)
IDDclient.insertBlip(player,{k,v,ujob,uteam})
IDDclient.insertBlip(v,{user_id,player,job,team})
end
end
end)
AddEventHandler("vRP:playerLeaveGroup", function(user_id, group, gtype)
if gtype == "job" then
local users = vRP.getUsers({})
for k,v in pairs(users) do
IDDclient.removeBlip(v,{user_id})
end
end
end)
function vRPidd.getUserTeamByGroup(user_id,group)
for k,v in pairs(cfg.teams) do
for l,w in pairs(v) do
if group == w then
return k
end
end
end
return nil
end
|
local Initial = PlayState:addState('Initial')
function DrawBestScore(self)
Color.WHITE:use()
love.graphics.setFont(self.best_font)
love.graphics.printf(string.format("BEST: %.1f", self.bestscore),
love.graphics.getWidth()/2 - love.graphics.getWidth()/2,
(love.graphics.getHeight()/2 - self.scale*PlayArea.SIZE/2)/2,
love.graphics.getWidth(), "center")
end
function Initial:enteredState()
if PLAY_RECORDING then
Timer.after(1, function() self:startGame() end)
end
end
function Initial:overlay()
PlayState.overlay(self)
Color.WHITE:use()
love.graphics.setFont(self.instruction_font)
local prompt = "TOUCH AND DRAG"
if not MOBILE then prompt = "CLICK AND DRAG" end
love.graphics.printf(prompt,
love.graphics.getWidth()/2 - 0.5*PlayArea.SIZE*self.scale,
love.graphics.getHeight()/2 + 25*self.scale,
PlayArea.SIZE*self.scale,
"center")
love.graphics.circle('fill', love.graphics.getWidth()/2,
love.graphics.getHeight()/2 + self.scale*65,
self.scale*10*(1 + 0.2*(math.sin(self.time))^2),
32)
if self.bestscore ~= nil then
DrawBestScore(self)
end
end
function Initial:update(dt)
GameState.update(self, dt)
self:updateButtons(dt)
end
function Initial:touchpressed(id, x, y, dx, dy, pressure)
PlayState.touchpressed(self, id, x, y, dx, dy, pressure)
if self.ignore_touch[id] then return end
self:startGame()
end
function Initial:touchmoved(id, x, y, dx, dy, pressure)
-- Ignore touch moves in Initial phase.
end
function Initial:keypressed(key, scancode, isrepeat)
PlayState.keypressed(self, key, scancode, isrepeat)
if key == "space" then
self:startGame()
end
end
|
sni.stage = "data-final-fixes"
---------------------------------------------------------------------------
if (not SNI.defaultPacks) or (#SNI.defaultPacks == 0) then
SNI.addDefaultPacks({{"automation-science-pack", 1}})
end
SNI.sendInvites()
--SNI.chechIntegrityInfiniteScience()
|
return {
tag = 'graphicsState',
summary = 'Set the background color.',
description = [[
Sets the background color used to clear the screen. Color components are from 0.0 to 1.0.
]],
arguments = {
r = {
type = 'number',
description = 'The red component of the background color.'
},
g = {
type = 'number',
description = 'The green component of the background color.'
},
b = {
type = 'number',
description = 'The blue component of the background color.'
},
a = {
type = 'number',
default = '1.0',
description = 'The alpha component of the background color.'
},
hex = {
type = 'number',
description = 'A hexcode like `0xffffff` to use for the background (does not support alpha).'
},
color = {
type = 'table',
description = 'A table containing 3 or 4 color components.'
}
},
returns = {},
variants = {
{
arguments = { 'r', 'g', 'b', 'a' },
returns = {}
},
{
arguments = { 'hex' },
returns = {}
},
{
arguments = { 'color' },
returns = {}
}
},
notes = 'The default background color is `(0.0, 0.0, 0.0, 1.0)`.'
}
|
function test_talk_seq_1()
local t = require "test.luaunit"
local o = require "talks.o"
local items = {"1","2","3"}
local co = coroutine.wrap(o.SEQ(items))
local args = {
data= {},
req = {},
}
t.assertEquals(co(args), "1")
t.assertEquals(co(args), "2")
t.assertEquals(co(args), "3")
t.assertEquals(co(args), nil)
end
function test_talk_inf()
local t = require "test.luaunit"
local o = require "talks.o"
local items = {"1","2","3"}
local co = coroutine.wrap(o.INFINITY(items))
local args = {
data= {},
req = {},
}
t.assertEquals(co(args), "1")
t.assertEquals(co(args), "2")
t.assertEquals(co(args), "3")
t.assertEquals(co(args), "1")
end
function test_talk_seq_fn()
local t = require "test.luaunit"
local o = require "talks.o"
local function func(args)
return "1"
end
local items = o.ONE(func)
local co = coroutine.wrap(o.SEQ(items))
local args = {
data= {},
req = {},
}
t.assertEquals(co(args), "1")
t.assertEquals(co(args), nil)
end
function test_talk_seq_str()
local t = require "test.luaunit"
local o = require "talks.o"
local items = "1"
local co = coroutine.wrap(o.SEQ(items))
local args = {
data= {},
req = {},
}
t.assertEquals(co(args), "1")
t.assertEquals(co(args), nil)
end
function test_talk_rand_1()
local t = require "test.luaunit"
local o = require "talks.o"
local items = {"1","1"}
local co = coroutine.wrap(o.RAND(items))
local args = {
data= {},
req = {},
}
t.assertEquals(co(args), "1")
t.assertEquals(co(args), "1")
t.assertEquals(co(args), nil)
end
function test_talk_rand_2()
local t = require "test.luaunit"
local o = require "talks.o"
local items = {"1","2"}
local co = coroutine.wrap(o.RAND(items))
local args = {
data= {},
req = {},
}
local a = co(args)
local b = co(args)
local c = co(args)
t.assertNotEquals(a, b)
t.assertEquals(c, nil)
end
function test_talk_seq_rev()
local t = require "test.luaunit"
local o = require "talks.o"
local function co_task(args)
coroutine.yield("2")
coroutine.yield("3")
end
local function one_task(args)
return "4"
end
local subs = {"5","6"}
local items = {
"1",
co_task,
o.ONE(one_task),
subs
}
local co = coroutine.wrap(o.SEQ(items))
local args = {
data= {},
req = {},
}
t.assertEquals(co(args), "1")
t.assertEquals(co(args), "2")
t.assertEquals(co(args), "3")
t.assertEquals(co(args), "4")
t.assertEquals(co(args), "5")
t.assertEquals(co(args), "6")
t.assertEquals(co(args), nil)
end
|
---@meta
---@class ccs.RotationFrame :ccs.Frame
local RotationFrame={ }
ccs.RotationFrame=RotationFrame
---*
---@param rotation float
---@return self
function RotationFrame:setRotation (rotation) end
---*
---@return float
function RotationFrame:getRotation () end
---*
---@return self
function RotationFrame:create () end
---*
---@return ccs.Frame
function RotationFrame:clone () end
---*
---@return self
function RotationFrame:RotationFrame () end
|
local http = require("socket.http")
local url = require("socket.url")
local mime = require("mime")
local ltn12 = require("ltn12")
local headers = {
Accept = "application/x-turtle",
--Accept = "application/json",
--["Content-Type"] = "application/json",
Authorization = "Basic " .. (mime.b64("admin:admin"))
-- SD-Connection-String: reasoning=QL
}
local output = {}
local x = http.request{headers = headers,
method = "GET",
url = "http://localhost:5820/banshee-sympatico/query?query=" .. url.escape("CONSTRUCT { bsbase:KenWilber ?p ?o } WHERE { bsbase:KenWilber ?p ?o }"),
--url = "http://localhost:5820/admin/databases/banshee-sympatico/options",
--source = ltn12.source.string('{"database.name":false}'),
--sink = ltn12.sink.file(io.open("temp-out.ttl", "w"))
sink = ltn12.sink.table(output)
}
x = table.concat(output)
print(x)
require('pl.pretty').dump(x)
|
-- preplists.lua
module(..., package.seeall)
local utils = require "lua.utils"
local iputils = require "lua.iputils"
local rangesbtree = require "lua.rangesbtree"
local cjson = require "cjson"
local json_safe = require "cjson.safe"
local dict = utils.dict
local defaultdict = utils.defaultdict
local slice = utils.slice
local parse_cidr = iputils.parse_cidr
local build_ranges_lists = rangesbtree.build_ranges_lists
function gen_masterdict(lst)
return {
-- copy essentials as is.
[ "id" ] = lst["id"],
[ "name" ] = lst["name"],
[ "entries_relation" ] = lst["entries_relation"],
[ "tags" ] = lst["tags"],
[ "singles" ] = defaultdict(dict),
[ "negate_singles" ] = defaultdict(dict),
[ "pairs" ] = defaultdict(dict),
[ "negate_pairs" ] = defaultdict(dict),
[ "iprange" ] = {},
[ "negate_iprange" ] = {}
}
end
function categorize_singles(key)
local mastercategory = "singles"
if key:startswith("!") then
mastercategory = "negate_singles"
end
return mastercategory, key
end
function categorize_pairs(pairv)
local mastercategory = "pairs"
if pairv:startswith("!") then
mastercategory = "negate_pairs"
pairv = pairv:sub(2)
end
return mastercategory, pairv
end
function get_annotation(data)
if #data > 1 then
return data[2]
else
return nil
end
end
function gen_list_entries(lst, handle)
local masterdict = gen_masterdict(lst)
for _, entry in ipairs(lst["entries"]) do
category, data = entry[1], slice(entry, 2)
-- pairs
if category:within("args cookies headers") then
local pairk, pairv, pairannotation = data[1][1], data[1][2], get_annotation(data)
local mastercategory, pairv = categorize_pairs(pairv)
masterdict[mastercategory][category][pairk] = { pairv, pairannotation }
-- singles
else
if category:within("path query uri asn country method") then
-- negate vs standard
local mastercategory, key = categorize_singles(data[1])
-- store
masterdict[mastercategory][category][key] = get_annotation(data)
else
if category == "ip" then
local address = data[1]
-- single address
if not ("/"):within(address) or address:endswith("/32") then
address = address:replace("/32", "")
mastercategory, key = categorize_singles(address)
-- store
masterdict[mastercategory][category][key] = get_annotation(data)
-- range
else
local cidr, mastercategory = data[1], "iprange"
if cidr:startswith("!") then
mastercategory = "negate_iprange"
cidr = cidr:sub(2)
end
local start_addr, end_addr = parse_cidr(cidr)
-- [[start,end], annotation]
if start_addr == nil then
handle:logDebug(string.format("CIDR %s could not be parsed", cidr))
else
elem = { {start_addr, end_addr}, get_annotation(data) }
table.insert(masterdict[mastercategory], elem)
end
end
end
end
end
end
if #masterdict['iprange'] > 0 then
masterdict['iprange'] = build_ranges_lists(masterdict['iprange'])
end
return masterdict
end
|
--[[
Variables
]]
MenuTypes, MenuEntries, MenuItems = {"general", "peds", "vehicles", "objects", "news", "k9", "judge", "realestate"}, {}, {}
local closedFromAction = false
for _, menuType in ipairs(MenuTypes) do
MenuEntries[menuType] = {}
end
-- Menu state
local showMenu = false
-- Keybind Lookup table
local keybindControls = {
["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57, ["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177, ["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18, ["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182, ["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81, ["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70, ["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178, ["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173, ["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118
}
local MAX_MENU_ITEMS = 7
--[[
Functions
]]
function CloseMenu(withNoFocus)
showMenu = false
if not withNoFocus then
SetNuiFocus(false, false)
end
SendNUIMessage({
state = "destroy"
})
end
function IsMenuWanted(pMenu, pEntity)
return pMenu == "general" or
(pMenu == "peds" and pEntity == 1) or
(pMenu == "vehicles" and pEntity == 2) or
(pMenu == "objects" and pEntity == 3) or
(pMenu =="news" and CurrentJob == "news") or
(pMenu == "k9" and exports["caue-jobs"]:getJob(false, "is_police")) or
(pMenu == "judge" and CurrentJob == "judge") or
(pMenu == "realestate" and CurrentJob == "real_estate")
end
function GetSubMenuEntries(pItems, pEntity, pContext)
local items = {}
local previous, current = items, {}
for index, item in ipairs(pItems) do
local entry = MenuItems[item]
if entry and (not entry["isEnabled"] or entry["isEnabled"](pEntity, pContext)) then
local subMenu = MenuItems[item]["data"]
current[#current+1] = subMenu
if index % MAX_MENU_ITEMS == 0 and index < (#pItems - 1) then
previous[MAX_MENU_ITEMS + 1] = {
id = "_more",
title = "More",
icon = "#more",
items = current
}
previous = current
current = {}
end
end
end
if #current > 0 then
previous[MAX_MENU_ITEMS + 1] = {
id = "_more",
title = "More",
icon = "#more",
items = current
}
end
if items[MAX_MENU_ITEMS + 1] then
items = items[MAX_MENU_ITEMS + 1].items
end
return items
end
function GetMenuEntries(pEntity, pContext)
local menus = {}
for _, menuType in ipairs(MenuTypes) do
if IsMenuWanted(menuType, pContext.type) then
for _, entry in ipairs(MenuEntries[menuType]) do
if entry.isEnabled(pEntity, pContext) then
local menu = entry.data
if entry.subMenus ~= nil and #entry.subMenus > 0 then
menu.items = GetSubMenuEntries(entry.subMenus, pEntity, pContext)
end
menus[#menus+1] = menu
end
end
end
end
return menus
end
--[[
Events
]]
RegisterNetEvent("menu:menuexit")
AddEventHandler("menu:menuexit", function()
CloseMenu()
end)
--[[
NUI
]]
-- Callback function for closing menu
RegisterNUICallback("closemenu", function(data, cb)
-- Clear focus and destroy UI
CloseMenu(data.withNoFocus)
-- Play sound
PlaySoundFrontend(-1, "NAV", "HUD_AMMO_SHOP_SOUNDSET", 1)
-- Send ACK to callback function
cb("ok")
end)
-- Callback function for when a slice is clicked, execute command
RegisterNUICallback("triggerAction", function(data, cb)
-- Clear focus and destroy UI
closedFromAction = true
CloseMenu()
-- Play sound
PlaySoundFrontend(-1, "NAV", "HUD_AMMO_SHOP_SOUNDSET", 1)
-- Run command
if (data.action) then
if data.parameters == nil then
data.parameters = {}
end
TriggerEvent(data.action, data.parameters, data.entity or 0, data.context or {})
end
-- Send ACK to callback function
cb("ok")
end)
--[[
Threads
]]
Citizen.CreateThread(function()
local keyBind = "F1"
while true do
Citizen.Wait(0)
if IsControlPressed(1, keybindControls[keyBind]) and GetLastInputMethod(2) and showMenu then
showMenu = false
SetNuiFocus(false, false)
end
if IsControlPressed(1, keybindControls[keyBind]) and GetLastInputMethod(2) then
if (not exports["caue-base"]:getVar("handcuffed") and (GetGameTimer() - exports["caue-base"]:getVar("recentcuff") > 15000)) or ((exports["caue-jobs"]:getJob(false, "is_police") or exports["caue-jobs"]:getJob(false, "is_medic")) and exports["caue-base"]:getVar("dead")) then
showMenu = true
PlayerCoords = GetEntityCoords(PlayerPedId())
local entity = exports["caue-target"]:GetCurrentEntity()
local context = GetEntityContext(entity)
local entries = GetMenuEntries(entity, context)
SendNUIMessage({
state = "show",
resourceName = GetCurrentResourceName(),
data = entries,
entity = entity,
context = context,
menuKeyBind = keyBind
})
SetCursorLocation(0.5, 0.5)
SetNuiFocus(true, true)
-- Play sound
PlaySoundFrontend(-1, "NAV", "HUD_AMMO_SHOP_SOUNDSET", 1)
end
while showMenu == true do Citizen.Wait(100) end
Citizen.Wait(100)
while IsControlPressed(1, keybindControls[keyBind]) and GetLastInputMethod(2) do Citizen.Wait(100) end
end
end
end)
|
ITEM.name = "Bag"
ITEM.description = "A bag to increase your carry capacity."
ITEM.model = "models/props_c17/suitcase001a.mdl"
ITEM.category = "Storage"
ITEM.width = 2
ITEM.height = 2
ITEM.price = 0
ITEM.isNewBag = true
ITEM.outfitCategory = "backpack"
ITEM.pacData = {}
ITEM.equipIcon = ix.util.GetMaterial("materials/vgui/ui/stalker/misc/equip.png")
ITEM.weight = 1
ITEM.carryinc = 10
function ITEM:GetDescription()
local quant = self:GetData("quantity", self.ammoAmount or self.quantity or 0)
local quantdesc = ""
local invdesc = ""
if self.longdesc then
invdesc = "\n\n"..(self.longdesc)
end
if self.quantdesc then
quantdesc = "\n\n"..Format(self.quantdesc, quant)
end
if (self.entity) then
return (self.description)
else
return (self.description..quantdesc..invdesc)
end
end
if (CLIENT) then
function ITEM:PaintOver(item, width, height)
if (item:GetData("equip")) then
surface.SetDrawColor(110, 255, 110, 255)
--surface.DrawRect(w - 14, h - 14, 8, 8)
else
surface.SetDrawColor(255, 110, 110, 255)
end
surface.SetMaterial(item.equipIcon)
surface.DrawTexturedRect(width-23,height-23,19,19)
end
end
function ITEM:PopulateTooltip(tooltip)
if (!self.entity) then
ix.util.PropertyDesc2(tooltip, "Backpack", Color(64, 224, 208), Material("vgui/ui/stalker/weaponupgrades/handling.png"))
end
if (self.PopulateTooltipIndividual) then
self:PopulateTooltipIndividual(tooltip)
end
end
ITEM.functions.Equip = {
name = "Put On",
tip = "equipTip",
icon = "icon16/stalker/equip.png",
OnRun = function(item)
local char = item.player:GetCharacter()
local items = char:GetInventory():GetItems()
for _, v in pairs(items) do
if (v.id != item.id) then
local itemTable = ix.item.instances[v.id]
if (itemTable.pacData and v.outfitCategory == item.outfitCategory and itemTable:GetData("equip")) then
item.player:Notify("You're already equipping this kind of outfit")
return false
end
end
end
item:SetData("equip", true)
item.player:AddPart(item.uniqueID, item)
char:UpdateWeight()
if (item.attribBoosts) then
for k, v in pairs(item.attribBoosts) do
char:AddBoost(item.uniqueID, k, v)
end
end
item:OnEquipped()
return false
end,
OnCanRun = function(item)
local client = item.player
return !IsValid(item.entity) and IsValid(client) and item:GetData("equip") != true and
hook.Run("CanPlayerEquipItem", client, item) != false and item.invID == client:GetCharacter():GetInventory():GetID()
end
}
ITEM.functions.EquipUn = { -- sorry, for name order.
name = "Take Off",
tip = "equipTip",
icon = "icon16/stalker/unequip.png",
OnRun = function(item)
local char = item.player:GetCharacter()
if (!char:CanRemoveCarry(item)) then
item.player:Notify("Removing this item would make you heavily overweight.")
return false
end
item:RemovePart(item.player)
char:UpdateWeight()
return false
end,
OnCanRun = function(item)
local client = item.player
return !IsValid(item.entity) and IsValid(client) and item:GetData("equip") == true and
hook.Run("CanPlayerUnequipItem", client, item) != false
end
}
ITEM:Hook("drop", function(item)
if (item:GetData("equip") && item.player:GetCharacter():CanRemoveCarry(item)) then
item:RemovePart(item.player)
end
end)
function ITEM:RemovePart(client)
local char = client:GetCharacter()
self:SetData("equip", false)
client:RemovePart(self.uniqueID)
if (self.attribBoosts) then
for k, _ in pairs(self.attribBoosts) do
char:RemoveBoost(self.uniqueID, k)
end
end
self:OnUnequipped()
end
-- Called before the item is permanently deleted.
function ITEM:OnRemoved()
local owner = self.player
if (self:GetData("equip")) then
self:RemovePart(owner)
end
end
function ITEM:OnEquipped()
self.player:EmitSound("stalkersound/inv_slot.mp3")
end
function ITEM:OnUnequipped()
self.player:EmitSound("stalkersound/inv_slot.mp3")
end
|
local LOREM_ISPUM = [[Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Suspendisse rutrum accumsan elit vel auctor.
Praesent sit amet aliquam turpis.
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.
Maecenas non erat ut elit sodales commodo.
Nam gravida ipsum quis nulla tempus, quis pulvinar augue tristique.
Nulla massa odio, imperdiet non ultricies tincidunt, viverra sed lorem.
Nulla elementum sapien ut commodo aliquet.
Pellentesque iaculis turpis tellus, eget laoreet augue condimentum vel.
Quisque at risus rhoncus, facilisis tellus nec, tristique dolor.
Maecenas cursus magna eget imperdiet laoreet.]]
return function(min_len, max_len)
max_len = max_len or min_len
local len = math.random(min_len, max_len)
local last_char = LOREM_ISPUM:sub(len, len)
while not (last_char == " " or last_char == ".") do
len = len - 1
last_char = LOREM_ISPUM:sub(len, len)
end
return LOREM_ISPUM:sub(1, len)
end
|
local gamestate = require "vendor/gamestate"
local Board = require "board"
local camera = require "camera"
local Dialog = {}
Dialog.__index = Dialog
---
-- Create a new Dialog
-- @param message to display
-- @param callback when user answer's say
-- @return Dialog
function Dialog.new(message, callback)
local say = {}
setmetatable(say, Dialog)
say.board = Board.new(312, 60)
say.board:open()
say.line = 1
say.cursor = 0
say.y = camera.y + camera:getHeight() - 36
say.x = camera.x + camera:getWidth() / 2
local state = gamestate.currentState()
if (state.player and state.player.position.y + state.player.height + 35 > say.y)
or state.floorspace then
say.y = camera.y + 100
end
if type(message) == 'string' then
say.messages = {message}
else
say.messages = message
end
say.callback = callback
say.blink = 0
say.state = 'opened'
say.result = false
return say
end
function Dialog:bbox()
return self.x - 156, self.y - 30, self.x + 156, self.y + 30
end
function Dialog:update(dt)
local rate = 15
self.blink = self.blink + dt < .50 and self.blink + dt or 0
self.board:update(dt)
self.cursor = math.min(self.cursor + (dt * rate), string.len(self.messages[self.line]))
if self.board.state == 'closed' and self.state ~= 'closed' then
self.state = 'closed'
if self.callback then self.callback(self.result) end
end
end
function Dialog:message()
local long = self.messages[self.line]
if math.floor(self.cursor) >= long:len() then
return long .. (self.blink > .25 and "^" or "")
else
return string.sub(long, 1, math.floor(self.cursor))
end
end
function Dialog:draw()
if self.board.state == 'closed' then
return
end
local font = love.graphics.getFont()
font:setLineHeight(1.3)
x, y = self.board:draw(self.x, self.y)
if self.board.state == 'opened' then
local message = self:message()
local _, lines = font:getWrap(message, self.board.width - 20)
local ox = math.floor(x - self.board.width / 2 + 10)
local oy = math.floor(y - (14 * lines / 2))
love.graphics.printf(message, ox, oy, self.board.width - 20)
end
love.graphics.setColor( 255, 255, 255, 255 )
font:setLineHeight(1.0)
return x, y
end
function Dialog:keypressed( button )
if self.board.state == 'closed' then
return false
end
if button == 'JUMP' then
if self.cursor < string.len(self.messages[self.line]) then
self.cursor = string.len(self.messages[self.line])
elseif self.line ~= #self.messages then
self.cursor = 0
self.line = self.line + 1
else
self.board:close()
self.state = 'closing'
end
end
return true
end
return Dialog
|
local keymap = vim.api.nvim_set_keymap
keymap('n', '<leader>fb', ':lua require("telescope.builtin").buffers()<CR>', { noremap = true, silent = true })
keymap('n', '<leader>ff', ':lua require("telescope.builtin").find_files()<CR>', { noremap = true, silent = true })
keymap('n', '<leader>fg', ':lua require("telescope.builtin").live_grep()<CR>', { noremap = true, silent = true })
|
local awful = require("awful")
local beautiful = require("beautiful")
-- Rules to apply to new clients (through the "manage" signal).
awful.rules.rules = {
-- All clients will match this rule.
{ rule = { },
properties = { border_width = beautiful.border_width,
border_color = beautiful.border_normal,
focus = awful.client.focus.filter,
raise = true,
keys = clientkeys,
buttons = clientbuttons,
screen = awful.screen.preferred,
placement = awful.placement.no_overlap+awful.placement.no_offscreen
}
},
-- Floating clients.
rule_any = {
instance = {
"copyq", -- Includes session name in class.
"plugin-container",
},
class = {
"Arandr",
"Gpick",
"Kruler",
"MessageWin", -- kalarm.
"qimgv",
"Sxiv",
"feh",
"Wpa_gui",
"pinentry",
"veromix",
"xtightvncviewer"},
name = {
"Event Tester", -- xev.
},
role = {
"AlarmWindow", -- Thunderbird's calendar.
"pop-up", -- e.g. Google Chrome's (detached) Developer Tools.
}
, properties = { floating = true }},
-- Application rules
{ rule = { class = "Firefox" },
properties = { screen = 1, tag = "www" } },
{ rule = { class = "discord" },
properties = { screen = 1, tag = "disc" } },
{ rule = { name = "spt" },
properties = { screen = 1, tag = "spot" } }
}
|
local login = require "snax.loginserver"
local crypt = require "skynet.crypt"
local skynet = require "skynet"
local server = {
host = "127.0.0.1",
port = 8001,
multilogin = false,
name = "login_master"
}
function server.auth_handler(token)
local user, server, password = token:match("([^@]+)@([^:]+):(.+)")
user = crypt.base64decode(user)
server = crypt.base64decode(server)
password = crypt.base64decode(password)
skynet.error(string.format("%s@%s:%s", user, server, password))
assert(password == "password", "Invite password")
return server, user
end
local subid = 0
function server.login_handler(server, uid, secret)
skynet.error(string.format("%s@%s is login, secret is %s", uid, server,
crypt.hexencode(secret)))
subid = subid + 1
return subid
end
local CMD = {}
function CMD.register_gate(server, address)
skynet.error("cmd register_gate")
end
function server.command_handler(command, ...)
local f = assert(CMD[command])
return f(...)
end
login(server)
|
-- config for running klipper 3D printer suite on local (desktop) machine.
-- i'm using this to simplify debugging of modifications to the klipper source code for my hobby project.
-- any prodction use of tools/configuration/setup provided here was not tested and cannot be guaranteed.
-- packages need to be installed:
-- libsodium-dev
-- for python2 klipper version: virtualenv python-dev libffi-dev build-essential cmake
-- for python3 klipper version (experimental): virtualenv python3-dev libffi-dev build-essential cmake
-- redefine defaults.recalculate function, that will be called by base config
defaults.recalculate_orig=defaults.recalculate
function defaults.recalculate()
-- redefine some parameters
tunables.features.x11host_target_dir="/dev/null"
tunables.datadir=loader.path.combine(loader.workdir,"userdata-klipper")
defaults.recalculate_orig()
defaults.mounts.resolvconf_mount=defaults.mounts.direct_resolvconf_mount
end
defaults.recalculate()
-- load base config
dofile(loader.path.combine(loader.workdir,"debian-sandbox.cfg.lua"))
-- remove some unneded features and mounts
loader.table.remove_value(sandbox.features,"dbus")
loader.table.remove_value(sandbox.features,"gvfs_fix")
loader.table.remove_value(sandbox.features,"pulse")
loader.table.remove_value(sandbox.features,"x11host")
-- remove some unneded mounts from base config
loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devsnd_mount)
loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devdri_mount)
loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devinput_mount)
loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.devshm_mount)
loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.sbin_ro_mount)
loader.table.remove_value(sandbox.setup.mounts,defaults.mounts.sys_mount)
-- modify PATH env
table.insert(sandbox.setup.env_set,{"PATH","/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"})
table.insert(sandbox.setup.mounts,{prio=99,"bind",loader.path.combine(loader.workdir,"gcode"),"/home/sandboxer/gcode"})
table.insert(sandbox.setup.mounts,{prio=99,"bind",loader.path.combine(loader.workdir,"configs"),"/home/sandboxer/configs"})
table.insert(sandbox.setup.mounts,{prio=99,"bind",loader.path.combine(loader.workdir,"logs"),"/home/sandboxer/logs"})
-- add bwrap unshare_ipc option
loader.table.remove_value(sandbox.bwrap,defaults.bwrap.unshare_ipc)
table.insert(sandbox.bwrap,defaults.bwrap.unshare_ipc)
-- profiles for installing all needed stuff individually
-- forward UART port from target MCUs over Ethernet/TCP-IP
uartclient_install={
exec="/bin/bash",
path="/home/sandboxer",
args={"-c","set -e;\
[[ ! -d uartbridge ]] && git clone https://github.com/DarkCaster/ArduinoUARTEthernetBridge.git uartbridge;\
(cd uartbridge && git reset --hard && git clean -dfx --force && git checkout main && git pull --force);\
cd uartbridge/Client;\
cmake .; make;\
cd ~; rm -rf uartclient_bin; mkdir -p uartclient_bin;\
mv uartbridge/Client/uartclient uartclient_bin;\
"},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=false,
exclusive=true,
}
-- component needed for klipper web-ui
-- TODO: create moonraker.conf with config sutable for this env, if missing
moonraker_install={
exec="/bin/bash",
path="/home/sandboxer",
args={"-c","set -e;\
[[ ! -d moonraker ]] && git clone https://github.com/Arksine/moonraker.git moonraker;\
(cd moonraker && git reset --hard && git clean -dfx --force && git checkout master && git pull --force);\
rm -rf moonraker_env;\
virtualenv -p python3 moonraker_env;\
moonraker_env/bin/pip install -r moonraker/scripts/moonraker-requirements.txt;\
[[ ! -f /home/sandboxer/configs/moonraker.conf ]] && echo \"installing sample config file\" && (cd /home/sandboxer/configs && wget \"https://raw.githubusercontent.com/Arksine/moonraker/master/docs/moonraker.conf\");\
true;\
"},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=false,
exclusive=true,
}
-- web UI
fluidd_install={
exec="/bin/bash",
path="/home/sandboxer",
args={"-c","set -e;\
rm -rf fluidd;\
mkdir fluidd;\
cd fluidd;\
wget -O fluidd.zip \"https://github.com/cadriel/fluidd/releases/latest/download/fluidd.zip\";\
unzip fluidd.zip;\
"},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=false,
exclusive=true,
}
klipper_install={
exec="/bin/bash",
path="/home/sandboxer",
args={"-c","set -e;\
[[ ! -d klipper_py2 ]] && git clone https://github.com/KevinOConnor/klipper.git klipper_py2;\
(cd klipper_py2 && git reset --hard && git clean -dfx --force && git checkout master && git pull --force);\
rm -rf klipper_env_py2;\
virtualenv -p python2 klipper_env_py2;\
klipper_env_py2/bin/pip install -r klipper_py2/scripts/klippy-requirements.txt;\
"},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=false,
exclusive=true,
}
-- avr-gcc and avrdude from arduino distribution for building firmware for my MCUs
avr_gcc_install={
exec="/bin/bash",
path="/home/sandboxer",
args={"-c","set -e;\
rm -rf avr;\
rm -rf avrdude;\
rm -fv avr-gcc.tar.bz2;\
rm -fv avrdude.tar.bz2;\
wget -O avr-gcc.tar.bz2 \"http://downloads.arduino.cc/tools/avr-gcc-7.3.0-atmel3.6.1-arduino7-x86_64-pc-linux-gnu.tar.bz2\";\
wget -O avrdude.tar.bz2 \"http://downloads.arduino.cc/tools/avrdude-6.3.0-arduino18-x86_64-pc-linux-gnu.tar.bz2\";\
bzip2 -d -c avr-gcc.tar.bz2 | tar xf - ;\
bzip2 -d -c avrdude.tar.bz2 | tar xf - ;\
rm -v avr-gcc.tar.bz2;\
rm -v avrdude.tar.bz2;\
[[ ! -d avr ]] && echo \"cannot find extracted 'avr' directory!\" && exit 1 || true;\
[[ ! -d avrdude ]] && echo \"cannot find extracted 'avrdude' directory!\" && exit 1 || true;\
"},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=false,
exclusive=true,
}
-- run make in klipper source directory
-- invocation example: sandboxer klipper.cfg.lua klipper_make menuconfig
klipper_make={
exec="/usr/bin/make",
path="/home/sandboxer/klipper_py2",
args=loader.args,
env_unset={"PATH","LANG"},
env_set={
{"PATH","/home/sandboxer/avr/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"},
{"TERM",os.getenv("TERM")},
},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=true,
exclusive=true,
}
-- uartclient configured for flashing image via optiboot/uart
uartclient={
exec="/home/sandboxer/uartclient_bin/uartclient",
path="/home/sandboxer",
args={"-ra","ENC28J65E366.lan","-tp","50000","-up","1","-pc","3","-pls","50","-rbs","1600","-ptl","4400","-ptr","4400","-lp1","/tmp/ttyETH1","-lp2","/tmp/ttyETH2","-lp3","/tmp/ttyETH3","-ps1","115200","-ps2","115200","-ps3","115200","-pm1","6","-pm2","6","-pm3","6","-rst1","1","-rst2","1","-rst3","1"},
env_unset={"LANG"},
env_set={{"TERM",os.getenv("TERM")}},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=true,
exclusive=true,
}
-- example for flashing image to AVR MCU with optiboot bootloader:
-- sandboxer klipper.cfg.lua avrdude -P/tmp/ttyETH3 -b115200 -carduino -patmega328p -v -D -Uflash:w:klipper_py2/out/klipper.elf.hex:i
avrdude={
exec="/home/sandboxer/avrdude/bin/avrdude",
path="/home/sandboxer",
args={"-C/home/sandboxer/avrdude/etc/avrdude.conf", table.unpack(loader.args)},
env_unset={"LANG"},
env_set={{"TERM",os.getenv("TERM")}},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=true,
exclusive=true,
}
-- start klipper, provide config file-name placed into "configs" directory as parameter
klipper={
exec="/home/sandboxer/klipper_env_py2/bin/python2",
path="/home/sandboxer/klipper_py2/klippy",
args={"klippy.py", "-l", "/home/sandboxer/logs/klipper.log", loader.path.combine("/home/sandboxer/configs",loader.args[1])},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=true,
exclusive=true,
}
-- run the whole suite and wait for ctrl+c, or termination signal:
-- 1. klipper firmware
-- 2. uart-ethernet-client for connecting to MCU uart port(s) via Ethernet/TCP-IP (see https://github.com/DarkCaster/ArduinoUARTEthernetBridge)
-- 3. moonraker server and fluidd for web UI
klipper_suite={
exec="/bin/bash",
path="/home/sandboxer",
args={"-c","\
klipper_pid=\"\"; uartclient_pid=\"\"; moonraker_pid=\"\";\
collect_logs() { local d=$(date +\"%Y.%m.%d.%H%M.%S\"); cp /tmp/klipper.log ~/logs/klipper.$d.log; };\
do_exit() { ec=\"$1\"; [[ -z $ec ]] && ec=\"1\"; [[ $ec != 0 ]] && echo 'stopping with error!' || echo 'stopping'; trap - ERR INT TERM HUP; kill -SIGTERM $klipper_pid 2>/dev/null; kill -SIGTERM $uartclient_pid 2>/dev/null; kill -SIGTERM $moonraker_pid 2>/dev/null; kill -SIGTERM $fluidd_pid 2>/dev/null; collect_logs; exit $ec; };\
trap 'do_exit' ERR;\
trap 'do_exit 0' INT TERM HUP;\
~/uartclient_bin/uartclient -ra ENC28J65E366.lan -tp 50000 -up 1 -pc 3 -pls 50 -rbs 1600 -ptl 7000 -ptr 7000 -lp1 /tmp/ttyETH1 -lp2 /tmp/ttyETH2 -lp3 /tmp/ttyETH3 -ps1 250000 -pm1 6 -ps2 250000 -pm2 6 -ps3 250000 -pm3 6 -rst1 1 -rst2 1 -rst3 1 &\
uartclient_pid=\"$!\";\
rm -rf /tmp/klipper.log;\
cd ~/klipper_py2/klippy;\
~/klipper_env_py2/bin/python2 klippy.py -a /tmp/klippy_uds -l /tmp/klipper.log \""..loader.path.combine("/home/sandboxer/configs",loader.args[1]).."\" &\
klipper_pid=\"$!\";\
cd ~/moonraker;\
~/moonraker_env/bin/python3 moonraker/moonraker.py -c /home/sandboxer/configs/moonraker.conf &>/tmp/moonraker.out.log &\
moonraker_pid=\"$!\";\
cd ~/fluidd;\
sleep 5;\
python3 -m http.server 8000 --bind 127.0.0.1 &>/tmp/fluidd.out.log &\
fluidd_pid=\"$!\";\
wait $uartclient_pid;\
wait $klipper_pid;\
wait $moonraker_pid;\
wait $fluidd_pid;\
"},
term_signal=defaults.signals.SIGHUP,
attach=true,
pty=true,
exclusive=true,
term_orphans=true,
}
-- display klipper log from container's tmpfs
klipper_log={
exec="/bin/bash",
path="/home/sandboxer",
args={"-c","cat /tmp/klipper.log"},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=false,
exclusive=false,
}
-- experimental python3 klipper-build, may have some issues
klipper_python3_install={
exec="/bin/bash",
path="/home/sandboxer",
args={"-c","set -e;\
[[ ! -d klipper_py3 ]] && git clone https://github.com/Doridian/klipper.git klipper_py3;\
(cd klipper_py3 && git reset --hard && git clean -dfx --force && git checkout custom && git pull --force);\
rm -rf klipper_env_py3;\
virtualenv -p python3 klipper_env_py3;\
klipper_env_py3/bin/pip install -r klipper_py3/scripts/klippy-requirements.txt;\
"},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=false,
exclusive=true,
}
klipper_python3={
exec="/home/sandboxer/klipper_env_py3/bin/python3",
path="/home/sandboxer/klipper_py3/klippy",
args={"klippy.py", "-l", "/home/sandboxer/logs/klipper_py3.log", loader.path.combine("/home/sandboxer/configs",loader.args[1])},
term_signal=defaults.signals.SIGTERM,
attach=true,
pty=true,
exclusive=true,
}
|
--- Module for generating random strings
-- @module lqc.generators.string
-- @alias new
local random = require 'lqc.random'
local lqc = require 'lqc.quickcheck'
local Gen = require 'lqc.generator'
local char = require 'lqc.generators.char'
local char_gen = char()
-- NOTE: The shrink algorithms are *heavily* based on triq
-- https://github.com/krestenkrab/triq
--- Determines how many items to shrink.
-- @param length size of the string
-- @return integer indicating how many items to shrink
local function shrink_how_many(length)
-- 20% chance more than 1 member is shrunk
if random.between(1, 5) == 1 then
return random.between(1, length)
end
return 1
end
--- Replaces a character in the string 'str' at index 'idx' with 'new_char'.
-- @param str string to be modified
-- @param new_char value that will replace the old character in the string
-- @param idx position in the string where the character should be replaced
-- @return updated string
local function string_replace_char(str, new_char, idx)
local result = {}
result[1] = string.sub(str, 1, idx - 1)
result[2] = new_char
result[3] = string.sub(str, idx + 1)
return table.concat(result)
end
--- Replaces 1 character at a random location in the string, tries up to 100
-- times if shrink gave back same result.
-- @param prev previously generated string value
-- @param length size of the string
-- @param iterations_count remaining tries to shrink down this string
-- @return shrunk down string value
local function do_shrink_generic(prev, length, iterations_count)
local idx = random.between(1, length)
local old_char = string.sub(prev, idx, idx)
local new_char = char_gen:shrink(old_char)
if new_char == old_char and iterations_count ~= 0 then
-- Shrink introduced no simpler result, retry at other index.
return do_shrink_generic(prev, length, iterations_count - 1)
end
return string_replace_char(prev, new_char, idx)
end
--- Shrinks an amount of characters in the string.
-- @param str string to be shrunk down
-- @param length size of the string
-- @param how_many amount of characters to shrink
-- @return shrunk down string value
local function shrink_generic(str, length, how_many)
if how_many ~= 0 then
local new_str = do_shrink_generic(str, length, lqc.numshrinks)
return shrink_generic(new_str, length, how_many - 1)
end
return str
end
--- Determines if the string should be shrunk down to a shorter string
-- @param str_len size of the string
-- @return true: string should be made shorter; false: string should remain
-- size during shrinking
local function should_shrink_smaller(str_len)
if str_len == 0 then return false end
return random.between(1, 5) == 1
end
--- Shrinks the string by removing 1 character
-- @param str string to be shrunk down
-- @param str_len size of the string
-- @return new string with 1 random character removed
local function shrink_smaller(str, str_len)
local idx = random.between(1, str_len)
-- Handle edge cases (first or last char)
if idx == 1 then
return string.sub(str, 2)
end
if idx == str_len then
return string.sub(str, 1, idx - 1)
end
local new_str = {
string.sub(str, 1, idx - 1),
string.sub(str, idx + 1)
}
return table.concat(new_str)
end
--- Generates a string with a specific size.
-- @param size size of the string to generate
-- @return string of a specific size
local function do_generic_pick(size)
local result = {}
for _ = 1, size do
result[#result + 1] = char_gen:pick()
end
return table.concat(result)
end
--- Generates a string with arbitrary length (0 <= size <= numtests).
-- @param numtests Number of times the property uses this generator; used to
-- guide the optimization process.
-- @return string of an arbitrary size
local function arbitrary_length_pick(numtests)
local size = random.between(0, numtests)
return do_generic_pick(size)
end
--- Shrinks a string to a simpler form (smaller / different chars).
-- 1. Returns empty strings instantly
-- 2. Determine if string should be made shorter
-- 2.1 if true: remove a char
-- 2.2 otherwise:
-- * simplify a random amount of characters
-- * remove a char if simplify did not help
-- * otherwise return the simplified string
-- @param prev previously generated string value
-- @return shrunk down string value
local function arbitrary_length_shrink(prev)
local length = #prev
if length == 0 then return prev end -- handle empty strings
if should_shrink_smaller(length) then
return shrink_smaller(prev, length)
end
local new_str = shrink_generic(prev, length, shrink_how_many(length))
if new_str == prev then
-- shrinking didn't help, remove an element
return shrink_smaller(new_str, length)
end
-- string shrunk succesfully!
return new_str
end
--- Helper function for generating a string with a specific size
-- @param size size of the string to generate
-- @return function that can generate strings of a specific size
local function specific_length_pick(size)
local function do_specific_pick()
return do_generic_pick(size)
end
return do_specific_pick
end
--- Shrinks a string to a simpler form (only different chars since length is fixed).
-- * "" -> ""
-- * non-empty string, shrinks upto max 5 chars of the string
-- @param prev previously generated string value
-- @return shrunk down string value
local function specific_length_shrink(prev)
local length = #prev
if length == 0 then return prev end -- handle empty strings
return shrink_generic(prev, length, shrink_how_many(length))
end
--- Generator for a string with an arbitrary size
-- @return generator for a string of arbitrary size
local function arbitrary_length_string()
return Gen.new(arbitrary_length_pick, arbitrary_length_shrink)
end
--- Creates a generator for a string of a specific size
-- @param size size of the string to generate
-- @return generator for a string of a specific size
local function specific_length_string(size)
return Gen.new(specific_length_pick(size), specific_length_shrink)
end
--- Creates a new ASCII string generator
-- @param size size of the string
-- @return generator that can generate the following:
-- 1. size provided: a string of a specific size
-- 2. no size provided: string of an arbitrary size
local function new(size)
if size then
return specific_length_string(size)
end
return arbitrary_length_string()
end
return new
|
-- Register tanks for each fluid
fluidity.bucket_cache = {}
fluidity.tanks = {}
-- Get fluid source block name for bucket item.
function fluidity.get_fluid_for_bucket(itemname)
for i,v in pairs(fluidity.bucket_cache) do
if v == itemname then
return i
end
end
end
-- Get bucket item name for fluid source block.
function fluidity.get_bucket_for_fluid(source)
return fluidity.bucket_cache[source]
end
-- Ensure that this fluid node exists.
function fluidity.get_fluid_node(name)
return minetest.registered_nodes[name]
end
-- Get a nodedef field.
local function get_nodedef_field(nodename, fieldname)
if not minetest.registered_nodes[nodename] then
return nil
end
return minetest.registered_nodes[nodename][fieldname]
end
-- Ensure that the node is a tank.
function fluidity.tanks.get_is_tank(node)
return minetest.get_item_group(node, "fluidity_tank") > 0
end
-- Ensure that the node is an empty tank.
function fluidity.tanks.get_is_empty_tank(node)
return minetest.get_item_group(node, "fluidity_tank_empty") > 0
end
-- Get tank data at position.
-- Returns fluid name, fluid level, capacity, base tank name and the mod it was added from.
-- Base tank name and mod name are used to construct different variants of this tank type.
function fluidity.tanks.get_tank_at(pos)
local meta = minetest.get_meta(pos)
local node = minetest.get_node(pos)
if not fluidity.tanks.get_is_tank(node.name) then return nil end
local ffluid = get_nodedef_field(node.name, "fluidity_fluid")
local fcapacity = get_nodedef_field(node.name, "_capacity")
local fbasetank = get_nodedef_field(node.name, "_dataname")
local fmod = get_nodedef_field(node.name, "_mod")
local fluidcount = meta:get_int("fluid")
return ffluid, fluidcount, fcapacity, fbasetank, fmod
end
-- Check to see if a fluid can go in the tank and pos.
function fluidity.tanks.can_fluid_go_in_tank(pos, fluid)
local fluid_name, count, capacity, base_tank, mod = fluidity.tanks.get_tank_at(pos)
if not fluid_name then return true end
if fluid_name ~= fluid then return false end
if count == capacity then return false end
local source_node = fluidity.get_fluid_node(fluid)
local fluid_desc = fluidity.fluid_name(source_node.description)
local shorthand_name = fluidity.fluid_short(fluid_desc)
if not minetest.registered_nodes[mod..":"..base_tank.."_"..shorthand_name] then return false end
return true
end
-- Fill the tank at pos with fluid.
-- Overfilling means it will return an integer as the second variable that shows the amount over the capacity.
function fluidity.tanks.fill_tank_at(pos, fluid, amount, overfill)
local fluid_name, count, capacity, base_tank, mod = fluidity.tanks.get_tank_at(pos)
if not fluid_name == fluid and fluid_name ~= nil then return nil end
local node = minetest.get_node(pos)
local meta = minetest.get_meta(pos)
local node_name = mod..":"..base_tank
local remainder = 0
if count + amount > capacity then
if overfill then
remainder = capacity - count
count = capacity
else
return nil
end
else
count = count + amount
end
local source_node = fluidity.get_fluid_node(fluid)
local fluid_desc = fluidity.fluid_name(source_node.description)
local shorthand_name = fluidity.fluid_short(fluid_desc)
node_name = mod..":"..base_tank.."_"..shorthand_name
if not minetest.registered_nodes[node_name] then return nil end
meta:set_int("fluid", count)
meta:set_string("infotext", "Tank of "..fluid_desc.."("..count.."/"..capacity.." mB)")
local param2 = math.min((count/capacity)*63, 63)
minetest.swap_node(pos, {name=node_name,param1=node.param1,param2=param2})
return fluid, remainder
end
-- Take some fluid from the tank at pos.
-- Underfill returns an integer as the second variable indicating level below zero.
function fluidity.tanks.take_from_tank_at(pos, amount, underfill)
local fluid_name, count, capacity, base_tank, mod = fluidity.tanks.get_tank_at(pos)
if not fluid_name then return nil end
local node = minetest.get_node(pos)
local meta = minetest.get_meta(pos)
local node_name = mod..":"..base_tank
local fluid = fluid_name
local leftover = 0
if count - amount < 0 then
if underfill then
leftover = (count - amount) * -1
count = 0
else
return nil
end
else
count = count - amount
end
if count == 0 then
fluid = nil
end
meta:set_int("fluid", count)
if fluid then
local source_node = fluidity.get_fluid_node(fluid)
local fluid_desc = fluidity.fluid_name(source_node.description)
local shorthand_name = fluidity.fluid_short(fluid_desc)
node_name = mod..":"..base_tank.."_"..shorthand_name
meta:set_string("infotext", "Tank of "..fluid_desc.."("..count.."/"..capacity.." mB)")
else
meta:set_string("infotext", "Empty Tank")
end
local param2 = math.min((count/capacity)*63, 63)
minetest.swap_node(pos, {name=node_name,param1=node.param1,param2=param2})
return fluid_name, leftover
end
local function bucket_fill(pos, node, clicker, itemstack, pointed_thing)
local stackname = itemstack:get_name()
local stack = "bucket:bucket_empty"
if not stackname:find("bucket") then
return itemstack
end
if stackname == "bucket:bucket_empty" then
if fluidity.tanks.get_is_empty_tank(node.name) then
return itemstack
end
local fluid = fluidity.tanks.take_from_tank_at(pos, 1000)
if not fluid then
return itemstack
end
stack = fluidity.get_bucket_for_fluid(fluid)
else
local srcnode = fluidity.get_fluid_for_bucket(stackname)
if not fluidity.tanks.can_fluid_go_in_tank(pos, srcnode) then
return itemstack
end
local fluid = fluidity.tanks.fill_tank_at(pos, srcnode, 1000)
if fluid == nil then
return itemstack
end
end
return ItemStack(stack)
end
-- Preserve fluid count in the item stack dropped
local function preserve_metadata(pos, oldnode, oldmeta, drops)
local fluid_name, count, capacity = fluidity.tanks.get_tank_at(pos)
local meta = minetest.get_meta(pos)
local fluid_cnt = meta:get_int("fluid")
local nodedesc = get_nodedef_field(oldnode.name, "description")
for i,stack in pairs(drops) do
local stack_meta = stack:get_meta()
stack_meta:set_int("fluid", fluid_cnt)
stack_meta:set_string("description", nodedesc.."\nContains "..count.."/"..capacity.." mB")
drops[i] = stack
end
return drops
end
-- Retrieve fluid count from itemstack when placed
local function after_place_node(pos, placer, itemstack, pointed_thing)
local item_meta = itemstack:get_meta()
local fluid_cnt = item_meta:get_int("fluid")
local fluid = get_nodedef_field(itemstack:get_name(), "fluidity_fluid")
if fluid_cnt then
-- Fill the tank to the count specified in item meta, don't care about overfill or what it returns.
fluidity.tanks.fill_tank_at(pos, fluid, fluid_cnt, true)
end
return false
end
-- Register a tank for a specific fluid
local function register_tankfluid(data)
local source_node = fluidity.get_fluid_node(data.source_name)
local fluid = fluidity.fluid_name(source_node.description)
local internal = fluidity.fluid_short(fluid)
local nodename = data.mod_name..":"..data.tank_name.."_"..internal
if minetest.registered_nodes[nodename] then
return
end
minetest.register_node(nodename, {
description = data.tank_description.." ("..fluid..")",
drawtype = "glasslike_framed_optional",
paramtype = "light",
paramtype2 = "glasslikeliquidlevel",
fluidity_fluid = data.source_name,
place_param2 = 0,
special_tiles = source_node.tiles,
is_ground_content = false,
sunlight_propagates = true,
on_rightclick = bucket_fill,
preserve_metadata = preserve_metadata,
after_place_node = after_place_node,
_mod = data.mod_name,
_dataname = data.tank_name,
_capacity = data.capacity,
groups = {cracky = 1, not_in_creative_inventory = 1, oddly_breakable_by_hand = 3, fluidity_tank = 1},
tiles = data.tiles
})
end
-- Register a new tank
function fluidity.tanks.register_fluid_tank(data)
local modname = data.mod_name or minetest.get_current_modname()
local tankname = data.tank_name or 'fluid_tank'
local tankdesc = data.tank_description or 'Fluid Tank'
local tiles = data.tiles or {"default_glass.png", "default_glass_detail.png"}
local capacity = data.capacity or 64000
local tanknode = modname..":"..tankname
if not minetest.registered_nodes[tanknode] then
minetest.register_node(tanknode, {
description = tankdesc,
drawtype = "glasslike_framed_optional",
paramtype = "light",
paramtype2 = "glasslikeliquidlevel",
is_ground_content = false,
sunlight_propagates = true,
fluidity_fluid = nil,
on_construct = function ( pos )
local meta = minetest.get_meta(pos)
meta:set_int("fluid", 0)
meta:set_string("infotext", "Empty "..tankdesc)
end,
on_rightclick = bucket_fill,
_mod = modname,
_dataname = tankname,
_capacity = capacity,
groups = {cracky = 1, oddly_breakable_by_hand = 3, fluidity_tank = 1, fluid_tank_empty = 1},
tiles = tiles
})
end
if data.fluids then
-- This tank only uses certain fluids
for _, v in pairs(data.fluids) do
register_tankfluid({
mod_name = modname,
tank_name = tankname,
tank_description = tankdesc,
tiles = tiles,
capacity = capacity,
source_name = v
})
end
else
-- Get all fluids and buckets and cache them
for i, v in pairs(bucket.liquids) do
if (i:find("source") ~= nil) then
-- Cache bucket
fluidity.bucket_cache[v["source"]] = v.itemname
-- Add tank
register_tankfluid({
mod_name = modname,
tank_name = tankname,
tank_description = tankdesc,
tiles = tiles,
capacity = capacity,
source_name = v["source"]
})
end
end
end
end
|
local ffi = require("ffi")
ffi.cdef[[
typedef struct {
int version;
uint8_t addr[16];
uint8_t mask[16];
int proto;
} CIDR;
CIDR *cidr_from_str(const char *);
char *cidr_to_str(const CIDR *, int);
int cidr_contains(const CIDR *, const CIDR *);
void cidr_free(CIDR *);
void free(void *);
]]
local cidr = ffi.load("cidr")
local lshift = bit.lshift
local errs = {
EINVAL = 22,
ENOENT = 2,
ENOMEM = 12,
EFAULT = 14,
EPROTO = 71,
}
local _M = {
_VERSION = "1.0.0"
}
_M.flags = {
NOFLAGS = 0,
NOCOMPACT = 1, -- Don't do :: compaction
VERBOSE = lshift(1, 1), -- Don't minimize leading zeros
USEV6 = lshift(1, 2), -- Use v6 form for v4 addresses
USEV4COMPAT = lshift(1, 3), -- Use v4-compat rather than v4-mapped
NETMASK = lshift(1, 4), -- Show netmask instead of pflen
ONLYADDR = lshift(1, 5), -- Only show the address
ONLYPFLEN = lshift(1, 6), -- Only show the pf/mask
WILDCARD = lshift(1, 7), -- Show wildcard-mask instead of netmask
FORCEV6 = lshift(1, 8), -- Force treating as v6 address
FORCEV4 = lshift(1, 9), -- Force treating as v4 address
REVERSE = lshift(1, 10), -- Return a DNS PTR name
}
function _M.from_str(string)
local result = cidr.cidr_from_str(string)
if result == nil then
local errno = ffi.errno()
if errno == errs.EFAULT then
return nil, "Passed NULL"
elseif errno == errs.EINVAL then
return nil, "Can't parse the input string"
elseif errno == errs.ENOENT then
return nil, "Internal error"
end
end
result = ffi.gc(result, cidr.cidr_free)
return result
end
function _M.to_str(struct, flags)
if type(struct) ~= "cdata" then
return nil, "Invalid argument (bad block or flags)"
end
if type(flags) ~= "number" then
flags = 0
end
local result = cidr.cidr_to_str(struct, flags)
if result == nil then
local errno = ffi.errno()
if errno == errs.EINVAL then
return nil, "Invalid argument (bad block or flags)"
elseif errno == errs.ENOENT then
return nil, "Internal error"
elseif errno == errs.ENOMEM then
return nil, "malloc() failed"
end
end
local string = ffi.string(result)
ffi.C.free(result)
return string
end
function _M.contains(big, little)
if big == nil or little == nil then
return nil, "Passed NULL"
elseif type(big) ~= "cdata" or type(little) ~= "cdata" then
return nil, "Invalid argument"
end
local result = cidr.cidr_contains(big, little)
if result == 0 then
return true
else
local errno = ffi.errno()
if errno == errs.EFAULT then
return nil, "Passed NULL"
elseif errno == errs.EINVAL then
return nil, "Invalid argument"
elseif errno == errs.ENOENT then
return nil, "Internal error"
elseif errno == errs.EPROTO then
return nil, "Protocols don't match"
end
return false
end
end
return _M
|
return {
fontHeight=12,
yspdMin=0,
yspdMax=3,
countdownMin=1,
countdownMax=3,
dropWidth=1,
dropHeight=6,
dropColor={0,255,255}
}
|
object_tangible_collection_plant_14 = object_tangible_collection_shared_plant_14:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_plant_14, "object/tangible/collection/plant_14.iff")
|
--[[ FORK OF ROBLOX'S BUILT IN RAGDOLL
Originally forked by BreakOn 03/2022
imported here & further modified by HashCollision 04/2022
--]]
local Rigging = {}
-- Gravity that joint friction values were tuned under.
local REFERENCE_GRAVITY = workspace.Gravity
-- ReferenceMass values from mass of child part. Used to normalized "stiffness" for differently
-- sized avatars (with different mass).
local DEFAULT_MAX_FRICTION_TORQUE = 500
local HEAD_LIMITS = {
UpperAngle = 45,
TwistLowerAngle = -40,
TwistUpperAngle = 40,
FrictionTorque = 400,
ReferenceMass = 1.0249234437943,
}
local WAIST_LIMITS = {
UpperAngle = 20,
TwistLowerAngle = -40,
TwistUpperAngle = 20,
FrictionTorque = 750,
ReferenceMass = 2.861558675766,
}
local ANKLE_LIMITS = {
UpperAngle = 10,
TwistLowerAngle = -10,
TwistUpperAngle = 10,
ReferenceMass = 0.43671694397926,
}
local ELBOW_LIMITS = {
-- Elbow is basically a hinge, but allow some twist for Supination and Pronation
UpperAngle = 20,
TwistLowerAngle = 5,
TwistUpperAngle = 120,
ReferenceMass = 0.70196455717087,
}
local WRIST_LIMITS = {
UpperAngle = 30,
TwistLowerAngle = -10,
TwistUpperAngle = 10,
ReferenceMass = 0.69132566452026,
}
local KNEE_LIMITS = {
UpperAngle = 5,
TwistLowerAngle = -120,
TwistUpperAngle = -5,
ReferenceMass = 0.65389388799667,
}
local SHOULDER_LIMITS = {
UpperAngle = 110,
TwistLowerAngle = -85,
TwistUpperAngle = 85,
FrictionTorque = 600,
ReferenceMass = 0.90918225049973,
}
local HIP_LIMITS = {
UpperAngle = 40,
TwistLowerAngle = -5,
TwistUpperAngle = 80,
FrictionTorque = 600,
ReferenceMass = 1.9175016880035,
}
local V3_ZERO = Vector3.zero
local V3_UP = Vector3.yAxis
local V3_DOWN = -Vector3.xAxis
local V3_RIGHT = Vector3.xAxis
local V3_LEFT = -Vector3.xAxis
-- To model shoulder cone and twist limits correctly we really need the primary axis of the UpperArm
-- to be going down the limb. the waist and neck joints attachments actually have the same problem
-- of non-ideal axis orientation, but it's not as noticable there since the limits for natural
-- motion are tighter for those joints anyway.
local R15_ADDITIONAL_ATTACHMENTS = {
{"UpperTorso", "RightShoulderRagdollAttachment", CFrame.fromMatrix(V3_ZERO, V3_RIGHT, V3_UP), "RightShoulderRigAttachment"},
{"RightUpperArm", "RightShoulderRagdollAttachment", CFrame.fromMatrix(V3_ZERO, V3_DOWN, V3_RIGHT), "RightShoulderRigAttachment"},
{"UpperTorso", "LeftShoulderRagdollAttachment", CFrame.fromMatrix(V3_ZERO, V3_LEFT, V3_UP), "LeftShoulderRigAttachment"},
{"LeftUpperArm", "LeftShoulderRagdollAttachment", CFrame.fromMatrix(V3_ZERO, V3_DOWN, V3_LEFT), "LeftShoulderRigAttachment"},
}
-- { { Part0 name (parent), Part1 name (child, parent of joint), attachmentName, limits }, ... }
local R15_RAGDOLL_RIG = {
{"UpperTorso", "Head", "NeckRigAttachment", HEAD_LIMITS},
{"LowerTorso", "UpperTorso", "WaistRigAttachment", WAIST_LIMITS},
{"UpperTorso", "LeftUpperArm", "LeftShoulderRagdollAttachment", SHOULDER_LIMITS},
{"LeftUpperArm", "LeftLowerArm", "LeftElbowRigAttachment", ELBOW_LIMITS},
{"LeftLowerArm", "LeftHand", "LeftWristRigAttachment", WRIST_LIMITS},
{"UpperTorso", "RightUpperArm", "RightShoulderRagdollAttachment", SHOULDER_LIMITS},
{"RightUpperArm", "RightLowerArm", "RightElbowRigAttachment", ELBOW_LIMITS},
{"RightLowerArm", "RightHand", "RightWristRigAttachment", WRIST_LIMITS},
{"LowerTorso", "LeftUpperLeg", "LeftHipRigAttachment", HIP_LIMITS},
{"LeftUpperLeg", "LeftLowerLeg", "LeftKneeRigAttachment", KNEE_LIMITS},
{"LeftLowerLeg", "LeftFoot", "LeftAnkleRigAttachment", ANKLE_LIMITS},
{"LowerTorso", "RightUpperLeg", "RightHipRigAttachment", HIP_LIMITS},
{"RightUpperLeg", "RightLowerLeg", "RightKneeRigAttachment", KNEE_LIMITS},
{"RightLowerLeg", "RightFoot", "RightAnkleRigAttachment", ANKLE_LIMITS},
}
-- { { Part0 name, Part1 name }, ... }
local R15_NO_COLLIDES = {
{"LowerTorso", "LeftUpperArm"},
{"LeftUpperArm", "LeftHand"},
{"LowerTorso", "RightUpperArm"},
{"RightUpperArm", "RightHand"},
{"LeftUpperLeg", "RightUpperLeg"},
{"UpperTorso", "RightUpperLeg"},
{"RightUpperLeg", "RightFoot"},
{"UpperTorso", "LeftUpperLeg"},
{"LeftUpperLeg", "LeftFoot"},
-- Support weird R15 rigs
{"UpperTorso", "LeftLowerLeg"},
{"UpperTorso", "RightLowerLeg"},
{"LowerTorso", "LeftLowerLeg"},
{"LowerTorso", "RightLowerLeg"},
{"UpperTorso", "LeftLowerArm"},
{"UpperTorso", "RightLowerArm"},
{"Head", "LeftUpperArm"},
{"Head", "RightUpperArm"},
}
-- { { Motor6D name, Part name }, ...}, must be in tree order, important for ApplyJointVelocities
local R15_MOTOR6DS = {
{"Waist", "UpperTorso"},
{"Neck", "Head"},
{"LeftShoulder", "LeftUpperArm"},
{"LeftElbow", "LeftLowerArm"},
{"LeftWrist", "LeftHand"},
{"RightShoulder", "RightUpperArm"},
{"RightElbow", "RightLowerArm"},
{"RightWrist", "RightHand"},
{"LeftHip", "LeftUpperLeg"},
{"LeftKnee", "LeftLowerLeg"},
{"LeftAnkle", "LeftFoot"},
{"RightHip", "RightUpperLeg"},
{"RightKnee", "RightLowerLeg"},
{"RightAnkle", "RightFoot"},
}
local BALL_SOCKET_NAME = "RagdollBallSocket"
local NO_COLLIDE_NAME = "RagdollNoCollision"
-- Index parts by name to save us from many O(n) FindFirstChild searches
local function indexParts(model)
local parts = {}
for _, child in ipairs(model:GetChildren()) do
if child:IsA("BasePart") then
local name = child.name
-- Index first, mimicing FindFirstChild
if not parts[name] then
parts[name] = child
end
end
end
return parts
end
local function createRigJoints(parts, rig)
for _, params in ipairs(rig) do
local part0Name, part1Name, attachmentName, limits = table.unpack(params)
local part0 = parts[part0Name]
local part1 = parts[part1Name]
if part0 and part1 then
local a0 = part0:FindFirstChild(attachmentName)
local a1 = part1:FindFirstChild(attachmentName)
if a0 and a1 and a0:IsA("Attachment") and a1:IsA("Attachment") then
-- Our rigs only have one joint per part (connecting each part to it's parent part), so
-- we can re-use it if we have to re-rig that part again.
local constraint = part1:FindFirstChild(BALL_SOCKET_NAME)
if not constraint then
constraint = Instance.new("BallSocketConstraint")
constraint.Name = BALL_SOCKET_NAME
end
constraint.Attachment0 = a0
constraint.Attachment1 = a1
constraint.LimitsEnabled = true
constraint.UpperAngle = limits.UpperAngle
constraint.TwistLimitsEnabled = true
constraint.TwistLowerAngle = limits.TwistLowerAngle
constraint.TwistUpperAngle = limits.TwistUpperAngle
-- Scale constant torque limit for joint friction relative to gravity and the mass of
-- the body part.
local gravityScale = workspace.Gravity / REFERENCE_GRAVITY
local referenceMass = limits.ReferenceMass
local massScale = referenceMass and (part1:GetMass() / referenceMass) or 1
local maxTorque = limits.FrictionTorque or DEFAULT_MAX_FRICTION_TORQUE
constraint.MaxFrictionTorque = maxTorque * massScale * gravityScale
constraint.Parent = part1
end
end
end
end
local function createAdditionalAttachments(parts, attachments)
for _, attachmentParams in ipairs(attachments) do
local partName, attachmentName, cframe, baseAttachmentName = table.unpack(attachmentParams)
local part = parts[partName]
if part then
local attachment = part:FindFirstChild(attachmentName)
-- Create or update existing attachment
if not attachment or attachment:IsA("Attachment") then
if baseAttachmentName then
local base = part:FindFirstChild(baseAttachmentName)
if base and base:IsA("Attachment") then
cframe = base.CFrame * cframe
end
end
-- The attachment names are unique within a part, so we can re-use
if not attachment then
attachment = Instance.new("Attachment")
attachment.Name = attachmentName
attachment.CFrame = cframe
attachment.Parent = part
else
attachment.CFrame = cframe
end
end
end
end
end
local function createNoCollides(parts, noCollides)
-- This one's trickier to handle for an already rigged character since a part will have multiple
-- NoCollide children with the same name. Having fewer unique names is better for
-- replication so we suck it up and deal with the complexity here.
-- { [Part1] = { [Part0] = true, ... }, ...}
local needed = {}
-- Following the convention of the Motor6Ds and everything else here we parent the NoCollide to
-- Part1, so we start by building the set of Part0s we need a NoCollide with for each Part1
for _, namePair in ipairs(noCollides) do
local part0Name, part1Name = unpack(namePair)
local p0, p1 = parts[part0Name], parts[part1Name]
if p0 and p1 then
local p0Set = needed[p1]
if not p0Set then
p0Set = {}
needed[p1] = p0Set
end
p0Set[p0] = true
end
end
-- Go through NoCollides that exist and remove Part0s from the needed set if we already have
-- them covered. Gather NoCollides that aren't between parts in the set for resue
local reusableNoCollides = {}
for part1, neededPart0s in pairs(needed) do
local reusables = {}
for _, child in ipairs(part1:GetChildren()) do
if child:IsA("NoCollisionConstraint") and child.Name == NO_COLLIDE_NAME then
local p0 = child.Part0
local p1 = child.Part1
if p1 == part1 and neededPart0s[p0] then
-- If this matches one that we needed, we don't need to create it anymore.
neededPart0s[p0] = nil
else
-- Otherwise we're free to reuse this NoCollide
table.insert(reusables, child)
end
end
end
reusableNoCollides[part1] = reusables
end
-- Create the remaining NoCollides needed, re-using old ones if possible
for part1, neededPart0s in pairs(needed) do
local reusables = reusableNoCollides[part1]
for part0, _ in pairs(neededPart0s) do
local constraint = table.remove(reusables)
if not constraint then
constraint = Instance.new("NoCollisionConstraint")
end
constraint.Name = NO_COLLIDE_NAME
constraint.Part0 = part0
constraint.Part1 = part1
constraint.Parent = part1
end
end
end
local function isAttachmetInPart(attachment, part)
return attachment and attachment.Parent == part or false
end
local function checkValidAttachment(part0, part1, attachment0, attachment1)
if isAttachmetInPart(attachment0, part0) and isAttachmetInPart(attachment1, part1) then
return true
end
if isAttachmetInPart(attachment0, part1) and isAttachmetInPart(attachment1, part0) then
return true
end
return false
end
local function hasValidConstraint(part0, part1)
for _, child in ipairs(part1:GetChildren()) do
if child:IsA("BallSocketConstraint") then
local attachment0 = child.Attachment0
local attachment1 = child.Attachment1
if checkValidAttachment(part0, part1, attachment0, attachment1) then
return true
end
end
end
return false
end
local function hasRagdollJoint(motor)
local part0 = motor.Part0
local part1 = motor.Part1
if not part0 or not part1 then
return false
end
if hasValidConstraint(part0, part1) then
return true
end
-- Don't enforce ordering for developer created ragdolls
if hasValidConstraint(part1, part0) then
return true
end
return false
end
local function disableMotorSet(model, motorSet)
local motors = {}
-- Destroy all regular joints:
for _, params in ipairs(motorSet) do
local part = model:FindFirstChild(params[2])
if part then
local motor = part:FindFirstChild(params[1])
if motor and motor:IsA("Motor6D") and hasRagdollJoint(motor) then
table.insert(motors, motor)
motor.Enabled = false
end
end
end
return motors
end
local function enableMotorSet(model, motorSet)
local motors = {}
-- Destroy all regular joints:
for _, params in ipairs(motorSet) do
local part = model:FindFirstChild(params[2])
if part then
local motor = part:FindFirstChild(params[1])
if motor and motor:IsA("Motor6D") and hasRagdollJoint(motor) then
table.insert(motors, motor)
motor.Enabled = true
end
end
end
return motors
end
local function setJointFriction(character)
local descendants = character:GetDescendants()
local frictionJoints = {}
for _, v in pairs(descendants) do
if v:IsA("BallSocketConstraint") and v.Name == BALL_SOCKET_NAME then
local current = v.MaxFrictionTorque
-- Keep the torso and neck a little stiffer...
local parentName = v.Parent.Name
local scale = (parentName == "UpperTorso" or parentName == "Head") and 0.5 or 0.05
local nextTorque = current * scale
frictionJoints[v] = { v, current, nextTorque }
end
end
for _, tuple in pairs(frictionJoints) do
local ballSocket, a, b = unpack(tuple)
ballSocket.MaxFrictionTorque = 0.3
end
end
function Rigging.CreateRagdollJoints(model)
local parts = indexParts(model)
createAdditionalAttachments(parts, R15_ADDITIONAL_ATTACHMENTS)
createRigJoints(parts, R15_RAGDOLL_RIG)
createNoCollides(parts, R15_NO_COLLIDES)
end
function Rigging.RemoveRagdollJoints(model)
for _, descendant in pairs(model:GetDescendants()) do
-- Remove BallSockets and NoCollides, leave the additional Attachments
if (descendant:IsA("BallSocketConstraint") and descendant.Name == BALL_SOCKET_NAME)
or (descendant:IsA("NoCollisionConstraint") and descendant.Name == NO_COLLIDE_NAME)
then
descendant:Destroy()
end
end
end
function Rigging.DisableMotors(model)
-- Note: We intentionally do not disable the root joint so that the mechanism root of the
-- character stays consistent when we break joints on the client. This avoid the need for the client to wait
-- for re-assignment of network ownership of a new mechanism, which creates a visible hitch.
local motors = disableMotorSet(model, R15_MOTOR6DS)
-- Set the root part to non-collide
local rootPart = model.PrimaryPart or model:FindFirstChild("HumanoidRootPart")
if rootPart and rootPart:IsA("BasePart") then
rootPart.CanCollide = false
end
local head = model:FindFirstChild("Head")
if head and head:IsA("BasePart") then
head.CanCollide = true
end
return motors
end
function Rigging.EnableMotors(model)
local motors = enableMotorSet(model, R15_MOTOR6DS)
-- Set the root part to collide
local rootPart = model.PrimaryPart or model:FindFirstChild("HumanoidRootPart")
if rootPart and rootPart:IsA("BasePart") then
rootPart.CanCollide = true
end
local head = model:FindFirstChild("Head")
if head and head:IsA("BasePart") then
head.CanCollide = false
end
return motors
end
local module = {}
local ragdolls = {}
function module.Enable(model)
local humanoid = model:WaitForChild("Humanoid")
humanoid:ChangeState(Enum.HumanoidStateType.Physics)
Rigging.CreateRagdollJoints(model)
Rigging.DisableMotors(model)
for _, anim in ipairs(humanoid.Animator:GetPlayingAnimationTracks()) do
anim:Stop()
end
setJointFriction(model)
end
function module.Disable(model)
local humanoid = model:WaitForChild("Humanoid")
humanoid:ChangeState(Enum.HumanoidStateType.GettingUp)
Rigging.EnableMotors(model)
Rigging.RemoveRagdollJoints(model)
end
function module.Start(character)
local info = {}
local function Changed()
local ragdoll = character:GetAttribute('ragdoll')
if ragdoll then
module.Enable(character)
else
module.Disable(character)
end
end
info.changed = character:GetAttributeChangedSignal('ragdoll'):Connect(Changed)
ragdolls[character] = info
end
function module.Stop(character)
local info = character and ragdolls[character]
if info then
info.changed:Disconnect()
ragdolls[character] = nil
end
end
return module
|
-----------------------------------------------
-- maletItem.lua
-- The code for the mace, when it is in the player's inventory.
-- Created by NimbusBP1729
-----------------------------------------------
return{
name = 'mallet',
type = 'weapon',
}
|
local M = {}
function M.remote()
local branch = vim.fn["gina#component#repo#branch"]()
local tracking = vim.fn["gina#component#repo#track"]()
local remote_name = tracking:sub(1, #tracking - #branch - 1)
if remote_name == "" then
return "origin"
end
return remote_name
end
function M._revision()
local tmp = vim.fn.getreg("+")
vim.fn["gina#action#call"]("yank:rev")
local revision = vim.fn.getreg("+")
vim.fn.setreg("+", tmp)
return revision
end
function M._path()
local tmp = vim.fn.getreg("+")
vim.fn["gina#action#call"]("yank:path")
local path = vim.fn.getreg("+")
vim.fn.setreg("+", tmp)
return path
end
function M.toggle_buffer(cmd, filetype)
if vim.bo.filetype ~= filetype then
return vim.cmd("Gina " .. cmd)
end
if #vim.fn.tabpagebuflist(vim.fn.tabpagenr()) == 1 then
return vim.cmd("edit #")
end
vim.cmd("quit")
end
function M.push_cmd()
local revision = M._revision()
return "Gina! push origin " .. revision
end
function M.fixup()
local revision = M._revision()
vim.cmd("Gina! commit --fixup=" .. revision)
end
function M.rebase_i()
local revision = M._revision()
vim.cmd("terminal")
vim.fn.jobsend(vim.b.terminal_job_id, "git rebase -i --autosquash " .. revision .. "~" .. vim.api.nvim_eval([["\<CR>"]]))
end
function M.stash_file()
local path = M._path()
vim.cmd("Gina! stash -- " .. path)
end
function M.yank_rev()
vim.fn["gina#action#call"]("yank:rev")
vim.api.nvim_echo({{vim.fn.getreg("+")}}, true, {})
end
function M.browse_yank()
vim.fn["gina#action#call"]("browse:yank")
vim.api.nvim_echo({{vim.fn.getreg("+")}}, true, {})
end
function M.edit(action)
local splitted = vim.split(vim.fn.getline("."), " ")
if #splitted == 0 then
return
end
local file_part = splitted[#splitted]
local git = vim.fn["gina#core#get_or_fail"]()
local abspath = vim.fn["gina#core#repo#abspath"](git, "")
local path = abspath .. vim.fn.substitute(file_part, "\\v(\\t\\e[31m|\\e\\[m)", "", "g")
if vim.fn.isdirectory(path) == 0 then
return vim.fn["gina#action#call"](action)
end
if action == "edit:tab" then
vim.cmd("tabnew")
end
vim.cmd("lcd " .. path)
require("kivi").open()
end
function M.relpath()
local git = vim.fn["gina#core#get_or_fail"]()
local abspath = vim.fn["gina#core#repo#abspath"](git, "")
local curpath = vim.fn.substitute(vim.fn.expand("%:p"), "\\", "/", "g")
return vim.fn.substitute(curpath, abspath, "", "")
end
return M
|
local RUF = RUF or LibStub("AceAddon-3.0"):GetAddon("RUF")
local LSM = LibStub("LibSharedMedia-3.0")
local _, ns = ...
local oUF = ns.oUF
local elementName = 'TargetMark'
local stringIconCircle = RUF.IndicatorGlyphs['Target-Circle']
local stringIconCross = RUF.IndicatorGlyphs['Target-Cross']
local stringIconDiamond = RUF.IndicatorGlyphs['Target-Diamond']
local stringIconMoon = RUF.IndicatorGlyphs['Target-Moon']
local stringIconSkull = RUF.IndicatorGlyphs['Target-Skull']
local stringIconSquare = RUF.IndicatorGlyphs['Target-Square']
local stringIconStar = RUF.IndicatorGlyphs['Target-Star']
local stringIconTriangle = RUF.IndicatorGlyphs['Target-Triangle']
local GetRaidTargetIndex = GetRaidTargetIndex
local SetRaidTargetIconTexture = SetRaidTargetIconTexture
local function Update(self, event)
local element = self.TargetMarkIndicator
element.Enabled = RUF.db.profile.unit[self.frame].Frame.Indicators[elementName].Enabled
if(element.PreUpdate) then
element:PreUpdate()
end
if element.Enabled == true then
self:EnableElement(elementName..'Indicator')
local index = GetRaidTargetIndex(self.unit)
if(index) then
element:Show()
if index == 1 then -- Star
element:SetText(stringIconStar)
element:SetWidth(element:GetStringWidth()+2)
element:SetTextColor(1,234/255,0/255)
elseif index == 2 then -- Circle
element:SetText(stringIconCircle)
element:SetWidth(element:GetStringWidth()+2)
element:SetTextColor(1,156/255,0/255)
elseif index == 3 then -- Diamond
element:SetText(stringIconDiamond)
element:SetWidth(element:GetStringWidth()+2)
element:SetTextColor(240/255,0/255,255/255)
elseif index == 4 then -- Triangle
element:SetText(stringIconTriangle)
element:SetWidth(element:GetStringWidth()+2)
element:SetTextColor(46/255,206/255,0/255)
elseif index == 5 then -- Moon
element:SetText(stringIconMoon)
element:SetWidth(element:GetStringWidth()+2)
element:SetTextColor(163/255,217/255,255/255)
elseif index == 6 then -- Square
element:SetText(stringIconSquare)
element:SetWidth(element:GetStringWidth()+2)
element:SetTextColor(61/255,180/255,255/255)
elseif index == 7 then -- Cross
element:SetText(stringIconCross)
element:SetWidth(element:GetStringWidth()+2)
element:SetTextColor(1,52/255,52/255)
elseif index == 8 then -- Skull
element:SetText(stringIconSkull)
element:SetWidth(element:GetStringWidth()+2)
element:SetTextColor(1,253/255,229/255)
else
element:SetText(" ")
element:SetWidth(1)
element:Hide()
end
else
element:SetText(" ")
element:SetWidth(1)
element:Hide()
end
if RUF.db.global.TestMode == true then
element:SetText(stringIconStar) -- Star
element:SetTextColor(1,234/255,0/255)
element:SetWidth(element:GetStringWidth()+2)
element:Show()
end
else
self:DisableElement('TargetMarkIndicator')
element:Hide()
end
if(element.PostUpdate) then
return element:PostUpdate()
end
end
local function Path(self, ...)
return (self.TargetMarkIndicator.Override or Update) (self, ...)
end
local function ForceUpdate(element)
if(not element.__owner.unit) then return end
return Path(element.__owner, 'ForceUpdate')
end
local function Enable(self)
local element = self.TargetMarkIndicator
if(element) then
element.__owner = self
element.ForceUpdate = ForceUpdate
self:RegisterEvent('RAID_TARGET_UPDATE', Path, true)
local profileReference = RUF.db.profile.unit[self.frame].Frame.Indicators[elementName]
element:SetFont([[Interface\Addons\RUF\Media\RUF.ttf]], profileReference.Size, 'OUTLINE')
element:SetText(' ')
element:SetJustifyH('CENTER')
element:ClearAllPoints()
element:SetPoint(
profileReference.Position.AnchorFrom,
RUF.GetIndicatorAnchorFrame(self,self.frame,elementName),
profileReference.Position.AnchorTo,
profileReference.Position.x,
profileReference.Position.y
)
element:Show()
return true
end
end
local function Disable(self)
local element = self.TargetMarkIndicator
if(element) then
element:Hide()
self:UnregisterEvent('RAID_TARGET_UPDATE', Path)
end
end
oUF:AddElement('TargetMarkIndicator', Path, Enable, Disable)
function RUF.Indicators.TargetMark(self, unit)
local element = self.Indicators:CreateFontString(self:GetName()..".TargetMarkIndicator", "OVERLAY")
element:SetPoint(
RUF.db.profile.unit[unit].Frame.Indicators[elementName].Position.AnchorFrom,
RUF.GetIndicatorAnchorFrame(self,unit,elementName),
RUF.db.profile.unit[unit].Frame.Indicators[elementName].Position.AnchorTo,
RUF.db.profile.unit[unit].Frame.Indicators[elementName].Position.x,
RUF.db.profile.unit[unit].Frame.Indicators[elementName].Position.y
)
element:SetFont([[Interface\Addons\RUF\Media\RUF.ttf]], RUF.db.profile.unit[unit].Frame.Indicators[elementName].Size, "OUTLINE")
self.TargetMarkIndicator = element
end
|
local VIS = {}
VIS.event = Sonus.lib.NewEventEmitter()
VIS.items = {}
VIS.itemSize = 20
VIS.itemAccel = 0
VIS.bars = 320
VIS.memeFactor = 0
VIS.memeCrement = 41 -- prime
VIS.actualMemeFactor = 0
VIS.rectAng = 0
local canShake = CreateClientConVar("sonus_genesis_shake",1,true,false,"Enable screenshakes")
local shakeMagnitude = CreateClientConVar("sonus_genesis_shake_magnitude",10,true,false,"Screenshake magnitude")
local shakeSensitivity = CreateClientConVar("sonus_genesis_shake_sensitivity",10,true,false,"Screenshake magnitude")
local rotatyBox = CreateClientConVar("sonus_genesis_rotatybox",1,true,false,"Enable rotating box")
function VIS:AddItem()
local right = math.random(0,1) == 0
self.items[#self.items+1] = {
x = right and ScrW() or -self.itemSize,
-- y = math.random(ScrH()/4,ScrH()),
y = math.sin(CurTime()) * ScrH()*3/8 + ScrH() * 5/8,
vel_x = (right and -1 or 1) * math.random(50,350),
vel_y = -math.random(0,300),
col = HSVToColor((self.audioData.TotalEnergy*720+60) % 360,0.75,1)
}
self.items[#self.items].col.a = self.audioData.TotalEnergy * 120 + 50
end
function VIS:DrawItems()
local items = {}
for i,item in ipairs(self.items) do
surface.SetDrawColor(item.col)
surface.DrawRect(item.x,item.y,self.itemSize,self.itemSize)
item.x = item.x + (item.vel_x * (RealFrameTime() + self.itemAccel))
item.y = item.y + item.vel_y * (RealFrameTime() + self.itemAccel)
item.vel_y = item.vel_y + 250 * (RealFrameTime() + self.itemAccel) + self.audioData.TotalEnergy * 0.001
if (item.x >= -self.itemSize) and (item.x <= ScrW()) and (item.y >= -self.itemSize) and (item.y <= ScrH()) then
items[#items+1] = item
end
end
self.items = items
end
VIS.event:on("Bass.peak",function(...)
for i=1,10 do
VIS:AddItem()
end
VIS.itemAccel = VIS.itemAccel + 0.1
VIS.memeFactor = VIS.memeFactor + VIS.memeCrement
end)
VIS.event:on("Peak",function(...)
VIS.memeFactor = VIS.memeFactor + VIS.memeCrement
end)
function draw.RotatedBox(x,y,w,h,ang,color)
draw.NoTexture()
surface.SetDrawColor(color or Color(255,255,255))
surface.DrawTexturedRectRotated(x,y,w,h,ang)
end
function VIS:DrawBars(amount,start)
local lp = Sonus.lib.LowPassFilter(self.audioData.EnergiesArray,self.bars,amount,start)
Sonus.lib.SmoothFilter(lp,5)
local width = math.floor(ScrW()/self.bars)
for i,energy in ipairs(lp) do
local height = math.floor(energy^0.5 * 10^3.75)
surface.DrawRect(ScrW() * 0.5 + (i - self.bars/2 - 1) * width,ScrH() - height,width,height)
end
end
function VIS:GetPowerColor(a,offset)
local powerColor = HSVToColor((self.actualMemeFactor + offset) % 360,1,1)
powerColor.a = a
return powerColor
end
VIS.event:on("Draw",function()
VIS.itemAccel = VIS.itemAccel - VIS.itemAccel / 8
VIS:DrawItems()
VIS.actualMemeFactor = 0.2 * VIS.memeFactor + 0.8 * VIS.actualMemeFactor -- exponential smoothing
VIS.rectAng = VIS.rectAng + VIS.audioData.TotalEnergy^2 * 50
if rotatyBox:GetBool() then
draw.RotatedBox(ScrW()/2,ScrH()/4,100,100,VIS.rectAng,VIS:GetPowerColor(150,0))
draw.SimpleText(string.format("%.3f W/m^2",VIS.audioData.TotalEnergy),"DermaDefault",ScrW()/2,ScrH()/4,Color(255,255,255),TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER)
end
if IsValid(VIS.Channel) then
local elapsed = VIS.Channel:GetTime()
local frac = (elapsed / VIS.Channel:GetLength())
surface.SetDrawColor(10,10,10,150)
surface.DrawRect(0,0,ScrW(),8)
surface.SetDrawColor(250,250,250,150)
surface.DrawRect(0,0,ScrW() * frac,8)
if elapsed <= 10 then
if VIS.Metadata and VIS.Metadata.Title then
draw.SimpleText(VIS.Metadata.Title,"DermaLarge",elapsed/7.5*ScrW(),ScrH()/4 + 10,Color(255,255,255,150),TEXT_ALIGN_RIGHT,TEXT_ALIGN_CENTER)
draw.SimpleText(VIS.Metadata.Artist,"DermaLarge",(1-elapsed/7.5)*ScrW(),ScrH()*3/4 + 10,Color(255,255,255,150),TEXT_ALIGN_LEFT,TEXT_ALIGN_CENTER)
end
end
end
surface.SetDrawColor(VIS:GetPowerColor(100,45))
VIS:DrawBars(#VIS.audioData.EnergiesArray/4,#VIS.audioData.EnergiesArray*3/4+1)
surface.SetDrawColor(VIS:GetPowerColor(150,30))
VIS:DrawBars(#VIS.audioData.EnergiesArray/4,#VIS.audioData.EnergiesArray/2+1)
surface.SetDrawColor(VIS:GetPowerColor(150,15))
VIS:DrawBars(#VIS.audioData.EnergiesArray/4,#VIS.audioData.EnergiesArray/4+1)
surface.SetDrawColor(VIS:GetPowerColor(150,0))
VIS:DrawBars(#VIS.audioData.EnergiesArray/4,1)
if canShake:GetBool() and (VIS.audioData.TotalEnergy^2*50) > shakeSensitivity:GetFloat() then
util.ScreenShake(LocalPlayer():GetPos(),5,1,0.1,shakeMagnitude:GetFloat())
end
end)
Sonus.Player:RegisterVisualiser("genesis",VIS)
:SetName("Genesis")
:SetVersion("11.1.6")
|
local Transformer
Transformer = require("moonscript.transform.transformer").Transformer
local NameProxy, LocalName, is_name_proxy
do
local _obj_0 = require("moonscript.transform.names")
NameProxy, LocalName, is_name_proxy = _obj_0.NameProxy, _obj_0.LocalName, _obj_0.is_name_proxy
end
local Run, transform_last_stm, implicitly_return, last_stm
do
local _obj_0 = require("moonscript.transform.statements")
Run, transform_last_stm, implicitly_return, last_stm = _obj_0.Run, _obj_0.transform_last_stm, _obj_0.implicitly_return, _obj_0.last_stm
end
local types = require("moonscript.types")
local build, ntype, is_value, smart_node, value_is_singular, is_slice, NOOP
build, ntype, is_value, smart_node, value_is_singular, is_slice, NOOP = types.build, types.ntype, types.is_value, types.smart_node, types.value_is_singular, types.is_slice, types.NOOP
local insert
insert = table.insert
local destructure = require("moonscript.transform.destructure")
local construct_comprehension
construct_comprehension = require("moonscript.transform.comprehension").construct_comprehension
local unpack
unpack = require("moonscript.util").unpack
local with_continue_listener
with_continue_listener = function(body)
local continue_name = nil
return {
Run(function(self)
return self:listen("continue", function()
if not (continue_name) then
continue_name = NameProxy("continue")
self:put_name(continue_name)
end
return continue_name
end)
end),
build.group(body),
Run(function(self)
if not (continue_name) then
return
end
local last = last_stm(body)
local enclose_lines = types.terminating[last and ntype(last)]
self:put_name(continue_name, nil)
return self:splice(function(lines)
if enclose_lines then
lines = {
"do",
{
lines
}
}
end
return {
{
"assign",
{
continue_name
},
{
"false"
}
},
{
"repeat",
"true",
{
lines,
{
"assign",
{
continue_name
},
{
"true"
}
}
}
},
{
"if",
{
"not",
continue_name
},
{
{
"break"
}
}
}
}
end)
end)
}
end
local extract_declarations
extract_declarations = function(self, body, start, out)
if body == nil then
body = self.current_stms
end
if start == nil then
start = self.current_stm_i + 1
end
if out == nil then
out = { }
end
for i = start, #body do
local _continue_0 = false
repeat
local stm = body[i]
if stm == nil then
_continue_0 = true
break
end
stm = self.transform.statement(stm)
body[i] = stm
local _exp_0 = stm[1]
if "assign" == _exp_0 or "declare" == _exp_0 then
local _list_0 = stm[2]
for _index_0 = 1, #_list_0 do
local name = _list_0[_index_0]
if ntype(name) == "ref" then
insert(out, name)
elseif type(name) == "string" then
insert(out, name)
end
end
elseif "group" == _exp_0 then
extract_declarations(self, stm[2], 1, out)
end
_continue_0 = true
until true
if not _continue_0 then
break
end
end
return out
end
local expand_elseif_assign
expand_elseif_assign = function(ifstm)
for i = 4, #ifstm do
local case = ifstm[i]
if ntype(case) == "elseif" and ntype(case[2]) == "assign" then
local split = {
unpack(ifstm, 1, i - 1)
}
insert(split, {
"else",
{
{
"if",
case[2],
case[3],
unpack(ifstm, i + 1)
}
}
})
return split
end
end
return ifstm
end
return Transformer({
transform = function(self, tuple)
local _, node, fn
_, node, fn = tuple[1], tuple[2], tuple[3]
return fn(node)
end,
root_stms = function(self, body)
return transform_last_stm(body, implicitly_return(self))
end,
["return"] = function(self, node)
local ret_val = node[2]
local ret_val_type = ntype(ret_val)
if ret_val_type == "explist" and #ret_val == 2 then
ret_val = ret_val[2]
ret_val_type = ntype(ret_val)
end
if types.cascading[ret_val_type] then
return implicitly_return(self)(ret_val)
end
if ret_val_type == "chain" or ret_val_type == "comprehension" or ret_val_type == "tblcomprehension" then
local Value = require("moonscript.transform.value")
ret_val = Value:transform_once(self, ret_val)
if ntype(ret_val) == "block_exp" then
return build.group(transform_last_stm(ret_val[2], function(stm)
return {
"return",
stm
}
end))
end
end
node[2] = ret_val
return node
end,
declare_glob = function(self, node)
local names = extract_declarations(self)
if node[2] == "^" then
do
local _accum_0 = { }
local _len_0 = 1
for _index_0 = 1, #names do
local _continue_0 = false
repeat
local name = names[_index_0]
local str_name
if ntype(name) == "ref" then
str_name = name[2]
else
str_name = name
end
if not (str_name:match("^%u")) then
_continue_0 = true
break
end
local _value_0 = name
_accum_0[_len_0] = _value_0
_len_0 = _len_0 + 1
_continue_0 = true
until true
if not _continue_0 then
break
end
end
names = _accum_0
end
end
return {
"declare",
names
}
end,
assign = function(self, node)
local names, values = unpack(node, 2)
local num_values = #values
local num_names = #values
if num_names == 1 and num_values == 1 then
local first_value = values[1]
local first_name = names[1]
local first_type = ntype(first_value)
if first_type == "chain" then
local Value = require("moonscript.transform.value")
first_value = Value:transform_once(self, first_value)
first_type = ntype(first_value)
end
local _exp_0 = ntype(first_value)
if "block_exp" == _exp_0 then
local block_body = first_value[2]
local idx = #block_body
block_body[idx] = build.assign_one(first_name, block_body[idx])
return build.group({
{
"declare",
{
first_name
}
},
{
"do",
block_body
}
})
elseif "comprehension" == _exp_0 or "tblcomprehension" == _exp_0 or "foreach" == _exp_0 or "for" == _exp_0 or "while" == _exp_0 then
local Value = require("moonscript.transform.value")
return build.assign_one(first_name, Value:transform_once(self, first_value))
else
values[1] = first_value
end
end
local transformed
if num_values == 1 then
local value = values[1]
local t = ntype(value)
if t == "decorated" then
value = self.transform.statement(value)
t = ntype(value)
end
if types.cascading[t] then
local ret
ret = function(stm)
if is_value(stm) then
return {
"assign",
names,
{
stm
}
}
else
return stm
end
end
transformed = build.group({
{
"declare",
names
},
self.transform.statement(value, ret, node)
})
end
end
node = transformed or node
if destructure.has_destructure(names) then
return destructure.split_assign(self, node)
end
return node
end,
continue = function(self, node)
local continue_name = self:send("continue")
if not (continue_name) then
error("continue must be inside of a loop")
end
return build.group({
build.assign_one(continue_name, "true"),
{
"break"
}
})
end,
export = function(self, node)
if #node > 2 then
if node[2] == "class" then
local cls = smart_node(node[3])
return build.group({
{
"export",
{
cls.name
}
},
cls
})
else
return build.group({
{
"export",
node[2]
},
build.assign({
names = node[2],
values = node[3]
})
})
end
else
return nil
end
end,
update = function(self, node)
local name, op, exp = unpack(node, 2)
local op_final = op:match("^(.+)=$")
if not op_final then
error("Unknown op: " .. op)
end
local lifted
if ntype(name) == "chain" then
lifted = { }
local new_chain
do
local _accum_0 = { }
local _len_0 = 1
for _index_0 = 3, #name do
local part = name[_index_0]
if ntype(part) == "index" then
local proxy = NameProxy("update")
table.insert(lifted, {
proxy,
part[2]
})
_accum_0[_len_0] = {
"index",
proxy
}
else
_accum_0[_len_0] = part
end
_len_0 = _len_0 + 1
end
new_chain = _accum_0
end
if next(lifted) then
name = {
name[1],
name[2],
unpack(new_chain)
}
end
end
if not (value_is_singular(exp)) then
exp = {
"parens",
exp
}
end
local out = build.assign_one(name, {
"exp",
name,
op_final,
exp
})
if lifted and next(lifted) then
local names
do
local _accum_0 = { }
local _len_0 = 1
for _index_0 = 1, #lifted do
local l = lifted[_index_0]
_accum_0[_len_0] = l[1]
_len_0 = _len_0 + 1
end
names = _accum_0
end
local values
do
local _accum_0 = { }
local _len_0 = 1
for _index_0 = 1, #lifted do
local l = lifted[_index_0]
_accum_0[_len_0] = l[2]
_len_0 = _len_0 + 1
end
values = _accum_0
end
out = build.group({
{
"assign",
names,
values
},
out
})
end
return out
end,
import = function(self, node)
local names, source = unpack(node, 2)
local table_values
do
local _accum_0 = { }
local _len_0 = 1
for _index_0 = 1, #names do
local name = names[_index_0]
local dest_name
if ntype(name) == "colon" then
dest_name = name[2]
else
dest_name = name
end
local _value_0 = {
{
"key_literal",
name
},
dest_name
}
_accum_0[_len_0] = _value_0
_len_0 = _len_0 + 1
end
table_values = _accum_0
end
local dest = {
"table",
table_values
}
return {
"assign",
{
dest
},
{
source
},
[-1] = node[-1]
}
end,
comprehension = function(self, node, action)
local exp, clauses = unpack(node, 2)
action = action or function(exp)
return {
exp
}
end
return construct_comprehension(action(exp), clauses)
end,
["do"] = function(self, node, ret)
if ret then
node[2] = transform_last_stm(node[2], ret)
end
return node
end,
decorated = function(self, node)
local stm, dec = unpack(node, 2)
local wrapped
local _exp_0 = dec[1]
if "if" == _exp_0 then
local cond, fail = unpack(dec, 2)
if fail then
fail = {
"else",
{
fail
}
}
end
wrapped = {
"if",
cond,
{
stm
},
fail
}
elseif "unless" == _exp_0 then
wrapped = {
"unless",
dec[2],
{
stm
}
}
elseif "comprehension" == _exp_0 then
wrapped = {
"comprehension",
stm,
dec[2]
}
else
wrapped = error("Unknown decorator " .. dec[1])
end
if ntype(stm) == "assign" then
wrapped = build.group({
build.declare({
names = (function()
local _accum_0 = { }
local _len_0 = 1
local _list_0 = stm[2]
for _index_0 = 1, #_list_0 do
local name = _list_0[_index_0]
if ntype(name) == "ref" then
_accum_0[_len_0] = name
_len_0 = _len_0 + 1
end
end
return _accum_0
end)()
}),
wrapped
})
end
return wrapped
end,
unless = function(self, node)
local clause = node[2]
if ntype(clause) == "assign" then
if destructure.has_destructure(clause[2]) then
error("destructure not allowed in unless assignment")
end
return build["do"]({
clause,
{
"if",
{
"not",
clause[2][1]
},
unpack(node, 3)
}
})
else
return {
"if",
{
"not",
{
"parens",
clause
}
},
unpack(node, 3)
}
end
end,
["if"] = function(self, node, ret)
if ntype(node[2]) == "assign" then
local assign, body = unpack(node, 2)
if destructure.has_destructure(assign[2]) then
local name = NameProxy("des")
body = {
destructure.build_assign(self, assign[2][1], name),
build.group(node[3])
}
return build["do"]({
build.assign_one(name, assign[3][1]),
{
"if",
name,
body,
unpack(node, 4)
}
})
else
local name = assign[2][1]
return build["do"]({
assign,
{
"if",
name,
unpack(node, 3)
}
})
end
end
node = expand_elseif_assign(node)
if ret then
smart_node(node)
node['then'] = transform_last_stm(node['then'], ret)
for i = 4, #node do
local case = node[i]
local body_idx = #node[i]
case[body_idx] = transform_last_stm(case[body_idx], ret)
end
end
return node
end,
with = function(self, node, ret)
local exp, block = unpack(node, 2)
local copy_scope = true
local scope_name, named_assign
do
local last = last_stm(block)
if last then
if types.terminating[ntype(last)] then
ret = false
end
end
end
if ntype(exp) == "assign" then
local names, values = unpack(exp, 2)
local first_name = names[1]
if ntype(first_name) == "ref" then
scope_name = first_name
named_assign = exp
exp = values[1]
copy_scope = false
else
scope_name = NameProxy("with")
exp = values[1]
values[1] = scope_name
named_assign = {
"assign",
names,
values
}
end
elseif self:is_local(exp) then
scope_name = exp
copy_scope = false
end
scope_name = scope_name or NameProxy("with")
local out = build["do"]({
copy_scope and build.assign_one(scope_name, exp) or NOOP,
named_assign or NOOP,
Run(function(self)
return self:set("scope_var", scope_name)
end),
unpack(block)
})
if ret then
table.insert(out[2], ret(scope_name))
end
return out
end,
foreach = function(self, node, _)
smart_node(node)
local source = unpack(node.iter)
local destructures = { }
do
local _accum_0 = { }
local _len_0 = 1
for i, name in ipairs(node.names) do
if ntype(name) == "table" then
do
local proxy = NameProxy("des")
insert(destructures, destructure.build_assign(self, name, proxy))
_accum_0[_len_0] = proxy
end
else
_accum_0[_len_0] = name
end
_len_0 = _len_0 + 1
end
node.names = _accum_0
end
if next(destructures) then
insert(destructures, build.group(node.body))
node.body = destructures
end
if ntype(source) == "unpack" then
local list = source[2]
local index_name = NameProxy("index")
local list_name = self:is_local(list) and list or NameProxy("list")
local slice_var = nil
local bounds
if is_slice(list) then
local slice = list[#list]
table.remove(list)
table.remove(slice, 1)
if self:is_local(list) then
list_name = list
end
if slice[2] and slice[2] ~= "" then
local max_tmp_name = NameProxy("max")
slice_var = build.assign_one(max_tmp_name, slice[2])
slice[2] = {
"exp",
max_tmp_name,
"<",
0,
"and",
{
"length",
list_name
},
"+",
max_tmp_name,
"or",
max_tmp_name
}
else
slice[2] = {
"length",
list_name
}
end
bounds = slice
else
bounds = {
1,
{
"length",
list_name
}
}
end
local names
do
local _accum_0 = { }
local _len_0 = 1
local _list_0 = node.names
for _index_0 = 1, #_list_0 do
local n = _list_0[_index_0]
_accum_0[_len_0] = is_name_proxy(n) and n or LocalName(n) or n
_len_0 = _len_0 + 1
end
names = _accum_0
end
return build.group({
list_name ~= list and build.assign_one(list_name, list) or NOOP,
slice_var or NOOP,
build["for"]({
name = index_name,
bounds = bounds,
body = {
{
"assign",
names,
{
NameProxy.index(list_name, index_name)
}
},
build.group(node.body)
}
})
})
end
node.body = with_continue_listener(node.body)
end,
["while"] = function(self, node)
smart_node(node)
node.body = with_continue_listener(node.body)
end,
["for"] = function(self, node)
smart_node(node)
node.body = with_continue_listener(node.body)
end,
switch = function(self, node, ret)
local exp, conds = unpack(node, 2)
local exp_name = NameProxy("exp")
local convert_cond
convert_cond = function(cond)
local t, case_exps, body = unpack(cond)
local out = { }
insert(out, t == "case" and "elseif" or "else")
if t ~= "else" then
local cond_exp = { }
for i, case in ipairs(case_exps) do
if i == 1 then
insert(cond_exp, "exp")
else
insert(cond_exp, "or")
end
if not (value_is_singular(case)) then
case = {
"parens",
case
}
end
insert(cond_exp, {
"exp",
case,
"==",
exp_name
})
end
insert(out, cond_exp)
else
body = case_exps
end
if ret then
body = transform_last_stm(body, ret)
end
insert(out, body)
return out
end
local first = true
local if_stm = {
"if"
}
for _index_0 = 1, #conds do
local cond = conds[_index_0]
local if_cond = convert_cond(cond)
if first then
first = false
insert(if_stm, if_cond[2])
insert(if_stm, if_cond[3])
else
insert(if_stm, if_cond)
end
end
return build.group({
build.assign_one(exp_name, exp),
if_stm
})
end,
class = require("moonscript.transform.class")
})
|
require"Engine"
Game=class({
static={
Initialize=function(self)
AssetManager:Initialize()
GraphicManager:Initialize()
SceneManager:Initialize(require("./Assets/scenes/level1/scene"))
DebugManager:Initialize()
end,
Tick=function(self,delta)
AssetManager:Tick(delta)
SceneManager:Tick(delta)
GraphicManager:Tick(delta)
DebugManager:Tick(delta)
end,
Finalize=function(self)
AssetManager:Finalize()
SceneManager:Finalize()
GraphicManager:Finalize()
DebugManager:Finalize()
end
}
})
|
local GlobalLoot = Class(function(self,inst)
self.inst = inst
self.loot = {}
self.inst:ListenForEvent("entity_death", function(world, data) self:OnEntityDeath(data) end, GetWorld())
end)
function GlobalLoot:AddGlobalLoot(data)
table.insert(self.loot, data)
end
function GlobalLoot:OnEntityDeath(data)
for k,v in pairs(self.loot) do
local canDrop = true
if v.candropfn and not v.candropfn(data.inst, v.loot) then
canDrop = false
end
if v.droppers and not table.contains(v.droppers, data.inst.prefab) then
canDrop = false
end
if canDrop then
if math.random() < v.dropchance then
data.inst.components.lootdropper:SpawnLootPrefab(v.loot)
end
end
end
end
return GlobalLoot
|
function sysCall_init()
-- do some initialization here:
-- Make sure you read the section on "Accessing general-type objects programmatically"
-- For instance, if you wish to retrieve the handle of a scene object, use following instruction:
--
-- handle=sim.getObjectHandle('sceneObjectName')
--
-- Above instruction retrieves the handle of 'sceneObjectName' if this script's name has no '#' in it
--
-- If this script's name contains a '#' (e.g. 'someName#4'), then above instruction retrieves the handle of object 'sceneObjectName#4'
-- This mechanism of handle retrieval is very convenient, since you don't need to adjust any code when a model is duplicated!
-- So if the script's name (or rather the name of the object associated with this script) is:
--
-- 'someName', then the handle of 'sceneObjectName' is retrieved
-- 'someName#0', then the handle of 'sceneObjectName#0' is retrieved
-- 'someName#1', then the handle of 'sceneObjectName#1' is retrieved
-- ...
--
-- If you always want to retrieve the same object's handle, no matter what, specify its full name, including a '#':
--
-- handle=sim.getObjectHandle('sceneObjectName#') always retrieves the handle of object 'sceneObjectName'
-- handle=sim.getObjectHandle('sceneObjectName#0') always retrieves the handle of object 'sceneObjectName#0'
-- handle=sim.getObjectHandle('sceneObjectName#1') always retrieves the handle of object 'sceneObjectName#1'
-- ...
--
-- Refer also to sim.getCollisionhandle, sim.getDistanceHandle, sim.getIkGroupHandle, etc.
end
|
local combat = Combat()
combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_EARTHDAMAGE)
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_SMALLPLANTS)
combat:setParameter(COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_EARTH)
local condition = Condition(CONDITION_POISON)
condition:setParameter(CONDITION_PARAM_DELAYED, 1)
condition:addDamage(25, 3000, -45)
combat:addCondition(condition)
local spell = Spell("instant")
function spell.onCastSpell(creature, var)
return combat:execute(creature, var)
end
spell:group("attack")
spell:id(142)
spell:name("Envenom")
spell:words("utori pox")
spell:level(50)
spell:mana(30)
spell:range(3)
spell:isAggressive(true)
spell:needTarget(true)
spell:blockWalls(true)
spell:cooldown(40 * 1000)
spell:groupCooldown(2 * 1000)
spell:needLearn(false)
spell:vocation("druid;true", "elder druid;true")
spell:register()
|
local syntax = require "core.syntax"
syntax.add {
files = {"%.fountain$"},
patterns = {
{ pattern = {"/%*", "%*/"}, type = "comment" }, -- this is the boneyard
{ regex = "^\\s*!\\s*.+", type = "normal"},
{ regex = "^\\s*~\\s*.+", type = "lyrics" },
{ pattern = {"%(", "%)"}, type = "parenthetical" },
{ pattern = {"_", "_"}, type = "underline" },
{ pattern = {"%*", "%*"}, type = "italic" },
{ pattern = {"%*%*", "%*%*"}, type = "bold" },
{ pattern = {"%[%[", "%]%]"}, type = "note"},
{ pattern = "^===+", type = "linebreak" },
{ regex = {"^\\s*[iIeE][nNxX][tT].*?\\n", "^\n"}, type = "heading" }, -- yes, this will detect "ixt." and "ent." but I don't care
{ regex = "^\\s*\\..*", type = "heading" },
{ regex = "^\\s*[A-Z\\s]*\\s+TO:\\s*$", type = "transition"},
{ regex = "^\\s*>[^<]*$", type = "transition" },
{ pattern = {">%s*", "%s*[<%c]"}, type = "center" },
{ regex = {"^\\s*[A-Z\\.\\s^]+\\s*(\\(.*?\\))?\\s*\n", "^\n"}, type = "character" },
{ regex = {"^\\s*@", "^\n"}, type = "character" },
},
symbols = {}
}
|
local conf = require("configuration")
local current_version = 010204 -- 1.2.4
---@param player LuaPlayer
local function reset_gui(player)
local root = player.gui.left["mpp_settings_frame"] or player.gui.screen["mpp_settings_frame"]
if root then
root.destroy()
end
local cursor_stack = player.cursor_stack
if cursor_stack and cursor_stack.valid and cursor_stack.valid_for_read and cursor_stack.name == "mining-patch-planner" then
cursor_stack.clear()
end
end
script.on_configuration_changed(function(config_changed_data)
if config_changed_data.mod_changes["mining-patch-planner"] then
local version = global.version or 0
if version < current_version then
global.tasks = global.tasks or {}
conf.initialize_deconstruction_filter()
for player_index, data in ipairs(global.players) do
---@type LuaPlayer
local player = game.players[player_index]
reset_gui(player)
conf.initialize_global(player_index)
end
end
global.version = current_version
else
for player_index, data in ipairs(global.players) do
reset_gui(game.players[player_index])
end
end
end)
|
local F, C = unpack(select(2, ...))
C.themes["Blizzard_ItemUpgradeUI"] = function()
local ItemUpgradeFrame = ItemUpgradeFrame
F.ReskinPortraitFrame(ItemUpgradeFrame)
local itemButton = ItemUpgradeFrame.ItemButton
itemButton.bg = F.CreateBDFrame(itemButton, .25)
itemButton.Frame:SetTexture("")
itemButton:SetPushedTexture("")
local hl = itemButton:GetHighlightTexture()
hl:SetColorTexture(1, 1, 1, .25)
hooksecurefunc("ItemUpgradeFrame_Update", function()
local icon, _, quality = GetItemUpgradeItemInfo()
if icon then
itemButton.IconTexture:SetTexCoord(.08, .92, .08, .92)
local color = BAG_ITEM_QUALITY_COLORS[quality or 1]
itemButton.bg:SetBackdropBorderColor(color.r, color.g, color.b)
else
itemButton.IconTexture:SetTexture("")
itemButton.bg:SetBackdropBorderColor(0, 0, 0)
end
end)
local textFrame = ItemUpgradeFrame.TextFrame
F.StripTextures(textFrame)
local bg = F.CreateBDFrame(textFrame, .25)
bg:SetPoint("TOPLEFT", itemButton.IconTexture, "TOPRIGHT", 3, C.mult)
bg:SetPoint("BOTTOMRIGHT", -6, 2)
F.StripTextures(ItemUpgradeFrame.ButtonFrame)
F.StripTextures(ItemUpgradeFrameMoneyFrame)
F.ReskinIcon(ItemUpgradeFrameMoneyFrame.Currency.icon)
F.Reskin(ItemUpgradeFrameUpgradeButton)
end
|
return {
size = { w = 9, h = 11 },
cells = {
{0,0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,1,1},
{1,0,0,0,1,0,0,0,1},
{1,0,1,1,1,1,1,0,1},
{1,0,1,0,1,0,1,0,1},
{1,1,1,1,1,1,1,1,1},
{1,0,1,0,1,0,1,0,1},
{1,0,1,1,1,1,1,0,1},
{1,0,0,0,1,0,0,0,1},
{1,1,1,1,1,1,1,1,1},
{0,0,0,0,0,0,0,0,0},
},
start_position = { x = 5, y = 6 },
start_shape = 'triangle',
enemies = {
{ shape = 'hexagon',
position = { x = 3, y = 6 }
},
{ shape = 'square',
position = { x = 7, y = 6 }
},
{ shape = 'pentagon',
position = { x = 3, y = 8 }
},
{ shape = 'circle',
position = { x = 5, y = 4 }
},
{ shape = 'pentagon',
position = { x = 7, y = 4 }
},
{ shape = 'circle',
position = { x = 1, y = 10 }
},
{ shape = 'triangle',
position = { x = 5, y = 10 }
},
{ shape = 'circle',
position = { x = 9, y = 10 }
},
{ shape = 'triangle',
position = { x = 9, y = 6 }
},
{ shape = 'triangle',
position = { x = 1, y = 2 }
},
{ shape = 'square',
position = { x = 5, y = 2 }
},
{ shape = 'triangle',
position = { x = 9, y = 2 }
},
},
intermission = {
background = 'shape_hexagon.png',
s_color = {96/256, 122/256, 143/256, 0},
o_color = {212/256, 8/256, 8/256, 0},
dialog = {
"<other>Your lack of vision is disturbing, Shape.</>",
"<other>Don't you see what we're trying to accomplish?</>",
"<shape>You're trying to blow up the world like a bunch of maniacs.</>",
"<other>That extremely shortsighted, Shape.</>",
"<other>We're going to usher a new era!</>",
"<other>Literally change the <big>shape</> of the world!</>",
"<shape>And what about those who don't want to change?</>",
"<other>They will be vanquished!</>",
"<shape>Not if I can stop it!</>",
"<other>Then come, Shape. Come.</>",
"<other>I was looking for a challenge.</>"
}
}
}
|
local folderOfThisFile = (...):match("(.-)[^%/%.]+$")
local class = require(folderOfThisFile.."/middleclass")
local Stack = class("Stack")
function Stack:init()
self._s = {}
end
function Stack:size()
return #self._s
end
function Stack:pop()
return table.remove(self._s, self:size())
end
function Stack:push(item)
table.insert(self._s, item)
end
return Stack
|
local playerService = game:GetService("Players")
local dataMod = require(script.Parent.Data)
local spawnParts = workspace.SpawnParts
local initializeMod = {}
local function getStage(stageNum)
for _, stagePart in pairs(spawnParts:GetChildren()) do
if stagePart:GetAttribute("Stage") == stageNum then
return stagePart
end
end
end
playerService.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(char)
char:WaitForChild("HumanoidRootPart")
initializeMod.givePremiumTools(player)
local stageNum = dataMod.get(player, "Stage")
local spawnPoint = getStage(stageNum)
task.wait()
char:SetPrimaryPartCFrame(spawnPoint.CFrame * CFrame.new(0,3,0))
end)
end)
local collectionService = game:GetService("CollectionService")
local marketService = game:GetService("MarketplaceService")
local monetization = require(script.Parent.Monetization)
local toolPasses = {}
initializeMod.givePremiumTools = function(player)
for _, passId in pairs(toolPasses) do
local key = player.UserId
local ownsPass = monetization.ownsPass(key, passId)
local hasTag = collectionService:HasTag(player, passId)
if hasTag or ownsPass then
monetization[passId](player)
end
end
end
return initializeMod
|
local S = aurum.get_translator()
aurum.magic.register_spell("summon_psyche_flare", {
description = S"Summon Psyche Flare",
max_level = 3,
apply_requirements = function(pointed_thing)
return not not minetest.get_pointed_thing_position(pointed_thing)
end,
apply = function(pointed_thing, level, player)
local object = aurum.mobs.spawn(minetest.get_pointed_thing_position(pointed_thing), "aurum_mobs_monsters:psyche_flare")
if object then
local data = object:get_luaentity()._data.gemai
data.attack.damage.psyche = 5 * level
data.parent = b.ref_to_table(player)
data.herd = "player:" .. player:get_player_name()
return true
end
return false
end,
})
|
-- Copyright 2011-2012 Nils Nordman <nino at nordman.org>
-- Copyright 2012-2014 Robert Gieseke <rob.g@web.de>
-- License: MIT (see LICENSE)
--[[
This example shows how to use the list with multi column items. It also
illustrates the optional use of headers, as well as the fact that the
`on_selection` callback will be passed the item exactly as it was given
which lets you use any arbitrary field in the selection logic.
]]
local M = {}
local textredux = require 'textredux'
local reduxstyle = textredux.core.style
local function on_selection(list, item)
-- We will get back exactly what we specified, so the code below will print
-- the IDs we specify further down (1, 2 or 3)
ui.statusbar_text = 'You selected ' .. item.id
end
function M.show_multi_column_list()
local list = textredux.core.list.new('Multi column list')
-- Set the headers. This is optional and can be skipped if so desired
list.headers = { 'Thing', 'Is' }
-- List of multi column items, with additional named fields
list.items = {
{'Volvo', 'Vehicle', id = 1},
{'Dog', 'Animal', id = 2},
{'Hell','Other people', id = 3}
}
list.column_styles = {reduxstyle.number, reduxstyle.operator}
list.on_selection = on_selection
list:show()
end
return M
|
data:extend({
{
type = "technology",
name = "toolbelt-2",
icon = "__base__/graphics/technology/toolbelt.png",
effects =
{
{
type = "num-quick-bars",
modifier = 1
}
},
prerequisites = {"toolbelt"},
unit =
{
count = 150,
ingredients =
{
{"science-pack-1", 1},
{"science-pack-2", 1}
},
time = 30
},
order = "c-k-m"
},
{
type = "technology",
name = "toolbelt-3",
icon = "__base__/graphics/technology/toolbelt.png",
effects =
{
{
type = "num-quick-bars",
modifier = 1
}
},
prerequisites = {"toolbelt-2"},
unit =
{
count = 150,
ingredients =
{
{"science-pack-1", 1},
{"science-pack-2", 1}
},
time = 30
},
order = "c-k-m"
},
})
|
local ScrollingDirection = import("../Enum/ScrollingDirection")
local ScrollBarInset = import("../Enum/ScrollBarInset")
local VerticalScrollBarPosition = import("../Enum/VerticalScrollBarPosition")
local GuiObject = import("./GuiObject")
local InstanceProperty = import("../InstanceProperty")
local UDim2 = import("../types/UDim2")
local Vector2 = import("../types/Vector2")
local ScrollingFrame = GuiObject:extend("ScrollingFrame", {
creatable = true,
})
ScrollingFrame.properties.AbsoluteWindowSize = InstanceProperty.readOnly({
get = function(self)
local size = self.AbsoluteSize
local thickness = self.ScrollBarThickness
local marginX = 0
local marginY = 0
if self:_canScrollHorizontal() then
marginX = thickness
end
if self:_canScrollVertical() then
marginY = thickness
end
return Vector2.new(
math.max(0, size.X - marginX),
math.max(0, size.Y - marginY)
)
end,
})
ScrollingFrame.properties.CanvasPosition = InstanceProperty.typed("Vector2", {
getDefault = function()
return Vector2.new()
end,
})
ScrollingFrame.properties.CanvasSize = InstanceProperty.typed("UDim2", {
getDefault = function()
return UDim2.new()
end,
})
ScrollingFrame.properties.ScrollBarThickness = InstanceProperty.typed("number", {
getDefault = function()
return 12
end,
})
ScrollingFrame.properties.ScrollingDirection = InstanceProperty.enum(ScrollingDirection, {
getDefault = function()
return ScrollingDirection.XY
end,
})
ScrollingFrame.properties.ScrollingEnabled = InstanceProperty.typed("boolean", {
getDefault = function()
return true
end,
})
ScrollingFrame.properties.VerticalScrollBarInset = InstanceProperty.enum(ScrollBarInset, {
getDefault = function()
return ScrollBarInset.None
end,
})
ScrollingFrame.properties.VerticalScrollBarPosition = InstanceProperty.enum(VerticalScrollBarPosition, {
getDefault = function()
return VerticalScrollBarPosition.Right
end,
})
function ScrollingFrame.prototype:_canScrollHorizontal()
local scrollDir = self.ScrollingDirection
return self.ScrollingEnabled and
(scrollDir == ScrollingDirection.X or
scrollDir == ScrollingDirection.XY)
end
function ScrollingFrame.prototype:_canScrollVertical()
local scrollDir = self.ScrollingDirection
return self.ScrollingEnabled and
(scrollDir == ScrollingDirection.Y or
scrollDir == ScrollingDirection.XY)
end
return ScrollingFrame
|
id = 'V-38473'
severity = 'low'
weight = 10.0
title = 'The system must use a separate file system for user home directories.'
description = 'Ensuring that "/home" is mounted on its own partition enables the setting of more restrictive mount options, and also helps ensure that users cannot trivially fill partitions used for log or audit data storage.'
fixtext = 'If user home directories will be stored locally, create a separate partition for "/home" at installation time (or migrate it later using LVM). If "/home" will be mounted from another system such as an NFS server, then creating a separate partition is not necessary at installation time, and the mountpoint can instead be configured later.'
checktext = [=[Run the following command to determine if "/home" is on its own partition or logical volume:
$ mount | grep "on /home "
If "/home" has its own partition or volume group, a line will be returned.
If no line is returned, this is a finding.]=]
function test()
end
function fix()
end
|
--
-- created with TexturePacker (http://www.codeandweb.com/texturepacker)
--
-- $TexturePacker:SmartUpdate:7074c7415c306dddc6a06d689bb50f6b:80c2cc27212c0fb58d9ee62e7dfb33ab:2c81e27ca2ed04347d4c1025c5eca84f$
--
-- local sheetInfo = require("mysheet")
-- local myImageSheet = graphics.newImageSheet( "mysheet.png", sheetInfo:getSheet() )
-- local sprite = display.newSprite( myImageSheet , {frames={sheetInfo:getFrameIndex("sprite")}} )
--
local SheetInfo = {}
SheetInfo.sheet =
{
frames = {
{
-- 1024tree00
x=0,
y=0,
width=906,
height=1024,
sourceX = 59,
sourceY = 0,
sourceWidth = 1024,
sourceHeight = 1024
},
{
-- 128cloud00
x=0,
y=1916,
width=128,
height=105,
sourceX = 0,
sourceY = 12,
sourceWidth = 128,
sourceHeight = 128
},
{
-- 2048hills00
x=0,
y=1024,
width=2048,
height=636,
sourceX = 0,
sourceY = 388,
sourceWidth = 2048,
sourceHeight = 1024
},
{
-- 2048hills01
x=2048,
y=0,
width=2048,
height=550,
sourceX = 0,
sourceY = 474,
sourceWidth = 2048,
sourceHeight = 1024
},
{
-- 2048hills02
x=2048,
y=550,
width=2048,
height=424,
sourceX = 0,
sourceY = 600,
sourceWidth = 2048,
sourceHeight = 1024
},
{
-- 256cloud00
x=460,
y=1660,
width=256,
height=209,
sourceX = 0,
sourceY = 24,
sourceWidth = 256,
sourceHeight = 256
},
{
-- 256house00
x=0,
y=1660,
width=233,
height=256,
sourceX = 12,
sourceY = 0,
sourceWidth = 256,
sourceHeight = 256
},
{
-- 256tree00
x=233,
y=1660,
width=227,
height=256,
sourceX = 15,
sourceY = 0,
sourceWidth = 256,
sourceHeight = 256
},
{
-- 512tree00
x=906,
y=0,
width=454,
height=512,
sourceX = 29,
sourceY = 0,
sourceWidth = 512,
sourceHeight = 512
},
},
sheetContentWidth = 4096,
sheetContentHeight = 2048
}
SheetInfo.frameIndex =
{
["1024tree00"] = 1,
["128cloud00"] = 2,
["2048hills00"] = 3,
["2048hills01"] = 4,
["2048hills02"] = 5,
["256cloud00"] = 6,
["256house00"] = 7,
["256tree00"] = 8,
["512tree00"] = 9,
}
function SheetInfo:getSheet()
return self.sheet;
end
function SheetInfo:getFrameIndex(name)
return self.frameIndex[name];
end
return SheetInfo
|
local ArchetypeManager = BaseClass()
ECS.ArchetypeManager = ArchetypeManager
function ArchetypeManager:Constructor( sharedComponentManager )
self.m_SharedComponentManager = sharedComponentManager
self.m_TypeLookup = {}
self.m_EmptyChunkPool = ECS.UnsafeLinkedListNode.New()
ECS.UnsafeLinkedListNode.InitializeList(self.m_EmptyChunkPool)
end
-- local GetHash = function ( componentTypeInArchetypes )
-- local hash = HashUtility.Fletcher32(componentTypeInArchetypes,
-- #componentTypeInArchetypes * sizeof(ComponentTypeInArchetype) / sizeof(ushort))
-- return hash
-- end
local GetTypesStr = function ( types, count )
local names = {}
for i=1,count do
table.insert(names, ECS.TypeManager.GetTypeNameByIndex(types[i].TypeIndex))
end
table.sort(names)
return table.concat(names, ":")
end
ArchetypeManager.GetTypesStr = GetTypesStr
function ArchetypeManager:GetOrCreateArchetypeInternal( types, count, groupManager )
local type = self:GetExistingArchetype(types, count)
return type~=nil and type or self:CreateArchetypeInternal(types, count, groupManager)
end
function ArchetypeManager:GetExistingArchetype( types, count )
local type_str = GetTypesStr(types, count)
return self.m_TypeLookup[type_str]
end
function ArchetypeManager:GetOrCreateArchetype( types, count, groupManager )
local srcArchetype = self:GetOrCreateArchetypeInternal(types, count, groupManager)
-- local removedTypes = 0
-- local prefabTypeIndex = ECS.TypeManager.GetTypeIndexByName("Prefab")
-- for t=1,srcArchetype.TypesCount do
-- local type = srcArchetype.Types[t]
-- -- local skip = type.IsSystemStateComponent or type.IsSystemStateSharedComponent or (type.TypeIndex == prefabTypeIndex)
-- -- if skip then
-- -- removedTypes = removedTypes + 1
-- -- else
-- types[t - removedTypes] = srcArchetype.Types[t]
-- -- end
-- end
-- srcArchetype.InstantiableArchetype = srcArchetype
-- if removedTypes > 0 then
-- local instantiableArchetype = self:GetOrCreateArchetypeInternal(types, count-removedTypes, groupManager)
-- srcArchetype.InstantiableArchetype = instantiableArchetype
-- instantiableArchetype.InstantiableArchetype = instantiableArchetype
-- end
return srcArchetype
end
function ArchetypeManager:CreateArchetypeInternal( types, count, groupManager )
local type = {}
type.TypesCount = count
type.Types = types--should be deepcopy
type.EntityCount = 0
type.ChunkCount = 0
type.NumSharedComponents = 0
type.SharedComponentOffset = nil
-- local disabledTypeIndex = ECS.TypeManager.GetTypeIndex("Disabled")
-- local prefabTypeIndex = ECS.TypeManager.GetTypeIndex("Prefab>")
-- type.Disabled = false
-- type.Prefab = false
-- for i=1,count do
-- if (ECS.TypeManager.GetTypeInfo(types[i].TypeIndex).Category == ECS.TypeManager.TypeCategory.ISharedComponentData) then
-- type.NumSharedComponents = type.NumSharedComponents + 1
-- end
-- if (types[i].TypeIndex == disabledTypeIndex) then
-- type.Disabled = true
-- end
-- if (types[i].TypeIndex == prefabTypeIndex) then
-- type.Prefab = true
-- end
-- end
local scalarEntityPatchCount = 0
local bufferEntityPatchCount = 0
for i=1,count do
local ct = ECS.TypeManager.GetTypeInfoByIndex(types[i].TypeIndex)
local entityOffsets = ct.EntityOffsets
if (entityOffsets ~= nil) then
if (ct.BufferCapacity >= 0) then
bufferEntityPatchCount = bufferEntityPatchCount + entityOffsets.Length
else
scalarEntityPatchCount = scalarEntityPatchCount + entityOffsets.Length
end
end
end
local chunkDataSize = ECS.Chunk.GetChunkBufferSize(type.TypesCount, type.NumSharedComponents)
type.Offsets = {}
type.SizeOfs = {}
type.TypeMemoryOrder = {}
type.ScalarEntityPatches = {}
type.ScalarEntityPatchCount = scalarEntityPatchCount
type.BufferEntityPatches = {}
type.BufferEntityPatchCount = bufferEntityPatchCount
local bytesPerInstance = 0
for i=1,count do
local cType = ECS.TypeManager.GetTypeInfoByIndex(types[i].TypeIndex)
local sizeOf = cType.SizeInChunk
type.SizeOfs[i] = sizeOf
bytesPerInstance = bytesPerInstance + sizeOf
end
type.ChunkCapacity = math.floor(chunkDataSize / bytesPerInstance)
local memoryOrderings = {}
for i=1,count do
memoryOrderings[i] = ECS.TypeManager.GetTypeInfoByIndex(types[i].TypeIndex).MemoryOrdering
end
for i=1,count do
local index = i
while (index > 1 and memoryOrderings[i] < memoryOrderings[type.TypeMemoryOrder[index - 1]]) do
type.TypeMemoryOrder[index] = type.TypeMemoryOrder[index - 1]
index = index - 1
end
type.TypeMemoryOrder[index] = i
end
local usedBytes = 0
for i=1,count do
local index = type.TypeMemoryOrder[i]
local sizeOf = type.SizeOfs[index]
type.Offsets[index] = usedBytes
usedBytes = usedBytes + sizeOf * type.ChunkCapacity
end
type.NumManagedArrays = 0
type.ManagedArrayOffset = null
for i=1,count do
if (ECS.TypeManager.GetTypeInfoByIndex(types[i].TypeIndex).Category == ECS.TypeManager.TypeCategory.Class) then
type.NumManagedArrays = type.NumManagedArrays + 1
end
end
if (type.NumManagedArrays > 0) then
type.ManagedArrayOffset = self.m_ArchetypeChunkAllocator.Allocate(sizeof(int) * count, 4)
local mi = 0
for i=1,count do
local index = type.TypeMemoryOrder[i]
local cType = ECS.TypeManager.GetTypeInfoByIndex(types[index].TypeIndex)
if (cType.Category == ECS.TypeManager.TypeCategory.Class) then
type.ManagedArrayOffset[index] = mi
mi = mi + 1
else
type.ManagedArrayOffset[index] = -1
end
end
end
if (type.NumSharedComponents > 0) then
type.SharedComponentOffset = self.m_ArchetypeChunkAllocator.Allocate(sizeof(int) * count, 4)
local mi = 0
for i=1,count do
local index = type.TypeMemoryOrder[i]
local cType = ECS.TypeManager.GetTypeInfoByIndex(types[index].TypeIndex)
if (cType.Category == ECS.TypeManager.TypeCategory.ISharedComponentData) then
type.SharedComponentOffset[index] = mi
mi = mi + 1
else
type.SharedComponentOffset[index] = -1
end
end
end
-- local scalarPatchInfo = type.ScalarEntityPatches
-- local bufferPatchInfo = type.BufferEntityPatches
-- for i=1,count do
-- local ct = ECS.TypeManager.GetTypeInfoByIndex(types[i].TypeIndex)
-- local offsets = ct.EntityOffsets
-- if (ct.BufferCapacity >= 0) then
-- bufferPatchInfo = EntityRemapUtility.AppendBufferEntityPatches(bufferPatchInfo, offsets, type.Offsets[i], type.SizeOfs[i], ct.ElementSize);
-- else
-- scalarPatchInfo = EntityRemapUtility.AppendEntityPatches(scalarPatchInfo, offsets, type.Offsets[i], type.SizeOfs[i]);
-- end
-- end
-- type.ScalarEntityPatchCount = scalarEntityPatchCount
-- type.BufferEntityPatchCount = bufferEntityPatchCount
type.PrevArchetype = self.m_LastArchetype
self.m_LastArchetype = type
type.ChunkList = ECS.UnsafeLinkedListNode.New()
type.ChunkListWithEmptySlots = ECS.UnsafeLinkedListNode.New()
ECS.UnsafeLinkedListNode.InitializeList(type.ChunkList)
ECS.UnsafeLinkedListNode.InitializeList(type.ChunkListWithEmptySlots)
-- type.FreeChunksBySharedComponents.Init(8)
-- m_TypeLookup.Add(GetHash(types, count), type)
local type_str = GetTypesStr(types, count)
self.m_TypeLookup[type_str] = type
-- type.SystemStateCleanupComplete = ArchetypeSystemStateCleanupComplete(type)
-- type.SystemStateCleanupNeeded = ArchetypeSystemStateCleanupNeeded(type)
groupManager:AddArchetypeIfMatching(type)
return type
end
function ArchetypeManager:AddExistingChunk( chunk )
local archetype = chunk.Archetype
archetype.ChunkList.Add(chunk.ChunkListNode)
archetype.ChunkCount = archetype.ChunkCount + 1
archetype.EntityCount = archetype.EntityCount + chunk.Count
for var=1,archetype.NumSharedComponents do
m_SharedComponentManager.AddReference(chunk.SharedComponentValueArray[i])
end
if (chunk.Count < chunk.Capacity) then
if (archetype.NumSharedComponents == 0) then
archetype.ChunkListWithEmptySlots.Add(chunk.ChunkListWithEmptySlotsNode)
else
archetype.FreeChunksBySharedComponents.Add(chunk)
end
end
end
function ArchetypeManager:ConstructChunk( archetype, chunk, sharedComponentDataIndices )
chunk.Archetype = archetype
chunk.Count = 0
chunk.Capacity = archetype.ChunkCapacity
chunk.ChunkListNode = ECS.UnsafeLinkedListNode.New()
chunk.ChunkListNode:SetChunk(chunk)
chunk.ChunkListWithEmptySlotsNode = ECS.UnsafeLinkedListNode.New()
chunk.ChunkListWithEmptySlotsNode:SetChunk(chunk)
local numSharedComponents = archetype.NumSharedComponents
local numTypes = archetype.TypesCount
local sharedComponentOffset = ECS.Chunk.GetSharedComponentOffset(numSharedComponents)
local changeVersionOffset = ECS.Chunk.GetChangedComponentOffset(numTypes, numSharedComponents)
-- chunk.SharedComponentValueArray = (chunk + sharedComponentOffset)
-- chunk.ChangeVersion = (chunk + changeVersionOffset)
archetype.ChunkList:Add(chunk.ChunkListNode)
archetype.ChunkCount = archetype.ChunkCount+1
-- Assert.IsTrue(!archetype.ChunkList.IsEmpty)
-- Assert.IsTrue(chunk == (Chunk*) archetype.ChunkList.Back)
if (numSharedComponents == 0) then
archetype.ChunkListWithEmptySlots:Add(chunk.ChunkListWithEmptySlotsNode)
-- Assert.IsTrue(chunk == GetChunkFromEmptySlotNode(archetype.ChunkListWithEmptySlots.Back))
-- Assert.IsTrue(!archetype.ChunkListWithEmptySlots.IsEmpty)
else
local sharedComponentValueArray = chunk.SharedComponentValueArray
UnsafeUtility.MemCpy(sharedComponentValueArray, sharedComponentDataIndices, archetype.NumSharedComponents*sizeof(int))
for i=1,archetype.NumSharedComponents do
local sharedComponentIndex = sharedComponentValueArray[i]
m_SharedComponentManager.AddReference(sharedComponentIndex)
end
archetype.FreeChunksBySharedComponents.Add(chunk)
-- Assert.IsTrue(archetype.FreeChunksBySharedComponents.GetChunkWithEmptySlots(sharedComponentDataIndices, archetype.NumSharedComponents) ~= nil)
end
if archetype.NumManagedArrays > 0 then
chunk.ManagedArrayIndex = AllocateManagedArrayStorage(archetype.NumManagedArrays * chunk.Capacity)
else
chunk.ManagedArrayIndex = -1
end
-- for i=1,archetype.TypesCount do
-- chunk.ChangeVersion[i] = 0
-- end
end
function ArchetypeManager:AllocateIntoChunk( chunk, count )
count = count or 1
local allocatedCount = math.min(chunk.Capacity - chunk.Count, count)
local newChunkIndex = chunk.Count+1
self:SetChunkCount(chunk, chunk.Count + allocatedCount)
chunk.Archetype.EntityCount = chunk.Archetype.EntityCount + allocatedCount
return allocatedCount, newChunkIndex
end
function ArchetypeManager:SetChunkCount( chunk, newCount )
-- Assert.AreNotEqual(newCount, chunk.Count);
local capacity = chunk.Capacity
-- Chunk released to empty chunk pool
if newCount == 0 then
-- Remove references to shared components
-- if (chunk.Archetype.NumSharedComponents > 0) then
-- local sharedComponentValueArray = chunk.SharedComponentValueArray
-- for i=1,chunk.Archetype.NumSharedComponents do
-- self.m_SharedComponentManager.RemoveReference(sharedComponentValueArray[i])
-- end
-- end
-- if (chunk.ManagedArrayIndex ~= -1) then
-- DeallocateManagedArrayStorage(chunk.ManagedArrayIndex)
-- chunk.ManagedArrayIndex = -1
-- end
chunk.Archetype.ChunkCount = chunk.Archetype.ChunkCount - 1
chunk.Archetype = nil
chunk.ChunkListNode:Remove()
chunk.ChunkListWithEmptySlotsNode:Remove()
self.m_EmptyChunkPool:Add(chunk.ChunkListNode)
-- Chunk is now full
elseif (newCount == capacity) then
chunk.ChunkListWithEmptySlotsNode:Remove()
-- Chunk is no longer full
elseif (chunk.Count == capacity) then
-- Assert.IsTrue(newCount < chunk.Count)
if (chunk.Archetype.NumSharedComponents == 0) then
chunk.Archetype.ChunkListWithEmptySlots:Add(chunk.ChunkListWithEmptySlotsNode)
else
chunk.Archetype.FreeChunksBySharedComponents:Add(chunk)
end
end
chunk.Count = newCount
end
function ArchetypeManager:GetChunkFromEmptySlotNode( node )
return node and node:GetChunk()
end
function ArchetypeManager:GetChunkWithEmptySlots( archetype, sharedComponentDataIndices )
if archetype.NumSharedComponents == 0 then
if not archetype.ChunkListWithEmptySlots:IsEmpty() then
local chunk = self:GetChunkFromEmptySlotNode(archetype.ChunkListWithEmptySlots:Begin())
-- Assert.AreNotEqual(chunk.Count, chunk.Capacity)
return chunk
end
else
local chunk = archetype.FreeChunksBySharedComponents:GetChunkWithEmptySlots(sharedComponentDataIndices,
archetype.NumSharedComponents)
if chunk ~= nil then
return chunk
end
end
-- Try existing archetype chunks
if not archetype.ChunkListWithEmptySlots.IsEmpty then
if self.lastChunkWithSharedComponentsAllocatedInto ~= nil
and self.lastChunkWithSharedComponentsAllocatedInto.Archetype == archetype
and self.lastChunkWithSharedComponentsAllocatedInto.Count < self.lastChunkWithSharedComponentsAllocatedInto.Capacity then
if self:ChunkHasSharedComponents(self.lastChunkWithSharedComponentsAllocatedInto, sharedComponentDataIndices) then
return self.lastChunkWithSharedComponentsAllocatedInto
end
end
if archetype.NumSharedComponents == 0 then
local chunk = self:GetChunkFromEmptySlotNode(archetype.ChunkListWithEmptySlots:Begin())
-- Assert.AreNotEqual(chunk.Count, chunk.Capacity)
return chunk
end
end
local newChunk
-- Try empty chunk pool
if not self.m_EmptyChunkPool or self.m_EmptyChunkPool:IsEmpty() then
-- Allocate new chunk
newChunk = ECS.Chunk.New()
else
newChunk = self.m_EmptyChunkPool:Begin()
newChunk.ChunkListNode.Remove()
end
self:ConstructChunk(archetype, newChunk, sharedComponentDataIndices)
if archetype.NumSharedComponents > 0 then
self.lastChunkWithSharedComponentsAllocatedInto = newChunk
end
return newChunk
end
return ArchetypeManager
|
--捕食植物アンブロメリドゥス
--
--Script by JSY1728
function c101108037.initial_effect(c)
--Fusion Material
c:EnableReviveLimit()
aux.AddFusionProcFunRep(c,aux.FilterBoolFunction(Card.IsFusionSetCard,0x10f3),2,true)
--To Hand
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(101108037,0))
e1:SetCategory(CATEGORY_SEARCH+CATEGORY_TOHAND)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCountLimit(1,101108037)
e1:SetCondition(c101108037.thcon)
e1:SetTarget(c101108037.thtg)
e1:SetOperation(c101108037.thop)
c:RegisterEffect(e1)
--Special Summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(101108037,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_RELEASE)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,101108037+100)
e2:SetTarget(c101108037.sptg)
e2:SetOperation(c101108037.spop)
c:RegisterEffect(e2)
end
function c101108037.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsSummonType(SUMMON_TYPE_FUSION)
end
function c101108037.thfilter(c)
return c:IsAbleToHand() and c:IsSetCard(0xf3) and (not c:IsType(TYPE_MONSTER) or c:IsSetCard(0x10f3)) and (c:IsFaceup() or not c:IsLocation(LOCATION_EXTRA))
end
function c101108037.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c101108037.thfilter,tp,LOCATION_DECK+LOCATION_GRAVE+LOCATION_EXTRA,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,1,nil,tp,LOCATION_DECK+LOCATION_GRAVE+LOCATION_EXTRA)
end
function c101108037.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c101108037.thfilter,tp,LOCATION_DECK+LOCATION_GRAVE+LOCATION_EXTRA,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function c101108037.relfilter(c,tp)
return c:IsReleasableByEffect() and (c:GetCounter(0x1041)>0 or c:IsControler(tp)) and Duel.GetMZoneCount(tp,c)>0
end
function c101108037.spfilter(c,e,tp)
return c:IsSetCard(0x10f3) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c101108037.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c101108037.relfilter(chkc,tp) end
if chk==0 then return Duel.IsExistingTarget(c101108037.relfilter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil,tp)
and Duel.IsExistingMatchingCard(c101108037.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE)
local g=Duel.SelectTarget(tp,c101108037.relfilter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c101108037.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and not tc:IsImmuneToEffect(e)
and Duel.Release(tc,REASON_EFFECT)>0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c101108037.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if #g>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
end
|
local r = require('rethinkdb')
describe('control', function()
local reql_db, reql_table, c
reql_table = 'func'
setup(function()
reql_db = 'control'
local err
c, err = r.connect()
if err then error(err.message) end
r.db_create(reql_db):run(c)
c:use(reql_db)
r.table_create(reql_table):run(c)
end)
after_each(function()
r.table(reql_table):delete():run(c)
end)
function test(name, query, res)
it(name, function()
assert.same(res, query:run(
c, function(err, cur)
if err then error(err.message) end
return cur:to_array(function(err, arr)
if err then error(err.message) end
return arr
end)
end
))
end)
end
function test_error(name, query, res)
it(name, function()
assert.has_error(
function()
query:run(
c, function(err, cur)
if err then error(err.message) end
cur:to_array(function(err, arr)
if err then error(err.msg) end
error(arr)
end)
end
)
end, res
)
end)
end
--[[
test_error('branch db', r.db(reql_db):branch(1, 2), 'Expected type DATUM but found DATABASE:')
--]]
test_error('branch error', r.branch(r.error_('a'), 1, 2), 'a')
test('branch false', r.branch(false, 1, 2), {2})
test('branch nil', r():branch(1, 2), {2})
test('branch num', r.branch(1, 'c', false), {'c'})
--[[
test_error('branch table', r.table(reql_table):branch(1, 2), 'Expected type DATUM but found TABLE:')
--]]
test('branch true', r.branch(true, 1, 2), {1})
test('do', r.do_(function() return 1 end), {1})
test('do add', r.do_(1, 2, function(x, y) return x:add(y) end), {3})
test('do append', r({0, 1, 2}):do_(function(v) return v:append(3) end), {{0, 1, 2, 3}})
if string.match(_VERSION, '5.[23]') then
test_error('do extra arg', r.do_(1, function(x, y) return x + y end), 'Expected 2 arguments but found 1.')
test_error('do missing arg', r.do_(1, 2, function(x) return x end), 'Expected 1 argument but found 2.')
end
test('do mul', r(1):do_(function(v) return v:mul(2) end), {2})
test_error('do no args', r.do_(), 'Expected 1 or more arguments but found 0.')
test('do no func', r.do_(1), {1})
it('do no return', function()
assert.has_error(
function()
r.do_(1, function(x) end)
end, 'Anonymous function returned `nil`. Did you forget a `return`?'
)
end)
it('do return nil', function()
assert.has_error(
function()
r.do_(1, function(x) return nil end)
end, 'Anonymous function returned `nil`. Did you forget a `return`?'
)
end)
test_error('do str add num', r('abc'):do_(function(v) return v:add(3) end), 'Expected type STRING but found NUMBER.')
test_error('do str add str add num', r('abc'):do_(function(v) return v:add('def') end):add(3), 'Expected type STRING but found NUMBER.')
test_error('do str append', r('abc'):do_(function(v) return v:append(3) end), 'Expected type ARRAY but found STRING.')
test_error('error', r.error_('Hello World'), 'Hello World')
test('js', r.js('1 + 1'), {2})
test('js add add', r.js('1 + 1; 2 + 2'), {4})
test('do js function add', r.do_(1, 2, r.js('(function(a, b) { return a + b; })')), {3})
test('do js function', r.do_(1, r.js('(function(x) { return x + 1; })')), {2})
test('do js function add str', r.do_('foo', r.js('(function(x) { return x + "bar"; })')), {'foobar'})
test('do js no timeout', r.js('1 + 2', {timeout = 1.2}), {3})
test_error('js function result', r.js('(function() { return 1; })'), 'Query result must be of type DATUM, GROUPED_DATA, or STREAM (got FUNCTION).')
test_error('js function no wrap', r.js('function() { return 1; }'), 'SyntaxError: Unexpected token (')
test('do js function missing arg', r.do_(1, 2, r.js('(function(a) { return a; })')), {1})
test('do js function extra arg', r.do_(1, 2, r.js('(function(a, b, c) { return a; })')), {1})
test_error('do js function return undefined', r.do_(1, 2, r.js('(function(a, b, c) { return c; })')), 'Cannot convert javascript `undefined` to ql::datum_t.')
test('filter js', r.filter({1, 2, 3}, r.js('(function(a) { return a >= 2; })')), {{2, 3}})
test('map js', r.map({1, 2, 3}, r.js('(function(a) { return a + 1; })')), {{2, 3, 4}})
--[[
test_error('map js constant', r.map({1, 2, 3}, r.js('1')), 'Expected type FUNCTION but found DATUM.')
--]]
test_error('filter js undefined', r.filter({1, 2, 3}, r.js('(function(a) {})')), 'Cannot convert javascript `undefined` to ql::datum_t.')
--[[
test_error('map constant', r.map({1, 2, 3}, 1), 'Expected type FUNCTION but found DATUM.')
--]]
test('filter constant str', r.filter({1, 2, 3}, 'foo'), {{1, 2, 3}})
test('filter constant obj', r.filter({1, 2, 3}, {}), {{1, 2, 3}})
test('filter nil', r.filter({1, 2, 3}, r()), {{}})
test('filter false', r.filter({1, 2, 3}, false), {{}})
test('for each insert', r.for_each({1, 2, 3}, function(row) return r.table(reql_table):insert({id = row}) end), {{deleted = 0, replaced = 0, unchanged = 0, errors = 0, skipped = 0, inserted = 3}})
it('count for each insert', function()
r.for_each({1, 2, 3}, function(row) return r.table(reql_table):insert({id = row}) end):run(
c, function(err, cur)
if err then error(err.message) end
cur:to_array(function(err, arr)
if err then error(err.message) end
end)
end
)
assert.same(r.table(reql_table):count():run(
c, function(err, cur)
if err then error(err.message) end
return cur:to_array(function(err, arr)
if err then error(err.message) end
return arr
end)
end
), {3})
end)
it('for each update', function()
r.for_each({1, 2, 3}, function(row) return r.table(reql_table):insert({id = row}) end):run(
c, function(err, cur)
if err then error(err.message) end
cur:to_array(function(err, arr)
if err then error(err.message) end
end)
end
)
assert.same(r.for_each({1, 2, 3}, function(row) return r.table(reql_table):update({foo = row}) end):run(
c, function(err, cur)
if err then error(err.message) end
return cur:to_array(function(err, arr)
if err then error(err.message) end
return arr
end)
end
), {{deleted = 0, replaced = 9, unchanged = 0, errors = 0, skipped = 0, inserted = 0}})
end)
it('for each insert with duplicates', function()
r.for_each({1, 2, 3}, function(row) return r.table(reql_table):insert({id = row}) end):run(
c, function(err, cur)
if err then error(err.message) end
cur:to_array(function(err, arr)
if err then error(err.message) end
end)
end
)
r.for_each({1, 2, 3}, function(row) return r.table(reql_table):update({foo = row}) end):run(
c, function(err, cur)
if err then error(err.message) end
return cur:to_array(function(err, arr)
if err then error(err.message) end
return arr
end)
end
)
assert.same(r.for_each({1, 2, 3}, function(row) return {r.table(reql_table):insert({id = row}), r.table(reql_table):insert({id = row * 10})} end):run(
c, function(err, cur)
if err then error(err.message) end
return cur:to_array(function(err, arr)
if err then error(err.message) end
return arr
end)
end
), {{first_error = 'Duplicate primary key `id`:\n{\n\t"foo":\t3,\n\t"id":\t1\n}\n{\n\t"id":\t1\n}', deleted = 0, replaced = 0, unchanged = 0, errors = 3, skipped = 0, inserted = 3}})
end)
it('for each update many', function()
r.for_each({1, 2, 3}, function(row) return r.table(reql_table):insert({id = row}) end):run(
c, function(err, cur)
if err then error(err.message) end
cur:to_array(function(err, arr)
if err then error(err.message) end
end)
end
)
r.for_each({1, 2, 3}, function(row) return r.table(reql_table):update({foo = row}) end):run(
c, function(err, cur)
if err then error(err.message) end
return cur:to_array(function(err, arr)
if err then error(err.message) end
return arr
end)
end
)
r.for_each({1, 2, 3}, function(row) return {r.table(reql_table):insert({id = row}), r.table(reql_table):insert({id = row * 10})} end):run(
c, function(err, cur)
if err then error(err.message) end
return cur:to_array(function(err, arr)
if err then error(err.message) end
return arr
end)
end
)
assert.same(r.for_each({1, 2, 3}, function(row) return {r.table(reql_table):update({foo = row}), r.table(reql_table):update({bar = row})} end):run(
c, function(err, cur)
if err then error(err.message) end
return cur:to_array(function(err, arr)
if err then error(err.message) end
return arr
end)
end
), {{deleted = 0, replaced = 36, unchanged = 0, errors = 0, skipped = 0, inserted = 0}})
end)
end)
--[[
# forEach negative cases
- cd: r.expr([1, 2, 3]).for_each( tbl2.insert({ 'id':r.row }) )
rb: []
ot: ({'deleted':0.0,'replaced':0.0,'unchanged':0.0,'errors':0.0,'skipped':0.0,'inserted':3})
- cd: r.expr([1, 2, 3]).for_each(1)
ot: 'err("RqlRuntimeError", "FOREACH expects one or more basic write queries. Expected type ARRAY but found NUMBER.", [0])'
- py: r.expr([1, 2, 3]).for_each(lambda x:x)
js: r([1, 2, 3]).forEach(function (x) { return x; })
rb: r([1, 2, 3]).for_each{ |x| x }
ot: 'err("RqlRuntimeError", "FOREACH expects one or more basic write queries. Expected type ARRAY but found NUMBER.", [1, 1])'
- cd: r.expr([1, 2, 3]).for_each(r.row)
rb: []
ot: 'err("RqlRuntimeError", "FOREACH expects one or more basic write queries. Expected type ARRAY but found NUMBER.", [1, 1])'
- js: r([1, 2, 3]).forEach(function (row) { return tbl; })
py: r.expr([1, 2, 3]).for_each(lambda row:tbl)
rb: r([1, 2, 3]).for_each{ |row| tbl }
ot: 'err("RqlRuntimeError", "FOREACH expects one or more basic write queries.", [1, 1])'
# Make sure write queries can't be nested into stream ops
- cd: r.expr(1).do(tbl.insert({'foo':r.row}))
rb: r(1).do{ |row| tbl.insert({ :foo => row }) }
ot: ({'deleted':0.0,'replaced':0.0,'generated_keys':arrlen(1,uuid()),'unchanged':0.0,'errors':0.0,'skipped':0.0,'inserted':1})
- py: r.expr([1, 2])[0].do(tbl.insert({'foo':r.row}))
js: r.expr([1, 2]).nth(0).do(tbl.insert({'foo':r.row}))
rb: r([1, 2])[0].do{ |row| tbl.insert({ :foo => row }) }
ot: ({'deleted':0.0,'replaced':0.0,'generated_keys':arrlen(1,uuid()),'unchanged':0.0,'errors':0.0,'skipped':0.0,'inserted':1})
- cd: r.expr([1, 2]).map(tbl.insert({'foo':r.row}))
rb: r([1, 2]).map{ |row| tbl.insert({ :foo => row }) }
ot: err('RqlCompileError', 'Cannot nest writes or meta ops in stream operations. Use FOREACH instead.', [0])
- cd: r.expr([1, 2]).map(r.db('test').table_create('nested_table'))
ot: err('RqlCompileError', 'Cannot nest writes or meta ops in stream operations. Use FOREACH instead.', [0])
- cd: r.expr(1).do(r.db('test').table_create('nested_table'))
ot: ({'created':1})
--]]
|
local openssl = require 'openssl'
local lu = require 'luaunit'
local asn1 = openssl.asn1
local first = true
TestObject = {}
function TestObject:setUp()
self.sn = 'C'
self.ln = 'countryName'
self.oid = '2.5.4.6'
self.nid = 14
lu.assertIsTable(asn1)
self.ne_sn = 'Good1'
self.ne_ln = 'GoodString1'
self.ne_oid = '1.2.3.4.1'
end
function TestObject:tearDown()
end
function TestObject:testAll()
local o1, o2, o3, o4, o5, o6, o7
o1 = asn1.new_object(self.sn)
o2 = asn1.new_object(self.ln)
o3 = asn1.new_object(self.nid)
o4 = asn1.new_object(self.oid)
o5 = asn1.new_object(self.oid, true)
assert(o1)
assert(o1 == o2)
assert(o1 == o3)
assert(o1 == o4)
assert(o1 == o5)
lu.assertEquals(openssl.error(), nil)
o6 = asn1.new_object(self.ln, true)
lu.assertNil(o6)
lu.assertNotNil(openssl.error())
lu.assertNil(openssl.error())
o6 = o1:dup()
assert(o1 == o6)
local sn, ln = o1:name()
local nid = o1:nid()
local sn1, ln1 = o1:sn(), o2:ln()
local txt = o1:txt()
local oid = o1:txt(true)
local dat = o1:data()
lu.assertEquals(sn, self.sn)
lu.assertEquals(ln, self.ln)
lu.assertEquals(oid, self.oid)
lu.assertEquals(nid, self.nid)
lu.assertEquals(ln, dat)
lu.assertEquals(sn1, sn)
lu.assertEquals(ln1, ln)
lu.assertEquals(txt, ln)
lu.assertEquals(o1:txt(false), txt)
local options = {
oid = '1.2.840.10045.2.1.2.1',
sn = 'gmsm21',
ln = 'CCSTC GMSM2 EC1'
}
lu.assertNil(openssl.error())
o7 = asn1.new_object(options.sn)
if not o7 then
lu.assertNotNil(openssl.error())
o7 = asn1.new_object(options)
lu.assertStrContains(tostring(o7), 'openssl.asn1_object')
lu.assertEquals(o7:txt(), options.ln)
lu.assertEquals(o7:txt(true), options.oid)
lu.assertEquals(asn1.txt2nid(options.sn), o7:nid())
lu.assertEquals(asn1.txt2nid(options.ln), o7:nid())
lu.assertEquals(asn1.txt2nid(options.oid), o7:nid())
end
if first then
lu.assertIsNil(asn1.txt2nid(self.ne_oid))
first = false
lu.assertIsNil(asn1.new_object(self.ne_sn))
lu.assertNotNil(openssl.error())
lu.assertIsNil(asn1.new_object(self.ne_ln))
lu.assertNotNil(openssl.error())
assert(asn1.new_object(self.ne_oid))
o1 = assert(asn1.new_object({
oid = self.ne_oid,
sn = self.ne_sn,
ln = self.ne_ln
}))
o2 = assert(asn1.new_object(self.ne_oid))
lu.assertEquals(o1, o2)
lu.assertNil(openssl.error())
else
assert(asn1.txt2nid(self.ne_oid))
assert(asn1.new_object(self.ne_sn))
assert(asn1.new_object(self.ne_ln))
assert(asn1.new_object(self.ne_oid))
end
end
TestString = {}
function TestString:setUp()
self.bmp = 'abcd'
self.bmp_cn = '中文名字'
end
function TestString:tearDown()
end
function TestString:testAll()
local s1, s2, s3, s4, s5, s6
s1 = asn1.new_string(self.bmp, asn1.BMPSTRING)
lu.assertEquals(s1:tostring(), self.bmp)
assert(#s1 == #self.bmp)
s2 = asn1.new_string(self.bmp_cn, asn1.BMPSTRING)
local utf_cn = s2:toutf8()
s3 = asn1.new_string(utf_cn, asn1.UTF8STRING)
lu.assertEquals(utf_cn, s3:data())
lu.assertEquals(#s3, #utf_cn)
lu.assertEquals(s3:length(), #utf_cn)
lu.assertEquals(s3:type(), asn1.UTF8STRING)
lu.assertEquals(s2:type(), asn1.BMPSTRING)
s4 = asn1.new_string('', asn1.UTF8STRING)
s4:data(utf_cn)
lu.assertEquals(s4, s3)
s6 = asn1.new_string(self.bmp, asn1.IA5STRING)
lu.assertEquals(s6:toprint(), self.bmp)
lu.assertStrMatches(s1:toprint(), [[\U6162\U6364]])
lu.assertStrMatches(s4:toprint(), [[\UE4B8\UADE6\U9687\UE590\U8DE5\UAD97]])
s5 = s4:dup()
lu.assertEquals(s5, s3)
assert(s4 == s3)
local o = asn1.new_string('octet', asn1.OCTET_STRING)
lu.assertEquals(o:type(), asn1.OCTET_STRING)
assert(type(asn1.tostring(asn1.UNIVERSAL,'tag'))=='string')
assert(type(asn1.tostring(asn1.APPLICATION,'class'))=='string')
end
TestTime = {}
function TestTime:get_timezone()
local now = os.time()
local gmt = os.time(os.date("!*t", now))
local tz = os.difftime(now, gmt)
return tz
end
function TestTime:setUp()
self.time = os.time()
self.gmt = self.time - self:get_timezone()
end
function TestTime:testUTCTime()
local at = openssl.asn1.new_utctime()
assert(at:set(self.time))
local t1 = at:get()
lu.assertEquals(self.gmt, t1)
at = openssl.asn1.new_utctime(self.time)
assert(at)
assert(type(at:tostring())=='string')
local d = at:i2d()
assert(type(d)=='string')
local ab = openssl.asn1.new_utctime()
ab:d2i(d)
assert(ab==at)
assert(at:check())
ab = openssl.asn1.new_utctime(self.time+1)
if ab.diff then
local day, sec = ab:diff(at)
assert(day==0)
assert(sec==-1)
at:adj(self.time, 1, 1)
day, sec = ab:diff(at)
assert(day==1, day)
assert(sec==0, day)
assert(type(ab:toprint()=='string'))
end
end
function TestTime:testGENERALIZEDTime()
local at = openssl.asn1.new_generalizedtime(self.time)
assert(at:set(self.time))
local t1 = at:get()
local d = at:i2d()
assert(type(d)=='string')
local ab = openssl.asn1.new_generalizedtime(self.time)
assert(ab:d2i(d))
assert(ab==at)
lu.assertEquals(self.gmt, t1)
assert(type(ab:toprint()=='string'))
end
TestNumber = {}
function TestNumber:testBasic()
local i = 0
local n = asn1.new_integer(i):i2d()
local m = asn1.new_integer()
assert(type(m:tostring())=='string')
m:d2i(n)
assert(m:i2d() == n)
n = asn1.new_integer():i2d()
assert(n)
n = asn1.new_integer(nil):i2d()
assert(n)
n = asn1.new_integer("Xabcdef")
assert(n)
local b = n:bn()
i = asn1.new_integer(b)
assert(i==n)
n:set(1)
assert(type(i:toprint()=='string'))
end
TestType = {}
function TestType:testBasic()
local o = asn1.new_type('timeStamping')
local d = assert(o:i2d())
assert(asn1.d2i_asn1type(d)==o)
o = asn1.new_type(true)
d = assert(o:i2d())
assert(asn1.d2i_asn1type(d)==o)
o = asn1.new_type(100)
d = assert(o:i2d())
assert(asn1.d2i_asn1type(d)==o)
local s = asn1.new_string("中文")
o = asn1.new_type(s)
d = assert(o:i2d())
assert(asn1.d2i_asn1type(d)==o)
s = asn1.new_string("BIT", asn1.BIT_STRING)
o = asn1.new_type(s)
d = assert(o:i2d())
assert(asn1.d2i_asn1type(d)==o)
assert(o:info())
s = asn1.new_string("BMP", asn1.BMP_STRING)
o = asn1.new_type(s)
d = assert(o:i2d())
assert(asn1.d2i_asn1type(d)==o)
assert(o:info())
s = asn1.new_string("octet", asn1.OCTET_STRING)
o = asn1.new_type(s)
d = assert(o:i2d())
assert(asn1.d2i_asn1type(d)==o)
assert(o:info())
assert(o:octet()=='octet')
assert(o:octet('abcd'))
assert(o:octet()=='abcd')
local t = openssl.asn1.new_utctime()
o = asn1.new_type(t)
d = assert(o:i2d())
assert(asn1.d2i_asn1type(d)==o)
assert(o:type())
assert(o:info())
assert(o:asn1string())
end
|
----------------------------------------------------------------------------------------------------
-- Creator Tools LUA Instrument Utilities File
----------------------------------------------------------------------------------------------------
-- Author: Native Instruments
-- Written by: Yaron Eshkar
-- Modified: April 23, 2021
--
-- This file includes useful functions for usage in Creator Tools Lua scripts.
-- Simply include this line in any script (if running a script from another location that users this file,
-- make sure to point to the correct path):
-- local ctInstrument = require("CtInstrument")
-- Then you can simply call any function like:
-- ctInstrument.test_function()
--
-- It is also possible of course to copy entire specific functions from this list directly into your script.
-- In that case remove the CtFile part from the function name, and then simply call it normally like:
-- test_function()
--
local CtInstrument = {}
--- Test Function.
-- Takes no arguments, prints to console when called.
function CtInstrument.test_function()
-- Show that the class import and test function executes by printing a line.
print("Test function called")
end
--- Applies a KSP Script.
-- Takes no arguments, prints to console when called.
-- @tparam string script_or_file KSP script in string form or a path to the script file. If link param is true, must be a path.
-- @tparam string name set the script name.
-- @tparam int slot set the script slot, defaults to zero if not set.
-- @tparam bool bypass when true the script will be applied but set to bypass.
-- @tparam bool link link to the given path or to apply the script as a string.
-- @treturn bool
function CtInstrument.apply_script(script_or_file,name,slot,bypass,link)
if slot == nil then slot = 0 end
if name == nil then name = "edited" end
if link then
instrument.scripts[slot].linked = true
instrument.scripts[slot].linkedFileName = filesystem.stem(script_or_file)
else
instrument.scripts[slot].sourceCode = script_or_file
end
instrument.scripts[slot].name = name
if bypass then instrument.scripts[slot].bypass = true end
return true
end
-- return the CtFile object.
return CtInstrument
|
operator = yarn {
name = "hello_test",
timeout = 10000,
memory = 1024,
cores = 1,
container = {
instances = 1,
--env = base_env,
resources = {
["HelloWorld.sh"] = {
file = "asapLibrary/operators/hello_test/HelloWorld.sh",
type = "file", -- other value: 'archive'
visibility = "application" -- other values: 'private', 'public'
},
["description"] = {
file = "asapLibrary/operators/hello_test/description",
type = "file", -- other value: 'archive'
visibility = "application" -- other values: 'private', 'public'
}
},
command = {
base = "./HelloWorld.sh"
}
}
}
|
--require("prototypes.processing.pulverizer")
data:extend({
{
type = "item",
name = "gravel",
icon = "__Engineersvsenvironmentalist__/graphics/icons/materials/gravel.png",
icon_size = 31,
flags = {"goes-to-main-inventory"},
subgroup = "stone-base",
order = "g1[other]",
stack_size = 250
},
{
type = "item",
name = "processed-gravel",
icon = "__Engineersvsenvironmentalist__/graphics/icons/materials/gravel-processed.png",
icon_size = 31,
flags = {"goes-to-main-inventory"},
subgroup = "stone-base",
order = "g1[other]",
stack_size = 750
},
{
type = "recipe",
name = "gravel-crushing",
icon = "__Engineersvsenvironmentalist__/graphics/icons/materials/sand.png",
icon_size = 31,
category = "crusher",
subgroup = "basic-processing",
order ="a-3",
energy_required = 1,
enabled = true,
ingredients =
{
{type="item", name="gravel", amount=10},
},
results = {{"gravel",8},{"sand",2}},
},
{
type = "recipe",
name = "gravel-sifting",
icon = "__Engineersvsenvironmentalist__/graphics/icons/materials/gravel-processed.png",
icon_size = 31,
category = "sifter",
subgroup = "basic-processing",
order ="a-4",
energy_required = 1,
enabled = true,
ingredients =
{
{"gravel", 2},
},
results=
{
{"processed-gravel",2},
{type="item",name="gold-ore", probability=0.0001, amount_min=1, amount_max=1},
{type="item",name="silver-ore", probability=0.001, amount_min=1, amount_max=1},
{type="item",name="platinum-grain", probability=0.00001, amount_min=1, amount_max=1},
}
},
{
type = "recipe",
name = "processed-gravel-crushing",
icon = "__Engineersvsenvironmentalist__/graphics/icons/materials/sand.png",
icon_size = 31,
category = "crusher",
subgroup = "basic-processing",
order ="a-5",
energy_required = 1,
enabled = true,
ingredients =
{
{type="item", name="processed-gravel", amount=10},
},
results = {{"processed-gravel",8},{"sand",2}},
},
})
|
-----------------------------------
-- Area: Valley of Sorrows
-- HNM: Adamantoise
-----------------------------------
local ID = require("scripts/zones/Valley_of_Sorrows/IDs")
mixins = {require("scripts/mixins/rage")}
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/titles")
-----------------------------------
function onMobSpawn(mob)
if LandKingSystem_NQ > 0 or LandKingSystem_HQ > 0 then
GetNPCByID(ID.npc.ADAMANTOISE_QM):setStatus(tpz.status.DISAPPEAR)
end
if LandKingSystem_HQ == 0 then
SetDropRate(24, 3344, 0) -- do not drop clump_of_red_pondweed
end
mob:setLocalVar("[rage]timer", 1800) -- 30 minutes
end
function onMobDeath(mob, player, isKiller)
player:addTitle(tpz.title.TORTOISE_TORTURER)
end
function onMobDespawn(mob)
local ToD = GetServerVariable("[POP]Aspidochelone")
local kills = GetServerVariable("[PH]Aspidochelone")
local popNow = (math.random(1, 5) == 3 or kills > 6)
if LandKingSystem_HQ ~= 1 and ToD <= os.time() and popNow then
-- 0 = timed spawn, 1 = force pop only, 2 = BOTH
if LandKingSystem_NQ == 0 then
DisallowRespawn(ID.mob.ADAMANTOISE, true)
end
DisallowRespawn(ID.mob.ASPIDOCHELONE, false)
UpdateNMSpawnPoint(ID.mob.ASPIDOCHELONE)
GetMobByID(ID.mob.ASPIDOCHELONE):setRespawnTime(75600 + math.random(0, 6) * 1800) -- 21 - 24 hours with half hour windows
else
if LandKingSystem_NQ ~= 1 then
UpdateNMSpawnPoint(ID.mob.ADAMANTOISE)
GetMobByID(ID.mob.ADAMANTOISE):setRespawnTime(75600 + math.random(0, 6) * 1800) -- 21 - 24 hours with half hour windows
SetServerVariable("[PH]Aspidochelone", kills + 1)
end
end
end
|
--
-- Built with,
--
-- ,gggg,
-- d8" "8I ,dPYb,
-- 88 ,dP IP'`Yb
-- 8888888P" I8 8I
-- 88 I8 8'
-- 88 gg gg ,g, I8 dPgg,
-- ,aa,_88 I8 8I ,8'8, I8dP" "8I
-- dP" "88P I8, ,8I ,8' Yb I8P I8
-- Yb,_,d88b,,_ ,d8b, ,d8b,,8'_ 8) ,d8 I8,
-- "Y8P" "Y888888P'"Y88P"`Y8P' "YY8P8P88P `Y8
--
-- vim.opt.keywordprg=":help" --Jump easily to hl-groups docs.
local lush = require("lush")
local hsluv = lush.hsluv
local palette = {}
palette.dark = {
a = {
bg = hsluv( 50, 20, 15);
overbg = hsluv( 50, 20, 20);
sel = hsluv( 50, 20, 30);
com = hsluv( 50, 30, 60);
faded = hsluv( 50, 30, 70);
fg = hsluv( 50, 30, 90);
};
b = {
red = hsluv( 20, 80, 65);
yellow = hsluv( 60, 70, 80);
green = hsluv(130, 40, 80);
cyan = hsluv(190, 40, 70);
blue = hsluv(250, 40, 70);
magenta = hsluv(310, 40, 70);
};
c = {
red = hsluv( 10, 40, 50);
yellow = hsluv( 40, 70, 70);
green = hsluv(130, 30, 60);
cyan = hsluv(190, 30, 65);
blue = hsluv(250, 30, 50);
magenta = hsluv(310, 30, 60);
};
d = {
red = hsluv( 10, 60, 30);
yellow = hsluv( 60, 70, 50);
green = hsluv(130, 50, 20);
cyan = hsluv(190, 50, 20);
blue = hsluv(250, 50, 20);
magenta = hsluv(310, 50, 20);
};
}
palette.light = {
a = {
bg = hsluv( 50, 20, 95);
overbg = hsluv( 50, 20, 90);
sel = hsluv( 50, 20, 85);
com = hsluv( 50, 30, 60);
faded = hsluv( 50, 30, 50);
fg = hsluv( 50, 30, 40);
};
b = {
red = hsluv( 20, 80, 50);
yellow = hsluv( 60, 90, 65);
green = hsluv(130, 50, 60);
cyan = hsluv(180, 50, 40);
blue = hsluv(250, 50, 40);
magenta = hsluv(310, 50, 40);
};
c = {
red = hsluv( 10, 50, 65);
yellow = hsluv( 40, 90, 60);
green = hsluv(130, 40, 70);
cyan = hsluv(180, 40, 60);
blue = hsluv(250, 40, 75);
magenta = hsluv(310, 40, 60);
};
d = {
red = hsluv( 20, 40, 80);
yellow = hsluv( 60, 50, 80);
green = hsluv(130, 30, 90);
cyan = hsluv(190, 30, 90);
blue = hsluv(250, 30, 90);
magenta = hsluv(310, 30, 90);
};
}
local bg = vim.opt.background:get()
local a = palette[bg].a
local b = palette[bg].b
local c = palette[bg].c
local d = palette[bg].d
-- Font variants:
-- This only works when loading this file directly, not when loading with `:colorscheme`
local bf, it, underline, undercurl;
if vim.g.melange_enable_font_variants ~= 0 then
bf = "bold"
it = "italic"
underline = "underline"
undercurl = "undercurl"
end
return lush(function() return {
---- :help highlight-default -------------------------------
Normal { fg=a.fg, bg=a.bg };
NormalFloat { bg=a.overbg };
-- NormalNC { };
-- Cursor { };
-- lCursor { };
-- CursorIM { };
-- TermCursor { };
-- TermCursorNC { };
ColorColumn { bg=a.overbg };
CursorColumn { ColorColumn };
CursorLine { ColorColumn };
VertSplit { fg=a.sel };
LineNr { fg=a.sel };
CursorLineNr { fg=c.yellow };
Folded { fg=a.com, bg=a.overbg };
FoldColumn { LineNr };
SignColumn { LineNr };
Pmenu { NormalFloat };
PmenuSel { bg=a.sel };
PmenuSbar { Pmenu };
PmenuThumb { PmenuSel };
StatusLine { NormalFloat };
StatusLineNC { StatusLine, fg=a.faded };
WildMenu { NormalFloat };
TabLine { StatusLineNC };
TabLineFill { StatusLine };
TabLineSel { StatusLine, gui=bf };
MatchParen { fg=b.yellow, bg=a.sel, gui=bf };
Substitute { fg=a.bg, bg=d.yellow };
Search { fg=a.bg, bg=d.yellow };
-- QuickFixLine { };
-- IncSearch { };
Visual { bg=a.sel };
-- VisualNOS { };
Conceal { fg=a.faded };
Whitespace { fg=a.sel };
EndOfBuffer { Whitespace };
NonText { Whitespace };
SpecialKey { Whitespace };
Directory { fg=c.cyan };
Title { fg=c.yellow };
ErrorMsg { bg=d.red };
ModeMsg { fg=a.faded };
-- MsgArea { };
-- MsgSeparator { };
MoreMsg { fg=c.green, gui=bf };
WarningMsg { fg=c.red };
Question { MoreMsg };
---- :help :diff -------------------------------------------
DiffAdd { bg=d.green };
DiffChange { bg=d.magenta };
DiffDelete { bg=d.red };
DiffText { bg=d.blue };
DiffAdded { DiffAdd };
DiffRemoved { DiffDelete };
---- :help spell -------------------------------------------
SpellBad { fg=c.red, gui=undercurl };
SpellCap { fg=c.blue, gui=undercurl };
SpellLocal { fg=c.yellow, gui=undercurl };
SpellRare { fg=b.yellow, gui=undercurl };
---- :help group-name --------------------------------------
Comment { fg=a.com, gui=it };
Identifier { fg=a.fg };
Function { fg=b.yellow };
Constant { fg=c.magenta };
String { fg=b.blue, gui=it };
Character { fg=b.blue };
Number { fg=b.magenta };
Boolean { fg=b.magenta };
-- Float { };
Statement { fg=c.yellow };
-- Conditional { };
-- Repeat { };
-- Label { };
Operator { fg=b.red };
-- Keyword { };
-- Exception { };
PreProc { fg=b.green };
-- Include { };
-- Define { };
-- Macro { };
-- PreCondit { };
Type { fg=c.cyan };
-- StorageClass { };
-- Structure { };
-- Typedef { };
Special { fg=b.yellow };
-- SpecialChar { };
-- Tag { };
Delimiter { fg=d.yellow };
-- SpecialComment { };
-- Debug { };
Underlined { gui=underline };
Bold { gui=bf };
Italic { gui=it };
Ignore { fg=a.com };
Error { bg=d.red };
Todo { Comment, fg=a.faded };
---- :help nvim-treesitter-highlights (external plugin) ----
-- TSAnnotation { };
-- TSAttribute { };
-- TSBoolean { };
-- TSCharacter { };
-- TSComment { };
-- TSConditional { };
-- TSConstant { };
TSConstBuiltin { Constant, gui=it };
TSConstMacro { Constant };
-- TSConstructor { };
-- TSError { gui=undercurl };
-- TSException { };
-- TSField { };
-- TSFloat { };
-- TSFunction { };
TSFuncBuiltin { Function };
TSFuncMacro { Function };
-- TSInclude { };
-- TSKeyword { };
TSKeywordFunction { PreProc };
-- TSKeywordOperator { };
-- TSKeywordReturn { };
-- TSLabel { };
-- TSMethod { };
TSNamespace { fg=c.green };
-- TSNone { };
-- TSNumber { };
-- TSOperator { };
-- TSParameter { };
-- TSParameterReference { };
-- TSProperty { };
TSPunctDelimiter { fg=c.red };
TSPunctBracket { Delimiter };
TSPunctSpecial { Delimiter };
-- TSRepeat { };
-- TSString { };
-- TSStringRegex { };
TSStringEscape { fg=c.blue };
TSSymbol { Identifier, gui=it };
-- TSType { };
-- TSTypeBuiltin { };
TSVariable { Identifier };
TSVariableBuiltin { Identifier, gui=it };
-- TSTag { };
-- TSTagDelimiter { };
-- TSText { };
TSStrong { gui=bf };
TSEmphasis { Italic };
TSUnderline { Underlined };
TSStrike { gui="strikethrough" };
-- TSTitle { };
-- TSLiteral { };
TSURI { String, gui=underline };
TSMath { fg=b.cyan };
-- TSTextReference { };
TSEnvironment { Statement };
TSEnvironmentName { PreProc };
-- TSNote { };
-- TSWarning { };
-- TSDanger { };
---- :help diagnostic-highlight ----------------------------
DiagnosticError { fg=c.red };
DiagnosticWarn { fg=b.yellow };
DiagnosticInfo { fg=b.blue };
DiagnosticHint { fg=b.green };
-- DiagnosticVirtualTextError { DiagnosticError };
-- DiagnosticVirtualTextWarn { DiagnosticWarn };
-- DiagnosticVirtualTextInfo { DiagnosticInfo };
-- DiagnosticVirtualTextHint { DiagnosticHint };
DiagnosticUnderlineError { gui=undercurl };
DiagnosticUnderlineWarn { gui=undercurl };
DiagnosticUnderlineInfo { gui=undercurl };
DiagnosticUnderlineHint { gui=undercurl };
-- DiagnosticFloatingError { DiagnosticError };
-- DiagnosticFloatingWarn { DiagnosticWarn };
-- DiagnosticFloatingInfo { DiagnosticInfo };
-- DiagnosticFloatingHint { DiagnosticHint };
-- DiagnosticSignError { DiagnosticError };
-- DiagnosticSignWarn { DiagnosticWarn };
-- DiagnosticSignInfo { DiagnosticInfo };
-- DiagnosticSignHint { DiagnosticHint };
---- :help lsp-highlight -----------------------------------
LspReferenceText { Visual };
LspReferenceRead { Visual };
LspReferenceWrite { Visual };
LspDiagnosticsDefaultError { DiagnosticError };
LspDiagnosticsDefaultWarning { DiagnosticWarn };
LspDiagnosticsDefaultInformation { DiagnosticInfo };
LspDiagnosticsDefaultHint { DiagnosticHint };
-- LspDiagnosticsVirtualTextError { };
-- LspDiagnosticsVirtualTextWarning { };
-- LspDiagnosticsVirtualTextInformation { };
-- LspDiagnosticsVirtualTextHint { };
LspDiagnosticsUnderlineError { gui=undercurl };
LspDiagnosticsUnderlineWarning { gui=undercurl };
LspDiagnosticsUnderlineInformation { gui=undercurl };
LspDiagnosticsUnderlineHint { gui=undercurl };
-- LspDiagnosticsFloatingError { };
-- LspDiagnosticsFloatingWarning { };
-- LspDiagnosticsFloatingInformation { };
-- LspDiagnosticsFloatingHint { };
-- LspDiagnosticsSignError { };
-- LspDiagnosticsSignWarning { };
-- LspDiagnosticsSignInformation { };
-- LspDiagnosticsSignHint { };
--- :help vimtex-syntax-reference (external plugin) --------
texOptSep { TSPunctDelimiter };
texOptEqual { Operator };
texFileArg { Constant };
texTitleArg { gui=bf };
texRefArg { Constant };
texMathCmd { Function };
texMathSymbol { Operator };
texMathZone { TSMath };
texMathDelimZone { TSPunctDelimiter };
texMathDelim { Delimiter };
texMathEnvArgName { PreProc };
--- netrw: there's no comprehensive list of highlights... --
netrwClassify { Delimiter };
netrwTreeBar { Delimiter };
netrwExe { fg=c.red };
netrwSymLink { fg=c.magenta };
---- Misc. -------------------------------------------------
HelpHyperTextJump { fg=c.yellow };
---- :h gitsigns (external plugin) -------------------------
GitSignsAdd { fg = a.bg, bg = d.green, gui = "reverse" };
GitSignsChange { fg = a.bg, bg = d.magenta, gui = "reverse" };
GitSignsDelete { fg = a.bg, bg = d.red, gui = "reverse" };
GitSignsCurrentLineBlame { fg = a.bg, bg = d.blue, gui = "reverse" };
SignifySignAdd { GitSignsAdd };
SignifySignChange { GitSignsChange };
SignifySignDelete { GitSignsDelete };
---- Metagroup (hack for builds) ---------------------------
Melange { lush = palette[bg] };
}end)
-- vi:nowrap
|
--[[--------------------------------------------------------------------
Copyright (C) 2013, 2014, 2015 Johnny C. Lam.
See the file LICENSE.txt for copying permission.
--]]--------------------------------------------------------------------
-- This addon tracks the player's current stance.
local OVALE, Ovale = ...
local OvaleStance = Ovale:NewModule("OvaleStance", "AceEvent-3.0")
Ovale.OvaleStance = OvaleStance
--<private-static-properties>
local L = Ovale.L
local OvaleDebug = Ovale.OvaleDebug
local OvaleProfiler = Ovale.OvaleProfiler
-- Forward declarations for module dependencies.
local OvaleData = nil
local OvaleState = nil
local ipairs = ipairs
local pairs = pairs
local substr = string.sub
local tconcat = table.concat
local tinsert = table.insert
local tonumber = tonumber
local tsort = table.sort
local type = type
local wipe = wipe
local API_GetNumShapeshiftForms = GetNumShapeshiftForms
local API_GetShapeshiftForm = GetShapeshiftForm
local API_GetShapeshiftFormInfo = GetShapeshiftFormInfo
local API_GetSpellInfo = GetSpellInfo
-- Register for profiling.
OvaleProfiler:RegisterProfiling(OvaleStance)
local SPELL_NAME_TO_STANCE = {
-- Druid
[API_GetSpellInfo( 768)] = "druid_cat_form",
[API_GetSpellInfo( 783)] = "druid_travel_form",
[API_GetSpellInfo( 1066)] = "druid_aquatic_form",
[API_GetSpellInfo( 5487)] = "druid_bear_form",
[API_GetSpellInfo( 24858)] = "druid_moonkin_form",
[API_GetSpellInfo( 33943)] = "druid_flight_form",
[API_GetSpellInfo( 40120)] = "druid_swift_flight_form",
-- Rogue
[API_GetSpellInfo( 1784)] = "rogue_stealth"
}
-- Table of all valid stance names.
local STANCE_NAME = {}
do
for _, name in pairs(SPELL_NAME_TO_STANCE) do
STANCE_NAME[name] = true
end
end
do
local debugOptions = {
stance = {
name = L["Stances"],
type = "group",
args = {
stance = {
name = L["Stances"],
type = "input",
multiline = 25,
width = "full",
get = function(info) return OvaleStance:DebugStances() end,
},
},
},
}
-- Insert debug options into OvaleDebug.
for k, v in pairs(debugOptions) do
OvaleDebug.options.args[k] = v
end
end
--</private-static-properties>
--<public-static-properties>
-- Whether the stance information is ready for use by other modules.
OvaleStance.ready = false
-- List of available stances, populated by CreateStanceList()
OvaleStance.stanceList = {}
-- Map stance names to stance ID (index on shapeshift/stance bar).
OvaleStance.stanceId = {}
-- Player's current stance.
OvaleStance.stance = nil
-- Table of all valid stance names.
OvaleStance.STANCE_NAME = STANCE_NAME
--</public-static-properties>
--<public-static-methods>
function OvaleStance:OnInitialize()
-- Resolve module dependencies.
OvaleData = Ovale.OvaleData
OvaleState = Ovale.OvaleState
end
function OvaleStance:OnEnable()
self:RegisterEvent("PLAYER_ENTERING_WORLD", "UpdateStances")
self:RegisterEvent("UPDATE_SHAPESHIFT_FORM")
self:RegisterEvent("UPDATE_SHAPESHIFT_FORMS")
self:RegisterMessage("Ovale_SpellsChanged", "UpdateStances")
self:RegisterMessage("Ovale_TalentsChanged", "UpdateStances")
OvaleData:RegisterRequirement("stance", "RequireStanceHandler", self)
OvaleState:RegisterState(self, self.statePrototype)
end
function OvaleStance:OnDisable()
OvaleState:UnregisterState(self)
OvaleData:UnregisterRequirement("stance")
self:UnregisterEvent("PLAYER_ALIVE")
self:UnregisterEvent("PLAYER_ENTERING_WORLD")
self:UnregisterEvent("UPDATE_SHAPESHIFT_FORM")
self:UnregisterEvent("UPDATE_SHAPESHIFT_FORMS")
self:UnregisterMessage("Ovale_SpellsChanged")
self:UnregisterMessage("Ovale_TalentsChanged")
end
function OvaleStance:PLAYER_TALENT_UPDATE(event)
-- Clear old stance ID since talent update may overwrite old stance with new one with same ID.
self.stance = nil
self:UpdateStances()
end
function OvaleStance:UPDATE_SHAPESHIFT_FORM(event)
self:ShapeshiftEventHandler()
end
function OvaleStance:UPDATE_SHAPESHIFT_FORMS(event)
self:ShapeshiftEventHandler()
end
-- Fill OvaleStance.stanceList with stance bar index <-> Ovale stance name mappings.
function OvaleStance:CreateStanceList()
self:StartProfiling("OvaleStance_CreateStanceList")
wipe(self.stanceList)
wipe(self.stanceId)
local _, name, stanceName
for i = 1, API_GetNumShapeshiftForms() do
_, name = API_GetShapeshiftFormInfo(i)
stanceName = SPELL_NAME_TO_STANCE[name]
if stanceName then
self.stanceList[i] = stanceName
self.stanceId[stanceName] = i
end
end
self:StopProfiling("OvaleStance_CreateStanceList")
end
-- Print out the list of stances in alphabetical order.
do
local array = {}
function OvaleStance:DebugStances()
wipe(array)
for k, v in pairs(self.stanceList) do
if self.stance == k then
tinsert(array, v .. " (active)")
else
tinsert(array, v)
end
end
tsort(array)
return tconcat(array, "\n")
end
end
-- Return the name of the given stance or the current stance.
function OvaleStance:GetStance(stanceId)
stanceId = stanceId or self.stance
return self.stanceList[stanceId]
end
-- Return true if the current stance matches the given name.
-- NOTE: Mirrored in statePrototype below.
function OvaleStance:IsStance(name)
if name and self.stance then
if type(name) == "number" then
return name == self.stance
else
return name == OvaleStance:GetStance(self.stance)
end
end
return false
end
function OvaleStance:IsStanceSpell(spellId)
local name = API_GetSpellInfo(spellId)
return not not (name and SPELL_NAME_TO_STANCE[name])
end
function OvaleStance:ShapeshiftEventHandler()
self:StartProfiling("OvaleStance_ShapeshiftEventHandler")
local oldStance = self.stance
local newStance = API_GetShapeshiftForm()
if oldStance ~= newStance then
self.stance = newStance
Ovale.refreshNeeded[Ovale.playerGUID] = true
self:SendMessage("Ovale_StanceChanged", self:GetStance(newStance), self:GetStance(oldStance))
end
self:StopProfiling("OvaleStance_ShapeshiftEventHandler")
end
function OvaleStance:UpdateStances()
self:CreateStanceList()
self:ShapeshiftEventHandler()
self.ready = true
end
-- Run-time check that the player is in a certain stance.
-- NOTE: Mirrored in statePrototype below.
function OvaleStance:RequireStanceHandler(spellId, atTime, requirement, tokens, index, targetGUID)
local verified = false
-- If index isn't given, then tokens holds the actual token value.
local stance = tokens
if index then
stance = tokens[index]
index = index + 1
end
if stance then
local isBang = false
if substr(stance, 1, 1) == "!" then
isBang = true
stance = substr(stance, 2)
end
stance = tonumber(stance) or stance
local isStance = self:IsStance(stance)
if not isBang and isStance or isBang and not isStance then
verified = true
end
local result = verified and "passed" or "FAILED"
if isBang then
self:Log(" Require NOT stance '%s': %s", stance, result)
else
self:Log(" Require stance '%s': %s", stance, result)
end
else
Ovale:OneTimeMessage("Warning: requirement '%s' is missing a stance argument.", requirement)
end
return verified, requirement, index
end
--</public-static-methods>
--[[----------------------------------------------------------------------------
State machine for simulator.
--]]----------------------------------------------------------------------------
--<public-static-properties>
OvaleStance.statePrototype = {}
--</public-static-properties>
--<private-static-properties>
local statePrototype = OvaleStance.statePrototype
--</private-static-properties>
--<state-properties>
statePrototype.stance = nil
--</state-properties>
--<public-static-methods>
-- Initialize the state.
function OvaleStance:InitializeState(state)
state.stance = nil
end
-- Reset the state to the current conditions.
function OvaleStance:ResetState(state)
self:StartProfiling("OvaleStance_ResetState")
state.stance = self.stance or 0
self:StopProfiling("OvaleStance_ResetState")
end
-- Apply the effects of the spell on the player's state, assuming the spellcast completes.
function OvaleStance:ApplySpellAfterCast(state, spellId, targetGUID, startCast, endCast, isChanneled, spellcast)
self:StartProfiling("OvaleStance_ApplySpellAfterCast")
local stance = state:GetSpellInfoProperty(spellId, endCast, "to_stance", targetGUID)
if stance then
if type(stance) == "string" then
stance = self.stanceId[stance]
end
state.stance = stance
end
self:StopProfiling("OvaleStance_ApplySpellAfterCast")
end
--</public-static-methods>
--<state-methods>
-- Mirrored methods.
statePrototype.IsStance = OvaleStance.IsStance
statePrototype.RequireStanceHandler = OvaleStance.RequireStanceHandler
--</state-methods>
|
local class = require('middleclass')
local Input = class('Input')
--[[
Touch.phase:
- Began A finger touched the screen.
- Moved A finger moved on the screen.
- Stationary A finger is touching the screen but hasn't moved.
- Ended A finger was lifted from the screen. This is the final phase of a touch.
- Canceled The system cancelled tracking for the touch.
]]
local function createTouchListener(self)
local listener = cc.EventListenerTouchOneByOne:create()
listener:setSwallowTouches(false)
listener:registerScriptHandler(function(touch, _)
touch.phase = 'Began'
table.insert(self.touches, touch)
touch:retain()
return true
end, cc.Handler.EVENT_TOUCH_BEGAN)
listener:registerScriptHandler(function(touch, _)
touch.phase = 'Moved'
end, cc.Handler.EVENT_TOUCH_MOVED)
listener:registerScriptHandler(function(touch, _)
touch.phase = 'Ended'
end, cc.Handler.EVENT_TOUCH_ENDED)
listener:registerScriptHandler(function(touch, _)
touch.phase = 'Canceled'
end, cc.Handler.EVENT_TOUCH_CANCELLED)
return listener
end
local function createKeyListener(self)
local listener = cc.EventListenerKeyboard:create()
listener:registerScriptHandler(function(keycode, _)
self.keys[keycode] = true
self.keydowns[keycode] = true
end, cc.Handler.EVENT_KEYBOARD_PRESSED)
listener:registerScriptHandler(function(keycode, _)
self.keys[keycode] = nil
self.keyups[keycode] = true
end, cc.Handler.EVENT_KEYBOARD_RELEASED)
return listener
end
local function createEndFreameListener(self, dispatcher)
return dispatcher:addCustomEventListener('director_after_draw', function()
for i=#self.touches,1,-1 do
local touch = self.touches[i]
if touch.phase == 'Ended' or touch.phase == 'Canceled' then
table.remove(self.touches, i)
touch:release()
else
touch.phase = 'Stationary'
end
end
self.keydowns = {}
self.keyups = {}
end)
end
function Input:initialize()
self.touches = {}
self.keys = {}
self.keydowns = {}
self.keyups = {}
local listeners = {}
local dispatcher = cc.Director:getInstance():getEventDispatcher()
for _, create in ipairs({createTouchListener, createKeyListener}) do
local listener = create(self)
dispatcher:addEventListenerWithFixedPriority(listener, -10000)
listeners[#listeners+1] = listener
end
listeners[#listeners+1] = createEndFreameListener(self, dispatcher)
self.listeners = listeners
end
function Input:delete()
local dispatcher = cc.Director:getInstance():getEventDispatcher()
for _, listener in ipairs(self.listeners) do
dispatcher:removeEventListener(listener)
end
end
function Input:getTouchCount()
return #self.touches
end
function Input:getTouch(index)
return self.touches[index]
end
local function convertKeycode(keycode)
return type(keycode) == 'string' and cc.KeyCode[keycode] or keycode
end
function Input:getKey(keycode)
return self.keys[convertKeycode(keycode)]
end
function Input:getKeyDown(keycode)
return self.keydowns[convertKeycode(keycode)]
end
function Input:getKeyUp(keycode)
return self.keyups[convertKeycode(keycode)]
end
return Input
|
local blog_name = nil
local url_count = 0
local tries = 0
local previous_status_code = nil
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.lookup_host = function(host)
-- DNS resolve may fail if a label starts or ends with a hyphen or too long
if string.match(host, "%-.*%.roon%.io") or string.match(host, "%-%.roon%.io") or (
string.match(host, "%.roon%.io") and host:len() > 30
) then
return "107.22.208.70"
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
-- io.stdout:write(" ?" .. url .. " " .. tostring(verdict) .. ". \n")
-- io.stdout:flush()
if verdict and string.match(url, "%.roon%.io") and blog_name then
-- Ensure we only grab the blog we are interested in
if string.match(url, "//" .. blog_name .. "%.roon%.io") then
return true
else
return false
end
elseif verdict and string.match(url, "gravatar%.com") then
-- Grab only the avatars and not their blog
if string.match(url, "/avatar/") then
return true
else
return false
end
end
return verdict
end
wget.callbacks.httploop_result = function(url, err, http_stat)
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
previous_status_code = status_code
-- Handle case where spammers create links that are malformed
if (status_code == 400 or status_code == 414) and string.match(url["url"], "%.roon%.io") then
return wget.actions.FINISH
end
if status_code == 0 or status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 5")
tries = tries + 1
if tries >= 20 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
local sleep_time = 0.1 * (math.random(750, 1250) / 1000.0)
if string.match(url["host"], "amazonaws")then
-- We should be able to go fast on images since that's what a web browser does
sleep_time = 0
end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
if string.match(url, "https://roon%.io/api/v1/blogs") then
local content = read_file(file)
if previous_status_code == 404 then
io.stdout:write(" Nothing to grab here.\n")
io.stdout:flush()
return urls
end
blog_name = string.match(content, '"url":"http://([%a%d-]+).roon.io/"')
assert(blog_name)
io.stdout:write(" Grabbing the blog of " .. blog_name .. ".\n")
io.stdout:flush()
local new_url = "http://" .. blog_name .. ".roon.io/"
table.insert(urls, { url=new_url, link_expect_html=1 })
local username = string.match(content, '"username":"([^"]+)"')
assert(username)
new_url = "https://roon.io/" .. username
table.insert(urls, { url=new_url, link_expect_html=1 })
end
if string.match(url, "roon%.io") then
local html = read_file(file)
for extra_url in string.gmatch(html, 'data-2x="(https?://[^"]+)"') do
table.insert(urls, { url=extra_url })
end
end
return urls
end
|
local class = require("pl.class")
local sfmt = string.format
local fs = require("pl.path")
local dir = require("pl.dir")
local file = require("pl.file")
local tablex = require("pl.tablex")
local pretty = require("pl.pretty")
local Data = require("core.Data")
local Area = require("core.Area")
local Command = require("core.Command")
local CommandType = require("core.CommandType")
local Item = require("core.Item")
local Npc = require("core.Npc")
local QuestGoal = require("core.QuestGoal")
local QuestReward = require("core.QuestReward")
local Room = require("core.Room")
local Skill = require("core.Skill")
local SkillType = require("core.SkillType")
local Helpfile = require("core.Helpfile")
local Logger = require("core.Logger")
local AttributeFormula = require("core.Attribute").AttributeFormula
local srcPath = "./"
---@class BundleManager : Class
---@field state GameState
local M = class()
function M:_init(path, state)
if not path or not fs.exists(path) then error("Invalid bundle path") end
self.state = state
self.bundlesPath = path
self.areas = {}
self.loaderRegistry = self.state.EntityLoaderRegistry
end
function M:loadBundles(distribute)
distribute = distribute == nil and true or distribute
Logger.verbose("LOAD: BUNDLES")
local bundles = dir.getdirectories(self.bundlesPath)
for _, bundlePath in ipairs(bundles) do
local bundle = bundlePath:sub(#self.bundlesPath + 1)
if fs.isfile(bundlePath) or bundle == "." or bundle == ".." then
goto continue
end
if not tablex.find(self.state.Config.get("bundles", {}), bundle) then
goto continue
end
self:loadBundle(bundle, bundlePath)
::continue::
end
self.state.AttributeFactory:validateAttributes()
Logger.verbose("ENDLOAD: BUNDLES")
if not distribute then return end
Logger.verbose("DIST: ...............")
for _, areaRef in ipairs(self.areas) do
Logger.verbose("-------------------DIST AREA:%s-------------------", areaRef)
local area = self.state.AreaFactory:create(areaRef)
area:hydrate(self.state)
self.state.AreaManager:addArea(area)
end
end
function M:loadBundle(bundle, bundlePath)
--- every bundle can have this features
local features = {
-- quest goals/rewards have to be loaded before areas that have quests which use those goals
{ path = "quest-goals/", fn = "loadQuestGoals" },
{ path = "quest-rewards/", fn = "loadQuestRewards" },
{ path = "attributes.lua", fn = "loadAttributes" },
-- any entity in an area, including the area itself, can have behaviors so load them first
{ path = "behaviors/", fn = "loadBehaviors" },
{ path = "channels.lua", fn = "loadChannels" },
{ path = "commands/", fn = "loadCommands" },
{ path = "effects/", fn = "loadEffects" },
{ path = "input-events/", fn = "loadInputEvents" },
{ path = "server-events/", fn = "loadServerEvents" },
{ path = "player-events.lua", fn = "loadPlayerEvents" },
{ path = "skills/", fn = "loadSkills" },
}
Logger.verbose("LOAD: BUNDLE [%s] START", bundle)
for _, feature in ipairs(features) do
local path = bundlePath .. "/" .. feature.path
if fs.exists(path) then self[feature.fn](self, bundle, path) end
end
self:loadAreas(bundle)
self:loadHelp(bundle)
Logger.verbose("ENDLOAD: BUNDLE [%q]", bundle)
end
function M:loadQuestGoals(bundle, goalsDir)
Logger.verbose("\tLOAD: Quest Goals...")
local files = dir.getfiles(goalsDir)
for _, goalPath in ipairs(files) do
local _, goalFile = fs.splitpath(goalPath)
if not Data.isScriptFile(goalPath, goalFile) then goto continue end
local goalName, ext = fs.splitext(goalFile)
local loader = loadfile(goalPath)()
local goalImport = QuestGoal:class_of(loader()) and loader or
loader(srcPath)
Logger.verbose("\t\t%s", goalName)
self.state.QuestGoalManager:set(goalName, goalImport)
Logger.verbose("\tENDLOAD: Quest Goals...")
::continue::
end
end
function M:loadQuestRewards(bundle, rewardsDir)
Logger.verbose("\tLOAD: Quest Rewards...")
local files = dir.getfiles(rewardsDir)
for _, rewardPath in ipairs(files) do
local _, rewardFile = fs.splitpath(rewardPath)
if not Data.isScriptFile(rewardPath, rewardFile) then goto continue end
local rewardName, ext = fs.splitext(rewardFile)
local loader = loadfile(rewardPath)()
local rewardImport = QuestReward:class_of(loader()) and loader or
loader(srcPath)
Logger.verbose("\t\t%s", rewardName)
self.state.QuestRewardManager:set(rewardName, rewardImport)
end
Logger.verbose("\tENDLOAD: Quest Rewards...")
::continue::
end
function M:loadAttributes(bundle, attributesFile)
Logger.verbose("\tLOAD: Attributes...")
local attributes = loadfile(attributesFile, "bt")()
local errormsg = sfmt("\tAttributes file [%s] from bundle [%s]",
attributesFile, bundle)
if type(attributes) ~= "table" then
Logger.error("%s does not define an array of attributes", errormsg)
return
end
for _, attribute in ipairs(attributes) do
if type(attribute) ~= "table" then
Logger.error("%s not an object", errormsg)
goto continue
end
if not attribute["name"] or not attribute["base"] then
Logger.error("%s does not include required properties name and base",
errormsg)
goto continue
end
local formula
if attribute.formula then
formula = AttributeFormula(attribute.formula.requires,
attribute.formula.fn)
end
Logger.verbose("\t\t-> %s", attribute.name)
self.state.AttributeFactory:add(attribute.name, attribute.base, formula,
attribute.metadata)
::continue::
end
Logger.verbose("\tENDLOAD: Attributes...")
end
function M:loadPlayerEvents(bundle, eventsFile)
Logger.verbose("\tLOAD: Player Events...")
local loader = loadfile(eventsFile)()
local playerListeners = self:_getLoader(loader, srcPath).listeners
for eventName, listener in pairs(playerListeners) do
Logger.verbose("\t\tEvent: %s", eventName)
self.state.PlayerManager:addListener(eventName, listener(self.state))
end
Logger.verbose("\tENDLOAD: Player Events...")
end
function M:loadAreas(bundle)
Logger.verbose("\tLOAD: Areas...");
local areaLoader = self.loaderRegistry:get("areas");
areaLoader:setBundle(bundle);
local areas = {};
if not areaLoader:hasData() then return areas end
areas = areaLoader:fetchAll();
for name, manifest in pairs(areas) do
self.areas[#self.areas + 1] = name
self:loadArea(bundle, name, manifest)
end
Logger.verbose("\tENDLOAD: Areas");
end
function M:loadArea(bundle, areaName, manifest)
local definition = {
bundle = bundle,
manifest = manifest,
quests = {},
items = {},
npcs = {},
rooms = {},
}
local scriptPath = self:_getAreaScriptPath(bundle, areaName)
if manifest.script then
local areaScriptPath = sfmt("%s/%s.lua", scriptPath, manifest.script) -- '${scriptPath}/${manifest.script}.js'
if not fs.exists(areaScriptPath) then
Logger.warn("\t\t\t[%s] has non-existent script \"%s\"", areaName,
manifest.script)
end
Logger.verbose("\t\t\tLoading Area Script for [%s]: %s", areaName,
manifest.script)
self:loadEntityScript(self.state.AreaFactory, areaName, areaScriptPath)
end
Logger.verbose("\t\tLOAD: Quests...")
definition.quests = self:loadQuests(bundle, areaName)
Logger.verbose("\t\tLOAD: Items...")
definition.items = self:loadEntities(bundle, areaName, "items",
self.state.ItemFactory)
Logger.verbose("\t\tLOAD: NPCs...")
definition.npcs = self:loadEntities(bundle, areaName, "npcs",
self.state.MobFactory)
Logger.verbose("\t\tLOAD: Rooms...")
definition.rooms = self:loadEntities(bundle, areaName, "rooms",
self.state.RoomFactory)
Logger.verbose("\t\tDone.")
for _, npcRef in pairs(definition.npcs) do
local npc = self.state.MobFactory:getDefinition(npcRef)
if not npc.quests then goto continue end
for _, qid in ipairs(npc.quests) do
local quest = self.state.QuestFactory:get(qid)
if not quest then
Logger.error("\t\t\tError: NPC is questor for non-existent quest [%q]",
qid)
goto continue2
end
quest.npc = npcRef
self.state.QuestFactory:set(qid, quest)
::continue2::
end
::continue::
end
self.state.AreaFactory:setDefinition(areaName, definition)
end
function M:loadEntities(bundle, areaName, type, factory)
local loader = self.loaderRegistry:get(type)
loader:setBundle(bundle)
loader:setArea(areaName)
if not loader:hasData() then return {} end
local entities = loader:fetchAll()
if not entities then
Logger.warn("\t\t\t%q has an invalid value [%q]", type, entities)
return {}
end
local scriptPath = self:_getAreaScriptPath(bundle, areaName)
local res = {}
for _, entity in ipairs(entities) do
local entityRef = factory:createEntityRef(areaName, entity.id)
factory:setDefinition(entityRef, entity)
if entity.script then
local entityScript = sfmt("%s/%s/%s.lua", scriptPath, type, entity.script)
if not fs.exists(entityScript) then
Logger.warn("\t\t\t[%s] has non-existent script \"%s\"", entityRef,
entity.script)
else
Logger.verbose("\t\t\tLoading Script [%s] %s", entityRef, entity.script)
self:loadEntityScript(factory, entityRef, entityScript)
end
end
res[#res + 1] = entityRef
end
return res
end
function M:loadEntityScript(factory, entityRef, scriptPath)
local loader = loadfile(scriptPath, "bt")()
local scriptListeners = self:_getLoader(loader, srcPath).listeners
for eventName, listener in pairs(scriptListeners) do
Logger.verbose("\t\t\t\tEvent: %s", eventName)
factory:addScriptListener(entityRef, eventName, listener(self.state))
end
end
function M:loadQuests(bundle, areaName)
local loader = self.loaderRegistry:get("quests")
loader:setBundle(bundle)
loader:setArea(areaName)
local ok, quests = pcall(loader.fetchAll, loader)
if not ok then
Logger.warn(quests)
quests = {}
end
local res = {}
for _, quest in pairs(quests) do
Logger.verbose("\t\t\tLoading Quest [%s:%s]", areaName, quest.id)
self.state.QuestFactory:add(areaName, quest.id, quest)
res[#res + 1] = self.state.QuestFactory:makeQuestKey(areaName, quest.id)
end
return res
end
function M:loadCommands(bundle, commandsDir)
Logger.verbose("\tLOAD: Commands...")
local files = dir.getallfiles(commandsDir)
for _, commandPath in ipairs(files) do
local _, commandFile = fs.splitpath(commandPath)
if not Data.isScriptFile(commandPath, commandFile) then goto continue end
local commandName = fs.splitext(commandFile)
Logger.verbose("\t\tCommand: %q", commandName)
local command = self:createCommand(commandPath, commandName, bundle)
self.state.CommandManager:add(command)
::continue::
end
Logger.verbose("\tENDLOAD: Commands...")
end
function M:createCommand(commandPath, commandName, bundle)
local loader = loadfile(commandPath)()
local cmdImport = self:_getLoader(loader, srcPath, self.bundlesPath)
cmdImport.command = cmdImport.command(self.state)
return Command(bundle, commandName, cmdImport, commandPath)
end
function M:loadChannels(bundle, channelsFile)
Logger.verbose("\tLOAD: Channels...")
local loader = loadfile(channelsFile)()
local channels = self:_getLoader(loader, srcPath)
if type(channels) ~= "table" then channels = { channels } end
tablex.foreachi(channels, function(channel, i)
channel.bundle = bundle
self.state.ChannelManager:add(channel)
end)
Logger.verbose("\tENDLOAD: Channels...")
end
function M:loadHelp(bundle)
Logger.verbose("\tLOAD: Help...")
local loader = self.loaderRegistry:get("help")
loader:setBundle(bundle)
if not loader:hasData() then return end
local records = loader:fetchAll()
for helpName, body in pairs(records) do
local hfile = Helpfile(bundle, helpName, body)
self.state.HelpManager:add(hfile)
end
Logger.verbose("\tENDLOAD: Help...")
end
function M:loadInputEvents(bundle, inputEventsDir)
Logger.verbose("\tLOAD: Events...")
local files = dir.getallfiles(inputEventsDir)
for _, eventPath in ipairs(files) do
local _, eventFile = fs.splitpath(eventPath)
if not Data.isScriptFile(eventPath, eventFile) then goto continue end
local eventName = fs.splitext(eventFile)
local loader = loadfile(eventPath)()
local eventImport = self:_getLoader(loader, srcPath)
if type(eventImport.event) ~= "function" then
error(sfmt(
"Bundle %s has an invalid input event %s. Expected a function, got: %q",
bundle, eventName, eventImport.event))
end
self.state.InputEventManager:add(eventName, eventImport.event(self.state))
::continue::
end
Logger.verbose("\tENDLOAD: Events...")
end
function M:loadBehaviors(bundle, behaviorsDir)
Logger.verbose("\tLOAD: Behaviors...")
local loadEntityBehaviors = function(type, manager, state)
local typeDir = behaviorsDir .. type .. "/"
if not fs.exists(typeDir) then return end
Logger.verbose("\t\tLOAD: BEHAVIORS [%s]...", type)
local files = dir.getallfiles(typeDir)
for _, behaviorPath in ipairs(files) do
local _, behaviorFile = fs.splitpath(behaviorPath)
-- local behaviorPath = typeDir .. behaviorFile
if not Data.isScriptFile(behaviorPath, behaviorFile) then
goto continue
end
local behaviorName = fs.splitext(behaviorFile)
Logger.verbose("\t\t\tLOAD: BEHAVIORS [%s] %s...", type, behaviorName)
local loader = loadfile(behaviorPath)()
local behaviorListeners = self:_getLoader(loader, srcPath).listeners
for eventName, listener in pairs(behaviorListeners) do
manager:addListener(behaviorName, eventName, listener(state))
end
::continue::
end
end
loadEntityBehaviors("area", self.state.AreaBehaviorManager, self.state)
loadEntityBehaviors("npc", self.state.MobBehaviorManager, self.state)
loadEntityBehaviors("item", self.state.ItemBehaviorManager, self.state)
loadEntityBehaviors("room", self.state.RoomBehaviorManager, self.state)
Logger.verbose("\tENDLOAD: Behaviors...")
end
function M:loadEffects(bundle, effectsDir)
Logger.verbose("\tLOAD: Effects...")
local files = dir.getallfiles(effectsDir)
for _, effectPath in ipairs(files) do
local _, effectFile = fs.splitpath(effectPath)
if not Data.isScriptFile(effectPath, effectFile) then goto continue end
local effectName = fs.splitext(effectFile)
local loader = loadfile(effectPath)()
Logger.verbose("\t\t%s", effectName)
self.state.EffectFactory:add(effectName, self:_getLoader(loader, srcPath),
self.state)
::continue::
end
Logger.verbose("\tENDLOAD: Effects...")
end
function M:loadSkills(bundle, skillsDir)
Logger.verbose("\tLOAD: Skills...")
local files = dir.getfiles(skillsDir)
for _, skillPath in ipairs(files) do
local _, skillFile = fs.splitpath(skillPath)
if not Data.isScriptFile(skillPath, skillFile) then goto continue end
local skillName = fs.splitext(skillFile)
local loader = loadfile(skillPath)()
local skillImport = self:_getLoader(loader, srcPath)
if skillImport.run then skillImport.run = skillImport.run(self.state) end
Logger.verbose("\t\t%s", skillName)
local skill = Skill(skillName, skillImport, self.state)
if skill.type == SkillType.SKILL then
self.state.SkillManager:add(skill)
else
self.state.SpellManager:add(skill)
end
::continue::
end
Logger.verbose("\tENDLOAD: Skills...")
end
function M:loadServerEvents(bundle, serverEventsDir)
Logger.verbose("\tLOAD: Server Events...")
local files = dir.getallfiles(serverEventsDir)
for _, eventsPath in ipairs(files) do
local _, eventsFile = fs.splitpath(eventsPath)
if not Data.isScriptFile(eventsPath, eventsFile) then goto continue end
local eventsName = fs.splitext(eventsFile)
Logger.verbose("\t\t\tLOAD: SERVER-EVENTS %s...", eventsName)
local loader = loadfile(eventsPath)()
local eventsListeners = self:_getLoader(loader, srcPath).listeners
for eventName, listener in pairs(eventsListeners) do
self.state.ServerEventManager:add(eventName, listener(self.state))
end
::continue::
end
Logger.verbose("\tENDLOAD: Server Events...")
end
function M:_getLoader(loader, ...)
if type(loader) == "function" then return loader(...) end
return loader
end
function M:_getAreaScriptPath(bundle, areaName)
return sfmt("%s/%s/areas/%s/scripts", self.bundlesPath, bundle, areaName)
end
return M
|
--死境邪龙·法芙娜
local m=14010042
local cm=_G["c"..m]
function cm.initial_effect(c)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(m,0))
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(cm.spcon)
e1:SetOperation(cm.spop)
c:RegisterEffect(e1)
--dis summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(m,1))
e2:SetCategory(CATEGORY_DISABLE_SUMMON+CATEGORY_REMOVE)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EVENT_SUMMON)
e2:SetCondition(cm.con)
e2:SetTarget(cm.tg)
e2:SetOperation(cm.op)
c:RegisterEffect(e2)
--immune
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_IMMUNE_EFFECT)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetRange(LOCATION_MZONE)
e3:SetValue(cm.efilter)
c:RegisterEffect(e3)
end
function cm.filter1(c,tp,rg)
return rg:IsExists(cm.filter2,1,c,tp,c,rg)
end
function cm.filter2(c,tp,mc,rg)
local mg=Group.FromCards(c,mc)
return rg:IsExists(cm.filter3,1,mg,tp,mg)
end
function cm.filter3(c,tp,mg)
mg:AddCard(c)
return Duel.GetMZoneCount(tp,mg,tp)>0
end
function cm.spcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
local rg=Duel.GetMatchingGroup(function(c) return c:IsSummonType(SUMMON_TYPE_NORMAL) and c:IsReleasable() end,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
return rg:IsExists(cm.filter1,1,nil,tp,rg)
end
function cm.spop(e,tp,eg,ep,ev,re,r,rp,c)
local rg=Duel.GetMatchingGroup(function(c) return c:IsSummonType(SUMMON_TYPE_NORMAL) and c:IsReleasable() end,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE)
local g=rg:FilterSelect(tp,cm.filter1,1,1,nil,tp,rg)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE)
local g2=rg:FilterSelect(tp,cm.filter2,1,1,g,tp,g:GetFirst(),rg)
g:Merge(g2)
local g3=rg:FilterSelect(tp,cm.filter3,1,1,g,tp,g)
g:Merge(g3)
Duel.Release(g,REASON_COST)
end
function cm.efilter(e,te)
local c=e:GetHandler()
local ec=te:GetHandler()
if ec:IsHasCardTarget(c) or (te:IsHasType(EFFECT_TYPE_ACTIONS) and te:IsHasProperty(EFFECT_FLAG_CARD_TARGET) and c:IsRelateToEffect(te)) then return false
end
return true
end
function cm.con(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentChain()==0 and rp==1-tp
end
function cm.tg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DISABLE_SUMMON,eg,eg:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,eg:GetCount(),0,0)
end
function cm.op(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateSummon(eg)
Duel.Destroy(eg,REASON_EFFECT)
end
|
local player = ...
local stats = STATSMAN:GetCurStageStats():GetPlayerStageStats(player)
local PercentDP = stats:GetPercentDancePoints()
local percent = FormatPercentScore(PercentDP)
-- Format the Percentage string, removing the % symbol
percent = percent:gsub("%%", "")
return Def.ActorFrame{
Name="PercentageContainer"..ToEnumShortString(player),
OnCommand=function(self)
self:y( 5 )
self:x( -101 )
end,
-- dark background quad behind player percent score
Def.Quad{
InitCommand=cmd(diffuse, color("#101519"); zoomto, 102,40)
},
LoadFont("_wendy white")..{
Name="Percent",
Text = percent,
InitCommand=cmd(vertalign, middle; horizalign, right; zoom, 0.38),
OnCommand=cmd(x, 45)
}
}
|
--- Item
-- @classmod Data.Item
local Item = {
__class = 'Item',
__index = require('__stdlib__/stdlib/data/data'),
__call = require('__stdlib__/stdlib/data/data').__call
}
setmetatable(Item, Item)
return Item
|
--------------------------------
-- @module PhysicsSprite3D
-- @extend Sprite3D
-- @parent_module cc
--------------------------------
-- synchronize node transformation to physics.
-- @function [parent=#PhysicsSprite3D] syncNodeToPhysics
-- @param self
-- @return PhysicsSprite3D#PhysicsSprite3D self (return value: cc.PhysicsSprite3D)
--------------------------------
-- synchronize physics transformation to node.
-- @function [parent=#PhysicsSprite3D] syncPhysicsToNode
-- @param self
-- @return PhysicsSprite3D#PhysicsSprite3D self (return value: cc.PhysicsSprite3D)
--------------------------------
-- Get the Physics3DObject.
-- @function [parent=#PhysicsSprite3D] getPhysicsObj
-- @param self
-- @return Physics3DObject#Physics3DObject ret (return value: cc.Physics3DObject)
--------------------------------
-- Set synchronization flag, see Physics3DComponent.
-- @function [parent=#PhysicsSprite3D] setSyncFlag
-- @param self
-- @param #int syncFlag
-- @return PhysicsSprite3D#PhysicsSprite3D self (return value: cc.PhysicsSprite3D)
--------------------------------
--
-- @function [parent=#PhysicsSprite3D] PhysicsSprite3D
-- @param self
-- @return PhysicsSprite3D#PhysicsSprite3D self (return value: cc.PhysicsSprite3D)
return nil
|
return {
CACHE_AGE = 3600, -- seconds
ID_DELAY = 5000, -- milliseconds
GATEWAY_DELAY = 500, -- milliseconds,
DISCORD_EPOCH = 1420070400000, -- milliseconds
GATEWAY_VERSION = 6,
DEFAULT_AVATARS = 5,
ZWSP = '\226\128\139',
NS_PER_US = 1000,
US_PER_MS = 1000,
MS_PER_S = 1000,
S_PER_MIN = 60,
MIN_PER_HOUR = 60,
HOUR_PER_DAY = 24,
DAY_PER_WEEK = 7,
GATEWAY_VERSION_VOICE = 3,
}
|
function gflags_configs()
return {system = false, configs = {mt = true, shared = true, debug = true}}
end
|
require( "components/cavern/cavern_encounter" )
--------------------------------------------------------------------
if encounter_combat_sniper == nil then
encounter_combat_sniper = class( {}, {}, CCavernEncounter )
end
--------------------------------------------------------------------
function encounter_combat_sniper:GetEncounterType()
return CAVERN_ROOM_TYPE_MOB
end
--------------------------------------------------------------------
function encounter_combat_sniper:GetEncounterLevels()
return { 2 }
end
--------------------------------------------------------------------
function encounter_combat_sniper:Start()
CCavernEncounter.Start( self )
self.nNumUnitsToSpawn = 1
for i = 1, self.nNumUnitsToSpawn do
local vSpawnPoint = self.hRoom.vRoomCenter
local hUnit = self:SpawnCreepByName( "npc_dota_creature_sniper", vSpawnPoint, true, nil, nil, DOTA_TEAM_BADGUYS )
--hUnit:FaceTowards( vSpawnPoint + RandomVector( 1 ) * flOffsetMin )
end
self.hRoom.hRoomVolume:SetContextThink( GetEncounterContext( "Sniper" ), function() return self:OnThink() end, 0.0 )
return true
end
--------------------------------------------------------------------
function encounter_combat_sniper:OnThink()
if IsServer() then
if not self.bActive then
return nil
end
return 1.0
end
end
--------------------------------------------------------------------
|
-- 1.2.1 Control de más salidas y su configuración
-- configuro los pines
local D1 = 1
local D2 = 2
-- condiguro los pines como salida
gpio.mode(D1, 0)
gpio.mode(D2, 0)
-- encneder los LEDs
gpio.write(D1,1)
gpio.write(D2,1)
|
------------------------------------------------------------------------
--- @file arp.lua
--- @brief Address resolution protocol (ARP) utility.
--- Utility functions for the arp_header struct
--- defined in \ref headers.lua . \n
--- Includes:
--- - Arp constants
--- - Arp address utility
--- - Arp header utility
--- - Definition of Arp packets
--- - Arp handler task
------------------------------------------------------------------------
local ffi = require "ffi"
local pkt = require "packet"
require "headers"
local dpdkc = require "dpdkc"
local dpdk = require "dpdk"
local memory = require "memory"
local filter = require "filter"
local ns = require "namespaces"
local eth = require "proto.ethernet"
local ntoh, hton = ntoh, hton
local ntoh16, hton16 = ntoh16, hton16
local bor, band, bnot, rshift, lshift= bit.bor, bit.band, bit.bnot, bit.rshift, bit.lshift
local format = string.format
local istype = ffi.istype
--------------------------------------------------------------------------------------------------------
---- ARP constants (c.f. http://www.iana.org/assignments/arp-parameters/arp-parameters.xhtml)
--------------------------------------------------------------------------------------------------------
--- Arp protocol constants
local arp = {}
--- Hardware address type for ethernet
arp.HARDWARE_ADDRESS_TYPE_ETHERNET = 1
--- Proto address type for IP (for ethernet based protocols uses etherType numbers \ref ethernet.lua)
arp.PROTO_ADDRESS_TYPE_IP = 0x0800
--- Operation: request
arp.OP_REQUEST = 1
--- Operation: reply
arp.OP_REPLY = 2
--------------------------------------------------------------------------------------------------------
---- ARP header
--------------------------------------------------------------------------------------------------------
--- Module for arp_header struct (see \ref headers.lua).
local arpHeader = {}
arpHeader.__index = arpHeader
--- Set the hardware address type.
--- @param int Type as 16 bit integer.
function arpHeader:setHardwareAddressType(int)
int = int or arp.HARDWARE_ADDRESS_TYPE_ETHERNET
self.hrd = hton16(int)
end
--- Retrieve the hardware address type.
--- @return Type as 16 bit integer.
function arpHeader:getHardwareAddressType()
return hton16(self.hrd)
end
--- Retrieve the hardware address type.
--- @return Type in string format.
function arpHeader:getHardwareAddressTypeString()
local type = self:getHardwareAddressType()
if type == arp.HARDWARE_ADDRESS_TYPE_ETHERNET then
return "Ethernet"
else
return format("0x%04x", type)
end
end
--- Set the protocol address type.
--- @param int Type as 16 bit integer.
function arpHeader:setProtoAddressType(int)
int = int or arp.PROTO_ADDRESS_TYPE_IP
self.pro = hton16(int)
end
--- Retrieve the protocol address type.
--- @return Type as 16 bit integer.
function arpHeader:getProtoAddressType()
return hton16(self.pro)
end
--- Retrieve the protocol address type.
--- @return Type in string format.
function arpHeader:getProtoAddressTypeString()
local type = self:getProtoAddressType()
if type == arp.PROTO_ADDR_TYPE_IP then
return "IPv4"
else
return format("0x%04x", type)
end
end
--- Set the hardware address length.
--- @param int Length as 8 bit integer.
function arpHeader:setHardwareAddressLength(int)
int = int or 6
self.hln = int
end
--- Retrieve the hardware address length.
--- @return Length as 8 bit integer.
function arpHeader:getHardwareAddressLength()
return self.hln
end
--- Retrieve the hardware address length.
--- @return Length in string format.
function arpHeader:getHardwareAddressLengthString()
return self:getHardwareAddressLength()
end
--- Set the protocol address length.
--- @param int Length as 8 bit integer.
function arpHeader:setProtoAddressLength(int)
int = int or 4
self.pln = int
end
--- Retrieve the protocol address length.
--- @return Length as 8 bit integer.
function arpHeader:getProtoAddressLength()
return self.pln
end
--- Retrieve the protocol address length.
--- @return Length in string format.
function arpHeader:getProtoAddressLengthString()
return self:getProtoAddressLength()
end
--- Set the operation.
--- @param int Operation as 16 bit integer.
function arpHeader:setOperation(int)
int = int or arp.OP_REQUEST
self.op = hton16(int)
end
--- Retrieve the operation.
--- @return Operation as 16 bit integer.
function arpHeader:getOperation()
return hton16(self.op)
end
--- Retrieve the operation.
--- @return Operation in string format.
function arpHeader:getOperationString()
local op = self:getOperation()
if op == arp.OP_REQUEST then
return "Request"
elseif op == arp.OP_REPLY then
return "Reply"
else
return op
end
end
--- Set the hardware source address.
--- @param addr Address in 'union mac_address' format.
function arpHeader:setHardwareSrc(addr)
self.sha:set(addr)
end
--- Retrieve the hardware source address.
--- @return Address in 'union mac_address' format.
function arpHeader:getHardwareSrc()
return self.sha:get()
end
--- Set the hardware source address.
--- @param addr Address in string format.
function arpHeader:setHardwareSrcString(addr)
self.sha:setString(addr)
end
--- Retrieve the hardware source address.
--- @return Address in string format.
function arpHeader:getHardwareSrcString()
return self.sha:getString()
end
--- Set the hardware destination address.
--- @param addr Address in 'union mac_address' format.
function arpHeader:setHardwareDst(addr)
self.tha:set(addr)
end
--- Retrieve the hardware destination address.
--- @return Address in 'union mac_address' format.
function arpHeader:getHardwareDst()
return self.tha:get()
end
--- Set the hardware destination address.
--- @param addr Address in string format.
function arpHeader:setHardwareDstString(addr)
self.tha:setString(addr)
end
--- Retrieve the hardware destination address.
--- @return Address in string format.
function arpHeader:getHardwareDstString()
return self.tha:getString()
end
--- Set the protocol source address.
--- @param addr Address in 'struct ip4_address' format.
function arpHeader:setProtoSrc(addr)
self.spa:set(addr)
end
--- Retrieve the protocol source address.
--- @return Address in 'struct ip4_address' format.
function arpHeader:getProtoSrc()
return self.spa:get()
end
--- Set the protocol source address.
--- @param addr Address in source format.
function arpHeader:setProtoSrcString(addr)
self.spa:setString(addr)
end
--- Retrieve the protocol source address.
--- @return Address in string format.
function arpHeader:getProtoSrcString()
return self.spa:getString()
end
--- Set the protocol destination address.
--- @param addr Address in 'struct ip4_address' format.
function arpHeader:setProtoDst(addr)
self.tpa:set(addr)
end
--- Retrieve the protocol destination address.
--- @return Address in 'struct ip4_address' format.
function arpHeader:getProtoDst()
return self.tpa:get()
end
--- Set the protocol destination address.
--- @param addr Address in string format.
function arpHeader:setProtoDstString(addr)
self.tpa:setString(addr)
end
--- Retrieve the protocol destination address.
--- @return Address in string format.
function arpHeader:getProtoDstString()
return self.tpa:getString()
end
--- Set all members of the ip header.
--- Per default, all members are set to default values specified in the respective set function.
--- Optional named arguments can be used to set a member to a user-provided value.
--- @param args Table of named arguments. Available arguments: HardwareAddressType, ProtoAddressType, HardwareAddressLength, ProtoAddressLength, Operation, HardwareSrc, HardwareDst, ProtoSrc, ProtoDst
--- @param pre prefix for namedArgs. Default 'arp'.
--- @code
--- fill() --- only default values
--- fill{ arpOperation=2, ipTTL=100 } --- all members are set to default values with the exception of arpOperation
--- @endcode
function arpHeader:fill(args, pre)
args = args or {}
pre = pre or "arp"
self:setHardwareAddressType(args[pre .. "HardwareAddressType"])
self:setProtoAddressType(args[pre .. "ProtoAddressType"])
self:setHardwareAddressLength(args[pre .. "HardwareAddressLength"])
self:setProtoAddressLength(args[pre .. "ProtoAddressLength"])
self:setOperation(args[pre .. "Operation"])
local hwSrc = pre .. "HardwareSrc"
local hwDst = pre .. "HardwareDst"
local prSrc = pre .. "ProtoSrc"
local prDst = pre .. "ProtoDst"
args[hwSrc] = args[hwSrc] or "01:02:03:04:05:06"
args[hwDst] = args[hwDst] or "07:08:09:0a:0b:0c"
args[prSrc] = args[prSrc] or "0.1.2.3"
args[prDst] = args[prDst] or "4.5.6.7"
-- if for some reason the address is in 'union mac_address'/'union ipv4_address' format, cope with it
if type(args[hwSrc]) == "string" then
self:setHardwareSrcString(args[hwSrc])
else
self:setHardwareSrc(args[hwSrc])
end
if type(args[hwDst]) == "string" then
self:setHardwareDstString(args[hwDst])
else
self:setHardwareDst(args[hwDst])
end
if type(args[prSrc]) == "string" then
self:setProtoSrcString(args[prSrc])
else
self:setProtoSrc(args[prSrc])
end
if type(args[prDst]) == "string" then
self:setProtoDstString(args[prDst])
else
self:setProtoDst(args[prDst])
end
end
--- Retrieve the values of all members.
--- @param pre prefix for namedArgs. Default 'arp'.
--- @return Table of named arguments. For a list of arguments see "See also".
--- @see arpHeader:fill
function arpHeader:get(pre)
pre = pre or "arp"
local args = {}
args[pre .. "HardwareAddressType"] = self:getHardwareAddressType()
args[pre .. "ProtoAddressType"] = self:getProtoAddressType()
args[pre .. "HardwareAddressLength"] = self:getHardwareAddressLength()
args[pre .. "ProtoAddressLength"] = self:getProtoAddressLength()
args[pre .. "Operation"] = self:getOperation()
args[pre .. "HardwareSrc"] = self:getHardwareSrc()
args[pre .. "HardwareDst"] = self:getHardwareDst()
args[pre .. "ProtoSrc"] = self:getProtoSrc()
args[pre .. "ProtoDst"] = self:getProtoDst()
return args
end
--- Retrieve the values of all members.
--- @return Values in string format.
function arpHeader:getString()
local str = "ARP hrd " .. self:getHardwareAddressTypeString()
.. " (hln " .. self:getHardwareAddressLengthString()
.. ") pro " .. self:getProtoAddressTypeString()
.. " (pln " .. self:getProtoAddressLength(String)
.. ") op " .. self:getOperationString()
local op = self:getOperation()
if op == arp.OP_REQUEST then
str = str .. " who-has " .. self:getProtoDstString()
.. " (" .. self:getHardwareDstString()
.. ") tell " .. self:getProtoSrcString()
.. " (" .. self:getHardwareSrcString()
.. ")"
elseif op == arp.OP_REPLY then
str = str .. " " .. self:getProtoSrcString()
.. " is-at " .. self:getHardwareSrcString()
.. " (for " .. self:getProtoDstString()
.. " @ " .. self:getHardwareDstString()
.. ")"
else
str = str .. " " .. self:getHardwareSrcString()
.. " > " .. self:getHardwareDstString()
.. " " .. self:getProtoSrcString()
.. " > " .. self:getProtoDstString()
end
return str
end
--- Resolve which header comes after this one (in a packet).
--- For instance: in tcp/udp based on the ports.
--- This function must exist and is only used when get/dump is executed on
--- an unknown (mbuf not yet casted to e.g. tcpv6 packet) packet (mbuf)
--- @return String next header (e.g. 'udp', 'icmp', nil)
function arpHeader:resolveNextHeader()
return nil
end
--- Change the default values for namedArguments (for fill/get).
--- This can be used to for instance calculate a length value based on the total packet length.
--- See proto/ip4.setDefaultNamedArgs as an example.
--- This function must exist and is only used by packet.fill.
--- @param pre The prefix used for the namedArgs, e.g. 'arp'
--- @param namedArgs Table of named arguments (see See Also)
--- @param nextHeader The header following after this header in a packet
--- @param accumulatedLength The so far accumulated length for previous headers in a packet
--- @return Table of namedArgs
--- @see arpHeader:fill
function arpHeader:setDefaultNamedArgs(pre, namedArgs, nextHeader, accumulatedLength)
return namedArgs
end
---------------------------------------------------------------------------------
---- Packets
---------------------------------------------------------------------------------
--- Cast the packet to an Arp packet
pkt.getArpPacket = packetCreate("eth", "arp")
---------------------------------------------------------------------------------
---- ARP Handler Task
---------------------------------------------------------------------------------
--- Arp handler task, responds to ARP queries for given IPs and performs arp lookups
--- @todo TODO implement garbage collection/refreshing entries \n
--- the current implementation does not handle large tables efficiently \n
--- @todo TODO multi-NIC support
arp.arpTask = "__MG_ARP_TASK"
--- Arp table
--- TODO docu
local arpTable = ns:get()
--- Arp handler task
--- @param qs TODO
--- @todo TODO docu
local function arpTask(qs)
-- two ways to call this: single nic or array of nics
if qs[1] == nil and qs.rxQueue then
return arpTask({ qs })
end
local ipToMac = {}
-- loop over NICs/Queues
for _, nic in pairs(qs) do
if nic.txQueue.dev ~= nic.rxQueue.dev then
error("both queues must belong to the same device")
end
if type(nic.ips) == "string" then
nic.ips = { nic.ips }
end
for _, ip in pairs(nic.ips) do
ipToMac[parseIPAddress(ip)] = nic.txQueue.dev:getMacString()
end
nic.txQueue.dev:l2Filter(eth.TYPE_ARP, nic.rxQueue)
end
local rxBufs = memory.createBufArray(1)
local txMem = memory.createMemPool(function(buf)
buf:getArpPacket():fill{
arpOperation = arp.OP_REPLY,
pktLength = 60
}
end)
local txBufs = txMem:bufArray(1)
arpTable.taskRunning = true
while dpdk.running() do
for _, nic in pairs(qs) do
rx = nic.rxQueue:tryRecvIdle(rxBufs, 1000)
assert(rx <= 1)
if rx > 0 then
local rxPkt = rxBufs[1]:getArpPacket()
if rxPkt.eth:getType() == eth.TYPE_ARP then
if rxPkt.arp:getOperation() == arp.OP_REQUEST then
local ip = rxPkt.arp:getProtoDst()
local mac = ipToMac[ip]
if mac then
txBufs:alloc(60)
-- TODO: a single-packet API would be nice for things like this
local pkt = txBufs[1]:getArpPacket()
pkt.eth:setSrcString(mac)
pkt.eth:setDst(rxPkt.eth:getSrc())
pkt.arp:setOperation(arp.OP_REPLY)
pkt.arp:setHardwareDst(rxPkt.arp:getHardwareSrc())
pkt.arp:setHardwareSrcString(mac)
pkt.arp:setProtoDst(rxPkt.arp:getProtoSrc())
pkt.arp:setProtoSrc(ip)
nic.txQueue:send(txBufs)
end
elseif rxPkt.arp:getOperation() == arp.OP_REPLY then
-- learn from all arp replies we see (arp cache poisoning doesn't matter here)
local mac = rxPkt.arp:getHardwareSrcString()
local ip = rxPkt.arp:getProtoSrcString()
arpTable[tostring(parseIPAddress(ip))] = { mac = mac, timestamp = dpdk.getTime() }
end
end
rxBufs:freeAll()
end
end
-- send outstanding requests
arpTable:forEach(function(ip, value)
-- TODO: refresh or GC old entries
if value ~= "pending" then
return
end
arpTable[ip] = "requested"
-- TODO: the format should be compatible with parseIPAddress
ip = tonumber(ip)
txBufs:alloc(60)
local pkt = txBufs[1]:getArpPacket()
pkt.eth:setDstString(eth.BROADCAST)
pkt.arp:setOperation(arp.OP_REQUEST)
pkt.arp:setHardwareDstString(eth.BROADCAST)
pkt.arp:setProtoDst(ip)
-- TODO: do not send requests on all devices, but only the relevant
for _, nic in pairs(qs) do
local mac = nic.txQueue.dev:getMacString()
pkt.eth:setSrcString(mac)
pkt.arp:setProtoSrc(parseIPAddress(nic.ips[1]))
pkt.arp:setHardwareSrcString(mac)
nic.txQueue:send(txBufs)
end
end)
dpdk.sleepMillisIdle(1)
end
end
--- Perform a lookup in the ARP table.
--- Lookup the MAC address for a given IP.
--- Blocks for up to 1 second if the arp task is not yet running
--- Caution: this function uses locks and namespaces, must not be used in the fast path
--- @param ip The ip address in string or cdata format to look up.
function arp.lookup(ip)
if type(ip) == "string" then
ip = parseIPAddress(ip)
elseif type(ip) == "cdata" then
ip = ip:get()
end
if not arpTable.taskRunning then
local waitForArpTask = 0
while not arpTable.taskRunning and waitForArpTask < 10 do
dpdk.sleepMillis(100)
end
if not arpTable.taskRunning then
error("ARP task is not running")
end
end
local mac = arpTable[tostring(ip)]
if type(mac) == "table" then
return mac.mac, mac.timestamp
end
arpTable.lock(function()
if not arpTable[tostring(ip)] then
arpTable[tostring(ip)] = "pending"
end
end)
return nil
end
--- Perform a non-blocking lookup in the ARP table.
--- @param ip The ip address in string or cdata format to look up.
--- @param timeout TODO
--- @todo FIXME: this only sends a single request
function arp.blockingLookup(ip, timeout)
local timeout = dpdk.getTime() + timeout
repeat
local mac, ts = arp.lookup(ip)
if mac then
return mac, ts
end
dpdk.sleepMillisIdle(1000)
until dpdk.getTime() >= timeout
end
__MG_ARP_TASK = arpTask
---------------------------------------------------------------------------------
---- Metatypes
---------------------------------------------------------------------------------
ffi.metatype("struct arp_header", arpHeader)
return arp
|
-- cbind - A library for generating bindings.
-- Written in 2014 by Jesper Oskarsson jesosk@gmail.com
--
-- To the extent possible under law, the author(s) have dedicated all copyright
-- and related and neighboring rights to this software to the public domain worldwide.
-- This software is distributed without any warranty.
--
-- You should have received a copy of the CC0 Public Domain Dedication along with this software.
-- If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
local function each( list, func )
for _, item in ipairs( list ) do
func( item )
end
end
local symbol_exists
local function add_identifier( symbol, name )
if symbol_exists[name] then
error( "Identifier has already been defined: '" .. name .. "'" )
end
symbol_exists[name] = true
end
local function class_statement( symbol )
if symbol.is_define_member then
for i = 1, #symbol.identifier_type_pairs do
add_identifier(symbol, symbol.identifier_type_pairs[i].name.token.value)
end
end
if symbol.is_property then
add_identifier(symbol, symbol.name.token.value)
end
end
function cdef_error_checking( symbol )
symbol_exists = {}
if symbol.is_class then
each( symbol.statements, class_statement )
end
end
|
local table_insert = table.insert
local todefault = function(x)
return x == 'default' and '' or x
end
local platform_table = {
macos='macosx',
}
local toplatform = function(plat)
return platform_table[plat] or plat
end
local compiler_table = {
msvc='cl',
}
local tocomp = function(comp)
return compiler_table[comp] or comp
end
return {
ignore = {
-- msvc_isystem=true,
msvc_isystem={external_as_include_system_flag=true},
},
tostroption=function(_, optname)
return _.optprefix .. optname:gsub('_', '-')
end,
start=function(_, optprefix)
_.optprefix = optprefix or ''
_:_vcond_init({
_not='not',
_and='and',
_or='or',
openblock='',
closeblock='',
ifopen='',
ifclose='then',
endif='end',
})
local funcprefix = (_.is_C and 'jln_c_' or 'jln_cxx_')
local compprefix = (_.is_C and 'cc' or 'cxx')
local cxflags = _.is_C and 'cflags' or 'cxxflags'
local import_base = _.is_C and 'c' or 'cpp'
_.cxflags_name = cxflags
local extraopts = {
{compprefix, 'Path or name of the compiler for jln functions'},
{compprefix..'_version', 'Force the compiler version for jln functions'},
{'ld', 'Path or name of the linker for jln functions'},
}
_:print('local _extraopt_flag_names = {')
for i,extra in ipairs(extraopts) do
local optname = extra[1]
local opt = _:tostroption(optname)
_:print(' ["' .. opt .. '"] = true,')
_:print(' ["' .. optname .. '"] = true,')
end
_:print('}\n')
_:print('local _flag_names = {')
for option in _:getoptions() do
local opt = _:tostroption(option.name)
local list = {}
for _,arg in ipairs(option.values) do
table_insert(list, '["' .. arg .. '"]="' .. todefault(arg) .. '", ')
end
local allowed = table.concat(list)
_:print(' ["' .. opt .. '"] = {' .. allowed .. '[""]=""},')
if opt ~= option.name then
_:print(' ["' .. option.name .. '"] = {' .. allowed .. '[""]=""},')
end
end
_:print('}\n')
local common_code = _:get_output()
_._strs = {}
_:print_header('--')
_:print([[
local _import_base = ']] .. import_base .. [['
-- Registers new command-line options and set default values
-- `default_options` (see create_options())
-- `extra_options` = {
-- category :string|boolean = false -- add a category for option()
-- import_base: string = ']] .. import_base .. [[' -- default value for ]] .. funcprefix .. [[rule()
-- }
]])
_:print('\nfunction ' .. funcprefix .. 'init_options(default_options, extra_options)')
_:print(common_code)
_:print([[
if default_options then
for k,v in pairs(default_options) do
local ref = _flag_names[k]
if not ref then
if not _extraopt_flag_names[k] then
local msg = "Unknown '" .. k .. "' jln flag name"
print(msg)
error(msg)
end
elseif not ref[v] then
local msg = "Unknown value '" .. v .. "' for '" .. k .. "'"
print(msg)
error(msg)
end
end
else
default_options = {}
end
local check_option = function(opt, optname)
local value = get_config(opt)
if not _flag_names[optname][value] then
os.raise(vformat("${color.error}Unknown value '%s' for '%s'", value, opt))
end
end
extra_options = extra_options or {}
_import_base = extra_options.import_base or _import_base
local category = extra_options.category
category = category == true and ']] .. funcprefix .. [[flags'
or category
or nil
]])
for option in _:getoptions() do
local optname = option.name
local opt = _:tostroption(optname)
_:print(' option("' .. opt .. '", {')
_:print(' showmenu=true,')
_:print(' category=category,')
_:print(' description="' .. quotable_desc(option) .. '",')
_:print(' values={"' .. table.concat(option.values, '", "') .. '"},')
_:print(' default=default_options["' .. optname .. '"] '
.. (opt ~= optname and 'or default_options["' .. opt .. '"] ' or '')
.. 'or "' .. option.default .. '",')
_:print(' after_check=function(option) check_option("'
.. opt .. '", "' .. optname .. '") end,')
_:print(' })')
end
for i,extra in ipairs(extraopts) do
local optname = extra[1]
local desc = extra[2]
local opt = _:tostroption(optname)
_:print(' option("' .. opt .. '", {showmenu=true, description="' .. desc .. '", default=""})')
end
_:print('end\n')
_:print([[
-- Set options for a specific mode (see also ]] .. funcprefix .. [[rule())
-- `options_by_modes` = {
-- [modename]: {
-- function() ... end, -- optional callback
-- stl_debug='on', ... -- options (see create_options())
-- }
-- }
-- `extra_options` = {
-- rulename :string = name for current mode (default value is '__]] .. funcprefix .. [[flags__')
-- other options are sent to ]] .. funcprefix .. [[rule()
-- }
function ]] .. funcprefix .. [[init_modes(options_by_modes, extra_options)
extra_options = extra_options or {}
local rulename = extra_options.rulename or '__]] .. funcprefix .. [[flags__'
for mode,options in pairs(options_by_modes) do
if is_mode(mode) then
local callback = options[1]
if callback then
options[1] = nil
end
]] .. funcprefix .. [[rule(rulename, options, extra_options)
if callback then
options[1] = callback
callback()
end
add_rules(rulename)
return
end
end
]] .. funcprefix .. [[rule(rulename, {}, extra_options)
add_rules(rulename)
end
local cached_flags = {}
-- Create a new rule. Options are added to the current configuration (see create_options())
-- `options`: same as create_options()
-- `extra_options` = {
-- import_base :string = import directory containing flags.lua (default: ']] .. import_base .. [[')
-- clone_options :boolean = make an internal copy of options
-- which prevents changing it after the call to ]] .. funcprefix .. [[rule().
-- (default: false)
-- other options are sent to get_flags()
-- }
function ]] .. funcprefix .. [[rule(rulename, options, extra_options)
extra_options = extra_options or {}
local import_base = extra_options.import_base or ']] .. import_base .. [['
if extra_options.clone_options then
local cloned = {}
for k, v in pairs(options) do
cloned[k] = v
end
options = cloned
end
rule(rulename)
on_load(function(target)
local cached = cached_flags[rulename]
if not cached then
import(import_base .. '.flags')
cached = flags.get_flags(options, extra_options)
table.insert(cached.cxxflags, {force=true})
table.insert(cached.ldflags, {force=true})
cached_flags[rulename] = cached
end
target:add('cxxflags', table.unpack(cached.cxxflags))
target:add('ldflags', table.unpack(cached.ldflags))
end)
rule_end()
end
]])
_._options_str = _:get_output()
_._strs = {}
_:print('-- File generated with https://github.com/jonathanpoelen/cpp-compiler-options\n')
_:print(common_code)
_:print([[
import'core.platform.platform'
import'lib.detect'
local _get_extra = function(opt)
local x = get_config(opt)
return x ~= '' and x or nil
end
local _check_flags = function(d)
for k,v in pairs(d) do
local ref = _flag_names[k]
if not ref then
if not _extraopt_flag_names[k] then
os.raise(vformat("${color.error}Unknown key: '%s'", k))
end
elseif not ref[v] then
os.raise(vformat("${color.error}Unknown value '%s' for '%s'", v, k))
end
end
end
-- Returns the merge of the default options and options parameter
-- `options`: table. ex: {warnings='on'}
-- `options` can have 3 additional fields:
-- - `cxx`: compiler name (otherwise deducted from --cxx and --toolchain)
-- - `cxx_version`: compiler version (otherwise deducted from cxx). ex: '7', '7.2'
-- - `ld`: linker name
-- `extra_options` = {
-- disable_other_options: bool = false
-- }
function create_options(options, extra_options)
if options then
_check_flags(options)
local disable_other_options = extra_options and extra_options.disable_other_options
return {]])
for option in _:getoptions() do
local optname = option.name
local opt = _:tostroption(optname)
local isnotsamename = (opt ~= optname)
_:print(' ' .. optname .. ' = options.' .. optname .. ' '
.. (isnotsamename and 'or options["' .. opt .. '"] ' or '')
.. 'or (disable_other_options and "" or _flag_names.' .. optname
.. '[get_config("' .. opt .. '")]),')
end
for i,extra in ipairs(extraopts) do
local optname = extra[1]
local opt = _:tostroption(optname)
_:print(' ' .. optname .. ' = options.' .. optname .. ' '
.. (isnotsamename and 'or options["' .. opt .. '"] ' or '')
.. 'or (not disable_other_options and _get_extra("' .. opt .. '")) or nil,')
end
_:print([[ }
else
return {]])
for option in _:getoptions() do
local optname = option.name
local opt = _:tostroption(optname)
_:print(' ["' .. optname .. '"] = _flag_names["' .. optname
.. '"][get_config("' .. opt .. '")],')
end
for i,extra in ipairs(extraopts) do
local optname = extra[1]
local opt = _:tostroption(optname)
_:print(' ["' .. optname .. '"] = _get_extra("' .. opt .. '"),')
end
_:print([[ }
end
end
-- Same as get_flags() and apply the options on a target
function set_flags(target, options, extra_options)
options = get_flags(options, extra_options)
table.insert(options.cxxflags, {force=true})
table.insert(options.ldflags, {force=true})
target:add(']] .. cxflags .. [[', table.unpack(options.]] .. cxflags .. [[))
target:add('ldflags', table.unpack(options.ldflags))
table.remove(options.cxxflags)
table.remove(options.ldflags)
return options
end
local _compiler_by_toolname = {
vs='cl',
cl='cl',
gcc='gcc',
gxx='gcc',
clang='clang',
clangxx='clang',
icc='icc',
icpc='icc',
icl='icl',
icx='icx',
icpx='icx',
dpcpp='icx',
}
local _comp_cache = {}
local _ld_cache
local extract_progname_and_version_from_path = function(compiler)
compiler = compiler:match('/([^/]+)$') or compiler
local version = compiler:match('%d+%.?%d*%.?%d*$') or ''
-- remove version suffix
local has_sep = compiler:byte(#compiler - #version) == 45 -- '-'
compiler = compiler:sub(1, #compiler - #version - (has_sep and 1 or 0))
return compiler, version
end
-- Returns an array of compile and link flags
-- `options`: same as create_options()
-- `extra_options` = {
-- disable_other_options: bool = false
-- print_compiler: bool = false -- for debug only
-- }
-- return {]] .. cxflags .. [[=table, ldflags=table}
function get_flags(options, extra_options)
options = create_options(options, extra_options)
local compiler = options.]] .. compprefix .. [[
local version = options.]] .. compprefix .. [[_version
local linker = options.ld
if not linker then
linker = _ld_cache
if not linker then
local program, toolname = platform.tool('ld')
linker = toolname or detect.find_toolname(program) or ''
_ld_cache = linker
end
end
local original_compiler = compiler or ''
local original_version = version or ''
local compcache = (_comp_cache[original_compiler] or {})[original_version]
local compversion
if compcache then
compiler = compcache[1]
version = compcache[2]
compversion = compcache[3]
if not compiler then
-- wrintf("Unknown compiler")
return {]] .. cxflags .. [[={}, ldflags={}}
end
else
if compiler then
local restored_version = version
compiler, version = extract_progname_and_version_from_path(compiler)
version = restored_version or version
else
local toolname
if not compiler then
compiler, toolname = platform.tool(']] .. (_.is_C and "cc" or "cxx") .. [[')
if not compiler then
-- wprint("Unknown compiler")
local tmp = _comp_cache[original_compiler] or {}
tmp[original_version] = {}
_comp_cache[original_compiler] = tmp
return {]] .. cxflags .. [[={}, ldflags={}}
end
end
local compinfos = detect.find_tool(toolname or compiler, {version=true, program=compiler})
if compinfos then
compiler = compinfos.name
version = compinfos.version
else
compiler, version = extract_progname_and_version_from_path(compiler)
end
end
compiler = _compiler_by_toolname[compiler] or compiler
compversion = {}
for i in version:gmatch("%d+") do
compversion[#compversion+1] = tonumber(i)
end
if not compversion[1] then
wprint("Wrong version format: %s", version)
compversion = 0
else
compversion = compversion[1] * 100000 + (compversion[2] or 0)
end
local tmp = _comp_cache[original_compiler] or {}
tmp[original_version] = {compiler, version, compversion}
_comp_cache[original_compiler] = tmp
end
if extra_options and extra_options.print_compiler then
cprint("get_flags: compiler: ${cyan}%s${reset}, version: ${cyan}%s", compiler, version)
end
local insert = table.insert
local jln_cxflags, jln_ldflags = {}, {}
]])
end,
_vcond_lvl=function(_, lvl, optname) return 'options.' .. optname .. ' == "' .. todefault(lvl) .. '"' end,
_vcond_verless=function(_, major, minor) return 'compversion < ' .. tostring(major * 100000 + minor) end,
_vcond_compiler=function(_, compiler) return 'compiler == "' .. tocomp(compiler) .. '"' end,
_vcond_platform=function(_, platform) return 'is_plat("' .. toplatform(platform) .. '")' end,
_vcond_linker=function(_, linker) return 'linker == "' .. linker .. '"' end,
cxx=function(_, x) return _.indent .. 'insert(jln_cxflags, "' .. x .. '")\n' end,
link=function(_, x) return _.indent .. 'insert(jln_ldflags, "' .. x .. '")\n' end,
act=function(_, name, datas, optname)
_:print(_.indent .. '-- unimplementable')
return true
end,
stop=function(_, filebase)
_:print(' return {' .. _.cxflags_name .. '=jln_cxflags, ldflags=jln_ldflags}\nend\n')
return filebase and {
{filebase .. '_options.lua', _._options_str},
{filebase, _:get_output()}
} or _:get_output()
end,
}
|
vim.o.completeopt = "menuone,noselect"
local cmp = require("cmp")
local luasnip = require("luasnip")
cmp.setup({
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body)
end,
},
mapping = {
['<C-p>'] = cmp.mapping.select_prev_item(),
['<C-n>'] = cmp.mapping.select_next_item(),
['<C-d>'] = cmp.mapping.scroll_docs(-4),
['<C-f>'] = cmp.mapping.scroll_docs(4),
["<C-s>"] = cmp.mapping.complete(),
["<C-e>"] = cmp.mapping.close(),
["<CR>"] = cmp.mapping.confirm({
behavior = cmp.ConfirmBehavior.Replace,
select = true,
}),
-- Tab mapping
['<Tab>'] = function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
else
fallback()
end
end,
['<S-Tab>'] = function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end,
},
sources = {
{ name = "nvim_lua" },
{ name = "nvim_lsp" },
{ name = "path" },
{ name = "luasnip" },
{ name = "buffer", keyword_length = 4 },
{ name = "treesitter" },
{ name = "emoji" },
},
formatting = {
format = require("lspkind").cmp_format({
with_text = true,
menu = {
nvim_lua = "[API]",
nvim_lsp = "[LSP]",
path = "[Path]",
luasnip = "[Snippet]",
buffer = "[Buffer]",
treesitter = "[TS]",
emoji = "[Emoji]",
},
}),
},
})
|
local ailment_buildup = {};
local player;
local language;
local config;
local ailments;
local ailment_buildup_UI_entity;
local time;
local small_monster;
local large_monster;
local table_helpers;
local drawing;
function ailment_buildup.draw_dynamic(monster, ailment_buildups_position_on_screen, opacity_scale)
local cached_config = config.current_config.large_monster_UI.dynamic.ailment_buildups;
local global_scale_modifier = config.current_config.global_settings.modifiers.global_scale_modifier;
if not cached_config.visibility then
return;
end
for id, ailment in pairs(monster.ailments) do
if id == ailments.stun_id then
if not cached_config.filter.stun then
goto continue;
end
elseif id == ailments.poison_id then
if not cached_config.filter.poison then
goto continue;
end
elseif id == ailments.blast_id then
if not cached_config.filter.blast then
goto continue;
end
else
goto continue;
end
if cached_config.settings.time_limit ~= 0 and time.total_elapsed_seconds - ailment.last_change_time > cached_config.settings.time_limit then
goto continue;
end
local total_buildup = 0;
local top_buildup = 0;
local displayed_players = {};
for player_id, player_buildup in pairs(ailment.buildup) do
total_buildup = total_buildup + player_buildup;
if player_buildup > top_buildup then
top_buildup = player_buildup;
end
table.insert(displayed_players,
{
["buildup"] = player_buildup,
["buildup_share"] = ailment.buildup_share[player_id],
["id"] = player_id
}
);
end
if total_buildup == 0 then
goto continue;
end
if cached_config.sorting.type == "Normal" then
if cached_config.sorting.reversed_order then
table.sort(displayed_players, function(left, right)
return left.id < right.id;
end);
else
table.sort(displayed_players, function(left, right)
return left.id > right.id;
end);
end
elseif cached_config.sorting.type == "Buildup" then
if cached_config.sorting.reversed_order then
table.sort(displayed_players, function(left, right)
return left.buildup < right.buildup;
end);
else
table.sort(displayed_players, function(left, right)
return left.buildup > right.buildup;
end);
end
elseif cached_config.sorting.type == "Buildup Percentage" then
if cached_config.sorting.reversed_order then
table.sort(displayed_players, function(left, right)
return left.buildup_share < right.buildup_share;
end);
else
table.sort(displayed_players, function(left, right)
return left.buildup_share > right.buildup_share;
end);
end
end
local ailment_name = "";
if cached_config.ailment_name_label.include.ailment_name then
ailment_name = ailment.name .. " ";
end
if cached_config.ailment_name_label.include.activation_count and ailment.activate_count ~= 0 then
ailment_name = ailment_name .. "x" .. tostring(ailment.activate_count);
end
drawing.draw_label(monster.ailments[ailments.stun_id].ailment_buildup_dynamic_UI.ailment_name_label, ailment_buildups_position_on_screen, opacity_scale, ailment_name);
local last_j = 0;
for j, _player in ipairs(displayed_players) do
local ailment_buildup_position_on_screen = {
x = ailment_buildups_position_on_screen.x + cached_config.player_spacing.x * (j - 1) * global_scale_modifier,
y = ailment_buildups_position_on_screen.y + cached_config.player_spacing.y * (j - 1) * global_scale_modifier;
};
ailment_buildup_UI_entity.draw_dynamic(_player, monster.ailments[ailments.stun_id].ailment_buildup_dynamic_UI, ailment_buildup_position_on_screen, opacity_scale, top_buildup);
last_j = j;
end
local total_buildup_position_on_screen = {
x = ailment_buildups_position_on_screen.x + cached_config.player_spacing.x * last_j * global_scale_modifier,
y = ailment_buildups_position_on_screen.y + cached_config.player_spacing.y * last_j * global_scale_modifier;
};
drawing.draw_label(monster.ailments[ailments.stun_id].ailment_buildup_dynamic_UI.total_buildup_label, total_buildup_position_on_screen, opacity_scale, language.current_language.UI.total_buildup);
drawing.draw_label(monster.ailments[ailments.stun_id].ailment_buildup_dynamic_UI.total_buildup_value_label, total_buildup_position_on_screen, opacity_scale, total_buildup);
ailment_buildups_position_on_screen = {
x = total_buildup_position_on_screen.x + cached_config.ailment_spacing.x * global_scale_modifier,
y = total_buildup_position_on_screen.y + 17 + cached_config.ailment_spacing.y * global_scale_modifier
};
::continue::
end
end
function ailment_buildup.draw_static(monster, ailment_buildups_position_on_screen, opacity_scale)
local cached_config = config.current_config.large_monster_UI.static.ailment_buildups;
local global_scale_modifier = config.current_config.global_settings.modifiers.global_scale_modifier;
if not cached_config.visibility then
return;
end
for id, ailment in pairs(monster.ailments) do
if id == ailments.stun_id then
if not cached_config.filter.stun then
goto continue;
end
elseif id == ailments.poison_id then
if not cached_config.filter.poison then
goto continue;
end
elseif id == ailments.blast_id then
if not cached_config.filter.blast then
goto continue;
end
else
goto continue;
end
if cached_config.settings.time_limit ~= 0 and time.total_elapsed_seconds - ailment.last_change_time > cached_config.settings.time_limit then
goto continue;
end
local total_buildup = 0;
local top_buildup = 0;
local displayed_players = {};
for player_id, player_buildup in pairs(ailment.buildup) do
total_buildup = total_buildup + player_buildup;
if player_buildup > top_buildup then
top_buildup = player_buildup;
end
table.insert(displayed_players,
{
["buildup"] = player_buildup,
["buildup_share"] = ailment.buildup_share[player_id],
["id"] = player_id
}
);
end
if total_buildup == 0 then
goto continue;
end
if cached_config.sorting.type == "Normal" then
if cached_config.sorting.reversed_order then
table.sort(displayed_players, function(left, right)
return left.id < right.id;
end);
else
table.sort(displayed_players, function(left, right)
return left.id > right.id;
end);
end
elseif cached_config.sorting.type == "Buildup" then
if cached_config.sorting.reversed_order then
table.sort(displayed_players, function(left, right)
return left.buildup < right.buildup;
end);
else
table.sort(displayed_players, function(left, right)
return left.buildup > right.buildup;
end);
end
elseif cached_config.sorting.type == "Buildup Percentage" then
if cached_config.sorting.reversed_order then
table.sort(displayed_players, function(left, right)
return left.buildup_share < right.buildup_share;
end);
else
table.sort(displayed_players, function(left, right)
return left.buildup_share > right.buildup_share;
end);
end
end
local ailment_name = "";
if cached_config.ailment_name_label.include.ailment_name then
ailment_name = ailment.name .. " ";
end
if cached_config.ailment_name_label.include.activation_count and ailment.activate_count ~= 0 then
ailment_name = ailment_name .. "x" .. tostring(ailment.activate_count);
end
drawing.draw_label(monster.ailments[ailments.stun_id].ailment_buildup_static_UI.ailment_name_label, ailment_buildups_position_on_screen, opacity_scale, ailment_name);
local last_j = 0;
for j, _player in ipairs(displayed_players) do
local ailment_buildup_position_on_screen = {
x = ailment_buildups_position_on_screen.x + cached_config.player_spacing.x * (j - 1) * global_scale_modifier,
y = ailment_buildups_position_on_screen.y + cached_config.player_spacing.y * (j - 1) * global_scale_modifier;
};
ailment_buildup_UI_entity.draw_static(_player, monster.ailments[ailments.stun_id].ailment_buildup_static_UI, ailment_buildup_position_on_screen, opacity_scale, top_buildup);
last_j = j;
end
local total_buildup_position_on_screen = {
x = ailment_buildups_position_on_screen.x + cached_config.player_spacing.x * last_j * global_scale_modifier,
y = ailment_buildups_position_on_screen.y + cached_config.player_spacing.y * last_j * global_scale_modifier;
};
drawing.draw_label(monster.ailments[ailments.stun_id].ailment_buildup_static_UI.total_buildup_label, total_buildup_position_on_screen, opacity_scale, language.current_language.UI.total_buildup);
drawing.draw_label(monster.ailments[ailments.stun_id].ailment_buildup_static_UI.total_buildup_value_label, total_buildup_position_on_screen, opacity_scale, total_buildup);
ailment_buildups_position_on_screen = {
x = total_buildup_position_on_screen.x + cached_config.ailment_spacing.x * global_scale_modifier,
y = total_buildup_position_on_screen.y + 17 + cached_config.ailment_spacing.y * global_scale_modifier
};
::continue::
end
end
function ailment_buildup.draw_highlighted(monster, ailment_buildups_position_on_screen, opacity_scale)
local cached_config = config.current_config.large_monster_UI.highlighted.ailment_buildups;
local global_scale_modifier = config.current_config.global_settings.modifiers.global_scale_modifier;
if not cached_config.visibility then
return;
end
for id, ailment in pairs(monster.ailments) do
if id == ailments.stun_id then
if not cached_config.filter.stun then
goto continue;
end
elseif id == ailments.poison_id then
if not cached_config.filter.poison then
goto continue;
end
elseif id == ailments.blast_id then
if not cached_config.filter.blast then
goto continue;
end
else
goto continue;
end
if cached_config.settings.time_limit ~= 0 and time.total_elapsed_seconds - ailment.last_change_time > cached_config.settings.time_limit then
goto continue;
end
local total_buildup = 0;
local top_buildup = 0;
local displayed_players = {};
for player_id, player_buildup in pairs(ailment.buildup) do
total_buildup = total_buildup + player_buildup;
if player_buildup > top_buildup then
top_buildup = player_buildup;
end
table.insert(displayed_players,
{
["buildup"] = player_buildup,
["buildup_share"] = ailment.buildup_share[player_id],
["id"] = player_id
}
);
end
if total_buildup == 0 then
goto continue;
end
if cached_config.sorting.type == "Normal" then
if cached_config.sorting.reversed_order then
table.sort(displayed_players, function(left, right)
return left.id < right.id;
end);
else
table.sort(displayed_players, function(left, right)
return left.id > right.id;
end);
end
elseif cached_config.sorting.type == "Buildup" then
if cached_config.sorting.reversed_order then
table.sort(displayed_players, function(left, right)
return left.buildup < right.buildup;
end);
else
table.sort(displayed_players, function(left, right)
return left.buildup > right.buildup;
end);
end
elseif cached_config.sorting.type == "Buildup Percentage" then
if cached_config.sorting.reversed_order then
table.sort(displayed_players, function(left, right)
return left.buildup_share < right.buildup_share;
end);
else
table.sort(displayed_players, function(left, right)
return left.buildup_share > right.buildup_share;
end);
end
end
local ailment_name = "";
if cached_config.ailment_name_label.include.ailment_name then
ailment_name = ailment.name .. " ";
end
if cached_config.ailment_name_label.include.activation_count and ailment.activate_count ~= 0 then
ailment_name = ailment_name .. "x" .. tostring(ailment.activate_count);
end
drawing.draw_label(monster.ailments[ailments.stun_id].ailment_buildup_highlighted_UI.ailment_name_label, ailment_buildups_position_on_screen, opacity_scale, ailment_name);
local last_j = 0;
for j, _player in ipairs(displayed_players) do
local ailment_buildup_position_on_screen = {
x = ailment_buildups_position_on_screen.x + cached_config.player_spacing.x * (j - 1) * global_scale_modifier,
y = ailment_buildups_position_on_screen.y + cached_config.player_spacing.y * (j - 1) * global_scale_modifier;
};
ailment_buildup_UI_entity.draw_highlighted(_player, monster.ailments[ailments.stun_id].ailment_buildup_highlighted_UI, ailment_buildup_position_on_screen, opacity_scale, top_buildup);
last_j = j;
end
local total_buildup_position_on_screen = {
x = ailment_buildups_position_on_screen.x + cached_config.player_spacing.x * last_j * global_scale_modifier,
y = ailment_buildups_position_on_screen.y + cached_config.player_spacing.y * last_j * global_scale_modifier;
};
drawing.draw_label(monster.ailments[ailments.stun_id].ailment_buildup_highlighted_UI.total_buildup_label, total_buildup_position_on_screen, opacity_scale, language.current_language.UI.total_buildup);
drawing.draw_label(monster.ailments[ailments.stun_id].ailment_buildup_highlighted_UI.total_buildup_value_label, total_buildup_position_on_screen, opacity_scale, total_buildup);
ailment_buildups_position_on_screen = {
x = total_buildup_position_on_screen.x + cached_config.ailment_spacing.x * global_scale_modifier,
y = total_buildup_position_on_screen.y + 17 + cached_config.ailment_spacing.y * global_scale_modifier
};
::continue::
end
end
function ailment_buildup.draw_small(monster, ailment_buildups_position_on_screen, opacity_scale)
local cached_config = config.current_config.small_monster_UI.ailment_buildups;
local global_scale_modifier = config.current_config.global_settings.modifiers.global_scale_modifier;
if not cached_config.visibility then
return;
end
for id, ailment in pairs(monster.ailments) do
if id == ailments.stun_id then
if not cached_config.filter.stun then
goto continue;
end
elseif id == ailments.poison_id then
if not cached_config.filter.poison then
goto continue;
end
elseif id == ailments.blast_id then
if not cached_config.filter.blast then
goto continue;
end
else
goto continue;
end
if cached_config.settings.time_limit ~= 0 and time.total_elapsed_seconds - ailment.last_change_time > cached_config.settings.time_limit then
goto continue;
end
local total_buildup = 0;
local top_buildup = 0;
local displayed_players = {};
for player_id, player_buildup in pairs(ailment.buildup) do
total_buildup = total_buildup + player_buildup;
if player_buildup > top_buildup then
top_buildup = player_buildup;
end
table.insert(displayed_players,
{
["buildup"] = player_buildup,
["buildup_share"] = ailment.buildup_share[player_id],
["id"] = player_id
}
);
end
if total_buildup == 0 then
goto continue;
end
if cached_config.sorting.type == "Normal" then
if cached_config.sorting.reversed_order then
table.sort(displayed_players, function(left, right)
return left.id < right.id;
end);
else
table.sort(displayed_players, function(left, right)
return left.id > right.id;
end);
end
elseif cached_config.sorting.type == "Buildup" then
if cached_config.sorting.reversed_order then
table.sort(displayed_players, function(left, right)
return left.buildup < right.buildup;
end);
else
table.sort(displayed_players, function(left, right)
return left.buildup > right.buildup;
end);
end
elseif cached_config.sorting.type == "Buildup Percentage" then
if cached_config.sorting.reversed_order then
table.sort(displayed_players, function(left, right)
return left.buildup_share < right.buildup_share;
end);
else
table.sort(displayed_players, function(left, right)
return left.buildup_share > right.buildup_share;
end);
end
end
local ailment_name = "";
if cached_config.ailment_name_label.include.ailment_name then
ailment_name = ailment.name .. " ";
end
if cached_config.ailment_name_label.include.activation_count and ailment.activate_count ~= 0 then
ailment_name = ailment_name .. "x" .. tostring(ailment.activate_count);
end
drawing.draw_label(monster.ailments[ailments.stun_id].ailment_buildup_small_UI.ailment_name_label, ailment_buildups_position_on_screen, opacity_scale, ailment_name);
local last_j = 0;
for j, _player in ipairs(displayed_players) do
local ailment_buildup_position_on_screen = {
x = ailment_buildups_position_on_screen.x + cached_config.player_spacing.x * (j - 1) * global_scale_modifier,
y = ailment_buildups_position_on_screen.y + cached_config.player_spacing.y * (j - 1) * global_scale_modifier;
};
ailment_buildup_UI_entity.draw_small(_player, monster.ailments[ailments.stun_id].ailment_buildup_small_UI, ailment_buildup_position_on_screen, opacity_scale, top_buildup);
last_j = j;
end
local total_buildup_position_on_screen = {
x = ailment_buildups_position_on_screen.x + cached_config.player_spacing.x * last_j * global_scale_modifier,
y = ailment_buildups_position_on_screen.y + cached_config.player_spacing.y * last_j * global_scale_modifier;
};
drawing.draw_label(monster.ailments[ailments.stun_id].ailment_buildup_small_UI.total_buildup_label, total_buildup_position_on_screen, opacity_scale, language.current_language.UI.total_buildup);
drawing.draw_label(monster.ailments[ailments.stun_id].ailment_buildup_small_UI.total_buildup_value_label, total_buildup_position_on_screen, opacity_scale, total_buildup);
ailment_buildups_position_on_screen = {
x = total_buildup_position_on_screen.x + cached_config.ailment_spacing.x * global_scale_modifier,
y = total_buildup_position_on_screen.y + 17 + cached_config.ailment_spacing.y * global_scale_modifier
};
::continue::
end
end
function ailment_buildup.init_module()
player = require("MHR_Overlay.Damage_Meter.player");
language = require("MHR_Overlay.Misc.language");
config = require("MHR_Overlay.Misc.config");
ailments = require("MHR_Overlay.Monsters.ailments");
ailment_buildup_UI_entity = require("MHR_Overlay.UI.UI_Entities.ailment_buildup_UI_entity");
time = require("MHR_Overlay.Game_Handler.time");
small_monster = require("MHR_Overlay.Monsters.small_monster");
large_monster = require("MHR_Overlay.Monsters.large_monster");
table_helpers = require("MHR_Overlay.Misc.table_helpers");
drawing = require("MHR_Overlay.UI.drawing");
end
return ailment_buildup;
|
workspace "Durna"
architecture "x64"
startproject "ExampleGame"
configurations
{
"Debug",
"Release",
"Dist"
}
defines
{
"_CRT_SECURE_NO_WARNINGS"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
IncludeDir = {}
IncludeDir["GLFW"] = "ThirdParty/GLFW/include"
IncludeDir["spdlog"] = "ThirdParty/spdlog/include"
IncludeDir["ImGui"] = "ThirdParty/ImGui"
IncludeDir["glm"] = "ThirdParty/glm"
include "ThirdParty/glfw/premake5.lua"
include "ThirdParty/Spdlog/premake5.lua"
include "ThirdParty/ImGui/premake5.lua"
project "Durna"
location "Durna"
kind "StaticLib"
language "c++"
cppdialect "c++17"
staticruntime "on"
targetdir ("Bin/" .. outputdir .. "/%{prj.name}")
objdir ("Intermediate/" .. outputdir .. "/%{prj.name}")
pchheader "DurnaPCH.h"
pchsource "Durna/Source/DurnaPCH.cpp"
files
{
"%{prj.name}/Source/**.h",
"%{prj.name}/Source/**.cpp",
"%{prj.name}/Source/ThirdParty/Glad/glad.c"
}
includedirs
{
"%{prj.name}/Source",
"%{prj.name}/Source/ThirdParty/Glad/include",
"%{IncludeDir.GLFW}",
"%{IncludeDir.spdlog}",
"%{IncludeDir.ImGui}",
"%{IncludeDir.glm}"
}
links
{
"glfw",
"opengl32.lib",
"ImGui",
"spdlog",
}
filter "files:**.c"
flags {"NoPCH"}
filter "system:windows"
systemversion "latest"
defines
{
"DRN_PLATFORM_WINDOWS",
"DRN_BUILD_DLL"
}
filter "configurations:Debug"
defines
{
"DRN_DEBUG"
}
runtime "Debug"
symbols "on"
filter "configurations:Release"
defines
{
"DRN_RELEASE"
}
runtime "Release"
optimize "on"
filter "configurations:Dist"
defines
{
"DRN_DIST"
}
runtime "Release"
optimize "on"
project "ExampleGame"
location "ExampleGame"
kind "ConsoleApp"
language "c++"
cppdialect "c++17"
staticruntime "on"
targetdir ("Bin/" .. outputdir .. "/%{prj.name}")
objdir ("Intermediate/" .. outputdir .. "/%{prj.name}")
files
{
"%{prj.name}/Source/**.h",
"%{prj.name}/Source/**.cpp"
}
includedirs
{
"Durna/Source",
"ThirdParty/Spdlog/include",
"%{IncludeDir.glm}",
"%{IncludeDir.ImGui}"
}
links "Durna"
filter "system:windows"
systemversion "latest"
defines
{
"DRN_PLATFORM_WINDOWS"
}
filter "configurations:Debug"
defines
{
"DRN_DEBUG"
}
runtime "Debug"
symbols "on"
filter "configurations:Release"
defines
{
"DRN_RELEASE"
}
runtime "Release"
optimize "on"
filter "configurations:Dist"
defines
{
"DRN_DIST"
}
runtime "Release"
optimize "on"
|
local HybridCNNLong = {}
function HybridCNNLong.cnn(alphasize, emb_dim, dropout, avg, cnn_dim)
dropout = dropout or 0.0
avg = avg or 0
cnn_dim = cnn_dim or 256
local inputs = {}
table.insert(inputs, nn.Identity()()) -- Bag
local net = nn.Sequential()
-- 201 x alphasize
net:add(nn.TemporalConvolution(alphasize, 384, 4))
net:add(nn.Threshold())
net:add(nn.TemporalMaxPooling(3, 3))
-- 66 x 256
net:add(nn.TemporalConvolution(384, 512, 4))
net:add(nn.Threshold())
net:add(nn.TemporalMaxPooling(3, 3))
-- 21 x 256
net:add(nn.TemporalConvolution(512, cnn_dim, 4))
net:add(nn.Threshold())
local h1 = nn.SplitTable(2)(net(inputs[1]))
local r2 = FixedRNN.rnn(18, avg, cnn_dim)(h1)
out = nn.Linear(cnn_dim, emb_dim)(nn.Dropout(dropout)(r2))
local outputs = {}
table.insert(outputs, out)
return nn.gModule(inputs, outputs)
end
return HybridCNNLong
|
local addonName, ns = ...
--Some Tags
oUF.Tags.Events["shorthp"] = "UNIT_HEALTH"
oUF.Tags.Methods["shorthp"] = function(unit)
if not UnitIsDeadOrGhost(unit) then
local hp = UnitHealth(unit)
return AbbreviateLargeNumbers(hp)
end
end
oUF.Tags.Events["shortpp"] = "UNIT_POWER"
oUF.Tags.Methods["shortpp"] = function(unit)
if not UnitIsDeadOrGhost(unit) then
local pp = UnitPower(unit)
return AbbreviateLargeNumbers(pp)
end
end
oUF.Tags.Events["shortname"] = "UNIT_NAME"
oUF.Tags.Methods["shortname"] = function(unit)
local name = UnitName(unit)
return string.sub(UnitName(unit), 1, 20)
end
oUF.Tags.Events["readycheckicon"] = "DoReadyCheck"
oUF.Tags.SharedEvents["IsInGroup"] = true
oUF.Tags.Methods["readycheckicon"] = function(unit)
if unit == "player" and IsInGroup() then
return [[|TInterface\RAIDFRAME\ReadyCheck-Ready|t]]
end
end
oUF.Tags.Events["rsicon"] = "PLAYER_UPDATE_RESTING"
oUF.Tags.SharedEvents["PLAYER_UPDATE_RESTING"] = true
oUF.Tags.Methods["rsicon"] = function(unit)
if unit == "player" and IsResting() then
return [[|TInterface\CharacterFrame\UI-StateIcon:0:0:0:-6:64:64:28:6:6:28|t]]
end
end
oUF.Tags.Events["combaticon"] = "PLAYER_REGEN_DISABLED PLAYER_REGEN_ENABLED"
oUF.Tags.SharedEvents["PLAYER_REGEN_DISABLED"] = true
oUF.Tags.SharedEvents["PLAYER_REGEN_ENABLED"] = true
oUF.Tags.Methods["combaticon"] = function(unit)
if unit == "player" and UnitAffectingCombat("player") then
return [[|TInterface\CharacterFrame\UI-StateIcon:0:0:0:0:64:64:37:58:5:26|t]]
end
end
oUF.Tags.Events["leadericon"] = "GROUP_ROSTER_UPDATE"
oUF.Tags.SharedEvents["GROUP_ROSTER_UPDATE"] = true
oUF.Tags.Methods["leadericon"] = function(unit)
if UnitIsGroupLeader(unit) then
return [[|TInterface\GroupFrame\UI-Group-LeaderIcon:0|t]]
elseif UnitInRaid(unit) and UnitIsGroupAssistant(unit) then
return [[|TInterface\GroupFrame\UI-Group-AssistantIcon:0|t]]
end
end
oUF.Tags.Events["mastericon"] = "PARTY_LOOT_METHOD_CHANGED GROUP_ROSTER_UPDATE"
oUF.Tags.SharedEvents["PARTY_LOOT_METHOD_CHANGED"] = true
oUF.Tags.SharedEvents["GROUP_ROSTER_UPDATE"] = true
oUF.Tags.Methods["mastericon"] = function(unit)
local method, pid, rid = GetLootMethod()
if method ~= "master" then return end
local munit
if pid then
if pid == 0 then
munit = "player"
else
munit = "party" .. pid
end
elseif rid then
munit = "raid" .. rid
end
if munit and UnitIsUnit(munit, unit) then
return [[|TInterface\GroupFrame\UI-Group-MasterLooter:0:0:0:2|t]]
end
end
ns.tags = tags
|
local L = BigWigs:NewBossLocale("Court of Stars Trash", "deDE")
if not L then return end
if L then
L.Guard = "Wachposten der Dämmerwache"
L.Construct = "Wächterkonstrukt"
L.Enforcer = "Dämonenversklavte Vollstreckerin"
L.Hound = "Legionshund"
L.Mistress = "Schattenmeisterin"
L.Gerenth = "Verdächtiger Adliger"
L.Jazshariu = "Jazshariu"
L.Imacutya = "Imacutya"
L.Baalgar = "Baalgar der Wachsame"
L.Inquisitor = "Wachsamer Inquisitor"
L.BlazingImp = "Lodernder Wichtel"
L.Energy = "Gebundene Energie"
L.Manifestation = "Arkane Manifestation"
L.Wyrm = "Manawyrm"
L.Arcanist = "Arkanist der Dämmerwache"
L.InfernalImp = "Höllenwichtel"
L.Malrodi = "Arkanistin Malrodi"
L.Velimar = "Velimar"
L.ArcaneKeys = "Arkane Schlüssel"
L.clues = "Hinweise"
L.InfernalTome = "Höllischer Foliant"
L.MagicalLantern = "Magische Laterne"
L.NightshadeRefreshments = "Nachtschattenerfrischungen"
L.StarlightRoseBrew = "Sternlichtrosenbräu"
L.UmbralBloom = "Umbralblüte"
L.WaterloggedScroll = "Durchnässte Schriftrolle"
L.BazaarGoods = "Basarwaren"
L.LifesizedNightborneStatue = "Lebensgroße Nachtgeborenenstatue"
L.DiscardedJunk = "Ausrangierter Schrott"
L.WoundedNightborneCivilian = "Verwundeter Zivilist der Nachtgeborenen"
L.announce_buff_items = "Buff-Items bekanntgeben"
L.announce_buff_items_desc = "Gibt bekannt, welche verfügbaren Buff-Items in der Instanz vorhanden sind und wer sie benutzen kann."
L.available = "%s|cffffffff%s|r vorhanden" -- Context: item is available to use
L.usableBy = "benutzbar von %s" -- Context: item is usable by someone
L.custom_on_use_buff_items = "Buff-Items sofort benutzen"
L.custom_on_use_buff_items_desc = "Durch die Aktivierung dieser Option werden die Buff-Items beim anklicken sofort benutzt, ausgenommen derjenigen, die eine der drei Botschafter des zweiten Bosses rufen."
L.spy_helper = "Spion Event Helfer"
L.spy_helper_desc = "Zeigt eine Infobox mit allen Hinweisen über den Spion an. Diese Hinweise werden ebenfalls im Chat an deine Gruppe geschickt."
L.clueFound = "Hinweise gefunden (%d/5): |cffffffff%s|r"
L.spyFound = "Der Spion wurde von %s gefunden!"
L.spyFoundChat = "Ich habe den Spion gefunden!"
L.spyFoundPattern = "Na, na, wir wollen doch nicht voreilig sein" -- Na, na, wir wollen doch nicht voreilig sein, [player]. Wieso folgt Ihr mir nicht, damit wir in etwas privaterer Umgebung darüber sprechen können...
L.hints = {
"Umhang",
"Kein Umhang",
"Geldbeutel",
"Fläschchen",
"Lange Ärmel",
"Kurze Ärmel",
"Handschuhe",
"Keine Handschuhe",
"Männlich",
"Weiblich",
"Helle Weste",
"Dunkle Weste",
"Kein Fläschchen",
"Buch",
}
--[[ !!! WICHTIGE INFORMATION FÜR ALLE ÜBERSETZER !!! ]]--
--[[ Die folgenden Übersetzungen müssen exakt mit den Texten der Geschwätzige Plaudertaschen übereinstimmen. ]]--
-- Umhang
L["Jemand erwähnte, dass der Spion vorhin hier hereinkam und einen Umhang trug."] = 1
L["Mir ist zu Ohren gekommen, dass der Spion gerne Umhänge trägt."] = 1
-- Kein Umhang
L["Ich hörte, dass der Spion seinen Umhang im Palast gelassen hat, bevor er hierhergekommen ist."] = 2
L["Ich hörte, dass der Spion keine Umhänge mag und sich weigert, einen zu tragen."] = 2
-- Geldbeutel
L["Ich hörte, dass der Gürtelbeutel des Spions mit ausgefallenem Garn gesäumt wurde."] = 3
L["Ein Freund behauptet, dass der Spion Gold liebt und einen Gürtelbeutel voll davon hat."] = 3
L["Mir ist zu Ohren gekommen, dass der Gürtelbeutel des Spions mit Gold gefüllt ist, um besonders extravagant zu erscheinen."] = 3
L["Ich hörte, dass der Spion immer einen magischen Beutel mit sich herumträgt."] = 3
-- Fläschchen
L["Ich bin mir ziemlich sicher, dass der Spion Tränke am Gürtel trägt."] = 4
L["Ich hörte, dass der Spion Tränke mitgebracht hat... Ich frage mich wieso?"] = 4
L["Wie ich hörte, hat der Spion einige Tränke mitgebracht... für alle Fälle."] = 4
L["Von mir habt Ihr das nicht... aber der Spion verkleidet sich als Alchemist und trägt Tränke an seinem Gürtel."] = 4
-- Lange Ärmel
L["Wie ich hörte, trägt der Spion heute Abend Kleidung mit langen Ärmeln."] = 5
L["Einer meiner Freunde erwähnte, dass der Spion lange Ärmel trägt."] = 5
L["Jemand sagte, dass der Spion heute Abend seine Arme mit langen Ärmeln bedeckt."] = 5
L["Ich habe am frühen Abend einen kurzen Blick auf die langen Ärmel des Spions erhascht."] = 5
-- Kurze Ärmel
L["Jemand sagte mir, dass der Spion lange Ärmel hasst."] = 6
L["Mir ist zu Ohren gekommen, dass der Spion kurze Ärmel trägt, damit er seine Arme ungehindert bewegen kann."] = 6
L["Man hat mir zugetragen, dass der Spion die kühle Luft mag und deshalb heute Abend keine langen Ärmel trägt."] = 6
L["Eine meiner Freundinnen sagte, dass sie die Kleidung des Spions gesehen hat. Er trägt keine langen Ärmel."] = 6
-- Handschuhe
L["Einem Gerücht zufolge trägt der Spion immer Handschuhe."] = 7
L["Wie ich hörte, verbirgt der Spion sorgfältig die Hände."] = 7
L["Jemand behauptete, dass der Spion Handschuhe trägt, um sichtbare Narben zu verbergen."] = 7
L["Ich hörte, dass der Spion immer Handschuhe anlegt."] = 7
-- Keine Handschuhe
L["Wisst Ihr... Ich habe ein zusätzliches Paar Handschuhe im Hinterzimmer gefunden. Wahrscheinlich ist der Spion hier irgendwo mit bloßen Händen unterwegs."] = 8
L["Es gibt Gerüchte, dass der Spion niemals Handschuhe trägt."] = 8
L["Ich hörte, dass der Spion es vermeidet, Handschuhe zu tragen, falls er schnell handeln muss."] = 8
L["Mir ist zu Ohren gekommen, dass der Spion ungern Handschuhe trägt."] = 8
-- Männlich
L["Irgendwo habe ich gehört, dass der Spion nicht weiblich ist."] = 9
L["Ich hörte, dass der Spion ein äußerst gutaussehender Herr ist."] = 9
L["Ein Gast sagte, sie sah, wie ein Herr an der Seite der Großmagistrix das Anwesen betreten hat."] = 9
L["Einer der Musiker sagte, er stellte unablässig Fragen über den Bezirk."] = 9
-- Weiblich
L["Jemand hat behauptet, dass unser neuester Gast nicht männlich ist."] = 10
L["Ein Gast hat beobachtet, wie sie und Elisande vorhin gemeinsam eingetroffen sind."] = 10
L["Man sagt, die Spionin wäre hier und sie wäre eine wahre Augenweide."] = 10
L["Wie ich höre, hat eine Frau sich ständig nach diesem Bezirk erkundigt..."] = 10
-- Helle Weste
L["Der Spion bevorzugt auf jeden Fall Westen mit hellen Farben."] = 11
L["Wie ich hörte, trägt der Spion auf der Party heute Abend eine helle Weste."] = 11
L["Die Leute sagen, dass der Spion heute Abend keine dunkle Weste trägt."] = 11
-- Dunkle Weste
L["Der Spion bevorzugt auf alle Fälle dunkle Kleidung."] = 12
L["Ich hörte, dass die Weste des Spions heute Abend von dunkler, kräftiger Farbe ist."] = 12
L["Dem Spion gefallen Westen mit dunklen Farben... dunkel wie die Nacht."] = 12
L["Gerüchten zufolge vermeidet der Spion es, helle Kleidung zu tragen, damit er nicht so auffällt."] = 12
-- Kein Fläschchen
L["Eine Musikerin erzählte mir, dass sie gesehen hat, wie der Spion seinen letzten Trank wegwarf und jetzt keinen mehr übrig hat."] = 13
L["Wie ich hörte, hat der Spion keine Tränke bei sich."] = 13
-- Buch
L["Gerüchten zufolge liest der Spion gerne und trägt immer mindestens ein Buch bei sich."] = 14
L["Ich hörte, dass der Spion immer ein Buch mit niedergeschriebenen Geheimnissen am Gürtel trägt."] = 14
end
L = BigWigs:NewBossLocale("Advisor Melandrus", "deDE")
if L then
L.warmup_trigger = "Eine weitere Fehlleistung, Melandrus. Aber Ihr könnt es wiedergutmachen. Vernichtet die Eindringlinge. Ich muss zurück zur Nachtfestung."
end
|
local db_mgr = require "common.db_mgr"
local agent_db = {}
return agent_db
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.